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.

279272 lines
7.5MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC
  76. #ifndef NDEBUG
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #ifdef __LITTLE_ENDIAN__
  80. #define JUCE_LITTLE_ENDIAN 1
  81. #else
  82. #define JUCE_BIG_ENDIAN 1
  83. #endif
  84. #if defined (__ppc__) || defined (__ppc64__)
  85. #define JUCE_PPC 1
  86. #else
  87. #define JUCE_INTEL 1
  88. #endif
  89. #ifdef __LP64__
  90. #define JUCE_64BIT 1
  91. #else
  92. #define JUCE_32BIT 1
  93. #endif
  94. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  95. #error "Building for OSX 10.3 is no longer supported!"
  96. #endif
  97. #ifndef MAC_OS_X_VERSION_10_5
  98. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  99. #endif
  100. #endif
  101. #if JUCE_IOS
  102. #ifndef NDEBUG
  103. #define JUCE_DEBUG 1
  104. #endif
  105. #ifdef __LITTLE_ENDIAN__
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #else
  108. #define JUCE_BIG_ENDIAN 1
  109. #endif
  110. #endif
  111. #if JUCE_LINUX
  112. #ifdef _DEBUG
  113. #define JUCE_DEBUG 1
  114. #endif
  115. // Allow override for big-endian Linux platforms
  116. #ifndef JUCE_BIG_ENDIAN
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #endif
  119. #if defined (__LP64__) || defined (_LP64)
  120. #define JUCE_64BIT 1
  121. #else
  122. #define JUCE_32BIT 1
  123. #endif
  124. #define JUCE_INTEL 1
  125. #endif
  126. // Compiler type macros.
  127. #ifdef __GNUC__
  128. #define JUCE_GCC 1
  129. #elif defined (_MSC_VER)
  130. #define JUCE_MSVC 1
  131. #if _MSC_VER >= 1400
  132. #define JUCE_USE_INTRINSICS 1
  133. #endif
  134. #else
  135. #error unknown compiler
  136. #endif
  137. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  138. /*** End of inlined file: juce_TargetPlatform.h ***/
  139. // FORCE_AMALGAMATOR_INCLUDE
  140. /*** Start of inlined file: juce_Config.h ***/
  141. #ifndef __JUCE_CONFIG_JUCEHEADER__
  142. #define __JUCE_CONFIG_JUCEHEADER__
  143. /*
  144. This file contains macros that enable/disable various JUCE features.
  145. */
  146. /** The name of the namespace that all Juce classes and functions will be
  147. put inside. If this is not defined, no namespace will be used.
  148. */
  149. #ifndef JUCE_NAMESPACE
  150. #define JUCE_NAMESPACE juce
  151. #endif
  152. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  153. project settings, but if you define this value, you can override this to force
  154. it to be true or false.
  155. */
  156. #ifndef JUCE_FORCE_DEBUG
  157. //#define JUCE_FORCE_DEBUG 0
  158. #endif
  159. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  160. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  161. Enabling it will also leave this turned on in release builds. When it's disabled,
  162. however, the jassert and jassertfalse macros will not be compiled in a
  163. release build.
  164. @see jassert, jassertfalse, Logger
  165. */
  166. #ifndef JUCE_LOG_ASSERTIONS
  167. #define JUCE_LOG_ASSERTIONS 0
  168. #endif
  169. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  170. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  171. on your Windows build machine.
  172. See the comments in the ASIOAudioIODevice class's header file for more
  173. info about this.
  174. */
  175. #ifndef JUCE_ASIO
  176. #define JUCE_ASIO 0
  177. #endif
  178. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  179. */
  180. #ifndef JUCE_WASAPI
  181. #define JUCE_WASAPI 0
  182. #endif
  183. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  184. */
  185. #ifndef JUCE_DIRECTSOUND
  186. #define JUCE_DIRECTSOUND 1
  187. #endif
  188. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  189. #ifndef JUCE_ALSA
  190. #define JUCE_ALSA 1
  191. #endif
  192. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  193. #ifndef JUCE_JACK
  194. #define JUCE_JACK 0
  195. #endif
  196. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  197. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  198. installed, and its header files will need to be on your include path.
  199. */
  200. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  201. #define JUCE_QUICKTIME 0
  202. #endif
  203. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  204. #undef JUCE_QUICKTIME
  205. #endif
  206. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  207. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  208. */
  209. #ifndef JUCE_OPENGL
  210. #define JUCE_OPENGL 1
  211. #endif
  212. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  213. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  214. */
  215. #ifndef JUCE_DIRECT2D
  216. #define JUCE_DIRECT2D 0
  217. #endif
  218. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  219. If your app doesn't need to read FLAC files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_FLAC
  223. #define JUCE_USE_FLAC 1
  224. #endif
  225. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  226. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  227. reduce the size of your codebase and build time.
  228. */
  229. #ifndef JUCE_USE_OGGVORBIS
  230. #define JUCE_USE_OGGVORBIS 1
  231. #endif
  232. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-burning, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  237. #define JUCE_USE_CDBURNER 0
  238. #endif
  239. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  240. Unless you're using CD-reading, you should probably turn this flag off to
  241. reduce code size.
  242. */
  243. #ifndef JUCE_USE_CDREADER
  244. #define JUCE_USE_CDREADER 0
  245. #endif
  246. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  247. */
  248. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  249. #define JUCE_USE_CAMERA 0
  250. #endif
  251. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  252. gets repainted will flash in a random colour, so that you can check exactly how much and how
  253. often your components are being drawn.
  254. */
  255. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  256. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  257. #endif
  258. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  259. Unless you specifically want to disable this, it's best to leave this option turned on.
  260. */
  261. #ifndef JUCE_USE_XINERAMA
  262. #define JUCE_USE_XINERAMA 1
  263. #endif
  264. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  265. turned on unless you have a good reason to disable it.
  266. */
  267. #ifndef JUCE_USE_XSHM
  268. #define JUCE_USE_XSHM 1
  269. #endif
  270. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  271. */
  272. #ifndef JUCE_USE_XRENDER
  273. #define JUCE_USE_XRENDER 0
  274. #endif
  275. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  276. unless you have a good reason to disable it.
  277. */
  278. #ifndef JUCE_USE_XCURSOR
  279. #define JUCE_USE_XCURSOR 1
  280. #endif
  281. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  282. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  283. you're building a plugin hosting app.
  284. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  285. */
  286. #ifndef JUCE_PLUGINHOST_VST
  287. #define JUCE_PLUGINHOST_VST 0
  288. #endif
  289. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  290. of course, and should only be enabled if you're building a plugin hosting app.
  291. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  292. */
  293. #ifndef JUCE_PLUGINHOST_AU
  294. #define JUCE_PLUGINHOST_AU 0
  295. #endif
  296. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  297. This should be enabled if you're writing a console application.
  298. */
  299. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  300. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  301. #endif
  302. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  303. If you're not using any embedded web-pages, turning this off may reduce your code size.
  304. */
  305. #ifndef JUCE_WEB_BROWSER
  306. #define JUCE_WEB_BROWSER 1
  307. #endif
  308. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  309. Carbon isn't required for a normal app, but may be needed by specialised classes like
  310. plugin-hosts, which support older APIs.
  311. */
  312. #ifndef JUCE_SUPPORT_CARBON
  313. #define JUCE_SUPPORT_CARBON 1
  314. #endif
  315. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  316. You might need to tweak this if you're linking to an external zlib library in your app,
  317. but for normal apps, this option should be left alone.
  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. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  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. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  341. that are thrown by the message dispatch loop. With it enabled, any unhandled 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 only building the core classes, we can explicitly turn off some features to avoid including them:
  348. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  349. #undef JUCE_QUICKTIME
  350. #define JUCE_QUICKTIME 0
  351. #undef JUCE_OPENGL
  352. #define JUCE_OPENGL 0
  353. #undef JUCE_USE_CDBURNER
  354. #define JUCE_USE_CDBURNER 0
  355. #undef JUCE_USE_CDREADER
  356. #define JUCE_USE_CDREADER 0
  357. #undef JUCE_WEB_BROWSER
  358. #define JUCE_WEB_BROWSER 0
  359. #undef JUCE_PLUGINHOST_AU
  360. #define JUCE_PLUGINHOST_AU 0
  361. #undef JUCE_PLUGINHOST_VST
  362. #define JUCE_PLUGINHOST_VST 0
  363. #endif
  364. #endif
  365. /*** End of inlined file: juce_Config.h ***/
  366. // FORCE_AMALGAMATOR_INCLUDE
  367. #ifndef JUCE_BUILD_CORE
  368. #define JUCE_BUILD_CORE 1
  369. #endif
  370. #ifndef JUCE_BUILD_MISC
  371. #define JUCE_BUILD_MISC 1
  372. #endif
  373. #ifndef JUCE_BUILD_GUI
  374. #define JUCE_BUILD_GUI 1
  375. #endif
  376. #ifndef JUCE_BUILD_NATIVE
  377. #define JUCE_BUILD_NATIVE 1
  378. #endif
  379. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  380. #undef JUCE_BUILD_MISC
  381. #undef JUCE_BUILD_GUI
  382. #endif
  383. //==============================================================================
  384. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  385. #if JUCE_WINDOWS
  386. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  387. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  388. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  389. #ifndef STRICT
  390. #define STRICT 1
  391. #endif
  392. #undef WIN32_LEAN_AND_MEAN
  393. #define WIN32_LEAN_AND_MEAN 1
  394. #if JUCE_MSVC
  395. #pragma warning (push)
  396. #pragma warning (disable : 4100 4201 4514 4312 4995)
  397. #endif
  398. #define _WIN32_WINNT 0x0500
  399. #define _UNICODE 1
  400. #define UNICODE 1
  401. #ifndef _WIN32_IE
  402. #define _WIN32_IE 0x0400
  403. #endif
  404. #include <windows.h>
  405. #include <windowsx.h>
  406. #include <commdlg.h>
  407. #include <shellapi.h>
  408. #include <mmsystem.h>
  409. #include <vfw.h>
  410. #include <tchar.h>
  411. #include <stddef.h>
  412. #include <ctime>
  413. #include <wininet.h>
  414. #include <nb30.h>
  415. #include <iphlpapi.h>
  416. #include <mapi.h>
  417. #include <float.h>
  418. #include <process.h>
  419. #include <Exdisp.h>
  420. #include <exdispid.h>
  421. #include <shlobj.h>
  422. #if ! JUCE_MINGW
  423. #include <crtdbg.h>
  424. #include <comutil.h>
  425. #endif
  426. #if JUCE_OPENGL
  427. #include <gl/gl.h>
  428. #endif
  429. #undef PACKED
  430. #if JUCE_ASIO
  431. /*
  432. This is very frustrating - we only need to use a handful of definitions from
  433. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  434. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  435. implementation...
  436. ..unfortunately that would break Steinberg's license agreement for use of
  437. their SDK, so I'm not allowed to do this.
  438. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  439. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  440. (see www.steinberg.net/Steinberg/Developers.asp).
  441. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  442. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  443. if you prefer). Make sure that your header search path will find the
  444. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  445. files are actually needed - so to simplify things, you could just copy
  446. these into your JUCE directory).
  447. If you're compiling and you get an error here because you don't have the
  448. ASIO SDK installed, you can disable ASIO support by commenting-out the
  449. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  450. */
  451. #include "iasiodrv.h"
  452. #endif
  453. #if JUCE_USE_CDBURNER
  454. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  455. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  456. flag in juce_Config.h to avoid these includes.
  457. */
  458. #include <imapi.h>
  459. #include <imapierror.h>
  460. #endif
  461. #if JUCE_USE_CAMERA
  462. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  463. These files are provided in the normal Windows SDK, but some Microsoft plonker
  464. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  465. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  466. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  467. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  468. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  469. The dummy file just needs to contain the following content:
  470. #define __IDxtCompositor_INTERFACE_DEFINED__
  471. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  472. #define __IDxtJpeg_INTERFACE_DEFINED__
  473. #define __IDxtKey_INTERFACE_DEFINED__
  474. ..and that should be enough to convince qedit.h that you have the SDK!
  475. */
  476. #include <dshow.h>
  477. #include <qedit.h>
  478. #include <dshowasf.h>
  479. #endif
  480. #if JUCE_WASAPI
  481. #include <MMReg.h>
  482. #include <mmdeviceapi.h>
  483. #include <Audioclient.h>
  484. #include <Avrt.h>
  485. #include <functiondiscoverykeys.h>
  486. #endif
  487. #if JUCE_QUICKTIME
  488. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  489. add its header directory to your include path.
  490. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  491. flag in juce_Config.h
  492. */
  493. #include <Movies.h>
  494. #include <QTML.h>
  495. #include <QuickTimeComponents.h>
  496. #include <MediaHandlers.h>
  497. #include <ImageCodec.h>
  498. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  499. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  500. your include search path to make these import statements work.
  501. */
  502. #import <QTOLibrary.dll>
  503. #import <QTOControl.dll>
  504. #endif
  505. #if JUCE_MSVC
  506. #pragma warning (pop)
  507. #endif
  508. #if JUCE_DIRECT2D
  509. #include <d2d1.h>
  510. #include <dwrite.h>
  511. #endif
  512. /** A simple COM smart pointer.
  513. Avoids having to include ATL just to get one of these.
  514. */
  515. template <class ComClass>
  516. class ComSmartPtr
  517. {
  518. public:
  519. ComSmartPtr() throw() : p (0) {}
  520. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  521. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  522. ~ComSmartPtr() { if (p != 0) p->Release(); }
  523. operator ComClass*() const throw() { return p; }
  524. ComClass& operator*() const throw() { return *p; }
  525. ComClass** operator&() throw() { return &p; }
  526. ComClass* operator->() const throw() { return p; }
  527. ComClass* operator= (ComClass* const newP)
  528. {
  529. if (newP != 0) newP->AddRef();
  530. if (p != 0) p->Release();
  531. p = newP;
  532. return newP;
  533. }
  534. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  535. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  536. {
  537. #ifndef __MINGW32__
  538. operator= (0);
  539. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  540. #else
  541. return S_FALSE;
  542. #endif
  543. }
  544. private:
  545. ComClass* p;
  546. };
  547. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  548. */
  549. template <class ComClass>
  550. class ComBaseClassHelper : public ComClass
  551. {
  552. public:
  553. ComBaseClassHelper() : refCount (1) {}
  554. virtual ~ComBaseClassHelper() {}
  555. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  556. {
  557. #ifndef __MINGW32__
  558. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  559. #endif
  560. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  561. *result = 0;
  562. return E_NOINTERFACE;
  563. }
  564. ULONG __stdcall AddRef() { return ++refCount; }
  565. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  566. protected:
  567. int refCount;
  568. };
  569. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  570. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  571. #elif JUCE_LINUX
  572. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  573. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  574. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  575. /*
  576. This file wraps together all the linux-specific headers, so
  577. that we can include them all just once, and compile all our
  578. platform-specific stuff in one big lump, keeping it out of the
  579. way of the rest of the codebase.
  580. */
  581. #include <sched.h>
  582. #include <pthread.h>
  583. #include <sys/time.h>
  584. #include <errno.h>
  585. #include <sys/stat.h>
  586. #include <sys/dir.h>
  587. #include <sys/ptrace.h>
  588. #include <sys/vfs.h>
  589. #include <sys/wait.h>
  590. #include <fnmatch.h>
  591. #include <utime.h>
  592. #include <pwd.h>
  593. #include <fcntl.h>
  594. #include <dlfcn.h>
  595. #include <netdb.h>
  596. #include <arpa/inet.h>
  597. #include <netinet/in.h>
  598. #include <sys/types.h>
  599. #include <sys/ioctl.h>
  600. #include <sys/socket.h>
  601. #include <net/if.h>
  602. #include <sys/sysinfo.h>
  603. #include <sys/file.h>
  604. #include <signal.h>
  605. /* Got a build error here? You'll need to install the freetype library...
  606. The name of the package to install is "libfreetype6-dev".
  607. */
  608. #include <ft2build.h>
  609. #include FT_FREETYPE_H
  610. #include <X11/Xlib.h>
  611. #include <X11/Xatom.h>
  612. #include <X11/Xresource.h>
  613. #include <X11/Xutil.h>
  614. #include <X11/Xmd.h>
  615. #include <X11/keysym.h>
  616. #include <X11/cursorfont.h>
  617. #if JUCE_USE_XINERAMA
  618. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  619. #include <X11/extensions/Xinerama.h>
  620. #endif
  621. #if JUCE_USE_XSHM
  622. #include <X11/extensions/XShm.h>
  623. #include <sys/shm.h>
  624. #include <sys/ipc.h>
  625. #endif
  626. #if JUCE_USE_XRENDER
  627. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  628. #include <X11/extensions/Xrender.h>
  629. #include <X11/extensions/Xcomposite.h>
  630. #endif
  631. #if JUCE_USE_XCURSOR
  632. // If you're missing this header, try installing the libxcursor-dev package
  633. #include <X11/Xcursor/Xcursor.h>
  634. #endif
  635. #if JUCE_OPENGL
  636. /* Got an include error here?
  637. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  638. and "freeglut3-dev".
  639. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  640. want to disable it.
  641. */
  642. #include <GL/glx.h>
  643. #endif
  644. #undef KeyPress
  645. #if JUCE_ALSA
  646. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  647. not got your paths set up correctly to find its header files.
  648. The package you need to install to get ASLA support is "libasound2-dev".
  649. If you don't have the ALSA library and don't want to build Juce with audio support,
  650. just disable the JUCE_ALSA flag in juce_Config.h
  651. */
  652. #include <alsa/asoundlib.h>
  653. #endif
  654. #if JUCE_JACK
  655. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  656. installed, or you've not got your paths set up correctly to find its header files.
  657. The package you need to install to get JACK support is "libjack-dev".
  658. If you don't have the jack-audio-connection-kit library and don't want to build
  659. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  660. */
  661. #include <jack/jack.h>
  662. //#include <jack/transport.h>
  663. #endif
  664. #undef SIZEOF
  665. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  666. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  667. #elif JUCE_MAC || JUCE_IPHONE
  668. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  669. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  670. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  671. /*
  672. This file wraps together all the mac-specific code, so that
  673. we can include all the native headers just once, and compile all our
  674. platform-specific stuff in one big lump, keeping it out of the way of
  675. the rest of the codebase.
  676. */
  677. #define USE_COREGRAPHICS_RENDERING 1
  678. #if JUCE_IOS
  679. #import <Foundation/Foundation.h>
  680. #import <UIKit/UIKit.h>
  681. #import <AudioToolbox/AudioToolbox.h>
  682. #import <AVFoundation/AVFoundation.h>
  683. #import <CoreData/CoreData.h>
  684. #import <MobileCoreServices/MobileCoreServices.h>
  685. #import <QuartzCore/QuartzCore.h>
  686. #include <sys/fcntl.h>
  687. #if JUCE_OPENGL
  688. #include <OpenGLES/ES1/gl.h>
  689. #include <OpenGLES/ES1/glext.h>
  690. #endif
  691. #else
  692. #import <Cocoa/Cocoa.h>
  693. #import <CoreAudio/HostTime.h>
  694. #import <CoreAudio/AudioHardware.h>
  695. #import <CoreMIDI/MIDIServices.h>
  696. #import <QTKit/QTKit.h>
  697. #import <WebKit/WebKit.h>
  698. #import <DiscRecording/DiscRecording.h>
  699. #import <IOKit/IOKitLib.h>
  700. #import <IOKit/IOCFPlugIn.h>
  701. #import <IOKit/hid/IOHIDLib.h>
  702. #import <IOKit/hid/IOHIDKeys.h>
  703. #import <IOKit/pwr_mgt/IOPMLib.h>
  704. #include <Carbon/Carbon.h>
  705. #include <sys/dir.h>
  706. #endif
  707. #include <sys/socket.h>
  708. #include <sys/sysctl.h>
  709. #include <sys/stat.h>
  710. #include <sys/param.h>
  711. #include <sys/mount.h>
  712. #include <fnmatch.h>
  713. #include <utime.h>
  714. #include <dlfcn.h>
  715. #include <ifaddrs.h>
  716. #include <net/if_dl.h>
  717. #include <mach/mach_time.h>
  718. #include <mach-o/dyld.h>
  719. #if MACOS_10_4_OR_EARLIER
  720. #include <GLUT/glut.h>
  721. #endif
  722. #if ! CGFLOAT_DEFINED
  723. #define CGFloat float
  724. #endif
  725. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  726. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  727. #else
  728. #error "Unknown platform!"
  729. #endif
  730. #endif
  731. //==============================================================================
  732. #define DONT_SET_USING_JUCE_NAMESPACE 1
  733. #undef max
  734. #undef min
  735. #define NO_DUMMY_DECL
  736. #if JUCE_BUILD_NATIVE
  737. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  738. #endif
  739. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  740. #pragma warning (disable: 4309 4305)
  741. #endif
  742. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  743. BEGIN_JUCE_NAMESPACE
  744. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  745. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  746. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  747. /**
  748. Creates a floating carbon window that can be used to hold a carbon UI.
  749. This is a handy class that's designed to be inlined where needed, e.g.
  750. in the audio plugin hosting code.
  751. */
  752. class CarbonViewWrapperComponent : public Component,
  753. public ComponentMovementWatcher,
  754. public Timer
  755. {
  756. public:
  757. CarbonViewWrapperComponent()
  758. : ComponentMovementWatcher (this),
  759. wrapperWindow (0),
  760. embeddedView (0),
  761. recursiveResize (false)
  762. {
  763. }
  764. virtual ~CarbonViewWrapperComponent()
  765. {
  766. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  767. }
  768. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  769. virtual void removeView (HIViewRef embeddedView) = 0;
  770. virtual void mouseDown (int, int) {}
  771. virtual void paint() {}
  772. virtual bool getEmbeddedViewSize (int& w, int& h)
  773. {
  774. if (embeddedView == 0)
  775. return false;
  776. HIRect bounds;
  777. HIViewGetBounds (embeddedView, &bounds);
  778. w = jmax (1, roundToInt (bounds.size.width));
  779. h = jmax (1, roundToInt (bounds.size.height));
  780. return true;
  781. }
  782. void createWindow()
  783. {
  784. if (wrapperWindow == 0)
  785. {
  786. Rect r;
  787. r.left = getScreenX();
  788. r.top = getScreenY();
  789. r.right = r.left + getWidth();
  790. r.bottom = r.top + getHeight();
  791. CreateNewWindow (kDocumentWindowClass,
  792. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  793. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  794. &r, &wrapperWindow);
  795. jassert (wrapperWindow != 0);
  796. if (wrapperWindow == 0)
  797. return;
  798. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  799. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  800. [ownerWindow addChildWindow: carbonWindow
  801. ordered: NSWindowAbove];
  802. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  803. EventTypeSpec windowEventTypes[] =
  804. {
  805. { kEventClassWindow, kEventWindowGetClickActivation },
  806. { kEventClassWindow, kEventWindowHandleDeactivate },
  807. { kEventClassWindow, kEventWindowBoundsChanging },
  808. { kEventClassMouse, kEventMouseDown },
  809. { kEventClassMouse, kEventMouseMoved },
  810. { kEventClassMouse, kEventMouseDragged },
  811. { kEventClassMouse, kEventMouseUp},
  812. { kEventClassWindow, kEventWindowDrawContent },
  813. { kEventClassWindow, kEventWindowShown },
  814. { kEventClassWindow, kEventWindowHidden }
  815. };
  816. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  817. InstallWindowEventHandler (wrapperWindow, upp,
  818. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  819. windowEventTypes, this, &eventHandlerRef);
  820. setOurSizeToEmbeddedViewSize();
  821. setEmbeddedWindowToOurSize();
  822. creationTime = Time::getCurrentTime();
  823. }
  824. }
  825. void deleteWindow()
  826. {
  827. removeView (embeddedView);
  828. embeddedView = 0;
  829. if (wrapperWindow != 0)
  830. {
  831. RemoveEventHandler (eventHandlerRef);
  832. DisposeWindow (wrapperWindow);
  833. wrapperWindow = 0;
  834. }
  835. }
  836. void setOurSizeToEmbeddedViewSize()
  837. {
  838. int w, h;
  839. if (getEmbeddedViewSize (w, h))
  840. {
  841. if (w != getWidth() || h != getHeight())
  842. {
  843. startTimer (50);
  844. setSize (w, h);
  845. if (getParentComponent() != 0)
  846. getParentComponent()->setSize (w, h);
  847. }
  848. else
  849. {
  850. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  851. }
  852. }
  853. else
  854. {
  855. stopTimer();
  856. }
  857. }
  858. void setEmbeddedWindowToOurSize()
  859. {
  860. if (! recursiveResize)
  861. {
  862. recursiveResize = true;
  863. if (embeddedView != 0)
  864. {
  865. HIRect r;
  866. r.origin.x = 0;
  867. r.origin.y = 0;
  868. r.size.width = (float) getWidth();
  869. r.size.height = (float) getHeight();
  870. HIViewSetFrame (embeddedView, &r);
  871. }
  872. if (wrapperWindow != 0)
  873. {
  874. Rect wr;
  875. wr.left = getScreenX();
  876. wr.top = getScreenY();
  877. wr.right = wr.left + getWidth();
  878. wr.bottom = wr.top + getHeight();
  879. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  880. ShowWindow (wrapperWindow);
  881. }
  882. recursiveResize = false;
  883. }
  884. }
  885. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  886. {
  887. setEmbeddedWindowToOurSize();
  888. }
  889. void componentPeerChanged()
  890. {
  891. deleteWindow();
  892. createWindow();
  893. }
  894. void componentVisibilityChanged (Component&)
  895. {
  896. if (isShowing())
  897. createWindow();
  898. else
  899. deleteWindow();
  900. setEmbeddedWindowToOurSize();
  901. }
  902. static void recursiveHIViewRepaint (HIViewRef view)
  903. {
  904. HIViewSetNeedsDisplay (view, true);
  905. HIViewRef child = HIViewGetFirstSubview (view);
  906. while (child != 0)
  907. {
  908. recursiveHIViewRepaint (child);
  909. child = HIViewGetNextView (child);
  910. }
  911. }
  912. void timerCallback()
  913. {
  914. setOurSizeToEmbeddedViewSize();
  915. // To avoid strange overpainting problems when the UI is first opened, we'll
  916. // repaint it a few times during the first second that it's on-screen..
  917. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  918. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  919. }
  920. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  921. EventRef event)
  922. {
  923. switch (GetEventKind (event))
  924. {
  925. case kEventWindowHandleDeactivate:
  926. ActivateWindow (wrapperWindow, TRUE);
  927. return noErr;
  928. case kEventWindowGetClickActivation:
  929. {
  930. getTopLevelComponent()->toFront (false);
  931. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  932. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  933. sizeof (ClickActivationResult), &howToHandleClick);
  934. HIViewSetNeedsDisplay (embeddedView, true);
  935. return noErr;
  936. }
  937. }
  938. return eventNotHandledErr;
  939. }
  940. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  941. EventRef event, void* userData)
  942. {
  943. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  944. }
  945. protected:
  946. WindowRef wrapperWindow;
  947. HIViewRef embeddedView;
  948. bool recursiveResize;
  949. Time creationTime;
  950. EventHandlerRef eventHandlerRef;
  951. };
  952. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  953. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  954. END_JUCE_NAMESPACE
  955. #endif
  956. #define JUCE_AMALGAMATED_TEMPLATE 1
  957. //==============================================================================
  958. #if JUCE_BUILD_CORE
  959. /*** Start of inlined file: juce_FileLogger.cpp ***/
  960. BEGIN_JUCE_NAMESPACE
  961. FileLogger::FileLogger (const File& logFile_,
  962. const String& welcomeMessage,
  963. const int maxInitialFileSizeBytes)
  964. : logFile (logFile_)
  965. {
  966. if (maxInitialFileSizeBytes >= 0)
  967. trimFileSize (maxInitialFileSizeBytes);
  968. if (! logFile_.exists())
  969. {
  970. // do this so that the parent directories get created..
  971. logFile_.create();
  972. }
  973. logStream = logFile_.createOutputStream (256);
  974. jassert (logStream != 0);
  975. String welcome;
  976. welcome << "\r\n**********************************************************\r\n"
  977. << welcomeMessage
  978. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  979. << "\r\n";
  980. logMessage (welcome);
  981. }
  982. FileLogger::~FileLogger()
  983. {
  984. }
  985. void FileLogger::logMessage (const String& message)
  986. {
  987. if (logStream != 0)
  988. {
  989. DBG (message);
  990. const ScopedLock sl (logLock);
  991. (*logStream) << message << "\r\n";
  992. logStream->flush();
  993. }
  994. }
  995. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  996. {
  997. if (maxFileSizeBytes <= 0)
  998. {
  999. logFile.deleteFile();
  1000. }
  1001. else
  1002. {
  1003. const int64 fileSize = logFile.getSize();
  1004. if (fileSize > maxFileSizeBytes)
  1005. {
  1006. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1007. jassert (in != 0);
  1008. if (in != 0)
  1009. {
  1010. in->setPosition (fileSize - maxFileSizeBytes);
  1011. String content;
  1012. {
  1013. MemoryBlock contentToSave;
  1014. contentToSave.setSize (maxFileSizeBytes + 4);
  1015. contentToSave.fillWith (0);
  1016. in->read (contentToSave.getData(), maxFileSizeBytes);
  1017. in = 0;
  1018. content = contentToSave.toString();
  1019. }
  1020. int newStart = 0;
  1021. while (newStart < fileSize
  1022. && content[newStart] != '\n'
  1023. && content[newStart] != '\r')
  1024. ++newStart;
  1025. logFile.deleteFile();
  1026. logFile.appendText (content.substring (newStart), false, false);
  1027. }
  1028. }
  1029. }
  1030. }
  1031. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1032. const String& logFileName,
  1033. const String& welcomeMessage,
  1034. const int maxInitialFileSizeBytes)
  1035. {
  1036. #if JUCE_MAC
  1037. File logFile ("~/Library/Logs");
  1038. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1039. .getChildFile (logFileName);
  1040. #else
  1041. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1042. if (logFile.isDirectory())
  1043. {
  1044. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1045. .getChildFile (logFileName);
  1046. }
  1047. #endif
  1048. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1049. }
  1050. END_JUCE_NAMESPACE
  1051. /*** End of inlined file: juce_FileLogger.cpp ***/
  1052. /*** Start of inlined file: juce_Logger.cpp ***/
  1053. BEGIN_JUCE_NAMESPACE
  1054. Logger::Logger()
  1055. {
  1056. }
  1057. Logger::~Logger()
  1058. {
  1059. }
  1060. Logger* Logger::currentLogger = 0;
  1061. void Logger::setCurrentLogger (Logger* const newLogger,
  1062. const bool deleteOldLogger)
  1063. {
  1064. Logger* const oldLogger = currentLogger;
  1065. currentLogger = newLogger;
  1066. if (deleteOldLogger)
  1067. delete oldLogger;
  1068. }
  1069. void Logger::writeToLog (const String& message)
  1070. {
  1071. if (currentLogger != 0)
  1072. currentLogger->logMessage (message);
  1073. else
  1074. outputDebugString (message);
  1075. }
  1076. #if JUCE_LOG_ASSERTIONS
  1077. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1078. {
  1079. String m ("JUCE Assertion failure in ");
  1080. m << filename << ", line " << lineNum;
  1081. Logger::writeToLog (m);
  1082. }
  1083. #endif
  1084. END_JUCE_NAMESPACE
  1085. /*** End of inlined file: juce_Logger.cpp ***/
  1086. /*** Start of inlined file: juce_Random.cpp ***/
  1087. BEGIN_JUCE_NAMESPACE
  1088. Random::Random (const int64 seedValue) throw()
  1089. : seed (seedValue)
  1090. {
  1091. }
  1092. Random::~Random() throw()
  1093. {
  1094. }
  1095. void Random::setSeed (const int64 newSeed) throw()
  1096. {
  1097. seed = newSeed;
  1098. }
  1099. void Random::combineSeed (const int64 seedValue) throw()
  1100. {
  1101. seed ^= nextInt64() ^ seedValue;
  1102. }
  1103. void Random::setSeedRandomly()
  1104. {
  1105. combineSeed ((int64) (pointer_sized_int) this);
  1106. combineSeed (Time::getMillisecondCounter());
  1107. combineSeed (Time::getHighResolutionTicks());
  1108. combineSeed (Time::getHighResolutionTicksPerSecond());
  1109. combineSeed (Time::currentTimeMillis());
  1110. }
  1111. int Random::nextInt() throw()
  1112. {
  1113. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1114. return (int) (seed >> 16);
  1115. }
  1116. int Random::nextInt (const int maxValue) throw()
  1117. {
  1118. jassert (maxValue > 0);
  1119. return (nextInt() & 0x7fffffff) % maxValue;
  1120. }
  1121. int64 Random::nextInt64() throw()
  1122. {
  1123. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1124. }
  1125. bool Random::nextBool() throw()
  1126. {
  1127. return (nextInt() & 0x80000000) != 0;
  1128. }
  1129. float Random::nextFloat() throw()
  1130. {
  1131. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1132. }
  1133. double Random::nextDouble() throw()
  1134. {
  1135. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1136. }
  1137. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1138. {
  1139. BigInteger n;
  1140. do
  1141. {
  1142. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1143. }
  1144. while (n >= maximumValue);
  1145. return n;
  1146. }
  1147. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1148. {
  1149. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1150. while ((startBit & 31) != 0 && numBits > 0)
  1151. {
  1152. arrayToChange.setBit (startBit++, nextBool());
  1153. --numBits;
  1154. }
  1155. while (numBits >= 32)
  1156. {
  1157. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1158. startBit += 32;
  1159. numBits -= 32;
  1160. }
  1161. while (--numBits >= 0)
  1162. arrayToChange.setBit (startBit + numBits, nextBool());
  1163. }
  1164. Random& Random::getSystemRandom() throw()
  1165. {
  1166. static Random sysRand (1);
  1167. return sysRand;
  1168. }
  1169. END_JUCE_NAMESPACE
  1170. /*** End of inlined file: juce_Random.cpp ***/
  1171. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1172. BEGIN_JUCE_NAMESPACE
  1173. RelativeTime::RelativeTime (const double seconds_) throw()
  1174. : seconds (seconds_)
  1175. {
  1176. }
  1177. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1178. : seconds (other.seconds)
  1179. {
  1180. }
  1181. RelativeTime::~RelativeTime() throw()
  1182. {
  1183. }
  1184. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1185. {
  1186. return RelativeTime (milliseconds * 0.001);
  1187. }
  1188. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1189. {
  1190. return RelativeTime (milliseconds * 0.001);
  1191. }
  1192. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1193. {
  1194. return RelativeTime (numberOfMinutes * 60.0);
  1195. }
  1196. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1197. {
  1198. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1199. }
  1200. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1201. {
  1202. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1203. }
  1204. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1205. {
  1206. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1207. }
  1208. int64 RelativeTime::inMilliseconds() const throw()
  1209. {
  1210. return (int64)(seconds * 1000.0);
  1211. }
  1212. double RelativeTime::inMinutes() const throw()
  1213. {
  1214. return seconds / 60.0;
  1215. }
  1216. double RelativeTime::inHours() const throw()
  1217. {
  1218. return seconds / (60.0 * 60.0);
  1219. }
  1220. double RelativeTime::inDays() const throw()
  1221. {
  1222. return seconds / (60.0 * 60.0 * 24.0);
  1223. }
  1224. double RelativeTime::inWeeks() const throw()
  1225. {
  1226. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1227. }
  1228. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1229. {
  1230. if (seconds < 0.001 && seconds > -0.001)
  1231. return returnValueForZeroTime;
  1232. String result;
  1233. if (seconds < 0)
  1234. result = "-";
  1235. int fieldsShown = 0;
  1236. int n = abs ((int) inWeeks());
  1237. if (n > 0)
  1238. {
  1239. result << n << ((n == 1) ? TRANS(" week ")
  1240. : TRANS(" weeks "));
  1241. ++fieldsShown;
  1242. }
  1243. n = abs ((int) inDays()) % 7;
  1244. if (n > 0)
  1245. {
  1246. result << n << ((n == 1) ? TRANS(" day ")
  1247. : TRANS(" days "));
  1248. ++fieldsShown;
  1249. }
  1250. if (fieldsShown < 2)
  1251. {
  1252. n = abs ((int) inHours()) % 24;
  1253. if (n > 0)
  1254. {
  1255. result << n << ((n == 1) ? TRANS(" hr ")
  1256. : TRANS(" hrs "));
  1257. ++fieldsShown;
  1258. }
  1259. if (fieldsShown < 2)
  1260. {
  1261. n = abs ((int) inMinutes()) % 60;
  1262. if (n > 0)
  1263. {
  1264. result << n << ((n == 1) ? TRANS(" min ")
  1265. : TRANS(" mins "));
  1266. ++fieldsShown;
  1267. }
  1268. if (fieldsShown < 2)
  1269. {
  1270. n = abs ((int) inSeconds()) % 60;
  1271. if (n > 0)
  1272. {
  1273. result << n << ((n == 1) ? TRANS(" sec ")
  1274. : TRANS(" secs "));
  1275. ++fieldsShown;
  1276. }
  1277. if (fieldsShown < 1)
  1278. {
  1279. n = abs ((int) inMilliseconds()) % 1000;
  1280. if (n > 0)
  1281. {
  1282. result << n << TRANS(" ms");
  1283. ++fieldsShown;
  1284. }
  1285. }
  1286. }
  1287. }
  1288. }
  1289. return result.trimEnd();
  1290. }
  1291. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1292. {
  1293. seconds = other.seconds;
  1294. return *this;
  1295. }
  1296. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1297. {
  1298. return seconds == other.seconds;
  1299. }
  1300. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1301. {
  1302. return seconds != other.seconds;
  1303. }
  1304. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1305. {
  1306. return seconds > other.seconds;
  1307. }
  1308. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1309. {
  1310. return seconds < other.seconds;
  1311. }
  1312. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1313. {
  1314. return seconds >= other.seconds;
  1315. }
  1316. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1317. {
  1318. return seconds <= other.seconds;
  1319. }
  1320. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1321. {
  1322. return RelativeTime (seconds + timeToAdd.seconds);
  1323. }
  1324. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1325. {
  1326. return RelativeTime (seconds - timeToSubtract.seconds);
  1327. }
  1328. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1329. {
  1330. return RelativeTime (seconds + secondsToAdd);
  1331. }
  1332. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1333. {
  1334. return RelativeTime (seconds - secondsToSubtract);
  1335. }
  1336. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1337. {
  1338. seconds += timeToAdd.seconds;
  1339. return *this;
  1340. }
  1341. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1342. {
  1343. seconds -= timeToSubtract.seconds;
  1344. return *this;
  1345. }
  1346. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1347. {
  1348. seconds += secondsToAdd;
  1349. return *this;
  1350. }
  1351. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1352. {
  1353. seconds -= secondsToSubtract;
  1354. return *this;
  1355. }
  1356. END_JUCE_NAMESPACE
  1357. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1358. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1359. BEGIN_JUCE_NAMESPACE
  1360. SystemStats::CPUFlags SystemStats::cpuFlags;
  1361. const String SystemStats::getJUCEVersion()
  1362. {
  1363. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1364. + "." + String (JUCE_MINOR_VERSION)
  1365. + "." + String (JUCE_BUILDNUMBER);
  1366. }
  1367. const StringArray SystemStats::getMACAddressStrings()
  1368. {
  1369. int64 macAddresses [16];
  1370. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1371. StringArray s;
  1372. for (int i = 0; i < numAddresses; ++i)
  1373. {
  1374. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1375. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1376. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1377. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1378. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1379. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1380. }
  1381. return s;
  1382. }
  1383. #ifdef JUCE_DLL
  1384. void* juce_Malloc (const int size)
  1385. {
  1386. return malloc (size);
  1387. }
  1388. void* juce_Calloc (const int size)
  1389. {
  1390. return calloc (1, size);
  1391. }
  1392. void* juce_Realloc (void* const block, const int size)
  1393. {
  1394. return realloc (block, size);
  1395. }
  1396. void juce_Free (void* const block)
  1397. {
  1398. free (block);
  1399. }
  1400. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1401. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1402. {
  1403. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1404. }
  1405. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1406. {
  1407. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1408. }
  1409. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1410. {
  1411. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1412. }
  1413. void juce_DebugFree (void* const block)
  1414. {
  1415. _free_dbg (block, _NORMAL_BLOCK);
  1416. }
  1417. #endif
  1418. #endif
  1419. END_JUCE_NAMESPACE
  1420. /*** End of inlined file: juce_SystemStats.cpp ***/
  1421. /*** Start of inlined file: juce_Time.cpp ***/
  1422. #if JUCE_MSVC
  1423. #pragma warning (push)
  1424. #pragma warning (disable: 4514)
  1425. #endif
  1426. #ifndef JUCE_WINDOWS
  1427. #include <sys/time.h>
  1428. #else
  1429. #include <ctime>
  1430. #endif
  1431. #include <sys/timeb.h>
  1432. #if JUCE_MSVC
  1433. #pragma warning (pop)
  1434. #ifdef _INC_TIME_INL
  1435. #define USE_NEW_SECURE_TIME_FNS
  1436. #endif
  1437. #endif
  1438. BEGIN_JUCE_NAMESPACE
  1439. namespace TimeHelpers
  1440. {
  1441. static struct tm millisToLocal (const int64 millis) throw()
  1442. {
  1443. struct tm result;
  1444. const int64 seconds = millis / 1000;
  1445. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1446. {
  1447. // use extended maths for dates beyond 1970 to 2037..
  1448. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1449. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1450. const int days = (int) (jdm / literal64bit (86400));
  1451. const int a = 32044 + days;
  1452. const int b = (4 * a + 3) / 146097;
  1453. const int c = a - (b * 146097) / 4;
  1454. const int d = (4 * c + 3) / 1461;
  1455. const int e = c - (d * 1461) / 4;
  1456. const int m = (5 * e + 2) / 153;
  1457. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1458. result.tm_mon = m + 2 - 12 * (m / 10);
  1459. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1460. result.tm_wday = (days + 1) % 7;
  1461. result.tm_yday = -1;
  1462. int t = (int) (jdm % literal64bit (86400));
  1463. result.tm_hour = t / 3600;
  1464. t %= 3600;
  1465. result.tm_min = t / 60;
  1466. result.tm_sec = t % 60;
  1467. result.tm_isdst = -1;
  1468. }
  1469. else
  1470. {
  1471. time_t now = static_cast <time_t> (seconds);
  1472. #if JUCE_WINDOWS
  1473. #ifdef USE_NEW_SECURE_TIME_FNS
  1474. if (now >= 0 && now <= 0x793406fff)
  1475. localtime_s (&result, &now);
  1476. else
  1477. zeromem (&result, sizeof (result));
  1478. #else
  1479. result = *localtime (&now);
  1480. #endif
  1481. #else
  1482. // more thread-safe
  1483. localtime_r (&now, &result);
  1484. #endif
  1485. }
  1486. return result;
  1487. }
  1488. static int extendedModulo (const int64 value, const int modulo) throw()
  1489. {
  1490. return (int) (value >= 0 ? (value % modulo)
  1491. : (value - ((value / modulo) + 1) * modulo));
  1492. }
  1493. static uint32 lastMSCounterValue = 0;
  1494. }
  1495. Time::Time() throw()
  1496. : millisSinceEpoch (0)
  1497. {
  1498. }
  1499. Time::Time (const Time& other) throw()
  1500. : millisSinceEpoch (other.millisSinceEpoch)
  1501. {
  1502. }
  1503. Time::Time (const int64 ms) throw()
  1504. : millisSinceEpoch (ms)
  1505. {
  1506. }
  1507. Time::Time (const int year,
  1508. const int month,
  1509. const int day,
  1510. const int hours,
  1511. const int minutes,
  1512. const int seconds,
  1513. const int milliseconds,
  1514. const bool useLocalTime) throw()
  1515. {
  1516. jassert (year > 100); // year must be a 4-digit version
  1517. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1518. {
  1519. // use extended maths for dates beyond 1970 to 2037..
  1520. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1521. : 0;
  1522. const int a = (13 - month) / 12;
  1523. const int y = year + 4800 - a;
  1524. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1525. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1526. - 32045;
  1527. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1528. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1529. + milliseconds;
  1530. }
  1531. else
  1532. {
  1533. struct tm t;
  1534. t.tm_year = year - 1900;
  1535. t.tm_mon = month;
  1536. t.tm_mday = day;
  1537. t.tm_hour = hours;
  1538. t.tm_min = minutes;
  1539. t.tm_sec = seconds;
  1540. t.tm_isdst = -1;
  1541. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1542. if (millisSinceEpoch < 0)
  1543. millisSinceEpoch = 0;
  1544. else
  1545. millisSinceEpoch += milliseconds;
  1546. }
  1547. }
  1548. Time::~Time() throw()
  1549. {
  1550. }
  1551. Time& Time::operator= (const Time& other) throw()
  1552. {
  1553. millisSinceEpoch = other.millisSinceEpoch;
  1554. return *this;
  1555. }
  1556. int64 Time::currentTimeMillis() throw()
  1557. {
  1558. static uint32 lastCounterResult = 0xffffffff;
  1559. static int64 correction = 0;
  1560. const uint32 now = getMillisecondCounter();
  1561. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1562. if (now < lastCounterResult)
  1563. {
  1564. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1565. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1566. {
  1567. // get the time once using normal library calls, and store the difference needed to
  1568. // turn the millisecond counter into a real time.
  1569. #if JUCE_WINDOWS
  1570. struct _timeb t;
  1571. #ifdef USE_NEW_SECURE_TIME_FNS
  1572. _ftime_s (&t);
  1573. #else
  1574. _ftime (&t);
  1575. #endif
  1576. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1577. #else
  1578. struct timeval tv;
  1579. struct timezone tz;
  1580. gettimeofday (&tv, &tz);
  1581. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1582. #endif
  1583. }
  1584. }
  1585. lastCounterResult = now;
  1586. return correction + now;
  1587. }
  1588. uint32 juce_millisecondsSinceStartup() throw();
  1589. uint32 Time::getMillisecondCounter() throw()
  1590. {
  1591. const uint32 now = juce_millisecondsSinceStartup();
  1592. if (now < TimeHelpers::lastMSCounterValue)
  1593. {
  1594. // in multi-threaded apps this might be called concurrently, so
  1595. // make sure that our last counter value only increases and doesn't
  1596. // go backwards..
  1597. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1598. TimeHelpers::lastMSCounterValue = now;
  1599. }
  1600. else
  1601. {
  1602. TimeHelpers::lastMSCounterValue = now;
  1603. }
  1604. return now;
  1605. }
  1606. uint32 Time::getApproximateMillisecondCounter() throw()
  1607. {
  1608. jassert (TimeHelpers::lastMSCounterValue != 0);
  1609. return TimeHelpers::lastMSCounterValue;
  1610. }
  1611. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1612. {
  1613. for (;;)
  1614. {
  1615. const uint32 now = getMillisecondCounter();
  1616. if (now >= targetTime)
  1617. break;
  1618. const int toWait = targetTime - now;
  1619. if (toWait > 2)
  1620. {
  1621. Thread::sleep (jmin (20, toWait >> 1));
  1622. }
  1623. else
  1624. {
  1625. // xxx should consider using mutex_pause on the mac as it apparently
  1626. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1627. for (int i = 10; --i >= 0;)
  1628. Thread::yield();
  1629. }
  1630. }
  1631. }
  1632. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1633. {
  1634. return ticks / (double) getHighResolutionTicksPerSecond();
  1635. }
  1636. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1637. {
  1638. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1639. }
  1640. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1641. {
  1642. return Time (currentTimeMillis());
  1643. }
  1644. const String Time::toString (const bool includeDate,
  1645. const bool includeTime,
  1646. const bool includeSeconds,
  1647. const bool use24HourClock) const throw()
  1648. {
  1649. String result;
  1650. if (includeDate)
  1651. {
  1652. result << getDayOfMonth() << ' '
  1653. << getMonthName (true) << ' '
  1654. << getYear();
  1655. if (includeTime)
  1656. result << ' ';
  1657. }
  1658. if (includeTime)
  1659. {
  1660. const int mins = getMinutes();
  1661. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1662. << (mins < 10 ? ":0" : ":") << mins;
  1663. if (includeSeconds)
  1664. {
  1665. const int secs = getSeconds();
  1666. result << (secs < 10 ? ":0" : ":") << secs;
  1667. }
  1668. if (! use24HourClock)
  1669. result << (isAfternoon() ? "pm" : "am");
  1670. }
  1671. return result.trimEnd();
  1672. }
  1673. const String Time::formatted (const String& format) const throw()
  1674. {
  1675. String buffer;
  1676. int bufferSize = 128;
  1677. buffer.preallocateStorage (bufferSize);
  1678. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1679. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1680. {
  1681. bufferSize += 128;
  1682. buffer.preallocateStorage (bufferSize);
  1683. }
  1684. return buffer;
  1685. }
  1686. int Time::getYear() const throw()
  1687. {
  1688. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1689. }
  1690. int Time::getMonth() const throw()
  1691. {
  1692. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1693. }
  1694. int Time::getDayOfMonth() const throw()
  1695. {
  1696. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1697. }
  1698. int Time::getDayOfWeek() const throw()
  1699. {
  1700. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1701. }
  1702. int Time::getHours() const throw()
  1703. {
  1704. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1705. }
  1706. int Time::getHoursInAmPmFormat() const throw()
  1707. {
  1708. const int hours = getHours();
  1709. if (hours == 0)
  1710. return 12;
  1711. else if (hours <= 12)
  1712. return hours;
  1713. else
  1714. return hours - 12;
  1715. }
  1716. bool Time::isAfternoon() const throw()
  1717. {
  1718. return getHours() >= 12;
  1719. }
  1720. int Time::getMinutes() const throw()
  1721. {
  1722. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1723. }
  1724. int Time::getSeconds() const throw()
  1725. {
  1726. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1727. }
  1728. int Time::getMilliseconds() const throw()
  1729. {
  1730. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1731. }
  1732. bool Time::isDaylightSavingTime() const throw()
  1733. {
  1734. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1735. }
  1736. const String Time::getTimeZone() const throw()
  1737. {
  1738. String zone[2];
  1739. #if JUCE_WINDOWS
  1740. _tzset();
  1741. #ifdef USE_NEW_SECURE_TIME_FNS
  1742. {
  1743. char name [128];
  1744. size_t length;
  1745. for (int i = 0; i < 2; ++i)
  1746. {
  1747. zeromem (name, sizeof (name));
  1748. _get_tzname (&length, name, 127, i);
  1749. zone[i] = name;
  1750. }
  1751. }
  1752. #else
  1753. const char** const zonePtr = (const char**) _tzname;
  1754. zone[0] = zonePtr[0];
  1755. zone[1] = zonePtr[1];
  1756. #endif
  1757. #else
  1758. tzset();
  1759. const char** const zonePtr = (const char**) tzname;
  1760. zone[0] = zonePtr[0];
  1761. zone[1] = zonePtr[1];
  1762. #endif
  1763. if (isDaylightSavingTime())
  1764. {
  1765. zone[0] = zone[1];
  1766. if (zone[0].length() > 3
  1767. && zone[0].containsIgnoreCase ("daylight")
  1768. && zone[0].contains ("GMT"))
  1769. zone[0] = "BST";
  1770. }
  1771. return zone[0].substring (0, 3);
  1772. }
  1773. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1774. {
  1775. return getMonthName (getMonth(), threeLetterVersion);
  1776. }
  1777. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1778. {
  1779. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1780. }
  1781. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1782. {
  1783. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1784. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1785. monthNumber %= 12;
  1786. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1787. : longMonthNames [monthNumber]);
  1788. }
  1789. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1790. {
  1791. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1792. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1793. day %= 7;
  1794. return TRANS (threeLetterVersion ? shortDayNames [day]
  1795. : longDayNames [day]);
  1796. }
  1797. END_JUCE_NAMESPACE
  1798. /*** End of inlined file: juce_Time.cpp ***/
  1799. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1800. BEGIN_JUCE_NAMESPACE
  1801. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1802. #endif
  1803. #if JUCE_WINDOWS
  1804. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1805. #endif
  1806. #if JUCE_DEBUG
  1807. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1808. #endif
  1809. #if JUCE_DEBUG
  1810. namespace SimpleUnitTests
  1811. {
  1812. template <typename Type>
  1813. class AtomicTester
  1814. {
  1815. public:
  1816. AtomicTester() {}
  1817. static void testInteger()
  1818. {
  1819. Atomic<Type> a, b;
  1820. a.set ((Type) 10);
  1821. a += (Type) 15;
  1822. a.memoryBarrier();
  1823. a -= (Type) 5;
  1824. ++a; ++a; --a;
  1825. a.memoryBarrier();
  1826. testFloat();
  1827. }
  1828. static void testFloat()
  1829. {
  1830. Atomic<Type> a, b;
  1831. a = (Type) 21;
  1832. a.memoryBarrier();
  1833. /* These are some simple test cases to check the atomics - let me know
  1834. if any of these assertions fail on your system!
  1835. */
  1836. jassert (a.get() == (Type) 21);
  1837. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1838. jassert (a.get() == (Type) 21);
  1839. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1840. jassert (a.get() == (Type) 101);
  1841. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1842. jassert (a.get() == (Type) 101);
  1843. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1844. jassert (a.get() == (Type) 200);
  1845. jassert (a.exchange ((Type) 300) == (Type) 200);
  1846. jassert (a.get() == (Type) 300);
  1847. b = a;
  1848. jassert (b.get() == a.get());
  1849. }
  1850. };
  1851. static void runBasicTests()
  1852. {
  1853. // Some simple test code, to keep an eye on things and make sure these functions
  1854. // work ok on all platforms. Let me know if any of these assertions fail on your system!
  1855. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1856. static_jassert (sizeof (int8) == 1);
  1857. static_jassert (sizeof (uint8) == 1);
  1858. static_jassert (sizeof (int16) == 2);
  1859. static_jassert (sizeof (uint16) == 2);
  1860. static_jassert (sizeof (int32) == 4);
  1861. static_jassert (sizeof (uint32) == 4);
  1862. static_jassert (sizeof (int64) == 8);
  1863. static_jassert (sizeof (uint64) == 8);
  1864. char a1[7];
  1865. jassert (numElementsInArray(a1) == 7);
  1866. int a2[3];
  1867. jassert (numElementsInArray(a2) == 3);
  1868. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1869. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1870. jassert (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1871. // Some quick stream tests..
  1872. int randomInt = Random::getSystemRandom().nextInt();
  1873. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1874. double randomDouble = Random::getSystemRandom().nextDouble();
  1875. String randomString;
  1876. for (int i = 50; --i >= 0;)
  1877. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1878. MemoryOutputStream mo;
  1879. mo.writeInt (randomInt);
  1880. mo.writeIntBigEndian (randomInt);
  1881. mo.writeCompressedInt (randomInt);
  1882. mo.writeString (randomString);
  1883. mo.writeInt64 (randomInt64);
  1884. mo.writeInt64BigEndian (randomInt64);
  1885. mo.writeDouble (randomDouble);
  1886. mo.writeDoubleBigEndian (randomDouble);
  1887. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1888. jassert (mi.readInt() == randomInt);
  1889. jassert (mi.readIntBigEndian() == randomInt);
  1890. jassert (mi.readCompressedInt() == randomInt);
  1891. jassert (mi.readString() == randomString);
  1892. jassert (mi.readInt64() == randomInt64);
  1893. jassert (mi.readInt64BigEndian() == randomInt64);
  1894. jassert (mi.readDouble() == randomDouble);
  1895. jassert (mi.readDoubleBigEndian() == randomDouble);
  1896. AtomicTester <int>::testInteger();
  1897. AtomicTester <unsigned int>::testInteger();
  1898. AtomicTester <int32>::testInteger();
  1899. AtomicTester <uint32>::testInteger();
  1900. AtomicTester <long>::testInteger();
  1901. AtomicTester <void*>::testInteger();
  1902. AtomicTester <int*>::testInteger();
  1903. AtomicTester <float>::testFloat();
  1904. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1905. AtomicTester <int64>::testInteger();
  1906. AtomicTester <uint64>::testInteger();
  1907. AtomicTester <double>::testFloat();
  1908. #endif
  1909. }
  1910. }
  1911. #endif
  1912. static bool juceInitialisedNonGUI = false;
  1913. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1914. {
  1915. if (! juceInitialisedNonGUI)
  1916. {
  1917. juceInitialisedNonGUI = true;
  1918. JUCE_AUTORELEASEPOOL
  1919. #if JUCE_DEBUG
  1920. SimpleUnitTests::runBasicTests();
  1921. #endif
  1922. DBG (SystemStats::getJUCEVersion());
  1923. SystemStats::initialiseStats();
  1924. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1925. }
  1926. }
  1927. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1928. {
  1929. if (juceInitialisedNonGUI)
  1930. {
  1931. juceInitialisedNonGUI = false;
  1932. JUCE_AUTORELEASEPOOL
  1933. LocalisedStrings::setCurrentMappings (0);
  1934. Thread::stopAllThreads (3000);
  1935. #if JUCE_WINDOWS
  1936. juce_shutdownWin32Sockets();
  1937. #endif
  1938. #if JUCE_DEBUG
  1939. juce_CheckForDanglingStreams();
  1940. #endif
  1941. }
  1942. }
  1943. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1944. void juce_setCurrentThreadName (const String& name);
  1945. static bool juceInitialisedGUI = false;
  1946. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1947. {
  1948. if (! juceInitialisedGUI)
  1949. {
  1950. juceInitialisedGUI = true;
  1951. JUCE_AUTORELEASEPOOL
  1952. initialiseJuce_NonGUI();
  1953. MessageManager::getInstance();
  1954. LookAndFeel::setDefaultLookAndFeel (0);
  1955. juce_setCurrentThreadName ("Juce Message Thread");
  1956. #if JUCE_DEBUG
  1957. // This section is just for catching people who mess up their project settings and
  1958. // turn RTTI off..
  1959. try
  1960. {
  1961. TextButton tb (String::empty);
  1962. Component* c = &tb;
  1963. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1964. c = dynamic_cast <Button*> (c);
  1965. }
  1966. catch (...)
  1967. {
  1968. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1969. jassertfalse;
  1970. }
  1971. #endif
  1972. }
  1973. }
  1974. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1975. {
  1976. if (juceInitialisedGUI)
  1977. {
  1978. juceInitialisedGUI = false;
  1979. JUCE_AUTORELEASEPOOL
  1980. DeletedAtShutdown::deleteAll();
  1981. LookAndFeel::clearDefaultLookAndFeel();
  1982. delete MessageManager::getInstance();
  1983. shutdownJuce_NonGUI();
  1984. }
  1985. }
  1986. #endif
  1987. END_JUCE_NAMESPACE
  1988. /*** End of inlined file: juce_Initialisation.cpp ***/
  1989. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1990. BEGIN_JUCE_NAMESPACE
  1991. BigInteger::BigInteger()
  1992. : numValues (4),
  1993. highestBit (-1),
  1994. negative (false)
  1995. {
  1996. values.calloc (numValues + 1);
  1997. }
  1998. BigInteger::BigInteger (const int value)
  1999. : numValues (4),
  2000. highestBit (31),
  2001. negative (value < 0)
  2002. {
  2003. values.calloc (numValues + 1);
  2004. values[0] = abs (value);
  2005. highestBit = getHighestBit();
  2006. }
  2007. BigInteger::BigInteger (int64 value)
  2008. : numValues (4),
  2009. highestBit (63),
  2010. negative (value < 0)
  2011. {
  2012. values.calloc (numValues + 1);
  2013. if (value < 0)
  2014. value = -value;
  2015. values[0] = (unsigned int) value;
  2016. values[1] = (unsigned int) (value >> 32);
  2017. highestBit = getHighestBit();
  2018. }
  2019. BigInteger::BigInteger (const unsigned int value)
  2020. : numValues (4),
  2021. highestBit (31),
  2022. negative (false)
  2023. {
  2024. values.calloc (numValues + 1);
  2025. values[0] = value;
  2026. highestBit = getHighestBit();
  2027. }
  2028. BigInteger::BigInteger (const BigInteger& other)
  2029. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  2030. highestBit (other.getHighestBit()),
  2031. negative (other.negative)
  2032. {
  2033. values.malloc (numValues + 1);
  2034. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2035. }
  2036. BigInteger::~BigInteger()
  2037. {
  2038. }
  2039. void BigInteger::swapWith (BigInteger& other) throw()
  2040. {
  2041. values.swapWith (other.values);
  2042. swapVariables (numValues, other.numValues);
  2043. swapVariables (highestBit, other.highestBit);
  2044. swapVariables (negative, other.negative);
  2045. }
  2046. BigInteger& BigInteger::operator= (const BigInteger& other)
  2047. {
  2048. if (this != &other)
  2049. {
  2050. highestBit = other.getHighestBit();
  2051. numValues = jmax (4, (highestBit >> 5) + 1);
  2052. negative = other.negative;
  2053. values.malloc (numValues + 1);
  2054. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2055. }
  2056. return *this;
  2057. }
  2058. void BigInteger::ensureSize (const int numVals)
  2059. {
  2060. if (numVals + 2 >= numValues)
  2061. {
  2062. int oldSize = numValues;
  2063. numValues = ((numVals + 2) * 3) / 2;
  2064. values.realloc (numValues + 1);
  2065. while (oldSize < numValues)
  2066. values [oldSize++] = 0;
  2067. }
  2068. }
  2069. bool BigInteger::operator[] (const int bit) const throw()
  2070. {
  2071. return bit <= highestBit && bit >= 0
  2072. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2073. }
  2074. int BigInteger::toInteger() const throw()
  2075. {
  2076. const int n = (int) (values[0] & 0x7fffffff);
  2077. return negative ? -n : n;
  2078. }
  2079. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2080. {
  2081. BigInteger r;
  2082. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2083. r.ensureSize (numBits >> 5);
  2084. r.highestBit = numBits;
  2085. int i = 0;
  2086. while (numBits > 0)
  2087. {
  2088. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2089. numBits -= 32;
  2090. startBit += 32;
  2091. }
  2092. r.highestBit = r.getHighestBit();
  2093. return r;
  2094. }
  2095. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2096. {
  2097. if (numBits > 32)
  2098. {
  2099. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2100. numBits = 32;
  2101. }
  2102. numBits = jmin (numBits, highestBit + 1 - startBit);
  2103. if (numBits <= 0)
  2104. return 0;
  2105. const int pos = startBit >> 5;
  2106. const int offset = startBit & 31;
  2107. const int endSpace = 32 - numBits;
  2108. uint32 n = ((uint32) values [pos]) >> offset;
  2109. if (offset > endSpace)
  2110. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2111. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2112. }
  2113. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2114. {
  2115. if (numBits > 32)
  2116. {
  2117. jassertfalse;
  2118. numBits = 32;
  2119. }
  2120. for (int i = 0; i < numBits; ++i)
  2121. {
  2122. setBit (startBit + i, (valueToSet & 1) != 0);
  2123. valueToSet >>= 1;
  2124. }
  2125. }
  2126. void BigInteger::clear()
  2127. {
  2128. if (numValues > 16)
  2129. {
  2130. numValues = 4;
  2131. values.calloc (numValues + 1);
  2132. }
  2133. else
  2134. {
  2135. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2136. }
  2137. highestBit = -1;
  2138. negative = false;
  2139. }
  2140. void BigInteger::setBit (const int bit)
  2141. {
  2142. if (bit >= 0)
  2143. {
  2144. if (bit > highestBit)
  2145. {
  2146. ensureSize (bit >> 5);
  2147. highestBit = bit;
  2148. }
  2149. values [bit >> 5] |= (1 << (bit & 31));
  2150. }
  2151. }
  2152. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2153. {
  2154. if (shouldBeSet)
  2155. setBit (bit);
  2156. else
  2157. clearBit (bit);
  2158. }
  2159. void BigInteger::clearBit (const int bit) throw()
  2160. {
  2161. if (bit >= 0 && bit <= highestBit)
  2162. values [bit >> 5] &= ~(1 << (bit & 31));
  2163. }
  2164. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2165. {
  2166. while (--numBits >= 0)
  2167. setBit (startBit++, shouldBeSet);
  2168. }
  2169. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2170. {
  2171. if (bit >= 0)
  2172. shiftBits (1, bit);
  2173. setBit (bit, shouldBeSet);
  2174. }
  2175. bool BigInteger::isZero() const throw()
  2176. {
  2177. return getHighestBit() < 0;
  2178. }
  2179. bool BigInteger::isOne() const throw()
  2180. {
  2181. return getHighestBit() == 0 && ! negative;
  2182. }
  2183. bool BigInteger::isNegative() const throw()
  2184. {
  2185. return negative && ! isZero();
  2186. }
  2187. void BigInteger::setNegative (const bool neg) throw()
  2188. {
  2189. negative = neg;
  2190. }
  2191. void BigInteger::negate() throw()
  2192. {
  2193. negative = (! negative) && ! isZero();
  2194. }
  2195. int BigInteger::countNumberOfSetBits() const throw()
  2196. {
  2197. int total = 0;
  2198. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2199. {
  2200. unsigned int n = values[i];
  2201. if (n == 0xffffffff)
  2202. {
  2203. total += 32;
  2204. }
  2205. else
  2206. {
  2207. while (n != 0)
  2208. {
  2209. total += (n & 1);
  2210. n >>= 1;
  2211. }
  2212. }
  2213. }
  2214. return total;
  2215. }
  2216. int BigInteger::getHighestBit() const throw()
  2217. {
  2218. for (int i = highestBit + 1; --i >= 0;)
  2219. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2220. return i;
  2221. return -1;
  2222. }
  2223. int BigInteger::findNextSetBit (int i) const throw()
  2224. {
  2225. for (; i <= highestBit; ++i)
  2226. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2227. return i;
  2228. return -1;
  2229. }
  2230. int BigInteger::findNextClearBit (int i) const throw()
  2231. {
  2232. for (; i <= highestBit; ++i)
  2233. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2234. break;
  2235. return i;
  2236. }
  2237. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2238. {
  2239. if (other.isNegative())
  2240. return operator-= (-other);
  2241. if (isNegative())
  2242. {
  2243. if (compareAbsolute (other) < 0)
  2244. {
  2245. BigInteger temp (*this);
  2246. temp.negate();
  2247. *this = other;
  2248. operator-= (temp);
  2249. }
  2250. else
  2251. {
  2252. negate();
  2253. operator-= (other);
  2254. negate();
  2255. }
  2256. }
  2257. else
  2258. {
  2259. if (other.highestBit > highestBit)
  2260. highestBit = other.highestBit;
  2261. ++highestBit;
  2262. const int numInts = (highestBit >> 5) + 1;
  2263. ensureSize (numInts);
  2264. int64 remainder = 0;
  2265. for (int i = 0; i <= numInts; ++i)
  2266. {
  2267. if (i < numValues)
  2268. remainder += values[i];
  2269. if (i < other.numValues)
  2270. remainder += other.values[i];
  2271. values[i] = (unsigned int) remainder;
  2272. remainder >>= 32;
  2273. }
  2274. jassert (remainder == 0);
  2275. highestBit = getHighestBit();
  2276. }
  2277. return *this;
  2278. }
  2279. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2280. {
  2281. if (other.isNegative())
  2282. return operator+= (-other);
  2283. if (! isNegative())
  2284. {
  2285. if (compareAbsolute (other) < 0)
  2286. {
  2287. BigInteger temp (other);
  2288. swapWith (temp);
  2289. operator-= (temp);
  2290. negate();
  2291. return *this;
  2292. }
  2293. }
  2294. else
  2295. {
  2296. negate();
  2297. operator+= (other);
  2298. negate();
  2299. return *this;
  2300. }
  2301. const int numInts = (highestBit >> 5) + 1;
  2302. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2303. int64 amountToSubtract = 0;
  2304. for (int i = 0; i <= numInts; ++i)
  2305. {
  2306. if (i <= maxOtherInts)
  2307. amountToSubtract += (int64) other.values[i];
  2308. if (values[i] >= amountToSubtract)
  2309. {
  2310. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2311. amountToSubtract = 0;
  2312. }
  2313. else
  2314. {
  2315. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2316. values[i] = (unsigned int) n;
  2317. amountToSubtract = 1;
  2318. }
  2319. }
  2320. return *this;
  2321. }
  2322. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2323. {
  2324. BigInteger total;
  2325. highestBit = getHighestBit();
  2326. const bool wasNegative = isNegative();
  2327. setNegative (false);
  2328. for (int i = 0; i <= highestBit; ++i)
  2329. {
  2330. if (operator[](i))
  2331. {
  2332. BigInteger n (other);
  2333. n.setNegative (false);
  2334. n <<= i;
  2335. total += n;
  2336. }
  2337. }
  2338. total.setNegative (wasNegative ^ other.isNegative());
  2339. swapWith (total);
  2340. return *this;
  2341. }
  2342. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2343. {
  2344. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2345. const int divHB = divisor.getHighestBit();
  2346. const int ourHB = getHighestBit();
  2347. if (divHB < 0 || ourHB < 0)
  2348. {
  2349. // division by zero
  2350. remainder.clear();
  2351. clear();
  2352. }
  2353. else
  2354. {
  2355. const bool wasNegative = isNegative();
  2356. swapWith (remainder);
  2357. remainder.setNegative (false);
  2358. clear();
  2359. BigInteger temp (divisor);
  2360. temp.setNegative (false);
  2361. int leftShift = ourHB - divHB;
  2362. temp <<= leftShift;
  2363. while (leftShift >= 0)
  2364. {
  2365. if (remainder.compareAbsolute (temp) >= 0)
  2366. {
  2367. remainder -= temp;
  2368. setBit (leftShift);
  2369. }
  2370. if (--leftShift >= 0)
  2371. temp >>= 1;
  2372. }
  2373. negative = wasNegative ^ divisor.isNegative();
  2374. remainder.setNegative (wasNegative);
  2375. }
  2376. }
  2377. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2378. {
  2379. BigInteger remainder;
  2380. divideBy (other, remainder);
  2381. return *this;
  2382. }
  2383. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2384. {
  2385. // this operation doesn't take into account negative values..
  2386. jassert (isNegative() == other.isNegative());
  2387. if (other.highestBit >= 0)
  2388. {
  2389. ensureSize (other.highestBit >> 5);
  2390. int n = (other.highestBit >> 5) + 1;
  2391. while (--n >= 0)
  2392. values[n] |= other.values[n];
  2393. if (other.highestBit > highestBit)
  2394. highestBit = other.highestBit;
  2395. highestBit = getHighestBit();
  2396. }
  2397. return *this;
  2398. }
  2399. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2400. {
  2401. // this operation doesn't take into account negative values..
  2402. jassert (isNegative() == other.isNegative());
  2403. int n = numValues;
  2404. while (n > other.numValues)
  2405. values[--n] = 0;
  2406. while (--n >= 0)
  2407. values[n] &= other.values[n];
  2408. if (other.highestBit < highestBit)
  2409. highestBit = other.highestBit;
  2410. highestBit = getHighestBit();
  2411. return *this;
  2412. }
  2413. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2414. {
  2415. // this operation will only work with the absolute values
  2416. jassert (isNegative() == other.isNegative());
  2417. if (other.highestBit >= 0)
  2418. {
  2419. ensureSize (other.highestBit >> 5);
  2420. int n = (other.highestBit >> 5) + 1;
  2421. while (--n >= 0)
  2422. values[n] ^= other.values[n];
  2423. if (other.highestBit > highestBit)
  2424. highestBit = other.highestBit;
  2425. highestBit = getHighestBit();
  2426. }
  2427. return *this;
  2428. }
  2429. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2430. {
  2431. BigInteger remainder;
  2432. divideBy (divisor, remainder);
  2433. swapWith (remainder);
  2434. return *this;
  2435. }
  2436. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2437. {
  2438. shiftBits (numBitsToShift, 0);
  2439. return *this;
  2440. }
  2441. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2442. {
  2443. return operator<<= (-numBitsToShift);
  2444. }
  2445. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2446. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2447. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2448. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2449. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2450. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2451. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2452. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2453. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2454. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2455. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2456. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2457. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2458. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2459. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2460. int BigInteger::compare (const BigInteger& other) const throw()
  2461. {
  2462. if (isNegative() == other.isNegative())
  2463. {
  2464. const int absComp = compareAbsolute (other);
  2465. return isNegative() ? -absComp : absComp;
  2466. }
  2467. else
  2468. {
  2469. return isNegative() ? -1 : 1;
  2470. }
  2471. }
  2472. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2473. {
  2474. const int h1 = getHighestBit();
  2475. const int h2 = other.getHighestBit();
  2476. if (h1 > h2)
  2477. return 1;
  2478. else if (h1 < h2)
  2479. return -1;
  2480. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2481. if (values[i] != other.values[i])
  2482. return (values[i] > other.values[i]) ? 1 : -1;
  2483. return 0;
  2484. }
  2485. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2486. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2487. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2488. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2489. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2490. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2491. void BigInteger::shiftBits (int bits, const int startBit)
  2492. {
  2493. if (highestBit < 0)
  2494. return;
  2495. if (startBit > 0)
  2496. {
  2497. if (bits < 0)
  2498. {
  2499. // right shift
  2500. for (int i = startBit; i <= highestBit; ++i)
  2501. setBit (i, operator[] (i - bits));
  2502. highestBit = getHighestBit();
  2503. }
  2504. else if (bits > 0)
  2505. {
  2506. // left shift
  2507. for (int i = highestBit + 1; --i >= startBit;)
  2508. setBit (i + bits, operator[] (i));
  2509. while (--bits >= 0)
  2510. clearBit (bits + startBit);
  2511. }
  2512. }
  2513. else
  2514. {
  2515. if (bits < 0)
  2516. {
  2517. // right shift
  2518. bits = -bits;
  2519. if (bits > highestBit)
  2520. {
  2521. clear();
  2522. }
  2523. else
  2524. {
  2525. const int wordsToMove = bits >> 5;
  2526. int top = 1 + (highestBit >> 5) - wordsToMove;
  2527. highestBit -= bits;
  2528. if (wordsToMove > 0)
  2529. {
  2530. int i;
  2531. for (i = 0; i < top; ++i)
  2532. values [i] = values [i + wordsToMove];
  2533. for (i = 0; i < wordsToMove; ++i)
  2534. values [top + i] = 0;
  2535. bits &= 31;
  2536. }
  2537. if (bits != 0)
  2538. {
  2539. const int invBits = 32 - bits;
  2540. --top;
  2541. for (int i = 0; i < top; ++i)
  2542. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2543. values[top] = (values[top] >> bits);
  2544. }
  2545. highestBit = getHighestBit();
  2546. }
  2547. }
  2548. else if (bits > 0)
  2549. {
  2550. // left shift
  2551. ensureSize (((highestBit + bits) >> 5) + 1);
  2552. const int wordsToMove = bits >> 5;
  2553. int top = 1 + (highestBit >> 5);
  2554. highestBit += bits;
  2555. if (wordsToMove > 0)
  2556. {
  2557. int i;
  2558. for (i = top; --i >= 0;)
  2559. values [i + wordsToMove] = values [i];
  2560. for (i = 0; i < wordsToMove; ++i)
  2561. values [i] = 0;
  2562. bits &= 31;
  2563. }
  2564. if (bits != 0)
  2565. {
  2566. const int invBits = 32 - bits;
  2567. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2568. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2569. values [wordsToMove] = values [wordsToMove] << bits;
  2570. }
  2571. highestBit = getHighestBit();
  2572. }
  2573. }
  2574. }
  2575. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2576. {
  2577. while (! m->isZero())
  2578. {
  2579. if (n->compareAbsolute (*m) > 0)
  2580. swapVariables (m, n);
  2581. *m -= *n;
  2582. }
  2583. return *n;
  2584. }
  2585. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2586. {
  2587. BigInteger m (*this);
  2588. while (! n.isZero())
  2589. {
  2590. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2591. return simpleGCD (&m, &n);
  2592. BigInteger temp1 (m), temp2;
  2593. temp1.divideBy (n, temp2);
  2594. m = n;
  2595. n = temp2;
  2596. }
  2597. return m;
  2598. }
  2599. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2600. {
  2601. BigInteger exp (exponent);
  2602. exp %= modulus;
  2603. BigInteger value (1);
  2604. swapWith (value);
  2605. value %= modulus;
  2606. while (! exp.isZero())
  2607. {
  2608. if (exp [0])
  2609. {
  2610. operator*= (value);
  2611. operator%= (modulus);
  2612. }
  2613. value *= value;
  2614. value %= modulus;
  2615. exp >>= 1;
  2616. }
  2617. }
  2618. void BigInteger::inverseModulo (const BigInteger& modulus)
  2619. {
  2620. if (modulus.isOne() || modulus.isNegative())
  2621. {
  2622. clear();
  2623. return;
  2624. }
  2625. if (isNegative() || compareAbsolute (modulus) >= 0)
  2626. operator%= (modulus);
  2627. if (isOne())
  2628. return;
  2629. if (! (*this)[0])
  2630. {
  2631. // not invertible
  2632. clear();
  2633. return;
  2634. }
  2635. BigInteger a1 (modulus);
  2636. BigInteger a2 (*this);
  2637. BigInteger b1 (modulus);
  2638. BigInteger b2 (1);
  2639. while (! a2.isOne())
  2640. {
  2641. BigInteger temp1, temp2, multiplier (a1);
  2642. multiplier.divideBy (a2, temp1);
  2643. temp1 = a2;
  2644. temp1 *= multiplier;
  2645. temp2 = a1;
  2646. temp2 -= temp1;
  2647. a1 = a2;
  2648. a2 = temp2;
  2649. temp1 = b2;
  2650. temp1 *= multiplier;
  2651. temp2 = b1;
  2652. temp2 -= temp1;
  2653. b1 = b2;
  2654. b2 = temp2;
  2655. }
  2656. while (b2.isNegative())
  2657. b2 += modulus;
  2658. b2 %= modulus;
  2659. swapWith (b2);
  2660. }
  2661. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2662. {
  2663. return stream << value.toString (10);
  2664. }
  2665. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2666. {
  2667. String s;
  2668. BigInteger v (*this);
  2669. if (base == 2 || base == 8 || base == 16)
  2670. {
  2671. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2672. static const char* const hexDigits = "0123456789abcdef";
  2673. for (;;)
  2674. {
  2675. const int remainder = v.getBitRangeAsInt (0, bits);
  2676. v >>= bits;
  2677. if (remainder == 0 && v.isZero())
  2678. break;
  2679. s = String::charToString (hexDigits [remainder]) + s;
  2680. }
  2681. }
  2682. else if (base == 10)
  2683. {
  2684. const BigInteger ten (10);
  2685. BigInteger remainder;
  2686. for (;;)
  2687. {
  2688. v.divideBy (ten, remainder);
  2689. if (remainder.isZero() && v.isZero())
  2690. break;
  2691. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2692. }
  2693. }
  2694. else
  2695. {
  2696. jassertfalse; // can't do the specified base!
  2697. return String::empty;
  2698. }
  2699. s = s.paddedLeft ('0', minimumNumCharacters);
  2700. return isNegative() ? "-" + s : s;
  2701. }
  2702. void BigInteger::parseString (const String& text, const int base)
  2703. {
  2704. clear();
  2705. const juce_wchar* t = text;
  2706. if (base == 2 || base == 8 || base == 16)
  2707. {
  2708. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2709. for (;;)
  2710. {
  2711. const juce_wchar c = *t++;
  2712. const int digit = CharacterFunctions::getHexDigitValue (c);
  2713. if (((unsigned int) digit) < (unsigned int) base)
  2714. {
  2715. operator<<= (bits);
  2716. operator+= (digit);
  2717. }
  2718. else if (c == 0)
  2719. {
  2720. break;
  2721. }
  2722. }
  2723. }
  2724. else if (base == 10)
  2725. {
  2726. const BigInteger ten ((unsigned int) 10);
  2727. for (;;)
  2728. {
  2729. const juce_wchar c = *t++;
  2730. if (c >= '0' && c <= '9')
  2731. {
  2732. operator*= (ten);
  2733. operator+= ((int) (c - '0'));
  2734. }
  2735. else if (c == 0)
  2736. {
  2737. break;
  2738. }
  2739. }
  2740. }
  2741. setNegative (text.trimStart().startsWithChar ('-'));
  2742. }
  2743. const MemoryBlock BigInteger::toMemoryBlock() const
  2744. {
  2745. const int numBytes = (getHighestBit() + 8) >> 3;
  2746. MemoryBlock mb ((size_t) numBytes);
  2747. for (int i = 0; i < numBytes; ++i)
  2748. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2749. return mb;
  2750. }
  2751. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2752. {
  2753. clear();
  2754. for (int i = (int) data.getSize(); --i >= 0;)
  2755. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2756. }
  2757. END_JUCE_NAMESPACE
  2758. /*** End of inlined file: juce_BigInteger.cpp ***/
  2759. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2760. BEGIN_JUCE_NAMESPACE
  2761. MemoryBlock::MemoryBlock() throw()
  2762. : size (0)
  2763. {
  2764. }
  2765. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2766. {
  2767. if (initialSize > 0)
  2768. {
  2769. size = initialSize;
  2770. data.allocate (initialSize, initialiseToZero);
  2771. }
  2772. else
  2773. {
  2774. size = 0;
  2775. }
  2776. }
  2777. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2778. : size (other.size)
  2779. {
  2780. if (size > 0)
  2781. {
  2782. jassert (other.data != 0);
  2783. data.malloc (size);
  2784. memcpy (data, other.data, size);
  2785. }
  2786. }
  2787. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2788. : size (jmax ((size_t) 0, sizeInBytes))
  2789. {
  2790. jassert (sizeInBytes >= 0);
  2791. if (size > 0)
  2792. {
  2793. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2794. data.malloc (size);
  2795. if (dataToInitialiseFrom != 0)
  2796. memcpy (data, dataToInitialiseFrom, size);
  2797. }
  2798. }
  2799. MemoryBlock::~MemoryBlock() throw()
  2800. {
  2801. jassert (size >= 0); // should never happen
  2802. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2803. }
  2804. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2805. {
  2806. if (this != &other)
  2807. {
  2808. setSize (other.size, false);
  2809. memcpy (data, other.data, size);
  2810. }
  2811. return *this;
  2812. }
  2813. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2814. {
  2815. return matches (other.data, other.size);
  2816. }
  2817. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2818. {
  2819. return ! operator== (other);
  2820. }
  2821. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2822. {
  2823. return size == dataSize
  2824. && memcmp (data, dataToCompare, size) == 0;
  2825. }
  2826. // this will resize the block to this size
  2827. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2828. {
  2829. if (size != newSize)
  2830. {
  2831. if (newSize <= 0)
  2832. {
  2833. data.free();
  2834. size = 0;
  2835. }
  2836. else
  2837. {
  2838. if (data != 0)
  2839. {
  2840. data.realloc (newSize);
  2841. if (initialiseToZero && (newSize > size))
  2842. zeromem (data + size, newSize - size);
  2843. }
  2844. else
  2845. {
  2846. data.allocate (newSize, initialiseToZero);
  2847. }
  2848. size = newSize;
  2849. }
  2850. }
  2851. }
  2852. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2853. {
  2854. if (size < minimumSize)
  2855. setSize (minimumSize, initialiseToZero);
  2856. }
  2857. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2858. {
  2859. swapVariables (size, other.size);
  2860. data.swapWith (other.data);
  2861. }
  2862. void MemoryBlock::fillWith (const uint8 value) throw()
  2863. {
  2864. memset (data, (int) value, size);
  2865. }
  2866. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2867. {
  2868. if (numBytes > 0)
  2869. {
  2870. const size_t oldSize = size;
  2871. setSize (size + numBytes);
  2872. memcpy (data + oldSize, srcData, numBytes);
  2873. }
  2874. }
  2875. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2876. {
  2877. const char* d = static_cast<const char*> (src);
  2878. if (offset < 0)
  2879. {
  2880. d -= offset;
  2881. num -= offset;
  2882. offset = 0;
  2883. }
  2884. if (offset + num > size)
  2885. num = size - offset;
  2886. if (num > 0)
  2887. memcpy (data + offset, d, num);
  2888. }
  2889. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2890. {
  2891. char* d = static_cast<char*> (dst);
  2892. if (offset < 0)
  2893. {
  2894. zeromem (d, -offset);
  2895. d -= offset;
  2896. num += offset;
  2897. offset = 0;
  2898. }
  2899. if (offset + num > size)
  2900. {
  2901. const size_t newNum = size - offset;
  2902. zeromem (d + newNum, num - newNum);
  2903. num = newNum;
  2904. }
  2905. if (num > 0)
  2906. memcpy (d, data + offset, num);
  2907. }
  2908. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2909. {
  2910. if (startByte < 0)
  2911. {
  2912. numBytesToRemove += startByte;
  2913. startByte = 0;
  2914. }
  2915. if (startByte + numBytesToRemove >= size)
  2916. {
  2917. setSize (startByte);
  2918. }
  2919. else if (numBytesToRemove > 0)
  2920. {
  2921. memmove (data + startByte,
  2922. data + startByte + numBytesToRemove,
  2923. size - (startByte + numBytesToRemove));
  2924. setSize (size - numBytesToRemove);
  2925. }
  2926. }
  2927. const String MemoryBlock::toString() const
  2928. {
  2929. return String (static_cast <const char*> (getData()), size);
  2930. }
  2931. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2932. {
  2933. int res = 0;
  2934. size_t byte = bitRangeStart >> 3;
  2935. int offsetInByte = (int) bitRangeStart & 7;
  2936. size_t bitsSoFar = 0;
  2937. while (numBits > 0 && (size_t) byte < size)
  2938. {
  2939. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2940. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2941. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2942. bitsSoFar += bitsThisTime;
  2943. numBits -= bitsThisTime;
  2944. ++byte;
  2945. offsetInByte = 0;
  2946. }
  2947. return res;
  2948. }
  2949. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2950. {
  2951. size_t byte = bitRangeStart >> 3;
  2952. int offsetInByte = (int) bitRangeStart & 7;
  2953. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2954. while (numBits > 0 && (size_t) byte < size)
  2955. {
  2956. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2957. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2958. const unsigned int tempBits = bitsToSet << offsetInByte;
  2959. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2960. ++byte;
  2961. numBits -= bitsThisTime;
  2962. bitsToSet >>= bitsThisTime;
  2963. mask >>= bitsThisTime;
  2964. offsetInByte = 0;
  2965. }
  2966. }
  2967. void MemoryBlock::loadFromHexString (const String& hex)
  2968. {
  2969. ensureSize (hex.length() >> 1);
  2970. char* dest = data;
  2971. int i = 0;
  2972. for (;;)
  2973. {
  2974. int byte = 0;
  2975. for (int loop = 2; --loop >= 0;)
  2976. {
  2977. byte <<= 4;
  2978. for (;;)
  2979. {
  2980. const juce_wchar c = hex [i++];
  2981. if (c >= '0' && c <= '9')
  2982. {
  2983. byte |= c - '0';
  2984. break;
  2985. }
  2986. else if (c >= 'a' && c <= 'z')
  2987. {
  2988. byte |= c - ('a' - 10);
  2989. break;
  2990. }
  2991. else if (c >= 'A' && c <= 'Z')
  2992. {
  2993. byte |= c - ('A' - 10);
  2994. break;
  2995. }
  2996. else if (c == 0)
  2997. {
  2998. setSize (static_cast <size_t> (dest - data));
  2999. return;
  3000. }
  3001. }
  3002. }
  3003. *dest++ = (char) byte;
  3004. }
  3005. }
  3006. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3007. const String MemoryBlock::toBase64Encoding() const
  3008. {
  3009. const size_t numChars = ((size << 3) + 5) / 6;
  3010. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3011. const int initialLen = destString.length();
  3012. destString.preallocateStorage (initialLen + 2 + numChars);
  3013. juce_wchar* d = destString;
  3014. d += initialLen;
  3015. *d++ = '.';
  3016. for (size_t i = 0; i < numChars; ++i)
  3017. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3018. *d++ = 0;
  3019. return destString;
  3020. }
  3021. bool MemoryBlock::fromBase64Encoding (const String& s)
  3022. {
  3023. const int startPos = s.indexOfChar ('.') + 1;
  3024. if (startPos <= 0)
  3025. return false;
  3026. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3027. setSize (numBytesNeeded, true);
  3028. const int numChars = s.length() - startPos;
  3029. const juce_wchar* srcChars = s;
  3030. srcChars += startPos;
  3031. int pos = 0;
  3032. for (int i = 0; i < numChars; ++i)
  3033. {
  3034. const char c = (char) srcChars[i];
  3035. for (int j = 0; j < 64; ++j)
  3036. {
  3037. if (encodingTable[j] == c)
  3038. {
  3039. setBitRange (pos, 6, j);
  3040. pos += 6;
  3041. break;
  3042. }
  3043. }
  3044. }
  3045. return true;
  3046. }
  3047. END_JUCE_NAMESPACE
  3048. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3049. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3050. BEGIN_JUCE_NAMESPACE
  3051. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  3052. : properties (ignoreCaseOfKeyNames),
  3053. fallbackProperties (0),
  3054. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3055. {
  3056. }
  3057. PropertySet::PropertySet (const PropertySet& other) throw()
  3058. : properties (other.properties),
  3059. fallbackProperties (other.fallbackProperties),
  3060. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3061. {
  3062. }
  3063. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  3064. {
  3065. properties = other.properties;
  3066. fallbackProperties = other.fallbackProperties;
  3067. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3068. propertyChanged();
  3069. return *this;
  3070. }
  3071. PropertySet::~PropertySet()
  3072. {
  3073. }
  3074. void PropertySet::clear()
  3075. {
  3076. const ScopedLock sl (lock);
  3077. if (properties.size() > 0)
  3078. {
  3079. properties.clear();
  3080. propertyChanged();
  3081. }
  3082. }
  3083. const String PropertySet::getValue (const String& keyName,
  3084. const String& defaultValue) const throw()
  3085. {
  3086. const ScopedLock sl (lock);
  3087. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3088. if (index >= 0)
  3089. return properties.getAllValues() [index];
  3090. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3091. : defaultValue;
  3092. }
  3093. int PropertySet::getIntValue (const String& keyName,
  3094. const int defaultValue) const throw()
  3095. {
  3096. const ScopedLock sl (lock);
  3097. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3098. if (index >= 0)
  3099. return properties.getAllValues() [index].getIntValue();
  3100. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3101. : defaultValue;
  3102. }
  3103. double PropertySet::getDoubleValue (const String& keyName,
  3104. const double defaultValue) const throw()
  3105. {
  3106. const ScopedLock sl (lock);
  3107. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3108. if (index >= 0)
  3109. return properties.getAllValues()[index].getDoubleValue();
  3110. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3111. : defaultValue;
  3112. }
  3113. bool PropertySet::getBoolValue (const String& keyName,
  3114. const bool defaultValue) const throw()
  3115. {
  3116. const ScopedLock sl (lock);
  3117. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3118. if (index >= 0)
  3119. return properties.getAllValues() [index].getIntValue() != 0;
  3120. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3121. : defaultValue;
  3122. }
  3123. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3124. {
  3125. XmlDocument doc (getValue (keyName));
  3126. return doc.getDocumentElement();
  3127. }
  3128. void PropertySet::setValue (const String& keyName, const var& v)
  3129. {
  3130. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3131. if (keyName.isNotEmpty())
  3132. {
  3133. const String value (v.toString());
  3134. const ScopedLock sl (lock);
  3135. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3136. if (index < 0 || properties.getAllValues() [index] != value)
  3137. {
  3138. properties.set (keyName, value);
  3139. propertyChanged();
  3140. }
  3141. }
  3142. }
  3143. void PropertySet::removeValue (const String& keyName)
  3144. {
  3145. if (keyName.isNotEmpty())
  3146. {
  3147. const ScopedLock sl (lock);
  3148. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3149. if (index >= 0)
  3150. {
  3151. properties.remove (keyName);
  3152. propertyChanged();
  3153. }
  3154. }
  3155. }
  3156. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3157. {
  3158. setValue (keyName, xml == 0 ? var::null
  3159. : var (xml->createDocument (String::empty, true)));
  3160. }
  3161. bool PropertySet::containsKey (const String& keyName) const throw()
  3162. {
  3163. const ScopedLock sl (lock);
  3164. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3165. }
  3166. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3167. {
  3168. const ScopedLock sl (lock);
  3169. fallbackProperties = fallbackProperties_;
  3170. }
  3171. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3172. {
  3173. const ScopedLock sl (lock);
  3174. XmlElement* const xml = new XmlElement (nodeName);
  3175. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3176. {
  3177. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3178. e->setAttribute ("name", properties.getAllKeys()[i]);
  3179. e->setAttribute ("val", properties.getAllValues()[i]);
  3180. }
  3181. return xml;
  3182. }
  3183. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3184. {
  3185. const ScopedLock sl (lock);
  3186. clear();
  3187. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3188. {
  3189. if (e->hasAttribute ("name")
  3190. && e->hasAttribute ("val"))
  3191. {
  3192. properties.set (e->getStringAttribute ("name"),
  3193. e->getStringAttribute ("val"));
  3194. }
  3195. }
  3196. if (properties.size() > 0)
  3197. propertyChanged();
  3198. }
  3199. void PropertySet::propertyChanged()
  3200. {
  3201. }
  3202. END_JUCE_NAMESPACE
  3203. /*** End of inlined file: juce_PropertySet.cpp ***/
  3204. /*** Start of inlined file: juce_Identifier.cpp ***/
  3205. BEGIN_JUCE_NAMESPACE
  3206. StringPool& Identifier::getPool()
  3207. {
  3208. static StringPool pool;
  3209. return pool;
  3210. }
  3211. Identifier::Identifier() throw()
  3212. : name (0)
  3213. {
  3214. }
  3215. Identifier::Identifier (const Identifier& other) throw()
  3216. : name (other.name)
  3217. {
  3218. }
  3219. Identifier& Identifier::operator= (const Identifier& other) throw()
  3220. {
  3221. name = other.name;
  3222. return *this;
  3223. }
  3224. Identifier::Identifier (const String& name_)
  3225. : name (Identifier::getPool().getPooledString (name_))
  3226. {
  3227. /* An Identifier string must be suitable for use as a script variable or XML
  3228. attribute, so it can only contain this limited set of characters.. */
  3229. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3230. }
  3231. Identifier::Identifier (const char* const name_)
  3232. : name (Identifier::getPool().getPooledString (name_))
  3233. {
  3234. /* An Identifier string must be suitable for use as a script variable or XML
  3235. attribute, so it can only contain this limited set of characters.. */
  3236. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3237. }
  3238. Identifier::~Identifier()
  3239. {
  3240. }
  3241. END_JUCE_NAMESPACE
  3242. /*** End of inlined file: juce_Identifier.cpp ***/
  3243. /*** Start of inlined file: juce_Variant.cpp ***/
  3244. BEGIN_JUCE_NAMESPACE
  3245. class var::VariantType
  3246. {
  3247. public:
  3248. VariantType() {}
  3249. virtual ~VariantType() {}
  3250. virtual int toInt (const ValueUnion&) const { return 0; }
  3251. virtual double toDouble (const ValueUnion&) const { return 0; }
  3252. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3253. virtual bool toBool (const ValueUnion&) const { return false; }
  3254. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3255. virtual bool isVoid() const throw() { return false; }
  3256. virtual bool isInt() const throw() { return false; }
  3257. virtual bool isBool() const throw() { return false; }
  3258. virtual bool isDouble() const throw() { return false; }
  3259. virtual bool isString() const throw() { return false; }
  3260. virtual bool isObject() const throw() { return false; }
  3261. virtual bool isMethod() const throw() { return false; }
  3262. virtual void cleanUp (ValueUnion&) const throw() {}
  3263. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3264. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3265. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3266. };
  3267. class var::VariantType_Void : public var::VariantType
  3268. {
  3269. public:
  3270. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3271. bool isVoid() const throw() { return true; }
  3272. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3273. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3274. };
  3275. class var::VariantType_Int : public var::VariantType
  3276. {
  3277. public:
  3278. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3279. int toInt (const ValueUnion& data) const { return data.intValue; };
  3280. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3281. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3282. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3283. bool isInt() const throw() { return true; }
  3284. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3285. {
  3286. return otherType.toInt (otherData) == data.intValue;
  3287. }
  3288. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3289. {
  3290. output.writeCompressedInt (5);
  3291. output.writeByte (1);
  3292. output.writeInt (data.intValue);
  3293. }
  3294. };
  3295. class var::VariantType_Double : public var::VariantType
  3296. {
  3297. public:
  3298. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3299. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3300. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3301. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3302. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3303. bool isDouble() const throw() { return true; }
  3304. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3305. {
  3306. return otherType.toDouble (otherData) == data.doubleValue;
  3307. }
  3308. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3309. {
  3310. output.writeCompressedInt (9);
  3311. output.writeByte (4);
  3312. output.writeDouble (data.doubleValue);
  3313. }
  3314. };
  3315. class var::VariantType_Bool : public var::VariantType
  3316. {
  3317. public:
  3318. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3319. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3320. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3321. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3322. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3323. bool isBool() const throw() { return true; }
  3324. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3325. {
  3326. return otherType.toBool (otherData) == data.boolValue;
  3327. }
  3328. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3329. {
  3330. output.writeCompressedInt (1);
  3331. output.writeByte (data.boolValue ? 2 : 3);
  3332. }
  3333. };
  3334. class var::VariantType_String : public var::VariantType
  3335. {
  3336. public:
  3337. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3338. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3339. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3340. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3341. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3342. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3343. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3344. || data.stringValue->trim().equalsIgnoreCase ("true")
  3345. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3346. bool isString() const throw() { return true; }
  3347. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3348. {
  3349. return otherType.toString (otherData) == *data.stringValue;
  3350. }
  3351. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3352. {
  3353. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3354. output.writeCompressedInt (len + 1);
  3355. output.writeByte (5);
  3356. HeapBlock<char> temp (len);
  3357. data.stringValue->copyToUTF8 (temp, len);
  3358. output.write (temp, len);
  3359. }
  3360. };
  3361. class var::VariantType_Object : public var::VariantType
  3362. {
  3363. public:
  3364. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3365. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3366. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3367. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3368. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3369. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3370. bool isObject() const throw() { return true; }
  3371. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3372. {
  3373. return otherType.toObject (otherData) == data.objectValue;
  3374. }
  3375. void writeToStream (const ValueUnion&, OutputStream& output) const
  3376. {
  3377. jassertfalse; // Can't write an object to a stream!
  3378. output.writeCompressedInt (0);
  3379. }
  3380. };
  3381. class var::VariantType_Method : public var::VariantType
  3382. {
  3383. public:
  3384. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3385. const String toString (const ValueUnion&) const { return "Method"; }
  3386. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3387. bool isMethod() const throw() { return true; }
  3388. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3389. {
  3390. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3391. }
  3392. void writeToStream (const ValueUnion&, OutputStream& output) const
  3393. {
  3394. jassertfalse; // Can't write a method to a stream!
  3395. output.writeCompressedInt (0);
  3396. }
  3397. };
  3398. var::var() throw()
  3399. : type (VariantType_Void::getInstance())
  3400. {
  3401. }
  3402. var::~var() throw()
  3403. {
  3404. type->cleanUp (value);
  3405. }
  3406. const var var::null;
  3407. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3408. {
  3409. type->createCopy (value, valueToCopy.value);
  3410. }
  3411. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3412. {
  3413. value.intValue = value_;
  3414. }
  3415. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3416. {
  3417. value.boolValue = value_;
  3418. }
  3419. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3420. {
  3421. value.doubleValue = value_;
  3422. }
  3423. var::var (const String& value_) : type (VariantType_String::getInstance())
  3424. {
  3425. value.stringValue = new String (value_);
  3426. }
  3427. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3428. {
  3429. value.stringValue = new String (value_);
  3430. }
  3431. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3432. {
  3433. value.stringValue = new String (value_);
  3434. }
  3435. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3436. {
  3437. value.objectValue = object;
  3438. if (object != 0)
  3439. object->incReferenceCount();
  3440. }
  3441. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3442. {
  3443. value.methodValue = method_;
  3444. }
  3445. bool var::isVoid() const throw() { return type->isVoid(); }
  3446. bool var::isInt() const throw() { return type->isInt(); }
  3447. bool var::isBool() const throw() { return type->isBool(); }
  3448. bool var::isDouble() const throw() { return type->isDouble(); }
  3449. bool var::isString() const throw() { return type->isString(); }
  3450. bool var::isObject() const throw() { return type->isObject(); }
  3451. bool var::isMethod() const throw() { return type->isMethod(); }
  3452. var::operator int() const { return type->toInt (value); }
  3453. var::operator bool() const { return type->toBool (value); }
  3454. var::operator float() const { return (float) type->toDouble (value); }
  3455. var::operator double() const { return type->toDouble (value); }
  3456. const String var::toString() const { return type->toString (value); }
  3457. var::operator const String() const { return type->toString (value); }
  3458. DynamicObject* var::getObject() const { return type->toObject (value); }
  3459. void var::swapWith (var& other) throw()
  3460. {
  3461. swapVariables (type, other.type);
  3462. swapVariables (value, other.value);
  3463. }
  3464. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3465. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3466. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3467. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3468. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3469. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3470. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3471. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3472. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3473. bool var::equals (const var& other) const throw()
  3474. {
  3475. return type->equals (value, other.value, *other.type);
  3476. }
  3477. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3478. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3479. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3480. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3481. void var::writeToStream (OutputStream& output) const
  3482. {
  3483. type->writeToStream (value, output);
  3484. }
  3485. const var var::readFromStream (InputStream& input)
  3486. {
  3487. const int numBytes = input.readCompressedInt();
  3488. if (numBytes > 0)
  3489. {
  3490. switch (input.readByte())
  3491. {
  3492. case 1: return var (input.readInt());
  3493. case 2: return var (true);
  3494. case 3: return var (false);
  3495. case 4: return var (input.readDouble());
  3496. case 5:
  3497. {
  3498. MemoryOutputStream mo;
  3499. mo.writeFromInputStream (input, numBytes - 1);
  3500. return var (mo.toUTF8());
  3501. }
  3502. default: input.skipNextBytes (numBytes - 1); break;
  3503. }
  3504. }
  3505. return var::null;
  3506. }
  3507. const var var::operator[] (const Identifier& propertyName) const
  3508. {
  3509. DynamicObject* const o = getObject();
  3510. return o != 0 ? o->getProperty (propertyName) : var::null;
  3511. }
  3512. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3513. {
  3514. DynamicObject* const o = getObject();
  3515. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3516. }
  3517. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3518. {
  3519. if (isMethod())
  3520. {
  3521. DynamicObject* const target = targetObject.getObject();
  3522. if (target != 0)
  3523. return (target->*(value.methodValue)) (arguments, numArguments);
  3524. }
  3525. return var::null;
  3526. }
  3527. const var var::call (const Identifier& method) const
  3528. {
  3529. return invoke (method, 0, 0);
  3530. }
  3531. const var var::call (const Identifier& method, const var& arg1) const
  3532. {
  3533. return invoke (method, &arg1, 1);
  3534. }
  3535. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3536. {
  3537. var args[] = { arg1, arg2 };
  3538. return invoke (method, args, 2);
  3539. }
  3540. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3541. {
  3542. var args[] = { arg1, arg2, arg3 };
  3543. return invoke (method, args, 3);
  3544. }
  3545. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3546. {
  3547. var args[] = { arg1, arg2, arg3, arg4 };
  3548. return invoke (method, args, 4);
  3549. }
  3550. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3551. {
  3552. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3553. return invoke (method, args, 5);
  3554. }
  3555. END_JUCE_NAMESPACE
  3556. /*** End of inlined file: juce_Variant.cpp ***/
  3557. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3558. BEGIN_JUCE_NAMESPACE
  3559. NamedValueSet::NamedValue::NamedValue() throw()
  3560. {
  3561. }
  3562. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3563. : name (name_), value (value_)
  3564. {
  3565. }
  3566. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3567. {
  3568. return name == other.name && value == other.value;
  3569. }
  3570. NamedValueSet::NamedValueSet() throw()
  3571. {
  3572. }
  3573. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3574. : values (other.values)
  3575. {
  3576. }
  3577. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3578. {
  3579. values = other.values;
  3580. return *this;
  3581. }
  3582. NamedValueSet::~NamedValueSet()
  3583. {
  3584. }
  3585. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3586. {
  3587. return values == other.values;
  3588. }
  3589. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3590. {
  3591. return ! operator== (other);
  3592. }
  3593. int NamedValueSet::size() const throw()
  3594. {
  3595. return values.size();
  3596. }
  3597. const var& NamedValueSet::operator[] (const Identifier& name) const
  3598. {
  3599. for (int i = values.size(); --i >= 0;)
  3600. {
  3601. const NamedValue& v = values.getReference(i);
  3602. if (v.name == name)
  3603. return v.value;
  3604. }
  3605. return var::null;
  3606. }
  3607. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3608. {
  3609. const var* v = getItem (name);
  3610. return v != 0 ? *v : defaultReturnValue;
  3611. }
  3612. var* NamedValueSet::getItem (const Identifier& name) const
  3613. {
  3614. for (int i = values.size(); --i >= 0;)
  3615. {
  3616. NamedValue& v = values.getReference(i);
  3617. if (v.name == name)
  3618. return &(v.value);
  3619. }
  3620. return 0;
  3621. }
  3622. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3623. {
  3624. for (int i = values.size(); --i >= 0;)
  3625. {
  3626. NamedValue& v = values.getReference(i);
  3627. if (v.name == name)
  3628. {
  3629. if (v.value == newValue)
  3630. return false;
  3631. v.value = newValue;
  3632. return true;
  3633. }
  3634. }
  3635. values.add (NamedValue (name, newValue));
  3636. return true;
  3637. }
  3638. bool NamedValueSet::contains (const Identifier& name) const
  3639. {
  3640. return getItem (name) != 0;
  3641. }
  3642. bool NamedValueSet::remove (const Identifier& name)
  3643. {
  3644. for (int i = values.size(); --i >= 0;)
  3645. {
  3646. if (values.getReference(i).name == name)
  3647. {
  3648. values.remove (i);
  3649. return true;
  3650. }
  3651. }
  3652. return false;
  3653. }
  3654. const Identifier NamedValueSet::getName (const int index) const
  3655. {
  3656. jassert (((unsigned int) index) < (unsigned int) values.size());
  3657. return values [index].name;
  3658. }
  3659. const var NamedValueSet::getValueAt (const int index) const
  3660. {
  3661. jassert (((unsigned int) index) < (unsigned int) values.size());
  3662. return values [index].value;
  3663. }
  3664. void NamedValueSet::clear()
  3665. {
  3666. values.clear();
  3667. }
  3668. END_JUCE_NAMESPACE
  3669. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3670. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3671. BEGIN_JUCE_NAMESPACE
  3672. DynamicObject::DynamicObject()
  3673. {
  3674. }
  3675. DynamicObject::~DynamicObject()
  3676. {
  3677. }
  3678. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3679. {
  3680. var* const v = properties.getItem (propertyName);
  3681. return v != 0 && ! v->isMethod();
  3682. }
  3683. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3684. {
  3685. return properties [propertyName];
  3686. }
  3687. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3688. {
  3689. properties.set (propertyName, newValue);
  3690. }
  3691. void DynamicObject::removeProperty (const Identifier& propertyName)
  3692. {
  3693. properties.remove (propertyName);
  3694. }
  3695. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3696. {
  3697. return getProperty (methodName).isMethod();
  3698. }
  3699. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3700. const var* parameters,
  3701. int numParameters)
  3702. {
  3703. return properties [methodName].invoke (var (this), parameters, numParameters);
  3704. }
  3705. void DynamicObject::setMethod (const Identifier& name,
  3706. var::MethodFunction methodFunction)
  3707. {
  3708. properties.set (name, var (methodFunction));
  3709. }
  3710. void DynamicObject::clear()
  3711. {
  3712. properties.clear();
  3713. }
  3714. END_JUCE_NAMESPACE
  3715. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3716. /*** Start of inlined file: juce_Expression.cpp ***/
  3717. BEGIN_JUCE_NAMESPACE
  3718. class Expression::Helpers
  3719. {
  3720. public:
  3721. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3722. class Constant : public Term
  3723. {
  3724. public:
  3725. Constant (const double value_, bool isResolutionTarget_)
  3726. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3727. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3728. double evaluate (const EvaluationContext&, int) const { return value; }
  3729. int getNumInputs() const { return 0; }
  3730. Term* getInput (int) const { return 0; }
  3731. const TermPtr negated()
  3732. {
  3733. return new Constant (-value, isResolutionTarget);
  3734. }
  3735. const String toString() const
  3736. {
  3737. if (isResolutionTarget)
  3738. return "@" + String (value);
  3739. return String (value);
  3740. }
  3741. double value;
  3742. bool isResolutionTarget;
  3743. };
  3744. class Symbol : public Term
  3745. {
  3746. public:
  3747. explicit Symbol (const String& symbol_)
  3748. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3749. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3750. {}
  3751. Symbol (const String& symbol_, const String& member_)
  3752. : mainSymbol (symbol_),
  3753. member (member_)
  3754. {}
  3755. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3756. {
  3757. if (++recursionDepth > 256)
  3758. throw EvaluationError ("Recursive symbol references");
  3759. try
  3760. {
  3761. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3762. }
  3763. catch (...)
  3764. {}
  3765. return 0;
  3766. }
  3767. Term* clone() const { return new Symbol (mainSymbol, member); }
  3768. int getNumInputs() const { return 0; }
  3769. Term* getInput (int) const { return 0; }
  3770. const String toString() const
  3771. {
  3772. return member.isEmpty() ? mainSymbol
  3773. : mainSymbol + "." + member;
  3774. }
  3775. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3776. {
  3777. if (s == mainSymbol)
  3778. return true;
  3779. if (++recursionDepth > 256)
  3780. throw EvaluationError ("Recursive symbol references");
  3781. try
  3782. {
  3783. return c.getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3784. }
  3785. catch (EvaluationError&)
  3786. {
  3787. return false;
  3788. }
  3789. }
  3790. String mainSymbol, member;
  3791. };
  3792. class Function : public Term
  3793. {
  3794. public:
  3795. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3796. : functionName (functionName_), parameters (parameters_)
  3797. {}
  3798. Term* clone() const { return new Function (functionName, parameters); }
  3799. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3800. {
  3801. HeapBlock <double> params (parameters.size());
  3802. for (int i = 0; i < parameters.size(); ++i)
  3803. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3804. return c.evaluateFunction (functionName, params, parameters.size());
  3805. }
  3806. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3807. int getNumInputs() const { return parameters.size(); }
  3808. Term* getInput (int i) const { return parameters [i]; }
  3809. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3810. {
  3811. for (int i = 0; i < parameters.size(); ++i)
  3812. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3813. return true;
  3814. return false;
  3815. }
  3816. const String toString() const
  3817. {
  3818. if (parameters.size() == 0)
  3819. return functionName + "()";
  3820. String s (functionName + " (");
  3821. for (int i = 0; i < parameters.size(); ++i)
  3822. {
  3823. s << parameters.getUnchecked(i)->toString();
  3824. if (i < parameters.size() - 1)
  3825. s << ", ";
  3826. }
  3827. s << ')';
  3828. return s;
  3829. }
  3830. const String functionName;
  3831. ReferenceCountedArray<Term> parameters;
  3832. };
  3833. class Negate : public Term
  3834. {
  3835. public:
  3836. Negate (const TermPtr& input_) : input (input_)
  3837. {
  3838. jassert (input_ != 0);
  3839. }
  3840. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3841. int getNumInputs() const { return 1; }
  3842. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3843. Term* clone() const { return new Negate (input->clone()); }
  3844. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3845. const TermPtr negated()
  3846. {
  3847. return input;
  3848. }
  3849. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3850. {
  3851. jassert (input_ == input);
  3852. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3853. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3854. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3855. }
  3856. const String toString() const
  3857. {
  3858. if (input->getOperatorPrecedence() > 0)
  3859. return "-(" + input->toString() + ")";
  3860. else
  3861. return "-" + input->toString();
  3862. }
  3863. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3864. {
  3865. return input->referencesSymbol (s, c, recursionDepth);
  3866. }
  3867. private:
  3868. const TermPtr input;
  3869. };
  3870. class BinaryTerm : public Term
  3871. {
  3872. public:
  3873. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3874. {
  3875. jassert (left_ != 0 && right_ != 0);
  3876. }
  3877. int getInputIndexFor (const Term* possibleInput) const
  3878. {
  3879. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3880. }
  3881. int getNumInputs() const { return 2; }
  3882. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3883. bool referencesSymbol (const String& s, const EvaluationContext& c, int recursionDepth) const
  3884. {
  3885. return left->referencesSymbol (s, c, recursionDepth)
  3886. || right->referencesSymbol (s, c, recursionDepth);
  3887. }
  3888. protected:
  3889. const TermPtr left, right;
  3890. const String createString (const String& op) const
  3891. {
  3892. String s;
  3893. const int ourPrecendence = getOperatorPrecedence();
  3894. if (left->getOperatorPrecedence() > ourPrecendence)
  3895. s << '(' << left->toString() << ')';
  3896. else
  3897. s = left->toString();
  3898. s << ' ' << op << ' ';
  3899. if (right->getOperatorPrecedence() >= ourPrecendence)
  3900. s << '(' << right->toString() << ')';
  3901. else
  3902. s << right->toString();
  3903. return s;
  3904. }
  3905. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3906. {
  3907. jassert (input == left || input == right);
  3908. if (input != left && input != right)
  3909. return 0;
  3910. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3911. if (dest == 0)
  3912. return new Constant (overallTarget, false);
  3913. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3914. }
  3915. };
  3916. class Add : public BinaryTerm
  3917. {
  3918. public:
  3919. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3920. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3921. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3922. const String toString() const { return createString ("+"); }
  3923. int getOperatorPrecedence() const { return 2; }
  3924. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3925. {
  3926. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3927. if (newDest == 0)
  3928. return 0;
  3929. return new Subtract (newDest, (input == left ? right : left)->clone());
  3930. }
  3931. };
  3932. class Subtract : public BinaryTerm
  3933. {
  3934. public:
  3935. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3936. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3937. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3938. const String toString() const { return createString ("-"); }
  3939. int getOperatorPrecedence() const { return 2; }
  3940. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3941. {
  3942. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3943. if (newDest == 0)
  3944. return 0;
  3945. if (input == left)
  3946. return new Add (newDest, right->clone());
  3947. else
  3948. return new Subtract (left->clone(), newDest);
  3949. }
  3950. };
  3951. class Multiply : public BinaryTerm
  3952. {
  3953. public:
  3954. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3955. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  3956. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  3957. const String toString() const { return createString ("*"); }
  3958. int getOperatorPrecedence() const { return 1; }
  3959. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3960. {
  3961. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3962. if (newDest == 0)
  3963. return 0;
  3964. return new Divide (newDest, (input == left ? right : left)->clone());
  3965. }
  3966. };
  3967. class Divide : public BinaryTerm
  3968. {
  3969. public:
  3970. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3971. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  3972. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  3973. const String toString() const { return createString ("/"); }
  3974. int getOperatorPrecedence() const { return 1; }
  3975. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3976. {
  3977. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3978. if (newDest == 0)
  3979. return 0;
  3980. if (input == left)
  3981. return new Multiply (newDest, right->clone());
  3982. else
  3983. return new Divide (left->clone(), newDest);
  3984. }
  3985. };
  3986. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  3987. {
  3988. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  3989. if (inputIndex >= 0)
  3990. return topLevel;
  3991. for (int i = topLevel->getNumInputs(); --i >= 0;)
  3992. {
  3993. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  3994. if (t != 0)
  3995. return t;
  3996. }
  3997. return 0;
  3998. }
  3999. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4000. {
  4001. Constant* c = dynamic_cast<Constant*> (term);
  4002. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4003. return c;
  4004. if (dynamic_cast<Function*> (term) != 0)
  4005. return 0;
  4006. int i;
  4007. const int numIns = term->getNumInputs();
  4008. for (i = 0; i < numIns; ++i)
  4009. {
  4010. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4011. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4012. return c;
  4013. }
  4014. for (i = 0; i < numIns; ++i)
  4015. {
  4016. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4017. if (c != 0)
  4018. return c;
  4019. }
  4020. return 0;
  4021. }
  4022. static bool containsAnySymbols (const Term* const t)
  4023. {
  4024. if (dynamic_cast <const Symbol*> (t) != 0)
  4025. return true;
  4026. for (int i = t->getNumInputs(); --i >= 0;)
  4027. if (containsAnySymbols (t->getInput (i)))
  4028. return true;
  4029. return false;
  4030. }
  4031. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4032. {
  4033. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4034. if (sym != 0 && sym->mainSymbol == oldName)
  4035. {
  4036. sym->mainSymbol = newName;
  4037. return true;
  4038. }
  4039. bool anyChanged = false;
  4040. for (int i = t->getNumInputs(); --i >= 0;)
  4041. if (renameSymbol (t->getInput (i), oldName, newName))
  4042. anyChanged = true;
  4043. return anyChanged;
  4044. }
  4045. class Parser
  4046. {
  4047. public:
  4048. Parser (const String& stringToParse, int& textIndex_)
  4049. : textString (stringToParse), textIndex (textIndex_)
  4050. {
  4051. text = textString;
  4052. }
  4053. const TermPtr readExpression()
  4054. {
  4055. TermPtr lhs (readMultiplyOrDivideExpression());
  4056. char opType;
  4057. while (lhs != 0 && readOperator ("+-", &opType))
  4058. {
  4059. TermPtr rhs (readMultiplyOrDivideExpression());
  4060. if (rhs == 0)
  4061. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4062. if (opType == '+')
  4063. lhs = new Add (lhs, rhs);
  4064. else
  4065. lhs = new Subtract (lhs, rhs);
  4066. }
  4067. return lhs;
  4068. }
  4069. private:
  4070. const String textString;
  4071. const juce_wchar* text;
  4072. int& textIndex;
  4073. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4074. {
  4075. return c >= '0' && c <= '9';
  4076. }
  4077. void skipWhitespace (int& i)
  4078. {
  4079. while (CharacterFunctions::isWhitespace (text [i]))
  4080. ++i;
  4081. }
  4082. bool readChar (const juce_wchar required)
  4083. {
  4084. if (text[textIndex] == required)
  4085. {
  4086. ++textIndex;
  4087. return true;
  4088. }
  4089. return false;
  4090. }
  4091. bool readOperator (const char* ops, char* const opType = 0)
  4092. {
  4093. skipWhitespace (textIndex);
  4094. while (*ops != 0)
  4095. {
  4096. if (readChar (*ops))
  4097. {
  4098. if (opType != 0)
  4099. *opType = *ops;
  4100. return true;
  4101. }
  4102. ++ops;
  4103. }
  4104. return false;
  4105. }
  4106. bool readIdentifier (String& identifier)
  4107. {
  4108. skipWhitespace (textIndex);
  4109. int i = textIndex;
  4110. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4111. {
  4112. ++i;
  4113. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4114. ++i;
  4115. }
  4116. if (i > textIndex)
  4117. {
  4118. identifier = String (text + textIndex, i - textIndex);
  4119. textIndex = i;
  4120. return true;
  4121. }
  4122. return false;
  4123. }
  4124. Term* readNumber()
  4125. {
  4126. skipWhitespace (textIndex);
  4127. int i = textIndex;
  4128. const bool isResolutionTarget = (text[i] == '@');
  4129. if (isResolutionTarget)
  4130. {
  4131. ++i;
  4132. skipWhitespace (i);
  4133. textIndex = i;
  4134. }
  4135. if (text[i] == '-')
  4136. {
  4137. ++i;
  4138. skipWhitespace (i);
  4139. }
  4140. int numDigits = 0;
  4141. while (isDecimalDigit (text[i]))
  4142. {
  4143. ++i;
  4144. ++numDigits;
  4145. }
  4146. const bool hasPoint = (text[i] == '.');
  4147. if (hasPoint)
  4148. {
  4149. ++i;
  4150. while (isDecimalDigit (text[i]))
  4151. {
  4152. ++i;
  4153. ++numDigits;
  4154. }
  4155. }
  4156. if (numDigits == 0)
  4157. return 0;
  4158. juce_wchar c = text[i];
  4159. const bool hasExponent = (c == 'e' || c == 'E');
  4160. if (hasExponent)
  4161. {
  4162. ++i;
  4163. c = text[i];
  4164. if (c == '+' || c == '-')
  4165. ++i;
  4166. int numExpDigits = 0;
  4167. while (isDecimalDigit (text[i]))
  4168. {
  4169. ++i;
  4170. ++numExpDigits;
  4171. }
  4172. if (numExpDigits == 0)
  4173. return 0;
  4174. }
  4175. const int start = textIndex;
  4176. textIndex = i;
  4177. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4178. }
  4179. const TermPtr readMultiplyOrDivideExpression()
  4180. {
  4181. TermPtr lhs (readUnaryExpression());
  4182. char opType;
  4183. while (lhs != 0 && readOperator ("*/", &opType))
  4184. {
  4185. TermPtr rhs (readUnaryExpression());
  4186. if (rhs == 0)
  4187. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4188. if (opType == '*')
  4189. lhs = new Multiply (lhs, rhs);
  4190. else
  4191. lhs = new Divide (lhs, rhs);
  4192. }
  4193. return lhs;
  4194. }
  4195. const TermPtr readUnaryExpression()
  4196. {
  4197. char opType;
  4198. if (readOperator ("+-", &opType))
  4199. {
  4200. TermPtr term (readUnaryExpression());
  4201. if (term == 0)
  4202. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4203. if (opType == '-')
  4204. term = term->negated();
  4205. return term;
  4206. }
  4207. return readPrimaryExpression();
  4208. }
  4209. const TermPtr readPrimaryExpression()
  4210. {
  4211. TermPtr e (readParenthesisedExpression());
  4212. if (e != 0)
  4213. return e;
  4214. e = readNumber();
  4215. if (e != 0)
  4216. return e;
  4217. String identifier;
  4218. if (readIdentifier (identifier))
  4219. {
  4220. if (readOperator ("(")) // method call...
  4221. {
  4222. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4223. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4224. TermPtr param (readExpression());
  4225. if (param == 0)
  4226. {
  4227. if (readOperator (")"))
  4228. return func.release();
  4229. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4230. }
  4231. f->parameters.add (param);
  4232. while (readOperator (","))
  4233. {
  4234. param = readExpression();
  4235. if (param == 0)
  4236. throw ParseError ("Expected expression after \",\"");
  4237. f->parameters.add (param);
  4238. }
  4239. if (readOperator (")"))
  4240. return func.release();
  4241. throw ParseError ("Expected \")\"");
  4242. }
  4243. else // just a symbol..
  4244. {
  4245. return new Symbol (identifier);
  4246. }
  4247. }
  4248. return 0;
  4249. }
  4250. const TermPtr readParenthesisedExpression()
  4251. {
  4252. if (! readOperator ("("))
  4253. return 0;
  4254. const TermPtr e (readExpression());
  4255. if (e == 0 || ! readOperator (")"))
  4256. return 0;
  4257. return e;
  4258. }
  4259. Parser (const Parser&);
  4260. Parser& operator= (const Parser&);
  4261. };
  4262. };
  4263. Expression::Expression()
  4264. : term (new Expression::Helpers::Constant (0, false))
  4265. {
  4266. }
  4267. Expression::~Expression()
  4268. {
  4269. }
  4270. Expression::Expression (Term* const term_)
  4271. : term (term_)
  4272. {
  4273. jassert (term != 0);
  4274. }
  4275. Expression::Expression (const double constant)
  4276. : term (new Expression::Helpers::Constant (constant, false))
  4277. {
  4278. }
  4279. Expression::Expression (const Expression& other)
  4280. : term (other.term)
  4281. {
  4282. }
  4283. Expression& Expression::operator= (const Expression& other)
  4284. {
  4285. term = other.term;
  4286. return *this;
  4287. }
  4288. Expression::Expression (const String& stringToParse)
  4289. {
  4290. int i = 0;
  4291. Helpers::Parser parser (stringToParse, i);
  4292. term = parser.readExpression();
  4293. if (term == 0)
  4294. term = new Helpers::Constant (0, false);
  4295. }
  4296. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4297. {
  4298. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4299. const Helpers::TermPtr term (parser.readExpression());
  4300. if (term != 0)
  4301. return Expression (term);
  4302. return Expression();
  4303. }
  4304. double Expression::evaluate() const
  4305. {
  4306. return evaluate (Expression::EvaluationContext());
  4307. }
  4308. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4309. {
  4310. return term->evaluate (context, 0);
  4311. }
  4312. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4313. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4314. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4315. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4316. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4317. const String Expression::toString() const
  4318. {
  4319. return term->toString();
  4320. }
  4321. const Expression Expression::symbol (const String& symbol)
  4322. {
  4323. return Expression (new Helpers::Symbol (symbol));
  4324. }
  4325. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4326. {
  4327. ReferenceCountedArray<Term> params;
  4328. for (int i = 0; i < parameters.size(); ++i)
  4329. params.add (parameters.getReference(i).term);
  4330. return Expression (new Helpers::Function (functionName, params));
  4331. }
  4332. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4333. const Expression::EvaluationContext& context) const
  4334. {
  4335. ScopedPointer<Term> newTerm (term->clone());
  4336. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4337. if (termToAdjust == 0)
  4338. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4339. if (termToAdjust == 0)
  4340. {
  4341. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4342. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4343. }
  4344. jassert (termToAdjust != 0);
  4345. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4346. if (parent == 0)
  4347. {
  4348. termToAdjust->value = targetValue;
  4349. }
  4350. else
  4351. {
  4352. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4353. if (reverseTerm == 0)
  4354. return Expression (targetValue);
  4355. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4356. }
  4357. return Expression (newTerm.release());
  4358. }
  4359. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4360. {
  4361. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4362. Expression newExpression (term->clone());
  4363. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4364. return newExpression;
  4365. }
  4366. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext& context) const
  4367. {
  4368. return term->referencesSymbol (symbol, context, 0);
  4369. }
  4370. bool Expression::usesAnySymbols() const
  4371. {
  4372. return Helpers::containsAnySymbols (term);
  4373. }
  4374. int Expression::Term::getOperatorPrecedence() const
  4375. {
  4376. return 0;
  4377. }
  4378. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext&, int) const
  4379. {
  4380. return false;
  4381. }
  4382. int Expression::Term::getInputIndexFor (const Term*) const
  4383. {
  4384. return -1;
  4385. }
  4386. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4387. {
  4388. jassertfalse;
  4389. return 0;
  4390. }
  4391. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4392. {
  4393. return new Helpers::Negate (this);
  4394. }
  4395. Expression::ParseError::ParseError (const String& message)
  4396. : description (message)
  4397. {
  4398. DBG ("Expression::ParseError: " + message);
  4399. }
  4400. Expression::EvaluationError::EvaluationError (const String& message)
  4401. : description (message)
  4402. {
  4403. DBG ("Expression::EvaluationError: " + message);
  4404. }
  4405. Expression::EvaluationContext::EvaluationContext() {}
  4406. Expression::EvaluationContext::~EvaluationContext() {}
  4407. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4408. {
  4409. throw EvaluationError ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")));
  4410. }
  4411. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4412. {
  4413. if (numParams > 0)
  4414. {
  4415. if (functionName == "min")
  4416. {
  4417. double v = parameters[0];
  4418. for (int i = 1; i < numParams; ++i)
  4419. v = jmin (v, parameters[i]);
  4420. return v;
  4421. }
  4422. else if (functionName == "max")
  4423. {
  4424. double v = parameters[0];
  4425. for (int i = 1; i < numParams; ++i)
  4426. v = jmax (v, parameters[i]);
  4427. return v;
  4428. }
  4429. else if (numParams == 1)
  4430. {
  4431. if (functionName == "sin")
  4432. return sin (parameters[0]);
  4433. else if (functionName == "cos")
  4434. return cos (parameters[0]);
  4435. else if (functionName == "tan")
  4436. return tan (parameters[0]);
  4437. else if (functionName == "abs")
  4438. return std::abs (parameters[0]);
  4439. }
  4440. }
  4441. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4442. }
  4443. END_JUCE_NAMESPACE
  4444. /*** End of inlined file: juce_Expression.cpp ***/
  4445. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4446. BEGIN_JUCE_NAMESPACE
  4447. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4448. {
  4449. jassert (keyData != 0);
  4450. jassert (keyBytes > 0);
  4451. static const uint32 initialPValues [18] =
  4452. {
  4453. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4454. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4455. 0x9216d5d9, 0x8979fb1b
  4456. };
  4457. static const uint32 initialSValues [4 * 256] =
  4458. {
  4459. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4460. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4461. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4462. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4463. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4464. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4465. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4466. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4467. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4468. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4469. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4470. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4471. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4472. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4473. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4474. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4475. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4476. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4477. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4478. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4479. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4480. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4481. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4482. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4483. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4484. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4485. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4486. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4487. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4488. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4489. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4490. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4491. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4492. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4493. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4494. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4495. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4496. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4497. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4498. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4499. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4500. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4501. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4502. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4503. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4504. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4505. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4506. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4507. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4508. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4509. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4510. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4511. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4512. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4513. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4514. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4515. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4516. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4517. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4518. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4519. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4520. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4521. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4522. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4523. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4524. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4525. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4526. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4527. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4528. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4529. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4530. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4531. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4532. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4533. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4534. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4535. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4536. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4537. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4538. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4539. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4540. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4541. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4542. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4543. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4544. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4545. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4546. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4547. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4548. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4549. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4550. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4551. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4552. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4553. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4554. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4555. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4556. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4557. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4558. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4559. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4560. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4561. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4562. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4563. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4564. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4565. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4566. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4567. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4568. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4569. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4570. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4571. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4572. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4573. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4574. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4575. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4576. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4577. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4578. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4579. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4580. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4581. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4582. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4583. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4584. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4585. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4586. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4587. };
  4588. memcpy (p, initialPValues, sizeof (p));
  4589. int i, j = 0;
  4590. for (i = 4; --i >= 0;)
  4591. {
  4592. s[i].malloc (256);
  4593. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4594. }
  4595. for (i = 0; i < 18; ++i)
  4596. {
  4597. uint32 d = 0;
  4598. for (int k = 0; k < 4; ++k)
  4599. {
  4600. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4601. if (++j >= keyBytes)
  4602. j = 0;
  4603. }
  4604. p[i] = initialPValues[i] ^ d;
  4605. }
  4606. uint32 l = 0, r = 0;
  4607. for (i = 0; i < 18; i += 2)
  4608. {
  4609. encrypt (l, r);
  4610. p[i] = l;
  4611. p[i + 1] = r;
  4612. }
  4613. for (i = 0; i < 4; ++i)
  4614. {
  4615. for (j = 0; j < 256; j += 2)
  4616. {
  4617. encrypt (l, r);
  4618. s[i][j] = l;
  4619. s[i][j + 1] = r;
  4620. }
  4621. }
  4622. }
  4623. BlowFish::BlowFish (const BlowFish& other)
  4624. {
  4625. for (int i = 4; --i >= 0;)
  4626. s[i].malloc (256);
  4627. operator= (other);
  4628. }
  4629. BlowFish& BlowFish::operator= (const BlowFish& other)
  4630. {
  4631. memcpy (p, other.p, sizeof (p));
  4632. for (int i = 4; --i >= 0;)
  4633. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4634. return *this;
  4635. }
  4636. BlowFish::~BlowFish()
  4637. {
  4638. }
  4639. uint32 BlowFish::F (const uint32 x) const throw()
  4640. {
  4641. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4642. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4643. }
  4644. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4645. {
  4646. uint32 l = data1;
  4647. uint32 r = data2;
  4648. for (int i = 0; i < 16; ++i)
  4649. {
  4650. l ^= p[i];
  4651. r ^= F(l);
  4652. swapVariables (l, r);
  4653. }
  4654. data1 = r ^ p[17];
  4655. data2 = l ^ p[16];
  4656. }
  4657. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4658. {
  4659. uint32 l = data1;
  4660. uint32 r = data2;
  4661. for (int i = 17; i > 1; --i)
  4662. {
  4663. l ^= p[i];
  4664. r ^= F(l);
  4665. swapVariables (l, r);
  4666. }
  4667. data1 = r ^ p[0];
  4668. data2 = l ^ p[1];
  4669. }
  4670. END_JUCE_NAMESPACE
  4671. /*** End of inlined file: juce_BlowFish.cpp ***/
  4672. /*** Start of inlined file: juce_MD5.cpp ***/
  4673. BEGIN_JUCE_NAMESPACE
  4674. MD5::MD5()
  4675. {
  4676. zerostruct (result);
  4677. }
  4678. MD5::MD5 (const MD5& other)
  4679. {
  4680. memcpy (result, other.result, sizeof (result));
  4681. }
  4682. MD5& MD5::operator= (const MD5& other)
  4683. {
  4684. memcpy (result, other.result, sizeof (result));
  4685. return *this;
  4686. }
  4687. MD5::MD5 (const MemoryBlock& data)
  4688. {
  4689. ProcessContext context;
  4690. context.processBlock (data.getData(), data.getSize());
  4691. context.finish (result);
  4692. }
  4693. MD5::MD5 (const void* data, const size_t numBytes)
  4694. {
  4695. ProcessContext context;
  4696. context.processBlock (data, numBytes);
  4697. context.finish (result);
  4698. }
  4699. MD5::MD5 (const String& text)
  4700. {
  4701. ProcessContext context;
  4702. const int len = text.length();
  4703. const juce_wchar* const t = text;
  4704. for (int i = 0; i < len; ++i)
  4705. {
  4706. // force the string into integer-sized unicode characters, to try to make it
  4707. // get the same results on all platforms + compilers.
  4708. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4709. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4710. }
  4711. context.finish (result);
  4712. }
  4713. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4714. {
  4715. ProcessContext context;
  4716. if (numBytesToRead < 0)
  4717. numBytesToRead = std::numeric_limits<int64>::max();
  4718. while (numBytesToRead > 0)
  4719. {
  4720. uint8 tempBuffer [512];
  4721. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4722. if (bytesRead <= 0)
  4723. break;
  4724. numBytesToRead -= bytesRead;
  4725. context.processBlock (tempBuffer, bytesRead);
  4726. }
  4727. context.finish (result);
  4728. }
  4729. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4730. {
  4731. processStream (input, numBytesToRead);
  4732. }
  4733. MD5::MD5 (const File& file)
  4734. {
  4735. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4736. if (fin != 0)
  4737. processStream (*fin, -1);
  4738. else
  4739. zerostruct (result);
  4740. }
  4741. MD5::~MD5()
  4742. {
  4743. }
  4744. namespace MD5Functions
  4745. {
  4746. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4747. {
  4748. for (int i = 0; i < (numBytes >> 2); ++i)
  4749. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4750. }
  4751. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4752. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4753. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4754. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4755. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4756. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4757. {
  4758. a += F (b, c, d) + x + ac;
  4759. a = rotateLeft (a, s) + b;
  4760. }
  4761. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4762. {
  4763. a += G (b, c, d) + x + ac;
  4764. a = rotateLeft (a, s) + b;
  4765. }
  4766. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4767. {
  4768. a += H (b, c, d) + x + ac;
  4769. a = rotateLeft (a, s) + b;
  4770. }
  4771. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4772. {
  4773. a += I (b, c, d) + x + ac;
  4774. a = rotateLeft (a, s) + b;
  4775. }
  4776. }
  4777. MD5::ProcessContext::ProcessContext()
  4778. {
  4779. state[0] = 0x67452301;
  4780. state[1] = 0xefcdab89;
  4781. state[2] = 0x98badcfe;
  4782. state[3] = 0x10325476;
  4783. count[0] = 0;
  4784. count[1] = 0;
  4785. }
  4786. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4787. {
  4788. int bufferPos = ((count[0] >> 3) & 0x3F);
  4789. count[0] += (uint32) (dataSize << 3);
  4790. if (count[0] < ((uint32) dataSize << 3))
  4791. count[1]++;
  4792. count[1] += (uint32) (dataSize >> 29);
  4793. const size_t spaceLeft = 64 - bufferPos;
  4794. size_t i = 0;
  4795. if (dataSize >= spaceLeft)
  4796. {
  4797. memcpy (buffer + bufferPos, data, spaceLeft);
  4798. transform (buffer);
  4799. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4800. transform (static_cast <const char*> (data) + i);
  4801. bufferPos = 0;
  4802. }
  4803. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4804. }
  4805. void MD5::ProcessContext::finish (void* const result)
  4806. {
  4807. unsigned char encodedLength[8];
  4808. MD5Functions::encode (encodedLength, count, 8);
  4809. // Pad out to 56 mod 64.
  4810. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4811. const int paddingLength = (index < 56) ? (56 - index)
  4812. : (120 - index);
  4813. uint8 paddingBuffer [64];
  4814. zeromem (paddingBuffer, paddingLength);
  4815. paddingBuffer [0] = 0x80;
  4816. processBlock (paddingBuffer, paddingLength);
  4817. processBlock (encodedLength, 8);
  4818. MD5Functions::encode (result, state, 16);
  4819. zerostruct (buffer);
  4820. }
  4821. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4822. {
  4823. using namespace MD5Functions;
  4824. uint32 a = state[0];
  4825. uint32 b = state[1];
  4826. uint32 c = state[2];
  4827. uint32 d = state[3];
  4828. uint32 x[16];
  4829. encode (x, bufferToTransform, 64);
  4830. enum Constants
  4831. {
  4832. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4833. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4834. };
  4835. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4836. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4837. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4838. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4839. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4840. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4841. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4842. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4843. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4844. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4845. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4846. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4847. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4848. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4849. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4850. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4851. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4852. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4853. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4854. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4855. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4856. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4857. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4858. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4859. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4860. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4861. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4862. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4863. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4864. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4865. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4866. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4867. state[0] += a;
  4868. state[1] += b;
  4869. state[2] += c;
  4870. state[3] += d;
  4871. zerostruct (x);
  4872. }
  4873. const MemoryBlock MD5::getRawChecksumData() const
  4874. {
  4875. return MemoryBlock (result, sizeof (result));
  4876. }
  4877. const String MD5::toHexString() const
  4878. {
  4879. return String::toHexString (result, sizeof (result), 0);
  4880. }
  4881. bool MD5::operator== (const MD5& other) const
  4882. {
  4883. return memcmp (result, other.result, sizeof (result)) == 0;
  4884. }
  4885. bool MD5::operator!= (const MD5& other) const
  4886. {
  4887. return ! operator== (other);
  4888. }
  4889. END_JUCE_NAMESPACE
  4890. /*** End of inlined file: juce_MD5.cpp ***/
  4891. /*** Start of inlined file: juce_Primes.cpp ***/
  4892. BEGIN_JUCE_NAMESPACE
  4893. namespace PrimesHelpers
  4894. {
  4895. static void createSmallSieve (const int numBits, BigInteger& result)
  4896. {
  4897. result.setBit (numBits);
  4898. result.clearBit (numBits); // to enlarge the array
  4899. result.setBit (0);
  4900. int n = 2;
  4901. do
  4902. {
  4903. for (int i = n + n; i < numBits; i += n)
  4904. result.setBit (i);
  4905. n = result.findNextClearBit (n + 1);
  4906. }
  4907. while (n <= (numBits >> 1));
  4908. }
  4909. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4910. const BigInteger& smallSieve, const int smallSieveSize)
  4911. {
  4912. jassert (! base[0]); // must be even!
  4913. result.setBit (numBits);
  4914. result.clearBit (numBits); // to enlarge the array
  4915. int index = smallSieve.findNextClearBit (0);
  4916. do
  4917. {
  4918. const int prime = (index << 1) + 1;
  4919. BigInteger r (base), remainder;
  4920. r.divideBy (prime, remainder);
  4921. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4922. if (r.isZero())
  4923. i += prime;
  4924. if ((i & 1) == 0)
  4925. i += prime;
  4926. i = (i - 1) >> 1;
  4927. while (i < numBits)
  4928. {
  4929. result.setBit (i);
  4930. i += prime;
  4931. }
  4932. index = smallSieve.findNextClearBit (index + 1);
  4933. }
  4934. while (index < smallSieveSize);
  4935. }
  4936. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4937. const int numBits, BigInteger& result, const int certainty)
  4938. {
  4939. for (int i = 0; i < numBits; ++i)
  4940. {
  4941. if (! sieve[i])
  4942. {
  4943. result = base + (unsigned int) ((i << 1) + 1);
  4944. if (Primes::isProbablyPrime (result, certainty))
  4945. return true;
  4946. }
  4947. }
  4948. return false;
  4949. }
  4950. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4951. {
  4952. const BigInteger one (1), two (2);
  4953. const BigInteger nMinusOne (n - one);
  4954. BigInteger d (nMinusOne);
  4955. const int s = d.findNextSetBit (0);
  4956. d >>= s;
  4957. BigInteger smallPrimes;
  4958. int numBitsInSmallPrimes = 0;
  4959. for (;;)
  4960. {
  4961. numBitsInSmallPrimes += 256;
  4962. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4963. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4964. if (numPrimesFound > iterations + 1)
  4965. break;
  4966. }
  4967. int smallPrime = 2;
  4968. while (--iterations >= 0)
  4969. {
  4970. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4971. BigInteger r (smallPrime);
  4972. r.exponentModulo (d, n);
  4973. if (r != one && r != nMinusOne)
  4974. {
  4975. for (int j = 0; j < s; ++j)
  4976. {
  4977. r.exponentModulo (two, n);
  4978. if (r == nMinusOne)
  4979. break;
  4980. }
  4981. if (r != nMinusOne)
  4982. return false;
  4983. }
  4984. }
  4985. return true;
  4986. }
  4987. }
  4988. const BigInteger Primes::createProbablePrime (const int bitLength,
  4989. const int certainty,
  4990. const int* randomSeeds,
  4991. int numRandomSeeds)
  4992. {
  4993. using namespace PrimesHelpers;
  4994. int defaultSeeds [16];
  4995. if (numRandomSeeds <= 0)
  4996. {
  4997. randomSeeds = defaultSeeds;
  4998. numRandomSeeds = numElementsInArray (defaultSeeds);
  4999. Random r (0);
  5000. for (int j = 10; --j >= 0;)
  5001. {
  5002. r.setSeedRandomly();
  5003. for (int i = numRandomSeeds; --i >= 0;)
  5004. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5005. }
  5006. }
  5007. BigInteger smallSieve;
  5008. const int smallSieveSize = 15000;
  5009. createSmallSieve (smallSieveSize, smallSieve);
  5010. BigInteger p;
  5011. for (int i = numRandomSeeds; --i >= 0;)
  5012. {
  5013. BigInteger p2;
  5014. Random r (randomSeeds[i]);
  5015. r.fillBitsRandomly (p2, 0, bitLength);
  5016. p ^= p2;
  5017. }
  5018. p.setBit (bitLength - 1);
  5019. p.clearBit (0);
  5020. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5021. while (p.getHighestBit() < bitLength)
  5022. {
  5023. p += 2 * searchLen;
  5024. BigInteger sieve;
  5025. bigSieve (p, searchLen, sieve,
  5026. smallSieve, smallSieveSize);
  5027. BigInteger candidate;
  5028. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5029. return candidate;
  5030. }
  5031. jassertfalse;
  5032. return BigInteger();
  5033. }
  5034. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5035. {
  5036. using namespace PrimesHelpers;
  5037. if (! number[0])
  5038. return false;
  5039. if (number.getHighestBit() <= 10)
  5040. {
  5041. const int num = number.getBitRangeAsInt (0, 10);
  5042. for (int i = num / 2; --i > 1;)
  5043. if (num % i == 0)
  5044. return false;
  5045. return true;
  5046. }
  5047. else
  5048. {
  5049. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5050. return false;
  5051. return passesMillerRabin (number, certainty);
  5052. }
  5053. }
  5054. END_JUCE_NAMESPACE
  5055. /*** End of inlined file: juce_Primes.cpp ***/
  5056. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5057. BEGIN_JUCE_NAMESPACE
  5058. RSAKey::RSAKey()
  5059. {
  5060. }
  5061. RSAKey::RSAKey (const String& s)
  5062. {
  5063. if (s.containsChar (','))
  5064. {
  5065. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5066. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5067. }
  5068. else
  5069. {
  5070. // the string needs to be two hex numbers, comma-separated..
  5071. jassertfalse;
  5072. }
  5073. }
  5074. RSAKey::~RSAKey()
  5075. {
  5076. }
  5077. bool RSAKey::operator== (const RSAKey& other) const throw()
  5078. {
  5079. return part1 == other.part1 && part2 == other.part2;
  5080. }
  5081. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5082. {
  5083. return ! operator== (other);
  5084. }
  5085. const String RSAKey::toString() const
  5086. {
  5087. return part1.toString (16) + "," + part2.toString (16);
  5088. }
  5089. bool RSAKey::applyToValue (BigInteger& value) const
  5090. {
  5091. if (part1.isZero() || part2.isZero() || value <= 0)
  5092. {
  5093. jassertfalse; // using an uninitialised key
  5094. value.clear();
  5095. return false;
  5096. }
  5097. BigInteger result;
  5098. while (! value.isZero())
  5099. {
  5100. result *= part2;
  5101. BigInteger remainder;
  5102. value.divideBy (part2, remainder);
  5103. remainder.exponentModulo (part1, part2);
  5104. result += remainder;
  5105. }
  5106. value.swapWith (result);
  5107. return true;
  5108. }
  5109. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5110. {
  5111. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5112. // are fast to divide + multiply
  5113. for (int i = 2; i <= 65536; i *= 2)
  5114. {
  5115. const BigInteger e (1 + i);
  5116. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5117. return e;
  5118. }
  5119. BigInteger e (4);
  5120. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5121. ++e;
  5122. return e;
  5123. }
  5124. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5125. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5126. {
  5127. jassert (numBits > 16); // not much point using less than this..
  5128. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5129. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5130. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5131. const BigInteger n (p * q);
  5132. const BigInteger m (--p * --q);
  5133. const BigInteger e (findBestCommonDivisor (p, q));
  5134. BigInteger d (e);
  5135. d.inverseModulo (m);
  5136. publicKey.part1 = e;
  5137. publicKey.part2 = n;
  5138. privateKey.part1 = d;
  5139. privateKey.part2 = n;
  5140. }
  5141. END_JUCE_NAMESPACE
  5142. /*** End of inlined file: juce_RSAKey.cpp ***/
  5143. /*** Start of inlined file: juce_InputStream.cpp ***/
  5144. BEGIN_JUCE_NAMESPACE
  5145. char InputStream::readByte()
  5146. {
  5147. char temp = 0;
  5148. read (&temp, 1);
  5149. return temp;
  5150. }
  5151. bool InputStream::readBool()
  5152. {
  5153. return readByte() != 0;
  5154. }
  5155. short InputStream::readShort()
  5156. {
  5157. char temp[2];
  5158. if (read (temp, 2) == 2)
  5159. return (short) ByteOrder::littleEndianShort (temp);
  5160. return 0;
  5161. }
  5162. short InputStream::readShortBigEndian()
  5163. {
  5164. char temp[2];
  5165. if (read (temp, 2) == 2)
  5166. return (short) ByteOrder::bigEndianShort (temp);
  5167. return 0;
  5168. }
  5169. int InputStream::readInt()
  5170. {
  5171. char temp[4];
  5172. if (read (temp, 4) == 4)
  5173. return (int) ByteOrder::littleEndianInt (temp);
  5174. return 0;
  5175. }
  5176. int InputStream::readIntBigEndian()
  5177. {
  5178. char temp[4];
  5179. if (read (temp, 4) == 4)
  5180. return (int) ByteOrder::bigEndianInt (temp);
  5181. return 0;
  5182. }
  5183. int InputStream::readCompressedInt()
  5184. {
  5185. const unsigned char sizeByte = readByte();
  5186. if (sizeByte == 0)
  5187. return 0;
  5188. const int numBytes = (sizeByte & 0x7f);
  5189. if (numBytes > 4)
  5190. {
  5191. jassertfalse; // trying to read corrupt data - this method must only be used
  5192. // to read data that was written by OutputStream::writeCompressedInt()
  5193. return 0;
  5194. }
  5195. char bytes[4] = { 0, 0, 0, 0 };
  5196. if (read (bytes, numBytes) != numBytes)
  5197. return 0;
  5198. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5199. return (sizeByte >> 7) ? -num : num;
  5200. }
  5201. int64 InputStream::readInt64()
  5202. {
  5203. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5204. if (read (n.asBytes, 8) == 8)
  5205. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5206. return 0;
  5207. }
  5208. int64 InputStream::readInt64BigEndian()
  5209. {
  5210. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5211. if (read (n.asBytes, 8) == 8)
  5212. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5213. return 0;
  5214. }
  5215. float InputStream::readFloat()
  5216. {
  5217. // the union below relies on these types being the same size...
  5218. static_jassert (sizeof (int32) == sizeof (float));
  5219. union { int32 asInt; float asFloat; } n;
  5220. n.asInt = (int32) readInt();
  5221. return n.asFloat;
  5222. }
  5223. float InputStream::readFloatBigEndian()
  5224. {
  5225. union { int32 asInt; float asFloat; } n;
  5226. n.asInt = (int32) readIntBigEndian();
  5227. return n.asFloat;
  5228. }
  5229. double InputStream::readDouble()
  5230. {
  5231. union { int64 asInt; double asDouble; } n;
  5232. n.asInt = readInt64();
  5233. return n.asDouble;
  5234. }
  5235. double InputStream::readDoubleBigEndian()
  5236. {
  5237. union { int64 asInt; double asDouble; } n;
  5238. n.asInt = readInt64BigEndian();
  5239. return n.asDouble;
  5240. }
  5241. const String InputStream::readString()
  5242. {
  5243. MemoryBlock buffer (256);
  5244. char* data = static_cast<char*> (buffer.getData());
  5245. size_t i = 0;
  5246. while ((data[i] = readByte()) != 0)
  5247. {
  5248. if (++i >= buffer.getSize())
  5249. {
  5250. buffer.setSize (buffer.getSize() + 512);
  5251. data = static_cast<char*> (buffer.getData());
  5252. }
  5253. }
  5254. return String::fromUTF8 (data, (int) i);
  5255. }
  5256. const String InputStream::readNextLine()
  5257. {
  5258. MemoryBlock buffer (256);
  5259. char* data = static_cast<char*> (buffer.getData());
  5260. size_t i = 0;
  5261. while ((data[i] = readByte()) != 0)
  5262. {
  5263. if (data[i] == '\n')
  5264. break;
  5265. if (data[i] == '\r')
  5266. {
  5267. const int64 lastPos = getPosition();
  5268. if (readByte() != '\n')
  5269. setPosition (lastPos);
  5270. break;
  5271. }
  5272. if (++i >= buffer.getSize())
  5273. {
  5274. buffer.setSize (buffer.getSize() + 512);
  5275. data = static_cast<char*> (buffer.getData());
  5276. }
  5277. }
  5278. return String::fromUTF8 (data, (int) i);
  5279. }
  5280. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5281. {
  5282. MemoryOutputStream mo (block, true);
  5283. return mo.writeFromInputStream (*this, numBytes);
  5284. }
  5285. const String InputStream::readEntireStreamAsString()
  5286. {
  5287. MemoryOutputStream mo;
  5288. mo.writeFromInputStream (*this, -1);
  5289. return mo.toString();
  5290. }
  5291. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5292. {
  5293. if (numBytesToSkip > 0)
  5294. {
  5295. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5296. HeapBlock<char> temp (skipBufferSize);
  5297. while (numBytesToSkip > 0 && ! isExhausted())
  5298. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5299. }
  5300. }
  5301. END_JUCE_NAMESPACE
  5302. /*** End of inlined file: juce_InputStream.cpp ***/
  5303. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5304. BEGIN_JUCE_NAMESPACE
  5305. #if JUCE_DEBUG
  5306. static CriticalSection activeStreamLock;
  5307. static Array<void*> activeStreams;
  5308. void juce_CheckForDanglingStreams()
  5309. {
  5310. /*
  5311. It's always a bad idea to leak any object, but if you're leaking output
  5312. streams, then there's a good chance that you're failing to flush a file
  5313. to disk properly, which could result in corrupted data and other similar
  5314. nastiness..
  5315. */
  5316. jassert (activeStreams.size() == 0);
  5317. };
  5318. #endif
  5319. OutputStream::OutputStream()
  5320. {
  5321. #if JUCE_DEBUG
  5322. const ScopedLock sl (activeStreamLock);
  5323. activeStreams.add (this);
  5324. #endif
  5325. }
  5326. OutputStream::~OutputStream()
  5327. {
  5328. #if JUCE_DEBUG
  5329. const ScopedLock sl (activeStreamLock);
  5330. activeStreams.removeValue (this);
  5331. #endif
  5332. }
  5333. void OutputStream::writeBool (const bool b)
  5334. {
  5335. writeByte (b ? (char) 1
  5336. : (char) 0);
  5337. }
  5338. void OutputStream::writeByte (char byte)
  5339. {
  5340. write (&byte, 1);
  5341. }
  5342. void OutputStream::writeShort (short value)
  5343. {
  5344. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5345. write (&v, 2);
  5346. }
  5347. void OutputStream::writeShortBigEndian (short value)
  5348. {
  5349. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5350. write (&v, 2);
  5351. }
  5352. void OutputStream::writeInt (int value)
  5353. {
  5354. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5355. write (&v, 4);
  5356. }
  5357. void OutputStream::writeIntBigEndian (int value)
  5358. {
  5359. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5360. write (&v, 4);
  5361. }
  5362. void OutputStream::writeCompressedInt (int value)
  5363. {
  5364. unsigned int un = (value < 0) ? (unsigned int) -value
  5365. : (unsigned int) value;
  5366. uint8 data[5];
  5367. int num = 0;
  5368. while (un > 0)
  5369. {
  5370. data[++num] = (uint8) un;
  5371. un >>= 8;
  5372. }
  5373. data[0] = (uint8) num;
  5374. if (value < 0)
  5375. data[0] |= 0x80;
  5376. write (data, num + 1);
  5377. }
  5378. void OutputStream::writeInt64 (int64 value)
  5379. {
  5380. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5381. write (&v, 8);
  5382. }
  5383. void OutputStream::writeInt64BigEndian (int64 value)
  5384. {
  5385. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5386. write (&v, 8);
  5387. }
  5388. void OutputStream::writeFloat (float value)
  5389. {
  5390. union { int asInt; float asFloat; } n;
  5391. n.asFloat = value;
  5392. writeInt (n.asInt);
  5393. }
  5394. void OutputStream::writeFloatBigEndian (float value)
  5395. {
  5396. union { int asInt; float asFloat; } n;
  5397. n.asFloat = value;
  5398. writeIntBigEndian (n.asInt);
  5399. }
  5400. void OutputStream::writeDouble (double value)
  5401. {
  5402. union { int64 asInt; double asDouble; } n;
  5403. n.asDouble = value;
  5404. writeInt64 (n.asInt);
  5405. }
  5406. void OutputStream::writeDoubleBigEndian (double value)
  5407. {
  5408. union { int64 asInt; double asDouble; } n;
  5409. n.asDouble = value;
  5410. writeInt64BigEndian (n.asInt);
  5411. }
  5412. void OutputStream::writeString (const String& text)
  5413. {
  5414. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5415. // if lots of large, persistent strings were to be written to streams).
  5416. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5417. HeapBlock<char> temp (numBytes);
  5418. text.copyToUTF8 (temp, numBytes);
  5419. write (temp, numBytes);
  5420. }
  5421. void OutputStream::writeText (const String& text, const bool asUnicode,
  5422. const bool writeUnicodeHeaderBytes)
  5423. {
  5424. if (asUnicode)
  5425. {
  5426. if (writeUnicodeHeaderBytes)
  5427. write ("\x0ff\x0fe", 2);
  5428. const juce_wchar* src = text;
  5429. bool lastCharWasReturn = false;
  5430. while (*src != 0)
  5431. {
  5432. if (*src == L'\n' && ! lastCharWasReturn)
  5433. writeShort ((short) L'\r');
  5434. lastCharWasReturn = (*src == L'\r');
  5435. writeShort ((short) *src++);
  5436. }
  5437. }
  5438. else
  5439. {
  5440. const char* src = text.toUTF8();
  5441. const char* t = src;
  5442. for (;;)
  5443. {
  5444. if (*t == '\n')
  5445. {
  5446. if (t > src)
  5447. write (src, (int) (t - src));
  5448. write ("\r\n", 2);
  5449. src = t + 1;
  5450. }
  5451. else if (*t == '\r')
  5452. {
  5453. if (t[1] == '\n')
  5454. ++t;
  5455. }
  5456. else if (*t == 0)
  5457. {
  5458. if (t > src)
  5459. write (src, (int) (t - src));
  5460. break;
  5461. }
  5462. ++t;
  5463. }
  5464. }
  5465. }
  5466. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5467. {
  5468. if (numBytesToWrite < 0)
  5469. numBytesToWrite = std::numeric_limits<int64>::max();
  5470. int numWritten = 0;
  5471. while (numBytesToWrite > 0 && ! source.isExhausted())
  5472. {
  5473. char buffer [8192];
  5474. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5475. if (num <= 0)
  5476. break;
  5477. write (buffer, num);
  5478. numBytesToWrite -= num;
  5479. numWritten += num;
  5480. }
  5481. return numWritten;
  5482. }
  5483. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5484. {
  5485. return stream << String (number);
  5486. }
  5487. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5488. {
  5489. return stream << String (number);
  5490. }
  5491. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5492. {
  5493. stream.writeByte (character);
  5494. return stream;
  5495. }
  5496. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5497. {
  5498. stream.write (text, (int) strlen (text));
  5499. return stream;
  5500. }
  5501. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5502. {
  5503. stream.write (data.getData(), (int) data.getSize());
  5504. return stream;
  5505. }
  5506. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5507. {
  5508. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5509. if (in != 0)
  5510. stream.writeFromInputStream (*in, -1);
  5511. return stream;
  5512. }
  5513. END_JUCE_NAMESPACE
  5514. /*** End of inlined file: juce_OutputStream.cpp ***/
  5515. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5516. BEGIN_JUCE_NAMESPACE
  5517. DirectoryIterator::DirectoryIterator (const File& directory,
  5518. bool isRecursive_,
  5519. const String& wildCard_,
  5520. const int whatToLookFor_)
  5521. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5522. wildCard (wildCard_),
  5523. path (File::addTrailingSeparator (directory.getFullPathName())),
  5524. index (-1),
  5525. totalNumFiles (-1),
  5526. whatToLookFor (whatToLookFor_),
  5527. isRecursive (isRecursive_)
  5528. {
  5529. // you have to specify the type of files you're looking for!
  5530. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5531. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5532. }
  5533. DirectoryIterator::~DirectoryIterator()
  5534. {
  5535. }
  5536. bool DirectoryIterator::next()
  5537. {
  5538. return next (0, 0, 0, 0, 0, 0);
  5539. }
  5540. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5541. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5542. {
  5543. if (subIterator != 0)
  5544. {
  5545. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5546. return true;
  5547. subIterator = 0;
  5548. }
  5549. String filename;
  5550. bool isDirectory, isHidden;
  5551. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5552. {
  5553. ++index;
  5554. if (! filename.containsOnly ("."))
  5555. {
  5556. const File fileFound (path + filename, 0);
  5557. bool matches = false;
  5558. if (isDirectory)
  5559. {
  5560. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5561. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5562. matches = (whatToLookFor & File::findDirectories) != 0;
  5563. }
  5564. else
  5565. {
  5566. matches = (whatToLookFor & File::findFiles) != 0;
  5567. }
  5568. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5569. if (matches && isRecursive)
  5570. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5571. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5572. matches = ! isHidden;
  5573. if (matches)
  5574. {
  5575. currentFile = fileFound;
  5576. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5577. if (isDirResult != 0) *isDirResult = isDirectory;
  5578. return true;
  5579. }
  5580. else if (subIterator != 0)
  5581. {
  5582. return next();
  5583. }
  5584. }
  5585. }
  5586. return false;
  5587. }
  5588. const File DirectoryIterator::getFile() const
  5589. {
  5590. if (subIterator != 0)
  5591. return subIterator->getFile();
  5592. return currentFile;
  5593. }
  5594. float DirectoryIterator::getEstimatedProgress() const
  5595. {
  5596. if (totalNumFiles < 0)
  5597. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5598. if (totalNumFiles <= 0)
  5599. return 0.0f;
  5600. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5601. : (float) index;
  5602. return detailedIndex / totalNumFiles;
  5603. }
  5604. END_JUCE_NAMESPACE
  5605. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5606. /*** Start of inlined file: juce_File.cpp ***/
  5607. #if ! JUCE_WINDOWS
  5608. #include <pwd.h>
  5609. #endif
  5610. BEGIN_JUCE_NAMESPACE
  5611. File::File (const String& fullPathName)
  5612. : fullPath (parseAbsolutePath (fullPathName))
  5613. {
  5614. }
  5615. File::File (const String& path, int)
  5616. : fullPath (path)
  5617. {
  5618. }
  5619. const File File::createFileWithoutCheckingPath (const String& path)
  5620. {
  5621. return File (path, 0);
  5622. }
  5623. File::File (const File& other)
  5624. : fullPath (other.fullPath)
  5625. {
  5626. }
  5627. File& File::operator= (const String& newPath)
  5628. {
  5629. fullPath = parseAbsolutePath (newPath);
  5630. return *this;
  5631. }
  5632. File& File::operator= (const File& other)
  5633. {
  5634. fullPath = other.fullPath;
  5635. return *this;
  5636. }
  5637. const File File::nonexistent;
  5638. const String File::parseAbsolutePath (const String& p)
  5639. {
  5640. if (p.isEmpty())
  5641. return String::empty;
  5642. #if JUCE_WINDOWS
  5643. // Windows..
  5644. String path (p.replaceCharacter ('/', '\\'));
  5645. if (path.startsWithChar (File::separator))
  5646. {
  5647. if (path[1] != File::separator)
  5648. {
  5649. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5650. If you're trying to parse a string that may be either a relative path or an absolute path,
  5651. you MUST provide a context against which the partial path can be evaluated - you can do
  5652. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5653. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5654. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5655. */
  5656. jassertfalse;
  5657. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5658. }
  5659. }
  5660. else if (! path.containsChar (':'))
  5661. {
  5662. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5663. If you're trying to parse a string that may be either a relative path or an absolute path,
  5664. you MUST provide a context against which the partial path can be evaluated - you can do
  5665. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5666. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5667. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5668. */
  5669. jassertfalse;
  5670. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5671. }
  5672. #else
  5673. // Mac or Linux..
  5674. String path (p.replaceCharacter ('\\', '/'));
  5675. if (path.startsWithChar ('~'))
  5676. {
  5677. if (path[1] == File::separator || path[1] == 0)
  5678. {
  5679. // expand a name of the form "~/abc"
  5680. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5681. + path.substring (1);
  5682. }
  5683. else
  5684. {
  5685. // expand a name of type "~dave/abc"
  5686. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5687. struct passwd* const pw = getpwnam (userName.toUTF8());
  5688. if (pw != 0)
  5689. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5690. }
  5691. }
  5692. else if (! path.startsWithChar (File::separator))
  5693. {
  5694. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5695. If you're trying to parse a string that may be either a relative path or an absolute path,
  5696. you MUST provide a context against which the partial path can be evaluated - you can do
  5697. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5698. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5699. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5700. */
  5701. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5702. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5703. }
  5704. #endif
  5705. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5706. path = path.dropLastCharacters (1);
  5707. return path;
  5708. }
  5709. const String File::addTrailingSeparator (const String& path)
  5710. {
  5711. return path.endsWithChar (File::separator) ? path
  5712. : path + File::separator;
  5713. }
  5714. #if JUCE_LINUX
  5715. #define NAMES_ARE_CASE_SENSITIVE 1
  5716. #endif
  5717. bool File::areFileNamesCaseSensitive()
  5718. {
  5719. #if NAMES_ARE_CASE_SENSITIVE
  5720. return true;
  5721. #else
  5722. return false;
  5723. #endif
  5724. }
  5725. bool File::operator== (const File& other) const
  5726. {
  5727. #if NAMES_ARE_CASE_SENSITIVE
  5728. return fullPath == other.fullPath;
  5729. #else
  5730. return fullPath.equalsIgnoreCase (other.fullPath);
  5731. #endif
  5732. }
  5733. bool File::operator!= (const File& other) const
  5734. {
  5735. return ! operator== (other);
  5736. }
  5737. bool File::operator< (const File& other) const
  5738. {
  5739. #if NAMES_ARE_CASE_SENSITIVE
  5740. return fullPath < other.fullPath;
  5741. #else
  5742. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5743. #endif
  5744. }
  5745. bool File::operator> (const File& other) const
  5746. {
  5747. #if NAMES_ARE_CASE_SENSITIVE
  5748. return fullPath > other.fullPath;
  5749. #else
  5750. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5751. #endif
  5752. }
  5753. bool File::setReadOnly (const bool shouldBeReadOnly,
  5754. const bool applyRecursively) const
  5755. {
  5756. bool worked = true;
  5757. if (applyRecursively && isDirectory())
  5758. {
  5759. Array <File> subFiles;
  5760. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5761. for (int i = subFiles.size(); --i >= 0;)
  5762. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5763. }
  5764. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5765. }
  5766. bool File::deleteRecursively() const
  5767. {
  5768. bool worked = true;
  5769. if (isDirectory())
  5770. {
  5771. Array<File> subFiles;
  5772. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5773. for (int i = subFiles.size(); --i >= 0;)
  5774. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5775. }
  5776. return deleteFile() && worked;
  5777. }
  5778. bool File::moveFileTo (const File& newFile) const
  5779. {
  5780. if (newFile.fullPath == fullPath)
  5781. return true;
  5782. #if ! NAMES_ARE_CASE_SENSITIVE
  5783. if (*this != newFile)
  5784. #endif
  5785. if (! newFile.deleteFile())
  5786. return false;
  5787. return moveInternal (newFile);
  5788. }
  5789. bool File::copyFileTo (const File& newFile) const
  5790. {
  5791. return (*this == newFile)
  5792. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5793. }
  5794. bool File::copyDirectoryTo (const File& newDirectory) const
  5795. {
  5796. if (isDirectory() && newDirectory.createDirectory())
  5797. {
  5798. Array<File> subFiles;
  5799. findChildFiles (subFiles, File::findFiles, false);
  5800. int i;
  5801. for (i = 0; i < subFiles.size(); ++i)
  5802. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5803. return false;
  5804. subFiles.clear();
  5805. findChildFiles (subFiles, File::findDirectories, false);
  5806. for (i = 0; i < subFiles.size(); ++i)
  5807. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5808. return false;
  5809. return true;
  5810. }
  5811. return false;
  5812. }
  5813. const String File::getPathUpToLastSlash() const
  5814. {
  5815. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5816. if (lastSlash > 0)
  5817. return fullPath.substring (0, lastSlash);
  5818. else if (lastSlash == 0)
  5819. return separatorString;
  5820. else
  5821. return fullPath;
  5822. }
  5823. const File File::getParentDirectory() const
  5824. {
  5825. return File (getPathUpToLastSlash(), (int) 0);
  5826. }
  5827. const String File::getFileName() const
  5828. {
  5829. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5830. }
  5831. int File::hashCode() const
  5832. {
  5833. return fullPath.hashCode();
  5834. }
  5835. int64 File::hashCode64() const
  5836. {
  5837. return fullPath.hashCode64();
  5838. }
  5839. const String File::getFileNameWithoutExtension() const
  5840. {
  5841. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5842. const int lastDot = fullPath.lastIndexOfChar ('.');
  5843. if (lastDot > lastSlash)
  5844. return fullPath.substring (lastSlash, lastDot);
  5845. else
  5846. return fullPath.substring (lastSlash);
  5847. }
  5848. bool File::isAChildOf (const File& potentialParent) const
  5849. {
  5850. if (potentialParent == File::nonexistent)
  5851. return false;
  5852. const String ourPath (getPathUpToLastSlash());
  5853. #if NAMES_ARE_CASE_SENSITIVE
  5854. if (potentialParent.fullPath == ourPath)
  5855. #else
  5856. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5857. #endif
  5858. {
  5859. return true;
  5860. }
  5861. else if (potentialParent.fullPath.length() >= ourPath.length())
  5862. {
  5863. return false;
  5864. }
  5865. else
  5866. {
  5867. return getParentDirectory().isAChildOf (potentialParent);
  5868. }
  5869. }
  5870. bool File::isAbsolutePath (const String& path)
  5871. {
  5872. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5873. #if JUCE_WINDOWS
  5874. || (path.isNotEmpty() && path[1] == ':');
  5875. #else
  5876. || path.startsWithChar ('~');
  5877. #endif
  5878. }
  5879. const File File::getChildFile (String relativePath) const
  5880. {
  5881. if (isAbsolutePath (relativePath))
  5882. {
  5883. // the path is really absolute..
  5884. return File (relativePath);
  5885. }
  5886. else
  5887. {
  5888. // it's relative, so remove any ../ or ./ bits at the start.
  5889. String path (fullPath);
  5890. if (relativePath[0] == '.')
  5891. {
  5892. #if JUCE_WINDOWS
  5893. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5894. #else
  5895. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5896. #endif
  5897. while (relativePath[0] == '.')
  5898. {
  5899. if (relativePath[1] == '.')
  5900. {
  5901. if (relativePath [2] == 0 || relativePath[2] == separator)
  5902. {
  5903. const int lastSlash = path.lastIndexOfChar (separator);
  5904. if (lastSlash >= 0)
  5905. path = path.substring (0, lastSlash);
  5906. relativePath = relativePath.substring (3);
  5907. }
  5908. else
  5909. {
  5910. break;
  5911. }
  5912. }
  5913. else if (relativePath[1] == separator)
  5914. {
  5915. relativePath = relativePath.substring (2);
  5916. }
  5917. else
  5918. {
  5919. break;
  5920. }
  5921. }
  5922. }
  5923. return File (addTrailingSeparator (path) + relativePath);
  5924. }
  5925. }
  5926. const File File::getSiblingFile (const String& fileName) const
  5927. {
  5928. return getParentDirectory().getChildFile (fileName);
  5929. }
  5930. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5931. {
  5932. if (bytes == 1)
  5933. {
  5934. return "1 byte";
  5935. }
  5936. else if (bytes < 1024)
  5937. {
  5938. return String ((int) bytes) + " bytes";
  5939. }
  5940. else if (bytes < 1024 * 1024)
  5941. {
  5942. return String (bytes / 1024.0, 1) + " KB";
  5943. }
  5944. else if (bytes < 1024 * 1024 * 1024)
  5945. {
  5946. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5947. }
  5948. else
  5949. {
  5950. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5951. }
  5952. }
  5953. bool File::create() const
  5954. {
  5955. if (exists())
  5956. return true;
  5957. {
  5958. const File parentDir (getParentDirectory());
  5959. if (parentDir == *this || ! parentDir.createDirectory())
  5960. return false;
  5961. FileOutputStream fo (*this, 8);
  5962. }
  5963. return exists();
  5964. }
  5965. bool File::createDirectory() const
  5966. {
  5967. if (! isDirectory())
  5968. {
  5969. const File parentDir (getParentDirectory());
  5970. if (parentDir == *this || ! parentDir.createDirectory())
  5971. return false;
  5972. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5973. return isDirectory();
  5974. }
  5975. return true;
  5976. }
  5977. const Time File::getCreationTime() const
  5978. {
  5979. int64 m, a, c;
  5980. getFileTimesInternal (m, a, c);
  5981. return Time (c);
  5982. }
  5983. const Time File::getLastModificationTime() const
  5984. {
  5985. int64 m, a, c;
  5986. getFileTimesInternal (m, a, c);
  5987. return Time (m);
  5988. }
  5989. const Time File::getLastAccessTime() const
  5990. {
  5991. int64 m, a, c;
  5992. getFileTimesInternal (m, a, c);
  5993. return Time (a);
  5994. }
  5995. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5996. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5997. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5998. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5999. {
  6000. if (! existsAsFile())
  6001. return false;
  6002. FileInputStream in (*this);
  6003. return getSize() == in.readIntoMemoryBlock (destBlock);
  6004. }
  6005. const String File::loadFileAsString() const
  6006. {
  6007. if (! existsAsFile())
  6008. return String::empty;
  6009. FileInputStream in (*this);
  6010. return in.readEntireStreamAsString();
  6011. }
  6012. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  6013. {
  6014. return (whatToLookFor & (isDir ? findDirectories
  6015. : findFiles)) != 0
  6016. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  6017. }
  6018. int File::findChildFiles (Array<File>& results,
  6019. const int whatToLookFor,
  6020. const bool searchRecursively,
  6021. const String& wildCardPattern) const
  6022. {
  6023. // you have to specify the type of files you're looking for!
  6024. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  6025. int total = 0;
  6026. if (isDirectory())
  6027. {
  6028. // find child files or directories in this directory first..
  6029. String path (addTrailingSeparator (fullPath)), filename;
  6030. bool itemIsDirectory, itemIsHidden;
  6031. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  6032. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  6033. {
  6034. if (! filename.containsOnly ("."))
  6035. {
  6036. const File fileFound (path + filename, 0);
  6037. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  6038. {
  6039. results.add (fileFound);
  6040. ++total;
  6041. }
  6042. if (searchRecursively && itemIsDirectory
  6043. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  6044. {
  6045. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  6046. }
  6047. }
  6048. }
  6049. }
  6050. return total;
  6051. }
  6052. int File::getNumberOfChildFiles (const int whatToLookFor,
  6053. const String& wildCardPattern) const
  6054. {
  6055. // you have to specify the type of files you're looking for!
  6056. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  6057. int count = 0;
  6058. if (isDirectory())
  6059. {
  6060. String filename;
  6061. bool itemIsDirectory, itemIsHidden;
  6062. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  6063. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  6064. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  6065. && ! filename.containsOnly ("."))
  6066. ++count;
  6067. }
  6068. else
  6069. {
  6070. // trying to search for files inside a non-directory?
  6071. jassertfalse;
  6072. }
  6073. return count;
  6074. }
  6075. bool File::containsSubDirectories() const
  6076. {
  6077. if (isDirectory())
  6078. {
  6079. String filename;
  6080. bool itemIsDirectory;
  6081. DirectoryIterator::NativeIterator i (*this, "*");
  6082. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  6083. if (itemIsDirectory)
  6084. return true;
  6085. }
  6086. return false;
  6087. }
  6088. const File File::getNonexistentChildFile (const String& prefix_,
  6089. const String& suffix,
  6090. bool putNumbersInBrackets) const
  6091. {
  6092. File f (getChildFile (prefix_ + suffix));
  6093. if (f.exists())
  6094. {
  6095. int num = 2;
  6096. String prefix (prefix_);
  6097. // remove any bracketed numbers that may already be on the end..
  6098. if (prefix.trim().endsWithChar (')'))
  6099. {
  6100. putNumbersInBrackets = true;
  6101. const int openBracks = prefix.lastIndexOfChar ('(');
  6102. const int closeBracks = prefix.lastIndexOfChar (')');
  6103. if (openBracks > 0
  6104. && closeBracks > openBracks
  6105. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6106. {
  6107. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6108. prefix = prefix.substring (0, openBracks);
  6109. }
  6110. }
  6111. // also use brackets if it ends in a digit.
  6112. putNumbersInBrackets = putNumbersInBrackets
  6113. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6114. do
  6115. {
  6116. if (putNumbersInBrackets)
  6117. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6118. else
  6119. f = getChildFile (prefix + String (num++) + suffix);
  6120. } while (f.exists());
  6121. }
  6122. return f;
  6123. }
  6124. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6125. {
  6126. if (exists())
  6127. {
  6128. return getParentDirectory()
  6129. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6130. getFileExtension(),
  6131. putNumbersInBrackets);
  6132. }
  6133. else
  6134. {
  6135. return *this;
  6136. }
  6137. }
  6138. const String File::getFileExtension() const
  6139. {
  6140. String ext;
  6141. if (! isDirectory())
  6142. {
  6143. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6144. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6145. ext = fullPath.substring (indexOfDot);
  6146. }
  6147. return ext;
  6148. }
  6149. bool File::hasFileExtension (const String& possibleSuffix) const
  6150. {
  6151. if (possibleSuffix.isEmpty())
  6152. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6153. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6154. if (semicolon >= 0)
  6155. {
  6156. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6157. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6158. }
  6159. else
  6160. {
  6161. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6162. {
  6163. if (possibleSuffix.startsWithChar ('.'))
  6164. return true;
  6165. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6166. if (dotPos >= 0)
  6167. return fullPath [dotPos] == '.';
  6168. }
  6169. }
  6170. return false;
  6171. }
  6172. const File File::withFileExtension (const String& newExtension) const
  6173. {
  6174. if (fullPath.isEmpty())
  6175. return File::nonexistent;
  6176. String filePart (getFileName());
  6177. int i = filePart.lastIndexOfChar ('.');
  6178. if (i >= 0)
  6179. filePart = filePart.substring (0, i);
  6180. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6181. filePart << '.';
  6182. return getSiblingFile (filePart + newExtension);
  6183. }
  6184. bool File::startAsProcess (const String& parameters) const
  6185. {
  6186. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6187. }
  6188. FileInputStream* File::createInputStream() const
  6189. {
  6190. if (existsAsFile())
  6191. return new FileInputStream (*this);
  6192. return 0;
  6193. }
  6194. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6195. {
  6196. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6197. if (out->failedToOpen())
  6198. return 0;
  6199. return out.release();
  6200. }
  6201. bool File::appendData (const void* const dataToAppend,
  6202. const int numberOfBytes) const
  6203. {
  6204. if (numberOfBytes > 0)
  6205. {
  6206. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6207. if (out == 0)
  6208. return false;
  6209. out->write (dataToAppend, numberOfBytes);
  6210. }
  6211. return true;
  6212. }
  6213. bool File::replaceWithData (const void* const dataToWrite,
  6214. const int numberOfBytes) const
  6215. {
  6216. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6217. if (numberOfBytes <= 0)
  6218. return deleteFile();
  6219. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6220. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6221. return tempFile.overwriteTargetFileWithTemporary();
  6222. }
  6223. bool File::appendText (const String& text,
  6224. const bool asUnicode,
  6225. const bool writeUnicodeHeaderBytes) const
  6226. {
  6227. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6228. if (out != 0)
  6229. {
  6230. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6231. return true;
  6232. }
  6233. return false;
  6234. }
  6235. bool File::replaceWithText (const String& textToWrite,
  6236. const bool asUnicode,
  6237. const bool writeUnicodeHeaderBytes) const
  6238. {
  6239. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6240. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6241. return tempFile.overwriteTargetFileWithTemporary();
  6242. }
  6243. bool File::hasIdenticalContentTo (const File& other) const
  6244. {
  6245. if (other == *this)
  6246. return true;
  6247. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6248. {
  6249. FileInputStream in1 (*this), in2 (other);
  6250. const int bufferSize = 4096;
  6251. HeapBlock <char> buffer1, buffer2;
  6252. buffer1.malloc (bufferSize);
  6253. buffer2.malloc (bufferSize);
  6254. for (;;)
  6255. {
  6256. const int num1 = in1.read (buffer1, bufferSize);
  6257. const int num2 = in2.read (buffer2, bufferSize);
  6258. if (num1 != num2)
  6259. break;
  6260. if (num1 <= 0)
  6261. return true;
  6262. if (memcmp (buffer1, buffer2, num1) != 0)
  6263. break;
  6264. }
  6265. }
  6266. return false;
  6267. }
  6268. const String File::createLegalPathName (const String& original)
  6269. {
  6270. String s (original);
  6271. String start;
  6272. if (s[1] == ':')
  6273. {
  6274. start = s.substring (0, 2);
  6275. s = s.substring (2);
  6276. }
  6277. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6278. .substring (0, 1024);
  6279. }
  6280. const String File::createLegalFileName (const String& original)
  6281. {
  6282. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6283. const int maxLength = 128; // only the length of the filename, not the whole path
  6284. const int len = s.length();
  6285. if (len > maxLength)
  6286. {
  6287. const int lastDot = s.lastIndexOfChar ('.');
  6288. if (lastDot > jmax (0, len - 12))
  6289. {
  6290. s = s.substring (0, maxLength - (len - lastDot))
  6291. + s.substring (lastDot);
  6292. }
  6293. else
  6294. {
  6295. s = s.substring (0, maxLength);
  6296. }
  6297. }
  6298. return s;
  6299. }
  6300. const String File::getRelativePathFrom (const File& dir) const
  6301. {
  6302. String thisPath (fullPath);
  6303. {
  6304. int len = thisPath.length();
  6305. while (--len >= 0 && thisPath [len] == File::separator)
  6306. thisPath [len] = 0;
  6307. }
  6308. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6309. : dir.fullPath));
  6310. const int len = jmin (thisPath.length(), dirPath.length());
  6311. int commonBitLength = 0;
  6312. for (int i = 0; i < len; ++i)
  6313. {
  6314. #if NAMES_ARE_CASE_SENSITIVE
  6315. if (thisPath[i] != dirPath[i])
  6316. #else
  6317. if (CharacterFunctions::toLowerCase (thisPath[i])
  6318. != CharacterFunctions::toLowerCase (dirPath[i]))
  6319. #endif
  6320. {
  6321. break;
  6322. }
  6323. ++commonBitLength;
  6324. }
  6325. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6326. --commonBitLength;
  6327. // if the only common bit is the root, then just return the full path..
  6328. if (commonBitLength <= 0
  6329. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6330. return fullPath;
  6331. thisPath = thisPath.substring (commonBitLength);
  6332. dirPath = dirPath.substring (commonBitLength);
  6333. while (dirPath.isNotEmpty())
  6334. {
  6335. #if JUCE_WINDOWS
  6336. thisPath = "..\\" + thisPath;
  6337. #else
  6338. thisPath = "../" + thisPath;
  6339. #endif
  6340. const int sep = dirPath.indexOfChar (separator);
  6341. if (sep >= 0)
  6342. dirPath = dirPath.substring (sep + 1);
  6343. else
  6344. dirPath = String::empty;
  6345. }
  6346. return thisPath;
  6347. }
  6348. const File File::createTempFile (const String& fileNameEnding)
  6349. {
  6350. const File tempFile (getSpecialLocation (tempDirectory)
  6351. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6352. .withFileExtension (fileNameEnding));
  6353. if (tempFile.exists())
  6354. return createTempFile (fileNameEnding);
  6355. else
  6356. return tempFile;
  6357. }
  6358. END_JUCE_NAMESPACE
  6359. /*** End of inlined file: juce_File.cpp ***/
  6360. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6361. BEGIN_JUCE_NAMESPACE
  6362. int64 juce_fileSetPosition (void* handle, int64 pos);
  6363. FileInputStream::FileInputStream (const File& f)
  6364. : file (f),
  6365. fileHandle (0),
  6366. currentPosition (0),
  6367. totalSize (0),
  6368. needToSeek (true)
  6369. {
  6370. openHandle();
  6371. }
  6372. FileInputStream::~FileInputStream()
  6373. {
  6374. closeHandle();
  6375. }
  6376. int64 FileInputStream::getTotalLength()
  6377. {
  6378. return totalSize;
  6379. }
  6380. int FileInputStream::read (void* buffer, int bytesToRead)
  6381. {
  6382. int num = 0;
  6383. if (needToSeek)
  6384. {
  6385. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6386. return 0;
  6387. needToSeek = false;
  6388. }
  6389. num = readInternal (buffer, bytesToRead);
  6390. currentPosition += num;
  6391. return num;
  6392. }
  6393. bool FileInputStream::isExhausted()
  6394. {
  6395. return currentPosition >= totalSize;
  6396. }
  6397. int64 FileInputStream::getPosition()
  6398. {
  6399. return currentPosition;
  6400. }
  6401. bool FileInputStream::setPosition (int64 pos)
  6402. {
  6403. pos = jlimit ((int64) 0, totalSize, pos);
  6404. needToSeek |= (currentPosition != pos);
  6405. currentPosition = pos;
  6406. return true;
  6407. }
  6408. END_JUCE_NAMESPACE
  6409. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6410. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6411. BEGIN_JUCE_NAMESPACE
  6412. int64 juce_fileSetPosition (void* handle, int64 pos);
  6413. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6414. : file (f),
  6415. fileHandle (0),
  6416. currentPosition (0),
  6417. bufferSize (bufferSize_),
  6418. bytesInBuffer (0),
  6419. buffer (jmax (bufferSize_, 16))
  6420. {
  6421. openHandle();
  6422. }
  6423. FileOutputStream::~FileOutputStream()
  6424. {
  6425. flush();
  6426. closeHandle();
  6427. }
  6428. int64 FileOutputStream::getPosition()
  6429. {
  6430. return currentPosition;
  6431. }
  6432. bool FileOutputStream::setPosition (int64 newPosition)
  6433. {
  6434. if (newPosition != currentPosition)
  6435. {
  6436. flush();
  6437. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6438. }
  6439. return newPosition == currentPosition;
  6440. }
  6441. void FileOutputStream::flush()
  6442. {
  6443. if (bytesInBuffer > 0)
  6444. {
  6445. writeInternal (buffer, bytesInBuffer);
  6446. bytesInBuffer = 0;
  6447. }
  6448. flushInternal();
  6449. }
  6450. bool FileOutputStream::write (const void* const src, const int numBytes)
  6451. {
  6452. if (bytesInBuffer + numBytes < bufferSize)
  6453. {
  6454. memcpy (buffer + bytesInBuffer, src, numBytes);
  6455. bytesInBuffer += numBytes;
  6456. currentPosition += numBytes;
  6457. }
  6458. else
  6459. {
  6460. if (bytesInBuffer > 0)
  6461. {
  6462. // flush the reservoir
  6463. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6464. bytesInBuffer = 0;
  6465. if (! wroteOk)
  6466. return false;
  6467. }
  6468. if (numBytes < bufferSize)
  6469. {
  6470. memcpy (buffer + bytesInBuffer, src, numBytes);
  6471. bytesInBuffer += numBytes;
  6472. currentPosition += numBytes;
  6473. }
  6474. else
  6475. {
  6476. const int bytesWritten = writeInternal (src, numBytes);
  6477. if (bytesWritten < 0)
  6478. return false;
  6479. currentPosition += bytesWritten;
  6480. return bytesWritten == numBytes;
  6481. }
  6482. }
  6483. return true;
  6484. }
  6485. END_JUCE_NAMESPACE
  6486. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6487. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6488. BEGIN_JUCE_NAMESPACE
  6489. FileSearchPath::FileSearchPath()
  6490. {
  6491. }
  6492. FileSearchPath::FileSearchPath (const String& path)
  6493. {
  6494. init (path);
  6495. }
  6496. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6497. : directories (other.directories)
  6498. {
  6499. }
  6500. FileSearchPath::~FileSearchPath()
  6501. {
  6502. }
  6503. FileSearchPath& FileSearchPath::operator= (const String& path)
  6504. {
  6505. init (path);
  6506. return *this;
  6507. }
  6508. void FileSearchPath::init (const String& path)
  6509. {
  6510. directories.clear();
  6511. directories.addTokens (path, ";", "\"");
  6512. directories.trim();
  6513. directories.removeEmptyStrings();
  6514. for (int i = directories.size(); --i >= 0;)
  6515. directories.set (i, directories[i].unquoted());
  6516. }
  6517. int FileSearchPath::getNumPaths() const
  6518. {
  6519. return directories.size();
  6520. }
  6521. const File FileSearchPath::operator[] (const int index) const
  6522. {
  6523. return File (directories [index]);
  6524. }
  6525. const String FileSearchPath::toString() const
  6526. {
  6527. StringArray directories2 (directories);
  6528. for (int i = directories2.size(); --i >= 0;)
  6529. if (directories2[i].containsChar (';'))
  6530. directories2.set (i, directories2[i].quoted());
  6531. return directories2.joinIntoString (";");
  6532. }
  6533. void FileSearchPath::add (const File& dir, const int insertIndex)
  6534. {
  6535. directories.insert (insertIndex, dir.getFullPathName());
  6536. }
  6537. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6538. {
  6539. for (int i = 0; i < directories.size(); ++i)
  6540. if (File (directories[i]) == dir)
  6541. return;
  6542. add (dir);
  6543. }
  6544. void FileSearchPath::remove (const int index)
  6545. {
  6546. directories.remove (index);
  6547. }
  6548. void FileSearchPath::addPath (const FileSearchPath& other)
  6549. {
  6550. for (int i = 0; i < other.getNumPaths(); ++i)
  6551. addIfNotAlreadyThere (other[i]);
  6552. }
  6553. void FileSearchPath::removeRedundantPaths()
  6554. {
  6555. for (int i = directories.size(); --i >= 0;)
  6556. {
  6557. const File d1 (directories[i]);
  6558. for (int j = directories.size(); --j >= 0;)
  6559. {
  6560. const File d2 (directories[j]);
  6561. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6562. {
  6563. directories.remove (i);
  6564. break;
  6565. }
  6566. }
  6567. }
  6568. }
  6569. void FileSearchPath::removeNonExistentPaths()
  6570. {
  6571. for (int i = directories.size(); --i >= 0;)
  6572. if (! File (directories[i]).isDirectory())
  6573. directories.remove (i);
  6574. }
  6575. int FileSearchPath::findChildFiles (Array<File>& results,
  6576. const int whatToLookFor,
  6577. const bool searchRecursively,
  6578. const String& wildCardPattern) const
  6579. {
  6580. int total = 0;
  6581. for (int i = 0; i < directories.size(); ++i)
  6582. total += operator[] (i).findChildFiles (results,
  6583. whatToLookFor,
  6584. searchRecursively,
  6585. wildCardPattern);
  6586. return total;
  6587. }
  6588. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6589. const bool checkRecursively) const
  6590. {
  6591. for (int i = directories.size(); --i >= 0;)
  6592. {
  6593. const File d (directories[i]);
  6594. if (checkRecursively)
  6595. {
  6596. if (fileToCheck.isAChildOf (d))
  6597. return true;
  6598. }
  6599. else
  6600. {
  6601. if (fileToCheck.getParentDirectory() == d)
  6602. return true;
  6603. }
  6604. }
  6605. return false;
  6606. }
  6607. END_JUCE_NAMESPACE
  6608. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6609. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6610. BEGIN_JUCE_NAMESPACE
  6611. NamedPipe::NamedPipe()
  6612. : internal (0)
  6613. {
  6614. }
  6615. NamedPipe::~NamedPipe()
  6616. {
  6617. close();
  6618. }
  6619. bool NamedPipe::openExisting (const String& pipeName)
  6620. {
  6621. currentPipeName = pipeName;
  6622. return openInternal (pipeName, false);
  6623. }
  6624. bool NamedPipe::createNewPipe (const String& pipeName)
  6625. {
  6626. currentPipeName = pipeName;
  6627. return openInternal (pipeName, true);
  6628. }
  6629. bool NamedPipe::isOpen() const
  6630. {
  6631. return internal != 0;
  6632. }
  6633. const String NamedPipe::getName() const
  6634. {
  6635. return currentPipeName;
  6636. }
  6637. // other methods for this class are implemented in the platform-specific files
  6638. END_JUCE_NAMESPACE
  6639. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6640. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6641. BEGIN_JUCE_NAMESPACE
  6642. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6643. {
  6644. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6645. "temp_" + String (Random::getSystemRandom().nextInt()),
  6646. suffix,
  6647. optionFlags);
  6648. }
  6649. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6650. : targetFile (targetFile_)
  6651. {
  6652. // If you use this constructor, you need to give it a valid target file!
  6653. jassert (targetFile != File::nonexistent);
  6654. createTempFile (targetFile.getParentDirectory(),
  6655. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6656. targetFile.getFileExtension(),
  6657. optionFlags);
  6658. }
  6659. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6660. const String& suffix, const int optionFlags)
  6661. {
  6662. if ((optionFlags & useHiddenFile) != 0)
  6663. name = "." + name;
  6664. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6665. }
  6666. TemporaryFile::~TemporaryFile()
  6667. {
  6668. if (! deleteTemporaryFile())
  6669. {
  6670. /* Failed to delete our temporary file! The most likely reason for this would be
  6671. that you've not closed an output stream that was being used to write to file.
  6672. If you find that something beyond your control is changing permissions on
  6673. your temporary files and preventing them from being deleted, you may want to
  6674. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6675. handle them appropriately.
  6676. */
  6677. jassertfalse;
  6678. }
  6679. }
  6680. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6681. {
  6682. // This method only works if you created this object with the constructor
  6683. // that takes a target file!
  6684. jassert (targetFile != File::nonexistent);
  6685. if (temporaryFile.exists())
  6686. {
  6687. // Have a few attempts at overwriting the file before giving up..
  6688. for (int i = 5; --i >= 0;)
  6689. {
  6690. if (temporaryFile.moveFileTo (targetFile))
  6691. return true;
  6692. Thread::sleep (100);
  6693. }
  6694. }
  6695. else
  6696. {
  6697. // There's no temporary file to use. If your write failed, you should
  6698. // probably check, and not bother calling this method.
  6699. jassertfalse;
  6700. }
  6701. return false;
  6702. }
  6703. bool TemporaryFile::deleteTemporaryFile() const
  6704. {
  6705. // Have a few attempts at deleting the file before giving up..
  6706. for (int i = 5; --i >= 0;)
  6707. {
  6708. if (temporaryFile.deleteFile())
  6709. return true;
  6710. Thread::sleep (50);
  6711. }
  6712. return false;
  6713. }
  6714. END_JUCE_NAMESPACE
  6715. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6716. /*** Start of inlined file: juce_Socket.cpp ***/
  6717. #if JUCE_WINDOWS
  6718. #include <winsock2.h>
  6719. #if JUCE_MSVC
  6720. #pragma warning (push)
  6721. #pragma warning (disable : 4127 4389 4018)
  6722. #endif
  6723. #else
  6724. #if JUCE_LINUX
  6725. #include <sys/types.h>
  6726. #include <sys/socket.h>
  6727. #include <sys/errno.h>
  6728. #include <unistd.h>
  6729. #include <netinet/in.h>
  6730. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6731. #include <CoreServices/CoreServices.h>
  6732. #endif
  6733. #include <fcntl.h>
  6734. #include <netdb.h>
  6735. #include <arpa/inet.h>
  6736. #include <netinet/tcp.h>
  6737. #endif
  6738. BEGIN_JUCE_NAMESPACE
  6739. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6740. typedef socklen_t juce_socklen_t;
  6741. #else
  6742. typedef int juce_socklen_t;
  6743. #endif
  6744. #if JUCE_WINDOWS
  6745. namespace SocketHelpers
  6746. {
  6747. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6748. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6749. }
  6750. static void initWin32Sockets()
  6751. {
  6752. static CriticalSection lock;
  6753. const ScopedLock sl (lock);
  6754. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6755. {
  6756. WSADATA wsaData;
  6757. const WORD wVersionRequested = MAKEWORD (1, 1);
  6758. WSAStartup (wVersionRequested, &wsaData);
  6759. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6760. }
  6761. }
  6762. void juce_shutdownWin32Sockets()
  6763. {
  6764. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6765. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6766. }
  6767. #endif
  6768. namespace SocketHelpers
  6769. {
  6770. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6771. {
  6772. const int sndBufSize = 65536;
  6773. const int rcvBufSize = 65536;
  6774. const int one = 1;
  6775. return handle > 0
  6776. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6777. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6778. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6779. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6780. }
  6781. static bool bindSocketToPort (const int handle, const int port) throw()
  6782. {
  6783. if (handle <= 0 || port <= 0)
  6784. return false;
  6785. struct sockaddr_in servTmpAddr;
  6786. zerostruct (servTmpAddr);
  6787. servTmpAddr.sin_family = PF_INET;
  6788. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6789. servTmpAddr.sin_port = htons ((uint16) port);
  6790. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6791. }
  6792. static int readSocket (const int handle,
  6793. void* const destBuffer, const int maxBytesToRead,
  6794. bool volatile& connected,
  6795. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6796. {
  6797. int bytesRead = 0;
  6798. while (bytesRead < maxBytesToRead)
  6799. {
  6800. int bytesThisTime;
  6801. #if JUCE_WINDOWS
  6802. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6803. #else
  6804. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  6805. && errno == EINTR
  6806. && connected)
  6807. {
  6808. }
  6809. #endif
  6810. if (bytesThisTime <= 0 || ! connected)
  6811. {
  6812. if (bytesRead == 0)
  6813. bytesRead = -1;
  6814. break;
  6815. }
  6816. bytesRead += bytesThisTime;
  6817. if (! blockUntilSpecifiedAmountHasArrived)
  6818. break;
  6819. }
  6820. return bytesRead;
  6821. }
  6822. static int waitForReadiness (const int handle, const bool forReading,
  6823. const int timeoutMsecs) throw()
  6824. {
  6825. struct timeval timeout;
  6826. struct timeval* timeoutp;
  6827. if (timeoutMsecs >= 0)
  6828. {
  6829. timeout.tv_sec = timeoutMsecs / 1000;
  6830. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6831. timeoutp = &timeout;
  6832. }
  6833. else
  6834. {
  6835. timeoutp = 0;
  6836. }
  6837. fd_set rset, wset;
  6838. FD_ZERO (&rset);
  6839. FD_SET (handle, &rset);
  6840. FD_ZERO (&wset);
  6841. FD_SET (handle, &wset);
  6842. fd_set* const prset = forReading ? &rset : 0;
  6843. fd_set* const pwset = forReading ? 0 : &wset;
  6844. #if JUCE_WINDOWS
  6845. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6846. return -1;
  6847. #else
  6848. {
  6849. int result;
  6850. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6851. && errno == EINTR)
  6852. {
  6853. }
  6854. if (result < 0)
  6855. return -1;
  6856. }
  6857. #endif
  6858. {
  6859. int opt;
  6860. juce_socklen_t len = sizeof (opt);
  6861. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6862. || opt != 0)
  6863. return -1;
  6864. }
  6865. if ((forReading && FD_ISSET (handle, &rset))
  6866. || ((! forReading) && FD_ISSET (handle, &wset)))
  6867. return 1;
  6868. return 0;
  6869. }
  6870. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6871. {
  6872. #if JUCE_WINDOWS
  6873. u_long nonBlocking = shouldBlock ? 0 : 1;
  6874. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6875. return false;
  6876. #else
  6877. int socketFlags = fcntl (handle, F_GETFL, 0);
  6878. if (socketFlags == -1)
  6879. return false;
  6880. if (shouldBlock)
  6881. socketFlags &= ~O_NONBLOCK;
  6882. else
  6883. socketFlags |= O_NONBLOCK;
  6884. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6885. return false;
  6886. #endif
  6887. return true;
  6888. }
  6889. static bool connectSocket (int volatile& handle,
  6890. const bool isDatagram,
  6891. void** serverAddress,
  6892. const String& hostName,
  6893. const int portNumber,
  6894. const int timeOutMillisecs) throw()
  6895. {
  6896. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6897. if (hostEnt == 0)
  6898. return false;
  6899. struct in_addr targetAddress;
  6900. memcpy (&targetAddress.s_addr,
  6901. *(hostEnt->h_addr_list),
  6902. sizeof (targetAddress.s_addr));
  6903. struct sockaddr_in servTmpAddr;
  6904. zerostruct (servTmpAddr);
  6905. servTmpAddr.sin_family = PF_INET;
  6906. servTmpAddr.sin_addr = targetAddress;
  6907. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6908. if (handle < 0)
  6909. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6910. if (handle < 0)
  6911. return false;
  6912. if (isDatagram)
  6913. {
  6914. *serverAddress = new struct sockaddr_in();
  6915. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6916. return true;
  6917. }
  6918. setSocketBlockingState (handle, false);
  6919. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6920. if (result < 0)
  6921. {
  6922. #if JUCE_WINDOWS
  6923. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6924. #else
  6925. if (errno == EINPROGRESS)
  6926. #endif
  6927. {
  6928. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6929. {
  6930. setSocketBlockingState (handle, true);
  6931. return false;
  6932. }
  6933. }
  6934. }
  6935. setSocketBlockingState (handle, true);
  6936. resetSocketOptions (handle, false, false);
  6937. return true;
  6938. }
  6939. }
  6940. StreamingSocket::StreamingSocket()
  6941. : portNumber (0),
  6942. handle (-1),
  6943. connected (false),
  6944. isListener (false)
  6945. {
  6946. #if JUCE_WINDOWS
  6947. initWin32Sockets();
  6948. #endif
  6949. }
  6950. StreamingSocket::StreamingSocket (const String& hostName_,
  6951. const int portNumber_,
  6952. const int handle_)
  6953. : hostName (hostName_),
  6954. portNumber (portNumber_),
  6955. handle (handle_),
  6956. connected (true),
  6957. isListener (false)
  6958. {
  6959. #if JUCE_WINDOWS
  6960. initWin32Sockets();
  6961. #endif
  6962. SocketHelpers::resetSocketOptions (handle_, false, false);
  6963. }
  6964. StreamingSocket::~StreamingSocket()
  6965. {
  6966. close();
  6967. }
  6968. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6969. {
  6970. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6971. : -1;
  6972. }
  6973. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6974. {
  6975. if (isListener || ! connected)
  6976. return -1;
  6977. #if JUCE_WINDOWS
  6978. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6979. #else
  6980. int result;
  6981. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6982. && errno == EINTR)
  6983. {
  6984. }
  6985. return result;
  6986. #endif
  6987. }
  6988. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6989. const int timeoutMsecs) const
  6990. {
  6991. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6992. : -1;
  6993. }
  6994. bool StreamingSocket::bindToPort (const int port)
  6995. {
  6996. return SocketHelpers::bindSocketToPort (handle, port);
  6997. }
  6998. bool StreamingSocket::connect (const String& remoteHostName,
  6999. const int remotePortNumber,
  7000. const int timeOutMillisecs)
  7001. {
  7002. if (isListener)
  7003. {
  7004. jassertfalse; // a listener socket can't connect to another one!
  7005. return false;
  7006. }
  7007. if (connected)
  7008. close();
  7009. hostName = remoteHostName;
  7010. portNumber = remotePortNumber;
  7011. isListener = false;
  7012. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7013. remotePortNumber, timeOutMillisecs);
  7014. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7015. {
  7016. close();
  7017. return false;
  7018. }
  7019. return true;
  7020. }
  7021. void StreamingSocket::close()
  7022. {
  7023. #if JUCE_WINDOWS
  7024. if (handle != SOCKET_ERROR || connected)
  7025. closesocket (handle);
  7026. connected = false;
  7027. #else
  7028. if (connected)
  7029. {
  7030. connected = false;
  7031. if (isListener)
  7032. {
  7033. // need to do this to interrupt the accept() function..
  7034. StreamingSocket temp;
  7035. temp.connect ("localhost", portNumber, 1000);
  7036. }
  7037. }
  7038. if (handle != -1)
  7039. ::close (handle);
  7040. #endif
  7041. hostName = String::empty;
  7042. portNumber = 0;
  7043. handle = -1;
  7044. isListener = false;
  7045. }
  7046. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7047. {
  7048. if (connected)
  7049. close();
  7050. hostName = "listener";
  7051. portNumber = newPortNumber;
  7052. isListener = true;
  7053. struct sockaddr_in servTmpAddr;
  7054. zerostruct (servTmpAddr);
  7055. servTmpAddr.sin_family = PF_INET;
  7056. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7057. if (localHostName.isNotEmpty())
  7058. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7059. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7060. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7061. if (handle < 0)
  7062. return false;
  7063. const int reuse = 1;
  7064. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7065. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7066. || listen (handle, SOMAXCONN) < 0)
  7067. {
  7068. close();
  7069. return false;
  7070. }
  7071. connected = true;
  7072. return true;
  7073. }
  7074. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7075. {
  7076. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7077. // prepare this socket as a listener.
  7078. if (connected && isListener)
  7079. {
  7080. struct sockaddr address;
  7081. juce_socklen_t len = sizeof (sockaddr);
  7082. const int newSocket = (int) accept (handle, &address, &len);
  7083. if (newSocket >= 0 && connected)
  7084. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7085. portNumber, newSocket);
  7086. }
  7087. return 0;
  7088. }
  7089. bool StreamingSocket::isLocal() const throw()
  7090. {
  7091. return hostName == "127.0.0.1";
  7092. }
  7093. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7094. : portNumber (0),
  7095. handle (-1),
  7096. connected (true),
  7097. allowBroadcast (allowBroadcast_),
  7098. serverAddress (0)
  7099. {
  7100. #if JUCE_WINDOWS
  7101. initWin32Sockets();
  7102. #endif
  7103. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7104. bindToPort (localPortNumber);
  7105. }
  7106. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7107. const int handle_, const int localPortNumber)
  7108. : hostName (hostName_),
  7109. portNumber (portNumber_),
  7110. handle (handle_),
  7111. connected (true),
  7112. allowBroadcast (false),
  7113. serverAddress (0)
  7114. {
  7115. #if JUCE_WINDOWS
  7116. initWin32Sockets();
  7117. #endif
  7118. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7119. bindToPort (localPortNumber);
  7120. }
  7121. DatagramSocket::~DatagramSocket()
  7122. {
  7123. close();
  7124. delete static_cast <struct sockaddr_in*> (serverAddress);
  7125. serverAddress = 0;
  7126. }
  7127. void DatagramSocket::close()
  7128. {
  7129. #if JUCE_WINDOWS
  7130. closesocket (handle);
  7131. connected = false;
  7132. #else
  7133. connected = false;
  7134. ::close (handle);
  7135. #endif
  7136. hostName = String::empty;
  7137. portNumber = 0;
  7138. handle = -1;
  7139. }
  7140. bool DatagramSocket::bindToPort (const int port)
  7141. {
  7142. return SocketHelpers::bindSocketToPort (handle, port);
  7143. }
  7144. bool DatagramSocket::connect (const String& remoteHostName,
  7145. const int remotePortNumber,
  7146. const int timeOutMillisecs)
  7147. {
  7148. if (connected)
  7149. close();
  7150. hostName = remoteHostName;
  7151. portNumber = remotePortNumber;
  7152. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7153. remoteHostName, remotePortNumber,
  7154. timeOutMillisecs);
  7155. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7156. {
  7157. close();
  7158. return false;
  7159. }
  7160. return true;
  7161. }
  7162. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7163. {
  7164. struct sockaddr address;
  7165. juce_socklen_t len = sizeof (sockaddr);
  7166. while (waitUntilReady (true, -1) == 1)
  7167. {
  7168. char buf[1];
  7169. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7170. {
  7171. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7172. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7173. -1, -1);
  7174. }
  7175. }
  7176. return 0;
  7177. }
  7178. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7179. const int timeoutMsecs) const
  7180. {
  7181. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7182. : -1;
  7183. }
  7184. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7185. {
  7186. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7187. : -1;
  7188. }
  7189. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7190. {
  7191. // You need to call connect() first to set the server address..
  7192. jassert (serverAddress != 0 && connected);
  7193. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7194. numBytesToWrite, 0,
  7195. (const struct sockaddr*) serverAddress,
  7196. sizeof (struct sockaddr_in))
  7197. : -1;
  7198. }
  7199. bool DatagramSocket::isLocal() const throw()
  7200. {
  7201. return hostName == "127.0.0.1";
  7202. }
  7203. #if JUCE_MSVC
  7204. #pragma warning (pop)
  7205. #endif
  7206. END_JUCE_NAMESPACE
  7207. /*** End of inlined file: juce_Socket.cpp ***/
  7208. /*** Start of inlined file: juce_URL.cpp ***/
  7209. BEGIN_JUCE_NAMESPACE
  7210. URL::URL()
  7211. {
  7212. }
  7213. URL::URL (const String& url_)
  7214. : url (url_)
  7215. {
  7216. int i = url.indexOfChar ('?');
  7217. if (i >= 0)
  7218. {
  7219. do
  7220. {
  7221. const int nextAmp = url.indexOfChar (i + 1, '&');
  7222. const int equalsPos = url.indexOfChar (i + 1, '=');
  7223. if (equalsPos > i + 1)
  7224. {
  7225. if (nextAmp < 0)
  7226. {
  7227. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7228. removeEscapeChars (url.substring (equalsPos + 1)));
  7229. }
  7230. else if (nextAmp > 0 && equalsPos < nextAmp)
  7231. {
  7232. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7233. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7234. }
  7235. }
  7236. i = nextAmp;
  7237. }
  7238. while (i >= 0);
  7239. url = url.upToFirstOccurrenceOf ("?", false, false);
  7240. }
  7241. }
  7242. URL::URL (const URL& other)
  7243. : url (other.url),
  7244. postData (other.postData),
  7245. parameters (other.parameters),
  7246. filesToUpload (other.filesToUpload),
  7247. mimeTypes (other.mimeTypes)
  7248. {
  7249. }
  7250. URL& URL::operator= (const URL& other)
  7251. {
  7252. url = other.url;
  7253. postData = other.postData;
  7254. parameters = other.parameters;
  7255. filesToUpload = other.filesToUpload;
  7256. mimeTypes = other.mimeTypes;
  7257. return *this;
  7258. }
  7259. URL::~URL()
  7260. {
  7261. }
  7262. static const String getMangledParameters (const StringPairArray& parameters)
  7263. {
  7264. String p;
  7265. for (int i = 0; i < parameters.size(); ++i)
  7266. {
  7267. if (i > 0)
  7268. p += '&';
  7269. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7270. << '='
  7271. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7272. }
  7273. return p;
  7274. }
  7275. const String URL::toString (const bool includeGetParameters) const
  7276. {
  7277. if (includeGetParameters && parameters.size() > 0)
  7278. return url + "?" + getMangledParameters (parameters);
  7279. else
  7280. return url;
  7281. }
  7282. bool URL::isWellFormed() const
  7283. {
  7284. //xxx TODO
  7285. return url.isNotEmpty();
  7286. }
  7287. static int findStartOfDomain (const String& url)
  7288. {
  7289. int i = 0;
  7290. while (CharacterFunctions::isLetterOrDigit (url[i])
  7291. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7292. ++i;
  7293. return url[i] == ':' ? i + 1 : 0;
  7294. }
  7295. const String URL::getDomain() const
  7296. {
  7297. int start = findStartOfDomain (url);
  7298. while (url[start] == '/')
  7299. ++start;
  7300. const int end1 = url.indexOfChar (start, '/');
  7301. const int end2 = url.indexOfChar (start, ':');
  7302. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7303. : jmin (end1, end2);
  7304. return url.substring (start, end);
  7305. }
  7306. const String URL::getSubPath() const
  7307. {
  7308. int start = findStartOfDomain (url);
  7309. while (url[start] == '/')
  7310. ++start;
  7311. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7312. return startOfPath <= 0 ? String::empty
  7313. : url.substring (startOfPath);
  7314. }
  7315. const String URL::getScheme() const
  7316. {
  7317. return url.substring (0, findStartOfDomain (url) - 1);
  7318. }
  7319. const URL URL::withNewSubPath (const String& newPath) const
  7320. {
  7321. int start = findStartOfDomain (url);
  7322. while (url[start] == '/')
  7323. ++start;
  7324. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7325. URL u (*this);
  7326. if (startOfPath > 0)
  7327. u.url = url.substring (0, startOfPath);
  7328. if (! u.url.endsWithChar ('/'))
  7329. u.url << '/';
  7330. if (newPath.startsWithChar ('/'))
  7331. u.url << newPath.substring (1);
  7332. else
  7333. u.url << newPath;
  7334. return u;
  7335. }
  7336. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7337. {
  7338. if (possibleURL.startsWithIgnoreCase ("http:")
  7339. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7340. return true;
  7341. if (possibleURL.startsWithIgnoreCase ("file:")
  7342. || possibleURL.containsChar ('@')
  7343. || possibleURL.endsWithChar ('.')
  7344. || (! possibleURL.containsChar ('.')))
  7345. return false;
  7346. if (possibleURL.startsWithIgnoreCase ("www.")
  7347. && possibleURL.substring (5).containsChar ('.'))
  7348. return true;
  7349. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7350. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7351. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7352. return true;
  7353. return false;
  7354. }
  7355. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7356. {
  7357. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7358. return atSign > 0
  7359. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7360. && (! possibleEmailAddress.endsWithChar ('.'));
  7361. }
  7362. void* juce_openInternetFile (const String& url,
  7363. const String& headers,
  7364. const MemoryBlock& optionalPostData,
  7365. const bool isPost,
  7366. URL::OpenStreamProgressCallback* callback,
  7367. void* callbackContext,
  7368. int timeOutMs);
  7369. void juce_closeInternetFile (void* handle);
  7370. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7371. int juce_seekInInternetFile (void* handle, int newPosition);
  7372. int64 juce_getInternetFileContentLength (void* handle);
  7373. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7374. class WebInputStream : public InputStream
  7375. {
  7376. public:
  7377. WebInputStream (const URL& url,
  7378. const bool isPost_,
  7379. URL::OpenStreamProgressCallback* const progressCallback_,
  7380. void* const progressCallbackContext_,
  7381. const String& extraHeaders,
  7382. const int timeOutMs_,
  7383. StringPairArray* const responseHeaders)
  7384. : position (0),
  7385. finished (false),
  7386. isPost (isPost_),
  7387. progressCallback (progressCallback_),
  7388. progressCallbackContext (progressCallbackContext_),
  7389. timeOutMs (timeOutMs_)
  7390. {
  7391. server = url.toString (! isPost);
  7392. if (isPost_)
  7393. createHeadersAndPostData (url);
  7394. headers += extraHeaders;
  7395. if (! headers.endsWithChar ('\n'))
  7396. headers << "\r\n";
  7397. handle = juce_openInternetFile (server, headers, postData, isPost,
  7398. progressCallback_, progressCallbackContext_,
  7399. timeOutMs);
  7400. if (responseHeaders != 0)
  7401. juce_getInternetFileHeaders (handle, *responseHeaders);
  7402. }
  7403. ~WebInputStream()
  7404. {
  7405. juce_closeInternetFile (handle);
  7406. }
  7407. bool isError() const { return handle == 0; }
  7408. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7409. bool isExhausted() { return finished; }
  7410. int64 getPosition() { return position; }
  7411. int read (void* dest, int bytes)
  7412. {
  7413. if (finished || isError())
  7414. {
  7415. return 0;
  7416. }
  7417. else
  7418. {
  7419. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7420. position += bytesRead;
  7421. if (bytesRead == 0)
  7422. finished = true;
  7423. return bytesRead;
  7424. }
  7425. }
  7426. bool setPosition (int64 wantedPos)
  7427. {
  7428. if (wantedPos != position)
  7429. {
  7430. finished = false;
  7431. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7432. if (actualPos == wantedPos)
  7433. {
  7434. position = wantedPos;
  7435. }
  7436. else
  7437. {
  7438. if (wantedPos < position)
  7439. {
  7440. juce_closeInternetFile (handle);
  7441. position = 0;
  7442. finished = false;
  7443. handle = juce_openInternetFile (server, headers, postData, isPost,
  7444. progressCallback, progressCallbackContext,
  7445. timeOutMs);
  7446. }
  7447. skipNextBytes (wantedPos - position);
  7448. }
  7449. }
  7450. return true;
  7451. }
  7452. juce_UseDebuggingNewOperator
  7453. private:
  7454. String server, headers;
  7455. MemoryBlock postData;
  7456. int64 position;
  7457. bool finished;
  7458. const bool isPost;
  7459. void* handle;
  7460. URL::OpenStreamProgressCallback* const progressCallback;
  7461. void* const progressCallbackContext;
  7462. const int timeOutMs;
  7463. void createHeadersAndPostData (const URL& url)
  7464. {
  7465. MemoryOutputStream data (postData, false);
  7466. if (url.getFilesToUpload().size() > 0)
  7467. {
  7468. // need to upload some files, so do it as multi-part...
  7469. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7470. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7471. data << "--" << boundary;
  7472. int i;
  7473. for (i = 0; i < url.getParameters().size(); ++i)
  7474. {
  7475. data << "\r\nContent-Disposition: form-data; name=\""
  7476. << url.getParameters().getAllKeys() [i]
  7477. << "\"\r\n\r\n"
  7478. << url.getParameters().getAllValues() [i]
  7479. << "\r\n--"
  7480. << boundary;
  7481. }
  7482. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7483. {
  7484. const File file (url.getFilesToUpload().getAllValues() [i]);
  7485. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7486. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7487. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7488. const String mimeType (url.getMimeTypesOfUploadFiles()
  7489. .getValue (paramName, String::empty));
  7490. if (mimeType.isNotEmpty())
  7491. data << "Content-Type: " << mimeType << "\r\n";
  7492. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7493. << file << "\r\n--" << boundary;
  7494. }
  7495. data << "--\r\n";
  7496. data.flush();
  7497. }
  7498. else
  7499. {
  7500. data << getMangledParameters (url.getParameters())
  7501. << url.getPostData();
  7502. data.flush();
  7503. // just a short text attachment, so use simple url encoding..
  7504. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7505. + String ((unsigned int) postData.getSize())
  7506. + "\r\n";
  7507. }
  7508. }
  7509. WebInputStream (const WebInputStream&);
  7510. WebInputStream& operator= (const WebInputStream&);
  7511. };
  7512. InputStream* URL::createInputStream (const bool usePostCommand,
  7513. OpenStreamProgressCallback* const progressCallback,
  7514. void* const progressCallbackContext,
  7515. const String& extraHeaders,
  7516. const int timeOutMs,
  7517. StringPairArray* const responseHeaders) const
  7518. {
  7519. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7520. progressCallback, progressCallbackContext,
  7521. extraHeaders, timeOutMs, responseHeaders));
  7522. return wi->isError() ? 0 : wi.release();
  7523. }
  7524. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7525. const bool usePostCommand) const
  7526. {
  7527. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7528. if (in != 0)
  7529. {
  7530. in->readIntoMemoryBlock (destData);
  7531. return true;
  7532. }
  7533. return false;
  7534. }
  7535. const String URL::readEntireTextStream (const bool usePostCommand) const
  7536. {
  7537. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7538. if (in != 0)
  7539. return in->readEntireStreamAsString();
  7540. return String::empty;
  7541. }
  7542. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7543. {
  7544. XmlDocument doc (readEntireTextStream (usePostCommand));
  7545. return doc.getDocumentElement();
  7546. }
  7547. const URL URL::withParameter (const String& parameterName,
  7548. const String& parameterValue) const
  7549. {
  7550. URL u (*this);
  7551. u.parameters.set (parameterName, parameterValue);
  7552. return u;
  7553. }
  7554. const URL URL::withFileToUpload (const String& parameterName,
  7555. const File& fileToUpload,
  7556. const String& mimeType) const
  7557. {
  7558. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7559. URL u (*this);
  7560. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7561. u.mimeTypes.set (parameterName, mimeType);
  7562. return u;
  7563. }
  7564. const URL URL::withPOSTData (const String& postData_) const
  7565. {
  7566. URL u (*this);
  7567. u.postData = postData_;
  7568. return u;
  7569. }
  7570. const StringPairArray& URL::getParameters() const
  7571. {
  7572. return parameters;
  7573. }
  7574. const StringPairArray& URL::getFilesToUpload() const
  7575. {
  7576. return filesToUpload;
  7577. }
  7578. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7579. {
  7580. return mimeTypes;
  7581. }
  7582. const String URL::removeEscapeChars (const String& s)
  7583. {
  7584. String result (s.replaceCharacter ('+', ' '));
  7585. int nextPercent = 0;
  7586. for (;;)
  7587. {
  7588. nextPercent = result.indexOfChar (nextPercent, '%');
  7589. if (nextPercent < 0)
  7590. break;
  7591. int hexDigit1 = 0, hexDigit2 = 0;
  7592. if ((hexDigit1 = CharacterFunctions::getHexDigitValue (result [nextPercent + 1])) >= 0
  7593. && (hexDigit2 = CharacterFunctions::getHexDigitValue (result [nextPercent + 2])) >= 0)
  7594. {
  7595. const juce_wchar replacementChar = (juce_wchar) ((hexDigit1 << 4) + hexDigit2);
  7596. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  7597. }
  7598. ++nextPercent;
  7599. }
  7600. return result;
  7601. }
  7602. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7603. {
  7604. String result;
  7605. result.preallocateStorage (s.length() + 8);
  7606. const char* utf8 = s.toUTF8();
  7607. const char* legalChars = isParameter ? "_-.*!'()"
  7608. : "_-$.*!'(),";
  7609. while (*utf8 != 0)
  7610. {
  7611. const char c = *utf8++;
  7612. if (CharacterFunctions::isLetterOrDigit (c)
  7613. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  7614. {
  7615. result << c;
  7616. }
  7617. else
  7618. {
  7619. const int v = (int) (uint8) c;
  7620. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  7621. }
  7622. }
  7623. return result;
  7624. }
  7625. bool URL::launchInDefaultBrowser() const
  7626. {
  7627. String u (toString (true));
  7628. if (u.containsChar ('@') && ! u.containsChar (':'))
  7629. u = "mailto:" + u;
  7630. return PlatformUtilities::openDocument (u, String::empty);
  7631. }
  7632. END_JUCE_NAMESPACE
  7633. /*** End of inlined file: juce_URL.cpp ***/
  7634. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7635. BEGIN_JUCE_NAMESPACE
  7636. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  7637. const int bufferSize_,
  7638. const bool deleteSourceWhenDestroyed)
  7639. : source (source_),
  7640. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  7641. bufferSize (jmax (256, bufferSize_)),
  7642. position (source_->getPosition()),
  7643. lastReadPos (0),
  7644. bufferOverlap (128)
  7645. {
  7646. const int sourceSize = (int) source_->getTotalLength();
  7647. if (sourceSize >= 0)
  7648. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  7649. bufferStart = position;
  7650. buffer.malloc (bufferSize);
  7651. }
  7652. BufferedInputStream::~BufferedInputStream()
  7653. {
  7654. }
  7655. int64 BufferedInputStream::getTotalLength()
  7656. {
  7657. return source->getTotalLength();
  7658. }
  7659. int64 BufferedInputStream::getPosition()
  7660. {
  7661. return position;
  7662. }
  7663. bool BufferedInputStream::setPosition (int64 newPosition)
  7664. {
  7665. position = jmax ((int64) 0, newPosition);
  7666. return true;
  7667. }
  7668. bool BufferedInputStream::isExhausted()
  7669. {
  7670. return (position >= lastReadPos)
  7671. && source->isExhausted();
  7672. }
  7673. void BufferedInputStream::ensureBuffered()
  7674. {
  7675. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7676. if (position < bufferStart || position >= bufferEndOverlap)
  7677. {
  7678. int bytesRead;
  7679. if (position < lastReadPos
  7680. && position >= bufferEndOverlap
  7681. && position >= bufferStart)
  7682. {
  7683. const int bytesToKeep = (int) (lastReadPos - position);
  7684. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7685. bufferStart = position;
  7686. bytesRead = source->read (buffer + bytesToKeep,
  7687. bufferSize - bytesToKeep);
  7688. lastReadPos += bytesRead;
  7689. bytesRead += bytesToKeep;
  7690. }
  7691. else
  7692. {
  7693. bufferStart = position;
  7694. source->setPosition (bufferStart);
  7695. bytesRead = source->read (buffer, bufferSize);
  7696. lastReadPos = bufferStart + bytesRead;
  7697. }
  7698. while (bytesRead < bufferSize)
  7699. buffer [bytesRead++] = 0;
  7700. }
  7701. }
  7702. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7703. {
  7704. if (position >= bufferStart
  7705. && position + maxBytesToRead <= lastReadPos)
  7706. {
  7707. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7708. position += maxBytesToRead;
  7709. return maxBytesToRead;
  7710. }
  7711. else
  7712. {
  7713. if (position < bufferStart || position >= lastReadPos)
  7714. ensureBuffered();
  7715. int bytesRead = 0;
  7716. while (maxBytesToRead > 0)
  7717. {
  7718. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7719. if (bytesAvailable > 0)
  7720. {
  7721. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7722. maxBytesToRead -= bytesAvailable;
  7723. bytesRead += bytesAvailable;
  7724. position += bytesAvailable;
  7725. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7726. }
  7727. const int64 oldLastReadPos = lastReadPos;
  7728. ensureBuffered();
  7729. if (oldLastReadPos == lastReadPos)
  7730. break; // if ensureBuffered() failed to read any more data, bail out
  7731. if (isExhausted())
  7732. break;
  7733. }
  7734. return bytesRead;
  7735. }
  7736. }
  7737. const String BufferedInputStream::readString()
  7738. {
  7739. if (position >= bufferStart
  7740. && position < lastReadPos)
  7741. {
  7742. const int maxChars = (int) (lastReadPos - position);
  7743. const char* const src = buffer + (int) (position - bufferStart);
  7744. for (int i = 0; i < maxChars; ++i)
  7745. {
  7746. if (src[i] == 0)
  7747. {
  7748. position += i + 1;
  7749. return String::fromUTF8 (src, i);
  7750. }
  7751. }
  7752. }
  7753. return InputStream::readString();
  7754. }
  7755. END_JUCE_NAMESPACE
  7756. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7757. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7758. BEGIN_JUCE_NAMESPACE
  7759. FileInputSource::FileInputSource (const File& file_)
  7760. : file (file_)
  7761. {
  7762. }
  7763. FileInputSource::~FileInputSource()
  7764. {
  7765. }
  7766. InputStream* FileInputSource::createInputStream()
  7767. {
  7768. return file.createInputStream();
  7769. }
  7770. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7771. {
  7772. return file.getSiblingFile (relatedItemPath).createInputStream();
  7773. }
  7774. int64 FileInputSource::hashCode() const
  7775. {
  7776. return file.hashCode();
  7777. }
  7778. END_JUCE_NAMESPACE
  7779. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7780. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7781. BEGIN_JUCE_NAMESPACE
  7782. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7783. const size_t sourceDataSize,
  7784. const bool keepInternalCopy)
  7785. : data (static_cast <const char*> (sourceData)),
  7786. dataSize (sourceDataSize),
  7787. position (0)
  7788. {
  7789. if (keepInternalCopy)
  7790. {
  7791. internalCopy.append (data, sourceDataSize);
  7792. data = static_cast <const char*> (internalCopy.getData());
  7793. }
  7794. }
  7795. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7796. const bool keepInternalCopy)
  7797. : data (static_cast <const char*> (sourceData.getData())),
  7798. dataSize (sourceData.getSize()),
  7799. position (0)
  7800. {
  7801. if (keepInternalCopy)
  7802. {
  7803. internalCopy = sourceData;
  7804. data = static_cast <const char*> (internalCopy.getData());
  7805. }
  7806. }
  7807. MemoryInputStream::~MemoryInputStream()
  7808. {
  7809. }
  7810. int64 MemoryInputStream::getTotalLength()
  7811. {
  7812. return dataSize;
  7813. }
  7814. int MemoryInputStream::read (void* const buffer, const int howMany)
  7815. {
  7816. jassert (howMany >= 0);
  7817. const int num = jmin (howMany, (int) (dataSize - position));
  7818. memcpy (buffer, data + position, num);
  7819. position += num;
  7820. return (int) num;
  7821. }
  7822. bool MemoryInputStream::isExhausted()
  7823. {
  7824. return (position >= dataSize);
  7825. }
  7826. bool MemoryInputStream::setPosition (const int64 pos)
  7827. {
  7828. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7829. return true;
  7830. }
  7831. int64 MemoryInputStream::getPosition()
  7832. {
  7833. return position;
  7834. }
  7835. END_JUCE_NAMESPACE
  7836. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7837. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7838. BEGIN_JUCE_NAMESPACE
  7839. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  7840. : data (internalBlock),
  7841. position (0),
  7842. size (0)
  7843. {
  7844. internalBlock.setSize (initialSize, false);
  7845. }
  7846. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  7847. const bool appendToExistingBlockContent)
  7848. : data (memoryBlockToWriteTo),
  7849. position (0),
  7850. size (0)
  7851. {
  7852. if (appendToExistingBlockContent)
  7853. position = size = memoryBlockToWriteTo.getSize();
  7854. }
  7855. MemoryOutputStream::~MemoryOutputStream()
  7856. {
  7857. flush();
  7858. }
  7859. void MemoryOutputStream::flush()
  7860. {
  7861. if (&data != &internalBlock)
  7862. data.setSize (size, false);
  7863. }
  7864. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  7865. {
  7866. data.ensureSize (bytesToPreallocate + 1);
  7867. }
  7868. void MemoryOutputStream::reset() throw()
  7869. {
  7870. position = 0;
  7871. size = 0;
  7872. }
  7873. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7874. {
  7875. if (howMany > 0)
  7876. {
  7877. const size_t storageNeeded = position + howMany;
  7878. if (storageNeeded >= data.getSize())
  7879. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  7880. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  7881. position += howMany;
  7882. size = jmax (size, position);
  7883. }
  7884. return true;
  7885. }
  7886. const void* MemoryOutputStream::getData() const throw()
  7887. {
  7888. void* const d = data.getData();
  7889. if (data.getSize() > size)
  7890. static_cast <char*> (d) [size] = 0;
  7891. return d;
  7892. }
  7893. bool MemoryOutputStream::setPosition (int64 newPosition)
  7894. {
  7895. if (newPosition <= (int64) size)
  7896. {
  7897. // ok to seek backwards
  7898. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7899. return true;
  7900. }
  7901. else
  7902. {
  7903. // trying to make it bigger isn't a good thing to do..
  7904. return false;
  7905. }
  7906. }
  7907. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  7908. {
  7909. // before writing from an input, see if we can preallocate to make it more efficient..
  7910. int64 availableData = source.getTotalLength() - source.getPosition();
  7911. if (availableData > 0)
  7912. {
  7913. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  7914. availableData = maxNumBytesToWrite;
  7915. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  7916. }
  7917. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  7918. }
  7919. const String MemoryOutputStream::toUTF8() const
  7920. {
  7921. return String (static_cast <const char*> (getData()), getDataSize());
  7922. }
  7923. const String MemoryOutputStream::toString() const
  7924. {
  7925. return String::createStringFromData (getData(), getDataSize());
  7926. }
  7927. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  7928. {
  7929. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  7930. return stream;
  7931. }
  7932. END_JUCE_NAMESPACE
  7933. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7934. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7935. BEGIN_JUCE_NAMESPACE
  7936. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7937. const int64 startPositionInSourceStream_,
  7938. const int64 lengthOfSourceStream_,
  7939. const bool deleteSourceWhenDestroyed)
  7940. : source (sourceStream),
  7941. startPositionInSourceStream (startPositionInSourceStream_),
  7942. lengthOfSourceStream (lengthOfSourceStream_)
  7943. {
  7944. if (deleteSourceWhenDestroyed)
  7945. sourceToDelete = source;
  7946. setPosition (0);
  7947. }
  7948. SubregionStream::~SubregionStream()
  7949. {
  7950. }
  7951. int64 SubregionStream::getTotalLength()
  7952. {
  7953. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7954. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7955. : srcLen;
  7956. }
  7957. int64 SubregionStream::getPosition()
  7958. {
  7959. return source->getPosition() - startPositionInSourceStream;
  7960. }
  7961. bool SubregionStream::setPosition (int64 newPosition)
  7962. {
  7963. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7964. }
  7965. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7966. {
  7967. if (lengthOfSourceStream < 0)
  7968. {
  7969. return source->read (destBuffer, maxBytesToRead);
  7970. }
  7971. else
  7972. {
  7973. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7974. if (maxBytesToRead <= 0)
  7975. return 0;
  7976. return source->read (destBuffer, maxBytesToRead);
  7977. }
  7978. }
  7979. bool SubregionStream::isExhausted()
  7980. {
  7981. if (lengthOfSourceStream >= 0)
  7982. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7983. else
  7984. return source->isExhausted();
  7985. }
  7986. END_JUCE_NAMESPACE
  7987. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7988. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7989. BEGIN_JUCE_NAMESPACE
  7990. PerformanceCounter::PerformanceCounter (const String& name_,
  7991. int runsPerPrintout,
  7992. const File& loggingFile)
  7993. : name (name_),
  7994. numRuns (0),
  7995. runsPerPrint (runsPerPrintout),
  7996. totalTime (0),
  7997. outputFile (loggingFile)
  7998. {
  7999. if (outputFile != File::nonexistent)
  8000. {
  8001. String s ("**** Counter for \"");
  8002. s << name_ << "\" started at: "
  8003. << Time::getCurrentTime().toString (true, true)
  8004. << "\r\n";
  8005. outputFile.appendText (s, false, false);
  8006. }
  8007. }
  8008. PerformanceCounter::~PerformanceCounter()
  8009. {
  8010. printStatistics();
  8011. }
  8012. void PerformanceCounter::start()
  8013. {
  8014. started = Time::getHighResolutionTicks();
  8015. }
  8016. void PerformanceCounter::stop()
  8017. {
  8018. const int64 now = Time::getHighResolutionTicks();
  8019. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8020. if (++numRuns == runsPerPrint)
  8021. printStatistics();
  8022. }
  8023. void PerformanceCounter::printStatistics()
  8024. {
  8025. if (numRuns > 0)
  8026. {
  8027. String s ("Performance count for \"");
  8028. s << name << "\" - average over " << numRuns << " run(s) = ";
  8029. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8030. if (micros > 10000)
  8031. s << (micros/1000) << " millisecs";
  8032. else
  8033. s << micros << " microsecs";
  8034. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8035. Logger::outputDebugString (s);
  8036. s << "\r\n";
  8037. if (outputFile != File::nonexistent)
  8038. outputFile.appendText (s, false, false);
  8039. numRuns = 0;
  8040. totalTime = 0;
  8041. }
  8042. }
  8043. END_JUCE_NAMESPACE
  8044. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8045. /*** Start of inlined file: juce_Uuid.cpp ***/
  8046. BEGIN_JUCE_NAMESPACE
  8047. Uuid::Uuid()
  8048. {
  8049. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8050. // to make it very very unlikely that two UUIDs will ever be the same..
  8051. static int64 macAddresses[2];
  8052. static bool hasCheckedMacAddresses = false;
  8053. if (! hasCheckedMacAddresses)
  8054. {
  8055. hasCheckedMacAddresses = true;
  8056. SystemStats::getMACAddresses (macAddresses, 2);
  8057. }
  8058. value.asInt64[0] = macAddresses[0];
  8059. value.asInt64[1] = macAddresses[1];
  8060. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8061. // whose seed will carry over between calls to this method.
  8062. Random r (macAddresses[0] ^ macAddresses[1]
  8063. ^ Random::getSystemRandom().nextInt64());
  8064. for (int i = 4; --i >= 0;)
  8065. {
  8066. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8067. value.asInt[i] ^= r.nextInt();
  8068. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8069. }
  8070. }
  8071. Uuid::~Uuid() throw()
  8072. {
  8073. }
  8074. Uuid::Uuid (const Uuid& other)
  8075. : value (other.value)
  8076. {
  8077. }
  8078. Uuid& Uuid::operator= (const Uuid& other)
  8079. {
  8080. value = other.value;
  8081. return *this;
  8082. }
  8083. bool Uuid::operator== (const Uuid& other) const
  8084. {
  8085. return value.asInt64[0] == other.value.asInt64[0]
  8086. && value.asInt64[1] == other.value.asInt64[1];
  8087. }
  8088. bool Uuid::operator!= (const Uuid& other) const
  8089. {
  8090. return ! operator== (other);
  8091. }
  8092. bool Uuid::isNull() const throw()
  8093. {
  8094. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8095. }
  8096. const String Uuid::toString() const
  8097. {
  8098. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8099. }
  8100. Uuid::Uuid (const String& uuidString)
  8101. {
  8102. operator= (uuidString);
  8103. }
  8104. Uuid& Uuid::operator= (const String& uuidString)
  8105. {
  8106. MemoryBlock mb;
  8107. mb.loadFromHexString (uuidString);
  8108. mb.ensureSize (sizeof (value.asBytes), true);
  8109. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8110. return *this;
  8111. }
  8112. Uuid::Uuid (const uint8* const rawData)
  8113. {
  8114. operator= (rawData);
  8115. }
  8116. Uuid& Uuid::operator= (const uint8* const rawData)
  8117. {
  8118. if (rawData != 0)
  8119. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8120. else
  8121. zeromem (value.asBytes, sizeof (value.asBytes));
  8122. return *this;
  8123. }
  8124. END_JUCE_NAMESPACE
  8125. /*** End of inlined file: juce_Uuid.cpp ***/
  8126. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8127. BEGIN_JUCE_NAMESPACE
  8128. class ZipFile::ZipEntryInfo
  8129. {
  8130. public:
  8131. ZipFile::ZipEntry entry;
  8132. int streamOffset;
  8133. int compressedSize;
  8134. bool compressed;
  8135. };
  8136. class ZipFile::ZipInputStream : public InputStream
  8137. {
  8138. public:
  8139. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8140. : file (file_),
  8141. zipEntryInfo (zei),
  8142. pos (0),
  8143. headerSize (0),
  8144. inputStream (0)
  8145. {
  8146. inputStream = file_.inputStream;
  8147. if (file_.inputSource != 0)
  8148. {
  8149. inputStream = file.inputSource->createInputStream();
  8150. }
  8151. else
  8152. {
  8153. #if JUCE_DEBUG
  8154. file_.numOpenStreams++;
  8155. #endif
  8156. }
  8157. char buffer [30];
  8158. if (inputStream != 0
  8159. && inputStream->setPosition (zei.streamOffset)
  8160. && inputStream->read (buffer, 30) == 30
  8161. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8162. {
  8163. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8164. + ByteOrder::littleEndianShort (buffer + 28);
  8165. }
  8166. }
  8167. ~ZipInputStream()
  8168. {
  8169. #if JUCE_DEBUG
  8170. if (inputStream != 0 && inputStream == file.inputStream)
  8171. file.numOpenStreams--;
  8172. #endif
  8173. if (inputStream != file.inputStream)
  8174. delete inputStream;
  8175. }
  8176. int64 getTotalLength()
  8177. {
  8178. return zipEntryInfo.compressedSize;
  8179. }
  8180. int read (void* buffer, int howMany)
  8181. {
  8182. if (headerSize <= 0)
  8183. return 0;
  8184. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8185. if (inputStream == 0)
  8186. return 0;
  8187. int num;
  8188. if (inputStream == file.inputStream)
  8189. {
  8190. const ScopedLock sl (file.lock);
  8191. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8192. num = inputStream->read (buffer, howMany);
  8193. }
  8194. else
  8195. {
  8196. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8197. num = inputStream->read (buffer, howMany);
  8198. }
  8199. pos += num;
  8200. return num;
  8201. }
  8202. bool isExhausted()
  8203. {
  8204. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8205. }
  8206. int64 getPosition()
  8207. {
  8208. return pos;
  8209. }
  8210. bool setPosition (int64 newPos)
  8211. {
  8212. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8213. return true;
  8214. }
  8215. private:
  8216. ZipFile& file;
  8217. ZipEntryInfo zipEntryInfo;
  8218. int64 pos;
  8219. int headerSize;
  8220. InputStream* inputStream;
  8221. ZipInputStream (const ZipInputStream&);
  8222. ZipInputStream& operator= (const ZipInputStream&);
  8223. };
  8224. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8225. : inputStream (source_)
  8226. #if JUCE_DEBUG
  8227. , numOpenStreams (0)
  8228. #endif
  8229. {
  8230. if (deleteStreamWhenDestroyed)
  8231. streamToDelete = inputStream;
  8232. init();
  8233. }
  8234. ZipFile::ZipFile (const File& file)
  8235. : inputStream (0)
  8236. #if JUCE_DEBUG
  8237. , numOpenStreams (0)
  8238. #endif
  8239. {
  8240. inputSource = new FileInputSource (file);
  8241. init();
  8242. }
  8243. ZipFile::ZipFile (InputSource* const inputSource_)
  8244. : inputStream (0),
  8245. inputSource (inputSource_)
  8246. #if JUCE_DEBUG
  8247. , numOpenStreams (0)
  8248. #endif
  8249. {
  8250. init();
  8251. }
  8252. ZipFile::~ZipFile()
  8253. {
  8254. #if JUCE_DEBUG
  8255. entries.clear();
  8256. // If you hit this assertion, it means you've created a stream to read
  8257. // one of the items in the zipfile, but you've forgotten to delete that
  8258. // stream object before deleting the file.. Streams can't be kept open
  8259. // after the file is deleted because they need to share the input
  8260. // stream that the file uses to read itself.
  8261. jassert (numOpenStreams == 0);
  8262. #endif
  8263. }
  8264. int ZipFile::getNumEntries() const throw()
  8265. {
  8266. return entries.size();
  8267. }
  8268. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8269. {
  8270. ZipEntryInfo* const zei = entries [index];
  8271. return zei != 0 ? &(zei->entry) : 0;
  8272. }
  8273. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8274. {
  8275. for (int i = 0; i < entries.size(); ++i)
  8276. if (entries.getUnchecked (i)->entry.filename == fileName)
  8277. return i;
  8278. return -1;
  8279. }
  8280. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8281. {
  8282. return getEntry (getIndexOfFileName (fileName));
  8283. }
  8284. InputStream* ZipFile::createStreamForEntry (const int index)
  8285. {
  8286. ZipEntryInfo* const zei = entries[index];
  8287. InputStream* stream = 0;
  8288. if (zei != 0)
  8289. {
  8290. stream = new ZipInputStream (*this, *zei);
  8291. if (zei->compressed)
  8292. {
  8293. stream = new GZIPDecompressorInputStream (stream, true, true,
  8294. zei->entry.uncompressedSize);
  8295. // (much faster to unzip in big blocks using a buffer..)
  8296. stream = new BufferedInputStream (stream, 32768, true);
  8297. }
  8298. }
  8299. return stream;
  8300. }
  8301. class ZipFile::ZipFilenameComparator
  8302. {
  8303. public:
  8304. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8305. {
  8306. return first->entry.filename.compare (second->entry.filename);
  8307. }
  8308. };
  8309. void ZipFile::sortEntriesByFilename()
  8310. {
  8311. ZipFilenameComparator sorter;
  8312. entries.sort (sorter);
  8313. }
  8314. void ZipFile::init()
  8315. {
  8316. ScopedPointer <InputStream> toDelete;
  8317. InputStream* in = inputStream;
  8318. if (inputSource != 0)
  8319. {
  8320. in = inputSource->createInputStream();
  8321. toDelete = in;
  8322. }
  8323. if (in != 0)
  8324. {
  8325. int numEntries = 0;
  8326. int pos = findEndOfZipEntryTable (in, numEntries);
  8327. if (pos >= 0 && pos < in->getTotalLength())
  8328. {
  8329. const int size = (int) (in->getTotalLength() - pos);
  8330. in->setPosition (pos);
  8331. MemoryBlock headerData;
  8332. if (in->readIntoMemoryBlock (headerData, size) == size)
  8333. {
  8334. pos = 0;
  8335. for (int i = 0; i < numEntries; ++i)
  8336. {
  8337. if (pos + 46 > size)
  8338. break;
  8339. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8340. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8341. if (pos + 46 + fileNameLen > size)
  8342. break;
  8343. ZipEntryInfo* const zei = new ZipEntryInfo();
  8344. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8345. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8346. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8347. const int year = 1980 + (date >> 9);
  8348. const int month = ((date >> 5) & 15) - 1;
  8349. const int day = date & 31;
  8350. const int hours = time >> 11;
  8351. const int minutes = (time >> 5) & 63;
  8352. const int seconds = (time & 31) << 1;
  8353. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8354. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8355. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8356. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8357. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8358. entries.add (zei);
  8359. pos += 46 + fileNameLen
  8360. + ByteOrder::littleEndianShort (buffer + 30)
  8361. + ByteOrder::littleEndianShort (buffer + 32);
  8362. }
  8363. }
  8364. }
  8365. }
  8366. }
  8367. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  8368. {
  8369. BufferedInputStream in (input, 8192, false);
  8370. in.setPosition (in.getTotalLength());
  8371. int64 pos = in.getPosition();
  8372. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8373. char buffer [32];
  8374. zeromem (buffer, sizeof (buffer));
  8375. while (pos > lowestPos)
  8376. {
  8377. in.setPosition (pos - 22);
  8378. pos = in.getPosition();
  8379. memcpy (buffer + 22, buffer, 4);
  8380. if (in.read (buffer, 22) != 22)
  8381. return 0;
  8382. for (int i = 0; i < 22; ++i)
  8383. {
  8384. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8385. {
  8386. in.setPosition (pos + i);
  8387. in.read (buffer, 22);
  8388. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8389. return ByteOrder::littleEndianInt (buffer + 16);
  8390. }
  8391. }
  8392. }
  8393. return 0;
  8394. }
  8395. void ZipFile::uncompressTo (const File& targetDirectory,
  8396. const bool shouldOverwriteFiles)
  8397. {
  8398. for (int i = 0; i < entries.size(); ++i)
  8399. {
  8400. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  8401. const File targetFile (targetDirectory.getChildFile (zei.filename));
  8402. if (zei.filename.endsWithChar ('/'))
  8403. {
  8404. targetFile.createDirectory(); // (entry is a directory, not a file)
  8405. }
  8406. else
  8407. {
  8408. ScopedPointer <InputStream> in (createStreamForEntry (i));
  8409. if (in != 0)
  8410. {
  8411. if (shouldOverwriteFiles)
  8412. targetFile.deleteFile();
  8413. if ((! targetFile.exists())
  8414. && targetFile.getParentDirectory().createDirectory())
  8415. {
  8416. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  8417. if (out != 0)
  8418. {
  8419. out->writeFromInputStream (*in, -1);
  8420. out = 0;
  8421. targetFile.setCreationTime (zei.fileTime);
  8422. targetFile.setLastModificationTime (zei.fileTime);
  8423. targetFile.setLastAccessTime (zei.fileTime);
  8424. }
  8425. }
  8426. }
  8427. }
  8428. }
  8429. }
  8430. END_JUCE_NAMESPACE
  8431. /*** End of inlined file: juce_ZipFile.cpp ***/
  8432. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8433. #if JUCE_MSVC
  8434. #pragma warning (push)
  8435. #pragma warning (disable: 4514 4996)
  8436. #endif
  8437. #include <cwctype>
  8438. #include <cctype>
  8439. #include <ctime>
  8440. BEGIN_JUCE_NAMESPACE
  8441. int CharacterFunctions::length (const char* const s) throw()
  8442. {
  8443. return (int) strlen (s);
  8444. }
  8445. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8446. {
  8447. return (int) wcslen (s);
  8448. }
  8449. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8450. {
  8451. strncpy (dest, src, maxChars);
  8452. }
  8453. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8454. {
  8455. wcsncpy (dest, src, maxChars);
  8456. }
  8457. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8458. {
  8459. mbstowcs (dest, src, maxChars);
  8460. }
  8461. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8462. {
  8463. wcstombs (dest, src, maxChars);
  8464. }
  8465. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8466. {
  8467. return (int) wcstombs (0, src, 0);
  8468. }
  8469. void CharacterFunctions::append (char* dest, const char* src) throw()
  8470. {
  8471. strcat (dest, src);
  8472. }
  8473. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8474. {
  8475. wcscat (dest, src);
  8476. }
  8477. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8478. {
  8479. return strcmp (s1, s2);
  8480. }
  8481. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8482. {
  8483. jassert (s1 != 0 && s2 != 0);
  8484. return wcscmp (s1, s2);
  8485. }
  8486. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8487. {
  8488. jassert (s1 != 0 && s2 != 0);
  8489. return strncmp (s1, s2, maxChars);
  8490. }
  8491. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8492. {
  8493. jassert (s1 != 0 && s2 != 0);
  8494. return wcsncmp (s1, s2, maxChars);
  8495. }
  8496. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8497. {
  8498. jassert (s1 != 0 && s2 != 0);
  8499. for (;;)
  8500. {
  8501. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8502. if (diff != 0)
  8503. return diff;
  8504. else if (*s1 == 0)
  8505. break;
  8506. ++s1;
  8507. ++s2;
  8508. }
  8509. return 0;
  8510. }
  8511. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8512. {
  8513. return -compare (s2, s1);
  8514. }
  8515. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8516. {
  8517. jassert (s1 != 0 && s2 != 0);
  8518. #if JUCE_WINDOWS
  8519. return stricmp (s1, s2);
  8520. #else
  8521. return strcasecmp (s1, s2);
  8522. #endif
  8523. }
  8524. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8525. {
  8526. jassert (s1 != 0 && s2 != 0);
  8527. #if JUCE_WINDOWS
  8528. return _wcsicmp (s1, s2);
  8529. #else
  8530. for (;;)
  8531. {
  8532. if (*s1 != *s2)
  8533. {
  8534. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8535. if (diff != 0)
  8536. return diff < 0 ? -1 : 1;
  8537. }
  8538. else if (*s1 == 0)
  8539. break;
  8540. ++s1;
  8541. ++s2;
  8542. }
  8543. return 0;
  8544. #endif
  8545. }
  8546. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8547. {
  8548. jassert (s1 != 0 && s2 != 0);
  8549. for (;;)
  8550. {
  8551. if (*s1 != *s2)
  8552. {
  8553. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8554. if (diff != 0)
  8555. return diff < 0 ? -1 : 1;
  8556. }
  8557. else if (*s1 == 0)
  8558. break;
  8559. ++s1;
  8560. ++s2;
  8561. }
  8562. return 0;
  8563. }
  8564. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8565. {
  8566. jassert (s1 != 0 && s2 != 0);
  8567. #if JUCE_WINDOWS
  8568. return strnicmp (s1, s2, maxChars);
  8569. #else
  8570. return strncasecmp (s1, s2, maxChars);
  8571. #endif
  8572. }
  8573. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8574. {
  8575. jassert (s1 != 0 && s2 != 0);
  8576. #if JUCE_WINDOWS
  8577. return _wcsnicmp (s1, s2, maxChars);
  8578. #else
  8579. while (--maxChars >= 0)
  8580. {
  8581. if (*s1 != *s2)
  8582. {
  8583. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8584. if (diff != 0)
  8585. return diff < 0 ? -1 : 1;
  8586. }
  8587. else if (*s1 == 0)
  8588. break;
  8589. ++s1;
  8590. ++s2;
  8591. }
  8592. return 0;
  8593. #endif
  8594. }
  8595. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8596. {
  8597. return strstr (haystack, needle);
  8598. }
  8599. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8600. {
  8601. return wcsstr (haystack, needle);
  8602. }
  8603. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8604. {
  8605. if (haystack != 0)
  8606. {
  8607. int i = 0;
  8608. if (ignoreCase)
  8609. {
  8610. const char n1 = toLowerCase (needle);
  8611. const char n2 = toUpperCase (needle);
  8612. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8613. {
  8614. while (haystack[i] != 0)
  8615. {
  8616. if (haystack[i] == n1 || haystack[i] == n2)
  8617. return i;
  8618. ++i;
  8619. }
  8620. return -1;
  8621. }
  8622. jassert (n1 == needle);
  8623. }
  8624. while (haystack[i] != 0)
  8625. {
  8626. if (haystack[i] == needle)
  8627. return i;
  8628. ++i;
  8629. }
  8630. }
  8631. return -1;
  8632. }
  8633. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8634. {
  8635. if (haystack != 0)
  8636. {
  8637. int i = 0;
  8638. if (ignoreCase)
  8639. {
  8640. const juce_wchar n1 = toLowerCase (needle);
  8641. const juce_wchar n2 = toUpperCase (needle);
  8642. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8643. {
  8644. while (haystack[i] != 0)
  8645. {
  8646. if (haystack[i] == n1 || haystack[i] == n2)
  8647. return i;
  8648. ++i;
  8649. }
  8650. return -1;
  8651. }
  8652. jassert (n1 == needle);
  8653. }
  8654. while (haystack[i] != 0)
  8655. {
  8656. if (haystack[i] == needle)
  8657. return i;
  8658. ++i;
  8659. }
  8660. }
  8661. return -1;
  8662. }
  8663. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8664. {
  8665. jassert (haystack != 0);
  8666. int i = 0;
  8667. while (haystack[i] != 0)
  8668. {
  8669. if (haystack[i] == needle)
  8670. return i;
  8671. ++i;
  8672. }
  8673. return -1;
  8674. }
  8675. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8676. {
  8677. jassert (haystack != 0);
  8678. int i = 0;
  8679. while (haystack[i] != 0)
  8680. {
  8681. if (haystack[i] == needle)
  8682. return i;
  8683. ++i;
  8684. }
  8685. return -1;
  8686. }
  8687. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8688. {
  8689. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8690. }
  8691. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8692. {
  8693. if (allowedChars == 0)
  8694. return 0;
  8695. int i = 0;
  8696. for (;;)
  8697. {
  8698. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8699. break;
  8700. ++i;
  8701. }
  8702. return i;
  8703. }
  8704. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8705. {
  8706. return (int) strftime (dest, maxChars, format, tm);
  8707. }
  8708. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8709. {
  8710. return (int) wcsftime (dest, maxChars, format, tm);
  8711. }
  8712. int CharacterFunctions::getIntValue (const char* const s) throw()
  8713. {
  8714. return atoi (s);
  8715. }
  8716. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8717. {
  8718. #if JUCE_WINDOWS
  8719. return _wtoi (s);
  8720. #else
  8721. int v = 0;
  8722. while (isWhitespace (*s))
  8723. ++s;
  8724. const bool isNeg = *s == '-';
  8725. if (isNeg)
  8726. ++s;
  8727. for (;;)
  8728. {
  8729. const wchar_t c = *s++;
  8730. if (c >= '0' && c <= '9')
  8731. v = v * 10 + (int) (c - '0');
  8732. else
  8733. break;
  8734. }
  8735. return isNeg ? -v : v;
  8736. #endif
  8737. }
  8738. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8739. {
  8740. #if JUCE_LINUX
  8741. return atoll (s);
  8742. #elif JUCE_WINDOWS
  8743. return _atoi64 (s);
  8744. #else
  8745. int64 v = 0;
  8746. while (isWhitespace (*s))
  8747. ++s;
  8748. const bool isNeg = *s == '-';
  8749. if (isNeg)
  8750. ++s;
  8751. for (;;)
  8752. {
  8753. const char c = *s++;
  8754. if (c >= '0' && c <= '9')
  8755. v = v * 10 + (int64) (c - '0');
  8756. else
  8757. break;
  8758. }
  8759. return isNeg ? -v : v;
  8760. #endif
  8761. }
  8762. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8763. {
  8764. #if JUCE_WINDOWS
  8765. return _wtoi64 (s);
  8766. #else
  8767. int64 v = 0;
  8768. while (isWhitespace (*s))
  8769. ++s;
  8770. const bool isNeg = *s == '-';
  8771. if (isNeg)
  8772. ++s;
  8773. for (;;)
  8774. {
  8775. const juce_wchar c = *s++;
  8776. if (c >= '0' && c <= '9')
  8777. v = v * 10 + (int64) (c - '0');
  8778. else
  8779. break;
  8780. }
  8781. return isNeg ? -v : v;
  8782. #endif
  8783. }
  8784. static double juce_mulexp10 (const double value, int exponent) throw()
  8785. {
  8786. if (exponent == 0)
  8787. return value;
  8788. if (value == 0)
  8789. return 0;
  8790. const bool negative = (exponent < 0);
  8791. if (negative)
  8792. exponent = -exponent;
  8793. double result = 1.0, power = 10.0;
  8794. for (int bit = 1; exponent != 0; bit <<= 1)
  8795. {
  8796. if ((exponent & bit) != 0)
  8797. {
  8798. exponent ^= bit;
  8799. result *= power;
  8800. if (exponent == 0)
  8801. break;
  8802. }
  8803. power *= power;
  8804. }
  8805. return negative ? (value / result) : (value * result);
  8806. }
  8807. template <class CharType>
  8808. double juce_atof (const CharType* const original) throw()
  8809. {
  8810. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8811. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8812. int exponent = 0, decPointIndex = 0, digit = 0;
  8813. int lastDigit = 0, numSignificantDigits = 0;
  8814. bool isNegative = false, digitsFound = false;
  8815. const int maxSignificantDigits = 15 + 2;
  8816. const CharType* s = original;
  8817. while (CharacterFunctions::isWhitespace (*s))
  8818. ++s;
  8819. switch (*s)
  8820. {
  8821. case '-': isNegative = true; // fall-through..
  8822. case '+': ++s;
  8823. }
  8824. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8825. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8826. for (;;)
  8827. {
  8828. if (CharacterFunctions::isDigit (*s))
  8829. {
  8830. lastDigit = digit;
  8831. digit = *s++ - '0';
  8832. digitsFound = true;
  8833. if (decPointIndex != 0)
  8834. exponentAdjustment[1]++;
  8835. if (numSignificantDigits == 0 && digit == 0)
  8836. continue;
  8837. if (++numSignificantDigits > maxSignificantDigits)
  8838. {
  8839. if (digit > 5)
  8840. ++accumulator [decPointIndex];
  8841. else if (digit == 5 && (lastDigit & 1) != 0)
  8842. ++accumulator [decPointIndex];
  8843. if (decPointIndex > 0)
  8844. exponentAdjustment[1]--;
  8845. else
  8846. exponentAdjustment[0]++;
  8847. while (CharacterFunctions::isDigit (*s))
  8848. {
  8849. ++s;
  8850. if (decPointIndex == 0)
  8851. exponentAdjustment[0]++;
  8852. }
  8853. }
  8854. else
  8855. {
  8856. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8857. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8858. {
  8859. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8860. + accumulator [decPointIndex];
  8861. accumulator [decPointIndex] = 0;
  8862. exponentAccumulator [decPointIndex] = 0;
  8863. }
  8864. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8865. exponentAccumulator [decPointIndex]++;
  8866. }
  8867. }
  8868. else if (decPointIndex == 0 && *s == '.')
  8869. {
  8870. ++s;
  8871. decPointIndex = 1;
  8872. if (numSignificantDigits > maxSignificantDigits)
  8873. {
  8874. while (CharacterFunctions::isDigit (*s))
  8875. ++s;
  8876. break;
  8877. }
  8878. }
  8879. else
  8880. {
  8881. break;
  8882. }
  8883. }
  8884. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8885. if (decPointIndex != 0)
  8886. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8887. if ((*s == 'e' || *s == 'E') && digitsFound)
  8888. {
  8889. bool negativeExponent = false;
  8890. switch (*++s)
  8891. {
  8892. case '-': negativeExponent = true; // fall-through..
  8893. case '+': ++s;
  8894. }
  8895. while (CharacterFunctions::isDigit (*s))
  8896. exponent = (exponent * 10) + (*s++ - '0');
  8897. if (negativeExponent)
  8898. exponent = -exponent;
  8899. }
  8900. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8901. if (decPointIndex != 0)
  8902. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8903. return isNegative ? -r : r;
  8904. }
  8905. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8906. {
  8907. return juce_atof <char> (s);
  8908. }
  8909. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8910. {
  8911. return juce_atof <juce_wchar> (s);
  8912. }
  8913. char CharacterFunctions::toUpperCase (const char character) throw()
  8914. {
  8915. return (char) toupper (character);
  8916. }
  8917. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8918. {
  8919. return towupper (character);
  8920. }
  8921. void CharacterFunctions::toUpperCase (char* s) throw()
  8922. {
  8923. #if JUCE_WINDOWS
  8924. strupr (s);
  8925. #else
  8926. while (*s != 0)
  8927. {
  8928. *s = toUpperCase (*s);
  8929. ++s;
  8930. }
  8931. #endif
  8932. }
  8933. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8934. {
  8935. #if JUCE_WINDOWS
  8936. _wcsupr (s);
  8937. #else
  8938. while (*s != 0)
  8939. {
  8940. *s = toUpperCase (*s);
  8941. ++s;
  8942. }
  8943. #endif
  8944. }
  8945. bool CharacterFunctions::isUpperCase (const char character) throw()
  8946. {
  8947. return isupper (character) != 0;
  8948. }
  8949. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8950. {
  8951. #if JUCE_WINDOWS
  8952. return iswupper (character) != 0;
  8953. #else
  8954. return toLowerCase (character) != character;
  8955. #endif
  8956. }
  8957. char CharacterFunctions::toLowerCase (const char character) throw()
  8958. {
  8959. return (char) tolower (character);
  8960. }
  8961. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8962. {
  8963. return towlower (character);
  8964. }
  8965. void CharacterFunctions::toLowerCase (char* s) throw()
  8966. {
  8967. #if JUCE_WINDOWS
  8968. strlwr (s);
  8969. #else
  8970. while (*s != 0)
  8971. {
  8972. *s = toLowerCase (*s);
  8973. ++s;
  8974. }
  8975. #endif
  8976. }
  8977. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8978. {
  8979. #if JUCE_WINDOWS
  8980. _wcslwr (s);
  8981. #else
  8982. while (*s != 0)
  8983. {
  8984. *s = toLowerCase (*s);
  8985. ++s;
  8986. }
  8987. #endif
  8988. }
  8989. bool CharacterFunctions::isLowerCase (const char character) throw()
  8990. {
  8991. return islower (character) != 0;
  8992. }
  8993. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8994. {
  8995. #if JUCE_WINDOWS
  8996. return iswlower (character) != 0;
  8997. #else
  8998. return toUpperCase (character) != character;
  8999. #endif
  9000. }
  9001. bool CharacterFunctions::isWhitespace (const char character) throw()
  9002. {
  9003. return character == ' ' || (character <= 13 && character >= 9);
  9004. }
  9005. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9006. {
  9007. return iswspace (character) != 0;
  9008. }
  9009. bool CharacterFunctions::isDigit (const char character) throw()
  9010. {
  9011. return (character >= '0' && character <= '9');
  9012. }
  9013. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9014. {
  9015. return iswdigit (character) != 0;
  9016. }
  9017. bool CharacterFunctions::isLetter (const char character) throw()
  9018. {
  9019. return (character >= 'a' && character <= 'z')
  9020. || (character >= 'A' && character <= 'Z');
  9021. }
  9022. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9023. {
  9024. return iswalpha (character) != 0;
  9025. }
  9026. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9027. {
  9028. return (character >= 'a' && character <= 'z')
  9029. || (character >= 'A' && character <= 'Z')
  9030. || (character >= '0' && character <= '9');
  9031. }
  9032. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9033. {
  9034. return iswalnum (character) != 0;
  9035. }
  9036. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9037. {
  9038. unsigned int d = digit - '0';
  9039. if (d < (unsigned int) 10)
  9040. return (int) d;
  9041. d += (unsigned int) ('0' - 'a');
  9042. if (d < (unsigned int) 6)
  9043. return (int) d + 10;
  9044. d += (unsigned int) ('a' - 'A');
  9045. if (d < (unsigned int) 6)
  9046. return (int) d + 10;
  9047. return -1;
  9048. }
  9049. #if JUCE_MSVC
  9050. #pragma warning (pop)
  9051. #endif
  9052. END_JUCE_NAMESPACE
  9053. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9054. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9055. BEGIN_JUCE_NAMESPACE
  9056. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9057. {
  9058. loadFromText (fileContents);
  9059. }
  9060. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9061. {
  9062. loadFromText (fileToLoad.loadFileAsString());
  9063. }
  9064. LocalisedStrings::~LocalisedStrings()
  9065. {
  9066. }
  9067. const String LocalisedStrings::translate (const String& text) const
  9068. {
  9069. return translations.getValue (text, text);
  9070. }
  9071. static int findCloseQuote (const String& text, int startPos)
  9072. {
  9073. juce_wchar lastChar = 0;
  9074. for (;;)
  9075. {
  9076. const juce_wchar c = text [startPos];
  9077. if (c == 0 || (c == '"' && lastChar != '\\'))
  9078. break;
  9079. lastChar = c;
  9080. ++startPos;
  9081. }
  9082. return startPos;
  9083. }
  9084. static const String unescapeString (const String& s)
  9085. {
  9086. return s.replace ("\\\"", "\"")
  9087. .replace ("\\\'", "\'")
  9088. .replace ("\\t", "\t")
  9089. .replace ("\\r", "\r")
  9090. .replace ("\\n", "\n");
  9091. }
  9092. void LocalisedStrings::loadFromText (const String& fileContents)
  9093. {
  9094. StringArray lines;
  9095. lines.addLines (fileContents);
  9096. for (int i = 0; i < lines.size(); ++i)
  9097. {
  9098. String line (lines[i].trim());
  9099. if (line.startsWithChar ('"'))
  9100. {
  9101. int closeQuote = findCloseQuote (line, 1);
  9102. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9103. if (originalText.isNotEmpty())
  9104. {
  9105. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9106. closeQuote = findCloseQuote (line, openingQuote + 1);
  9107. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9108. if (newText.isNotEmpty())
  9109. translations.set (originalText, newText);
  9110. }
  9111. }
  9112. else if (line.startsWithIgnoreCase ("language:"))
  9113. {
  9114. languageName = line.substring (9).trim();
  9115. }
  9116. else if (line.startsWithIgnoreCase ("countries:"))
  9117. {
  9118. countryCodes.addTokens (line.substring (10).trim(), true);
  9119. countryCodes.trim();
  9120. countryCodes.removeEmptyStrings();
  9121. }
  9122. }
  9123. }
  9124. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9125. {
  9126. translations.setIgnoresCase (shouldIgnoreCase);
  9127. }
  9128. static CriticalSection currentMappingsLock;
  9129. static LocalisedStrings* currentMappings = 0;
  9130. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9131. {
  9132. const ScopedLock sl (currentMappingsLock);
  9133. delete currentMappings;
  9134. currentMappings = newTranslations;
  9135. }
  9136. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9137. {
  9138. return currentMappings;
  9139. }
  9140. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9141. {
  9142. const ScopedLock sl (currentMappingsLock);
  9143. if (currentMappings != 0)
  9144. return currentMappings->translate (text);
  9145. return text;
  9146. }
  9147. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9148. {
  9149. return translateWithCurrentMappings (String (text));
  9150. }
  9151. END_JUCE_NAMESPACE
  9152. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9153. /*** Start of inlined file: juce_String.cpp ***/
  9154. #if JUCE_MSVC
  9155. #pragma warning (push)
  9156. #pragma warning (disable: 4514)
  9157. #endif
  9158. #include <locale>
  9159. BEGIN_JUCE_NAMESPACE
  9160. #if JUCE_MSVC
  9161. #pragma warning (pop)
  9162. #endif
  9163. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9164. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9165. #endif
  9166. class StringHolder
  9167. {
  9168. public:
  9169. StringHolder()
  9170. : refCount (0x3fffffff), allocatedNumChars (0)
  9171. {
  9172. text[0] = 0;
  9173. }
  9174. static juce_wchar* createUninitialised (const size_t numChars)
  9175. {
  9176. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9177. s->refCount.value = 0;
  9178. s->allocatedNumChars = numChars;
  9179. return &(s->text[0]);
  9180. }
  9181. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9182. {
  9183. juce_wchar* const dest = createUninitialised (numChars);
  9184. copyChars (dest, src, numChars);
  9185. return dest;
  9186. }
  9187. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9188. {
  9189. juce_wchar* const dest = createUninitialised (numChars);
  9190. CharacterFunctions::copy (dest, src, (int) numChars);
  9191. dest [numChars] = 0;
  9192. return dest;
  9193. }
  9194. static inline juce_wchar* getEmpty() throw()
  9195. {
  9196. return &(empty.text[0]);
  9197. }
  9198. static void retain (juce_wchar* const text) throw()
  9199. {
  9200. ++(bufferFromText (text)->refCount);
  9201. }
  9202. static inline void release (StringHolder* const b) throw()
  9203. {
  9204. if (--(b->refCount) == -1 && b != &empty)
  9205. delete[] reinterpret_cast <char*> (b);
  9206. }
  9207. static void release (juce_wchar* const text) throw()
  9208. {
  9209. release (bufferFromText (text));
  9210. }
  9211. static juce_wchar* makeUnique (juce_wchar* const text)
  9212. {
  9213. StringHolder* const b = bufferFromText (text);
  9214. if (b->refCount.get() <= 0)
  9215. return text;
  9216. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9217. release (b);
  9218. return newText;
  9219. }
  9220. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9221. {
  9222. StringHolder* const b = bufferFromText (text);
  9223. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9224. return text;
  9225. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9226. copyChars (newText, text, b->allocatedNumChars);
  9227. release (b);
  9228. return newText;
  9229. }
  9230. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9231. {
  9232. return bufferFromText (text)->allocatedNumChars;
  9233. }
  9234. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9235. {
  9236. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9237. dest [numChars] = 0;
  9238. }
  9239. Atomic<int> refCount;
  9240. size_t allocatedNumChars;
  9241. juce_wchar text[1];
  9242. static StringHolder empty;
  9243. private:
  9244. static inline StringHolder* bufferFromText (void* const text) throw()
  9245. {
  9246. // (Can't use offsetof() here because of warnings about this not being a POD)
  9247. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9248. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9249. }
  9250. };
  9251. StringHolder StringHolder::empty;
  9252. const String String::empty;
  9253. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9254. {
  9255. jassert (t[numChars] == 0); // must have a null terminator
  9256. text = StringHolder::createCopy (t, numChars);
  9257. }
  9258. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9259. {
  9260. if (numExtraChars > 0)
  9261. {
  9262. const int oldLen = length();
  9263. const int newTotalLen = oldLen + numExtraChars;
  9264. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9265. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9266. }
  9267. }
  9268. void String::preallocateStorage (const size_t numChars)
  9269. {
  9270. text = StringHolder::makeUniqueWithSize (text, numChars);
  9271. }
  9272. String::String() throw()
  9273. : text (StringHolder::getEmpty())
  9274. {
  9275. }
  9276. String::~String() throw()
  9277. {
  9278. StringHolder::release (text);
  9279. }
  9280. String::String (const String& other) throw()
  9281. : text (other.text)
  9282. {
  9283. StringHolder::retain (text);
  9284. }
  9285. void String::swapWith (String& other) throw()
  9286. {
  9287. swapVariables (text, other.text);
  9288. }
  9289. String& String::operator= (const String& other) throw()
  9290. {
  9291. juce_wchar* const newText = other.text;
  9292. StringHolder::retain (newText);
  9293. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9294. return *this;
  9295. }
  9296. String::String (const size_t numChars, const int /*dummyVariable*/)
  9297. : text (StringHolder::createUninitialised (numChars))
  9298. {
  9299. }
  9300. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9301. {
  9302. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9303. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9304. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9305. }
  9306. String::String (const char* const t)
  9307. {
  9308. if (t != 0 && *t != 0)
  9309. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9310. else
  9311. text = StringHolder::getEmpty();
  9312. }
  9313. String::String (const juce_wchar* const t)
  9314. {
  9315. if (t != 0 && *t != 0)
  9316. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9317. else
  9318. text = StringHolder::getEmpty();
  9319. }
  9320. String::String (const char* const t, const size_t maxChars)
  9321. {
  9322. int i;
  9323. for (i = 0; (size_t) i < maxChars; ++i)
  9324. if (t[i] == 0)
  9325. break;
  9326. if (i > 0)
  9327. text = StringHolder::createCopy (t, i);
  9328. else
  9329. text = StringHolder::getEmpty();
  9330. }
  9331. String::String (const juce_wchar* const t, const size_t maxChars)
  9332. {
  9333. int i;
  9334. for (i = 0; (size_t) i < maxChars; ++i)
  9335. if (t[i] == 0)
  9336. break;
  9337. if (i > 0)
  9338. text = StringHolder::createCopy (t, i);
  9339. else
  9340. text = StringHolder::getEmpty();
  9341. }
  9342. const String String::charToString (const juce_wchar character)
  9343. {
  9344. String result ((size_t) 1, (int) 0);
  9345. result.text[0] = character;
  9346. result.text[1] = 0;
  9347. return result;
  9348. }
  9349. namespace NumberToStringConverters
  9350. {
  9351. // pass in a pointer to the END of a buffer..
  9352. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9353. {
  9354. *--t = 0;
  9355. int64 v = (n >= 0) ? n : -n;
  9356. do
  9357. {
  9358. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9359. v /= 10;
  9360. } while (v > 0);
  9361. if (n < 0)
  9362. *--t = '-';
  9363. return t;
  9364. }
  9365. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9366. {
  9367. *--t = 0;
  9368. do
  9369. {
  9370. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9371. v /= 10;
  9372. } while (v > 0);
  9373. return t;
  9374. }
  9375. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9376. {
  9377. if (n == (int) 0x80000000) // (would cause an overflow)
  9378. return int64ToString (t, n);
  9379. *--t = 0;
  9380. int v = abs (n);
  9381. do
  9382. {
  9383. *--t = (juce_wchar) ('0' + (v % 10));
  9384. v /= 10;
  9385. } while (v > 0);
  9386. if (n < 0)
  9387. *--t = '-';
  9388. return t;
  9389. }
  9390. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9391. {
  9392. *--t = 0;
  9393. do
  9394. {
  9395. *--t = (juce_wchar) ('0' + (v % 10));
  9396. v /= 10;
  9397. } while (v > 0);
  9398. return t;
  9399. }
  9400. static juce_wchar getDecimalPoint()
  9401. {
  9402. #if JUCE_WINDOWS && _MSC_VER < 1400
  9403. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9404. #else
  9405. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9406. #endif
  9407. return dp;
  9408. }
  9409. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9410. {
  9411. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9412. {
  9413. juce_wchar* const end = buffer + numChars;
  9414. juce_wchar* t = end;
  9415. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9416. *--t = (juce_wchar) 0;
  9417. while (numDecPlaces >= 0 || v > 0)
  9418. {
  9419. if (numDecPlaces == 0)
  9420. *--t = getDecimalPoint();
  9421. *--t = (juce_wchar) ('0' + (v % 10));
  9422. v /= 10;
  9423. --numDecPlaces;
  9424. }
  9425. if (n < 0)
  9426. *--t = '-';
  9427. len = end - t - 1;
  9428. return t;
  9429. }
  9430. else
  9431. {
  9432. #if JUCE_WINDOWS
  9433. #if _MSC_VER <= 1400
  9434. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9435. #else
  9436. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9437. #endif
  9438. #else
  9439. len = swprintf (buffer, numChars, L"%.9g", n);
  9440. #endif
  9441. return buffer;
  9442. }
  9443. }
  9444. }
  9445. String::String (const int number)
  9446. {
  9447. juce_wchar buffer [16];
  9448. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9449. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9450. createInternal (start, end - start - 1);
  9451. }
  9452. String::String (const unsigned int number)
  9453. {
  9454. juce_wchar buffer [16];
  9455. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9456. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9457. createInternal (start, end - start - 1);
  9458. }
  9459. String::String (const short number)
  9460. {
  9461. juce_wchar buffer [16];
  9462. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9463. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9464. createInternal (start, end - start - 1);
  9465. }
  9466. String::String (const unsigned short number)
  9467. {
  9468. juce_wchar buffer [16];
  9469. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9470. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9471. createInternal (start, end - start - 1);
  9472. }
  9473. String::String (const int64 number)
  9474. {
  9475. juce_wchar buffer [32];
  9476. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9477. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9478. createInternal (start, end - start - 1);
  9479. }
  9480. String::String (const uint64 number)
  9481. {
  9482. juce_wchar buffer [32];
  9483. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9484. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9485. createInternal (start, end - start - 1);
  9486. }
  9487. String::String (const float number, const int numberOfDecimalPlaces)
  9488. {
  9489. juce_wchar buffer [48];
  9490. size_t len;
  9491. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9492. createInternal (start, len);
  9493. }
  9494. String::String (const double number, const int numberOfDecimalPlaces)
  9495. {
  9496. juce_wchar buffer [48];
  9497. size_t len;
  9498. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9499. createInternal (start, len);
  9500. }
  9501. int String::length() const throw()
  9502. {
  9503. return CharacterFunctions::length (text);
  9504. }
  9505. int String::hashCode() const throw()
  9506. {
  9507. const juce_wchar* t = text;
  9508. int result = 0;
  9509. while (*t != (juce_wchar) 0)
  9510. result = 31 * result + *t++;
  9511. return result;
  9512. }
  9513. int64 String::hashCode64() const throw()
  9514. {
  9515. const juce_wchar* t = text;
  9516. int64 result = 0;
  9517. while (*t != (juce_wchar) 0)
  9518. result = 101 * result + *t++;
  9519. return result;
  9520. }
  9521. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  9522. {
  9523. return string1.compare (string2) == 0;
  9524. }
  9525. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  9526. {
  9527. return string1.compare (string2) == 0;
  9528. }
  9529. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  9530. {
  9531. return string1.compare (string2) == 0;
  9532. }
  9533. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  9534. {
  9535. return string1.compare (string2) != 0;
  9536. }
  9537. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  9538. {
  9539. return string1.compare (string2) != 0;
  9540. }
  9541. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  9542. {
  9543. return string1.compare (string2) != 0;
  9544. }
  9545. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  9546. {
  9547. return string1.compare (string2) > 0;
  9548. }
  9549. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  9550. {
  9551. return string1.compare (string2) < 0;
  9552. }
  9553. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  9554. {
  9555. return string1.compare (string2) >= 0;
  9556. }
  9557. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  9558. {
  9559. return string1.compare (string2) <= 0;
  9560. }
  9561. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9562. {
  9563. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9564. : isEmpty();
  9565. }
  9566. bool String::equalsIgnoreCase (const char* t) const throw()
  9567. {
  9568. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9569. : isEmpty();
  9570. }
  9571. bool String::equalsIgnoreCase (const String& other) const throw()
  9572. {
  9573. return text == other.text
  9574. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9575. }
  9576. int String::compare (const String& other) const throw()
  9577. {
  9578. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9579. }
  9580. int String::compare (const char* other) const throw()
  9581. {
  9582. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9583. }
  9584. int String::compare (const juce_wchar* other) const throw()
  9585. {
  9586. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9587. }
  9588. int String::compareIgnoreCase (const String& other) const throw()
  9589. {
  9590. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9591. }
  9592. int String::compareLexicographically (const String& other) const throw()
  9593. {
  9594. const juce_wchar* s1 = text;
  9595. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9596. ++s1;
  9597. const juce_wchar* s2 = other.text;
  9598. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9599. ++s2;
  9600. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9601. }
  9602. String& String::operator+= (const juce_wchar* const t)
  9603. {
  9604. if (t != 0)
  9605. appendInternal (t, CharacterFunctions::length (t));
  9606. return *this;
  9607. }
  9608. String& String::operator+= (const String& other)
  9609. {
  9610. if (isEmpty())
  9611. operator= (other);
  9612. else
  9613. appendInternal (other.text, other.length());
  9614. return *this;
  9615. }
  9616. String& String::operator+= (const char ch)
  9617. {
  9618. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9619. return operator+= (static_cast <const juce_wchar*> (asString));
  9620. }
  9621. String& String::operator+= (const juce_wchar ch)
  9622. {
  9623. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9624. return operator+= (static_cast <const juce_wchar*> (asString));
  9625. }
  9626. String& String::operator+= (const int number)
  9627. {
  9628. juce_wchar buffer [16];
  9629. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9630. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9631. appendInternal (start, (int) (end - start));
  9632. return *this;
  9633. }
  9634. String& String::operator+= (const unsigned int number)
  9635. {
  9636. juce_wchar buffer [16];
  9637. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9638. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9639. appendInternal (start, (int) (end - start));
  9640. return *this;
  9641. }
  9642. void String::append (const juce_wchar* const other, const int howMany)
  9643. {
  9644. if (howMany > 0)
  9645. {
  9646. int i;
  9647. for (i = 0; i < howMany; ++i)
  9648. if (other[i] == 0)
  9649. break;
  9650. appendInternal (other, i);
  9651. }
  9652. }
  9653. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  9654. {
  9655. String s (string1);
  9656. return s += string2;
  9657. }
  9658. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  9659. {
  9660. String s (string1);
  9661. return s += string2;
  9662. }
  9663. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  9664. {
  9665. return String::charToString (string1) + string2;
  9666. }
  9667. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  9668. {
  9669. return String::charToString (string1) + string2;
  9670. }
  9671. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  9672. {
  9673. return string1 += string2;
  9674. }
  9675. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  9676. {
  9677. return string1 += string2;
  9678. }
  9679. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  9680. {
  9681. return string1 += string2;
  9682. }
  9683. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  9684. {
  9685. return string1 += string2;
  9686. }
  9687. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  9688. {
  9689. return string1 += string2;
  9690. }
  9691. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  9692. {
  9693. return string1 += characterToAppend;
  9694. }
  9695. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  9696. {
  9697. return string1 += characterToAppend;
  9698. }
  9699. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  9700. {
  9701. return string1 += string2;
  9702. }
  9703. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  9704. {
  9705. return string1 += string2;
  9706. }
  9707. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  9708. {
  9709. return string1 += string2;
  9710. }
  9711. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  9712. {
  9713. return string1 += (int) number;
  9714. }
  9715. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  9716. {
  9717. return string1 += number;
  9718. }
  9719. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  9720. {
  9721. return string1 += number;
  9722. }
  9723. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  9724. {
  9725. return string1 += (int) number;
  9726. }
  9727. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  9728. {
  9729. return string1 += (unsigned int) number;
  9730. }
  9731. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9732. {
  9733. return string1 += String (number);
  9734. }
  9735. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9736. {
  9737. return string1 += String (number);
  9738. }
  9739. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9740. {
  9741. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9742. // if lots of large, persistent strings were to be written to streams).
  9743. const int numBytes = text.getNumBytesAsUTF8();
  9744. HeapBlock<char> temp (numBytes + 1);
  9745. text.copyToUTF8 (temp, numBytes + 1);
  9746. stream.write (temp, numBytes);
  9747. return stream;
  9748. }
  9749. int String::indexOfChar (const juce_wchar character) const throw()
  9750. {
  9751. const juce_wchar* t = text;
  9752. for (;;)
  9753. {
  9754. if (*t == character)
  9755. return (int) (t - text);
  9756. if (*t++ == 0)
  9757. return -1;
  9758. }
  9759. }
  9760. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9761. {
  9762. for (int i = length(); --i >= 0;)
  9763. if (text[i] == character)
  9764. return i;
  9765. return -1;
  9766. }
  9767. int String::indexOf (const String& t) const throw()
  9768. {
  9769. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9770. return r == 0 ? -1 : (int) (r - text);
  9771. }
  9772. int String::indexOfChar (const int startIndex,
  9773. const juce_wchar character) const throw()
  9774. {
  9775. if (startIndex > 0 && startIndex >= length())
  9776. return -1;
  9777. const juce_wchar* t = text + jmax (0, startIndex);
  9778. for (;;)
  9779. {
  9780. if (*t == character)
  9781. return (int) (t - text);
  9782. if (*t == 0)
  9783. return -1;
  9784. ++t;
  9785. }
  9786. }
  9787. int String::indexOfAnyOf (const String& charactersToLookFor,
  9788. const int startIndex,
  9789. const bool ignoreCase) const throw()
  9790. {
  9791. if (startIndex > 0 && startIndex >= length())
  9792. return -1;
  9793. const juce_wchar* t = text + jmax (0, startIndex);
  9794. while (*t != 0)
  9795. {
  9796. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  9797. return (int) (t - text);
  9798. ++t;
  9799. }
  9800. return -1;
  9801. }
  9802. int String::indexOf (const int startIndex, const String& other) const throw()
  9803. {
  9804. if (startIndex > 0 && startIndex >= length())
  9805. return -1;
  9806. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  9807. return found == 0 ? -1 : (int) (found - text);
  9808. }
  9809. int String::indexOfIgnoreCase (const String& other) const throw()
  9810. {
  9811. if (other.isNotEmpty())
  9812. {
  9813. const int len = other.length();
  9814. const int end = length() - len;
  9815. for (int i = 0; i <= end; ++i)
  9816. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9817. return i;
  9818. }
  9819. return -1;
  9820. }
  9821. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9822. {
  9823. if (other.isNotEmpty())
  9824. {
  9825. const int len = other.length();
  9826. const int end = length() - len;
  9827. for (int i = jmax (0, startIndex); i <= end; ++i)
  9828. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9829. return i;
  9830. }
  9831. return -1;
  9832. }
  9833. int String::lastIndexOf (const String& other) const throw()
  9834. {
  9835. if (other.isNotEmpty())
  9836. {
  9837. const int len = other.length();
  9838. int i = length() - len;
  9839. if (i >= 0)
  9840. {
  9841. const juce_wchar* n = text + i;
  9842. while (i >= 0)
  9843. {
  9844. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9845. return i;
  9846. --i;
  9847. }
  9848. }
  9849. }
  9850. return -1;
  9851. }
  9852. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9853. {
  9854. if (other.isNotEmpty())
  9855. {
  9856. const int len = other.length();
  9857. int i = length() - len;
  9858. if (i >= 0)
  9859. {
  9860. const juce_wchar* n = text + i;
  9861. while (i >= 0)
  9862. {
  9863. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9864. return i;
  9865. --i;
  9866. }
  9867. }
  9868. }
  9869. return -1;
  9870. }
  9871. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9872. {
  9873. for (int i = length(); --i >= 0;)
  9874. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9875. return i;
  9876. return -1;
  9877. }
  9878. bool String::contains (const String& other) const throw()
  9879. {
  9880. return indexOf (other) >= 0;
  9881. }
  9882. bool String::containsChar (const juce_wchar character) const throw()
  9883. {
  9884. const juce_wchar* t = text;
  9885. for (;;)
  9886. {
  9887. if (*t == 0)
  9888. return false;
  9889. if (*t == character)
  9890. return true;
  9891. ++t;
  9892. }
  9893. }
  9894. bool String::containsIgnoreCase (const String& t) const throw()
  9895. {
  9896. return indexOfIgnoreCase (t) >= 0;
  9897. }
  9898. int String::indexOfWholeWord (const String& word) const throw()
  9899. {
  9900. if (word.isNotEmpty())
  9901. {
  9902. const int wordLen = word.length();
  9903. const int end = length() - wordLen;
  9904. const juce_wchar* t = text;
  9905. for (int i = 0; i <= end; ++i)
  9906. {
  9907. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9908. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9909. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9910. {
  9911. return i;
  9912. }
  9913. ++t;
  9914. }
  9915. }
  9916. return -1;
  9917. }
  9918. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9919. {
  9920. if (word.isNotEmpty())
  9921. {
  9922. const int wordLen = word.length();
  9923. const int end = length() - wordLen;
  9924. const juce_wchar* t = text;
  9925. for (int i = 0; i <= end; ++i)
  9926. {
  9927. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9928. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9929. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9930. {
  9931. return i;
  9932. }
  9933. ++t;
  9934. }
  9935. }
  9936. return -1;
  9937. }
  9938. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9939. {
  9940. return indexOfWholeWord (wordToLookFor) >= 0;
  9941. }
  9942. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9943. {
  9944. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9945. }
  9946. static int indexOfMatch (const juce_wchar* const wildcard,
  9947. const juce_wchar* const test,
  9948. const bool ignoreCase) throw()
  9949. {
  9950. int start = 0;
  9951. while (test [start] != 0)
  9952. {
  9953. int i = 0;
  9954. for (;;)
  9955. {
  9956. const juce_wchar wc = wildcard [i];
  9957. const juce_wchar c = test [i + start];
  9958. if (wc == c
  9959. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9960. || (wc == '?' && c != 0))
  9961. {
  9962. if (wc == 0)
  9963. return start;
  9964. ++i;
  9965. }
  9966. else
  9967. {
  9968. if (wc == '*' && (wildcard [i + 1] == 0
  9969. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9970. {
  9971. return start;
  9972. }
  9973. break;
  9974. }
  9975. }
  9976. ++start;
  9977. }
  9978. return -1;
  9979. }
  9980. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9981. {
  9982. int i = 0;
  9983. for (;;)
  9984. {
  9985. const juce_wchar wc = wildcard.text [i];
  9986. const juce_wchar c = text [i];
  9987. if (wc == c
  9988. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9989. || (wc == '?' && c != 0))
  9990. {
  9991. if (wc == 0)
  9992. return true;
  9993. ++i;
  9994. }
  9995. else
  9996. {
  9997. return wc == '*' && (wildcard [i + 1] == 0
  9998. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  9999. }
  10000. }
  10001. }
  10002. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10003. {
  10004. const int len = stringToRepeat.length();
  10005. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10006. juce_wchar* n = result.text;
  10007. *n = 0;
  10008. while (--numberOfTimesToRepeat >= 0)
  10009. {
  10010. StringHolder::copyChars (n, stringToRepeat.text, len);
  10011. n += len;
  10012. }
  10013. return result;
  10014. }
  10015. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10016. {
  10017. jassert (padCharacter != 0);
  10018. const int len = length();
  10019. if (len >= minimumLength || padCharacter == 0)
  10020. return *this;
  10021. String result ((size_t) minimumLength + 1, (int) 0);
  10022. juce_wchar* n = result.text;
  10023. minimumLength -= len;
  10024. while (--minimumLength >= 0)
  10025. *n++ = padCharacter;
  10026. StringHolder::copyChars (n, text, len);
  10027. return result;
  10028. }
  10029. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10030. {
  10031. jassert (padCharacter != 0);
  10032. const int len = length();
  10033. if (len >= minimumLength || padCharacter == 0)
  10034. return *this;
  10035. String result (*this, (size_t) minimumLength);
  10036. juce_wchar* n = result.text + len;
  10037. minimumLength -= len;
  10038. while (--minimumLength >= 0)
  10039. *n++ = padCharacter;
  10040. *n = 0;
  10041. return result;
  10042. }
  10043. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10044. {
  10045. if (index < 0)
  10046. {
  10047. // a negative index to replace from?
  10048. jassertfalse;
  10049. index = 0;
  10050. }
  10051. if (numCharsToReplace < 0)
  10052. {
  10053. // replacing a negative number of characters?
  10054. numCharsToReplace = 0;
  10055. jassertfalse;
  10056. }
  10057. const int len = length();
  10058. if (index + numCharsToReplace > len)
  10059. {
  10060. if (index > len)
  10061. {
  10062. // replacing beyond the end of the string?
  10063. index = len;
  10064. jassertfalse;
  10065. }
  10066. numCharsToReplace = len - index;
  10067. }
  10068. const int newStringLen = stringToInsert.length();
  10069. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10070. if (newTotalLen <= 0)
  10071. return String::empty;
  10072. String result ((size_t) newTotalLen, (int) 0);
  10073. StringHolder::copyChars (result.text, text, index);
  10074. if (newStringLen > 0)
  10075. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10076. const int endStringLen = newTotalLen - (index + newStringLen);
  10077. if (endStringLen > 0)
  10078. StringHolder::copyChars (result.text + (index + newStringLen),
  10079. text + (index + numCharsToReplace),
  10080. endStringLen);
  10081. return result;
  10082. }
  10083. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10084. {
  10085. const int stringToReplaceLen = stringToReplace.length();
  10086. const int stringToInsertLen = stringToInsert.length();
  10087. int i = 0;
  10088. String result (*this);
  10089. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10090. : result.indexOf (i, stringToReplace))) >= 0)
  10091. {
  10092. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10093. i += stringToInsertLen;
  10094. }
  10095. return result;
  10096. }
  10097. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10098. {
  10099. const int index = indexOfChar (charToReplace);
  10100. if (index < 0)
  10101. return *this;
  10102. String result (*this, size_t());
  10103. juce_wchar* t = result.text + index;
  10104. while (*t != 0)
  10105. {
  10106. if (*t == charToReplace)
  10107. *t = charToInsert;
  10108. ++t;
  10109. }
  10110. return result;
  10111. }
  10112. const String String::replaceCharacters (const String& charactersToReplace,
  10113. const String& charactersToInsertInstead) const
  10114. {
  10115. String result (*this, size_t());
  10116. juce_wchar* t = result.text;
  10117. const int len2 = charactersToInsertInstead.length();
  10118. // the two strings passed in are supposed to be the same length!
  10119. jassert (len2 == charactersToReplace.length());
  10120. while (*t != 0)
  10121. {
  10122. const int index = charactersToReplace.indexOfChar (*t);
  10123. if (((unsigned int) index) < (unsigned int) len2)
  10124. *t = charactersToInsertInstead [index];
  10125. ++t;
  10126. }
  10127. return result;
  10128. }
  10129. bool String::startsWith (const String& other) const throw()
  10130. {
  10131. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10132. }
  10133. bool String::startsWithIgnoreCase (const String& other) const throw()
  10134. {
  10135. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10136. }
  10137. bool String::startsWithChar (const juce_wchar character) const throw()
  10138. {
  10139. jassert (character != 0); // strings can't contain a null character!
  10140. return text[0] == character;
  10141. }
  10142. bool String::endsWithChar (const juce_wchar character) const throw()
  10143. {
  10144. jassert (character != 0); // strings can't contain a null character!
  10145. return text[0] != 0
  10146. && text [length() - 1] == character;
  10147. }
  10148. bool String::endsWith (const String& other) const throw()
  10149. {
  10150. const int thisLen = length();
  10151. const int otherLen = other.length();
  10152. return thisLen >= otherLen
  10153. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10154. }
  10155. bool String::endsWithIgnoreCase (const String& other) const throw()
  10156. {
  10157. const int thisLen = length();
  10158. const int otherLen = other.length();
  10159. return thisLen >= otherLen
  10160. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10161. }
  10162. const String String::toUpperCase() const
  10163. {
  10164. String result (*this, size_t());
  10165. CharacterFunctions::toUpperCase (result.text);
  10166. return result;
  10167. }
  10168. const String String::toLowerCase() const
  10169. {
  10170. String result (*this, size_t());
  10171. CharacterFunctions::toLowerCase (result.text);
  10172. return result;
  10173. }
  10174. juce_wchar& String::operator[] (const int index)
  10175. {
  10176. jassert (((unsigned int) index) <= (unsigned int) length());
  10177. text = StringHolder::makeUnique (text);
  10178. return text [index];
  10179. }
  10180. juce_wchar String::getLastCharacter() const throw()
  10181. {
  10182. return isEmpty() ? juce_wchar() : text [length() - 1];
  10183. }
  10184. const String String::substring (int start, int end) const
  10185. {
  10186. if (start < 0)
  10187. start = 0;
  10188. else if (end <= start)
  10189. return empty;
  10190. int len = 0;
  10191. while (len <= end && text [len] != 0)
  10192. ++len;
  10193. if (end >= len)
  10194. {
  10195. if (start == 0)
  10196. return *this;
  10197. end = len;
  10198. }
  10199. return String (text + start, end - start);
  10200. }
  10201. const String String::substring (const int start) const
  10202. {
  10203. if (start <= 0)
  10204. return *this;
  10205. const int len = length();
  10206. if (start >= len)
  10207. return empty;
  10208. return String (text + start, len - start);
  10209. }
  10210. const String String::dropLastCharacters (const int numberToDrop) const
  10211. {
  10212. return String (text, jmax (0, length() - numberToDrop));
  10213. }
  10214. const String String::getLastCharacters (const int numCharacters) const
  10215. {
  10216. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10217. }
  10218. const String String::fromFirstOccurrenceOf (const String& sub,
  10219. const bool includeSubString,
  10220. const bool ignoreCase) const
  10221. {
  10222. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10223. : indexOf (sub);
  10224. if (i < 0)
  10225. return empty;
  10226. return substring (includeSubString ? i : i + sub.length());
  10227. }
  10228. const String String::fromLastOccurrenceOf (const String& sub,
  10229. const bool includeSubString,
  10230. const bool ignoreCase) const
  10231. {
  10232. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10233. : lastIndexOf (sub);
  10234. if (i < 0)
  10235. return *this;
  10236. return substring (includeSubString ? i : i + sub.length());
  10237. }
  10238. const String String::upToFirstOccurrenceOf (const String& sub,
  10239. const bool includeSubString,
  10240. const bool ignoreCase) const
  10241. {
  10242. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10243. : indexOf (sub);
  10244. if (i < 0)
  10245. return *this;
  10246. return substring (0, includeSubString ? i + sub.length() : i);
  10247. }
  10248. const String String::upToLastOccurrenceOf (const String& sub,
  10249. const bool includeSubString,
  10250. const bool ignoreCase) const
  10251. {
  10252. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10253. : lastIndexOf (sub);
  10254. if (i < 0)
  10255. return *this;
  10256. return substring (0, includeSubString ? i + sub.length() : i);
  10257. }
  10258. bool String::isQuotedString() const
  10259. {
  10260. const String trimmed (trimStart());
  10261. return trimmed[0] == '"'
  10262. || trimmed[0] == '\'';
  10263. }
  10264. const String String::unquoted() const
  10265. {
  10266. String s (*this);
  10267. if (s.text[0] == '"' || s.text[0] == '\'')
  10268. s = s.substring (1);
  10269. const int lastCharIndex = s.length() - 1;
  10270. if (lastCharIndex >= 0
  10271. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10272. s [lastCharIndex] = 0;
  10273. return s;
  10274. }
  10275. const String String::quoted (const juce_wchar quoteCharacter) const
  10276. {
  10277. if (isEmpty())
  10278. return charToString (quoteCharacter) + quoteCharacter;
  10279. String t (*this);
  10280. if (! t.startsWithChar (quoteCharacter))
  10281. t = charToString (quoteCharacter) + t;
  10282. if (! t.endsWithChar (quoteCharacter))
  10283. t += quoteCharacter;
  10284. return t;
  10285. }
  10286. const String String::trim() const
  10287. {
  10288. if (isEmpty())
  10289. return empty;
  10290. int start = 0;
  10291. while (CharacterFunctions::isWhitespace (text [start]))
  10292. ++start;
  10293. const int len = length();
  10294. int end = len - 1;
  10295. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10296. --end;
  10297. ++end;
  10298. if (end <= start)
  10299. return empty;
  10300. else if (start > 0 || end < len)
  10301. return String (text + start, end - start);
  10302. return *this;
  10303. }
  10304. const String String::trimStart() const
  10305. {
  10306. if (isEmpty())
  10307. return empty;
  10308. const juce_wchar* t = text;
  10309. while (CharacterFunctions::isWhitespace (*t))
  10310. ++t;
  10311. if (t == text)
  10312. return *this;
  10313. return String (t);
  10314. }
  10315. const String String::trimEnd() const
  10316. {
  10317. if (isEmpty())
  10318. return empty;
  10319. const juce_wchar* endT = text + (length() - 1);
  10320. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10321. --endT;
  10322. return String (text, (int) (++endT - text));
  10323. }
  10324. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10325. {
  10326. const juce_wchar* t = text;
  10327. while (charactersToTrim.containsChar (*t))
  10328. ++t;
  10329. return t == text ? *this : String (t);
  10330. }
  10331. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10332. {
  10333. if (isEmpty())
  10334. return empty;
  10335. const int len = length();
  10336. const juce_wchar* endT = text + (len - 1);
  10337. int numToRemove = 0;
  10338. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10339. {
  10340. ++numToRemove;
  10341. --endT;
  10342. }
  10343. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10344. }
  10345. const String String::retainCharacters (const String& charactersToRetain) const
  10346. {
  10347. if (isEmpty())
  10348. return empty;
  10349. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10350. juce_wchar* dst = result.text;
  10351. const juce_wchar* src = text;
  10352. while (*src != 0)
  10353. {
  10354. if (charactersToRetain.containsChar (*src))
  10355. *dst++ = *src;
  10356. ++src;
  10357. }
  10358. *dst = 0;
  10359. return result;
  10360. }
  10361. const String String::removeCharacters (const String& charactersToRemove) const
  10362. {
  10363. if (isEmpty())
  10364. return empty;
  10365. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10366. juce_wchar* dst = result.text;
  10367. const juce_wchar* src = text;
  10368. while (*src != 0)
  10369. {
  10370. if (! charactersToRemove.containsChar (*src))
  10371. *dst++ = *src;
  10372. ++src;
  10373. }
  10374. *dst = 0;
  10375. return result;
  10376. }
  10377. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10378. {
  10379. int i = 0;
  10380. for (;;)
  10381. {
  10382. if (! permittedCharacters.containsChar (text[i]))
  10383. break;
  10384. ++i;
  10385. }
  10386. return substring (0, i);
  10387. }
  10388. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10389. {
  10390. const juce_wchar* const t = text;
  10391. int i = 0;
  10392. while (t[i] != 0)
  10393. {
  10394. if (charactersToStopAt.containsChar (t[i]))
  10395. return String (text, i);
  10396. ++i;
  10397. }
  10398. return empty;
  10399. }
  10400. bool String::containsOnly (const String& chars) const throw()
  10401. {
  10402. const juce_wchar* t = text;
  10403. while (*t != 0)
  10404. if (! chars.containsChar (*t++))
  10405. return false;
  10406. return true;
  10407. }
  10408. bool String::containsAnyOf (const String& chars) const throw()
  10409. {
  10410. const juce_wchar* t = text;
  10411. while (*t != 0)
  10412. if (chars.containsChar (*t++))
  10413. return true;
  10414. return false;
  10415. }
  10416. bool String::containsNonWhitespaceChars() const throw()
  10417. {
  10418. const juce_wchar* t = text;
  10419. while (*t != 0)
  10420. if (! CharacterFunctions::isWhitespace (*t++))
  10421. return true;
  10422. return false;
  10423. }
  10424. const String String::formatted (const juce_wchar* const pf, ... )
  10425. {
  10426. jassert (pf != 0);
  10427. va_list args;
  10428. va_start (args, pf);
  10429. size_t bufferSize = 256;
  10430. String result (bufferSize, (int) 0);
  10431. result.text[0] = 0;
  10432. for (;;)
  10433. {
  10434. #if JUCE_LINUX && JUCE_64BIT
  10435. va_list tempArgs;
  10436. va_copy (tempArgs, args);
  10437. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10438. va_end (tempArgs);
  10439. #elif JUCE_WINDOWS
  10440. #if JUCE_MSVC
  10441. #pragma warning (push)
  10442. #pragma warning (disable: 4996)
  10443. #endif
  10444. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10445. #if JUCE_MSVC
  10446. #pragma warning (pop)
  10447. #endif
  10448. #else
  10449. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10450. #endif
  10451. if (num > 0)
  10452. return result;
  10453. bufferSize += 256;
  10454. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10455. break; // returns -1 because of an error rather than because it needs more space.
  10456. result.preallocateStorage (bufferSize);
  10457. }
  10458. return empty;
  10459. }
  10460. int String::getIntValue() const throw()
  10461. {
  10462. return CharacterFunctions::getIntValue (text);
  10463. }
  10464. int String::getTrailingIntValue() const throw()
  10465. {
  10466. int n = 0;
  10467. int mult = 1;
  10468. const juce_wchar* t = text + length();
  10469. while (--t >= text)
  10470. {
  10471. const juce_wchar c = *t;
  10472. if (! CharacterFunctions::isDigit (c))
  10473. {
  10474. if (c == '-')
  10475. n = -n;
  10476. break;
  10477. }
  10478. n += mult * (c - '0');
  10479. mult *= 10;
  10480. }
  10481. return n;
  10482. }
  10483. int64 String::getLargeIntValue() const throw()
  10484. {
  10485. return CharacterFunctions::getInt64Value (text);
  10486. }
  10487. float String::getFloatValue() const throw()
  10488. {
  10489. return (float) CharacterFunctions::getDoubleValue (text);
  10490. }
  10491. double String::getDoubleValue() const throw()
  10492. {
  10493. return CharacterFunctions::getDoubleValue (text);
  10494. }
  10495. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10496. const String String::toHexString (const int number)
  10497. {
  10498. juce_wchar buffer[32];
  10499. juce_wchar* const end = buffer + 32;
  10500. juce_wchar* t = end;
  10501. *--t = 0;
  10502. unsigned int v = (unsigned int) number;
  10503. do
  10504. {
  10505. *--t = hexDigits [v & 15];
  10506. v >>= 4;
  10507. } while (v != 0);
  10508. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10509. }
  10510. const String String::toHexString (const int64 number)
  10511. {
  10512. juce_wchar buffer[32];
  10513. juce_wchar* const end = buffer + 32;
  10514. juce_wchar* t = end;
  10515. *--t = 0;
  10516. uint64 v = (uint64) number;
  10517. do
  10518. {
  10519. *--t = hexDigits [(int) (v & 15)];
  10520. v >>= 4;
  10521. } while (v != 0);
  10522. return String (t, (int) (((char*) end) - (char*) t));
  10523. }
  10524. const String String::toHexString (const short number)
  10525. {
  10526. return toHexString ((int) (unsigned short) number);
  10527. }
  10528. const String String::toHexString (const unsigned char* data,
  10529. const int size,
  10530. const int groupSize)
  10531. {
  10532. if (size <= 0)
  10533. return empty;
  10534. int numChars = (size * 2) + 2;
  10535. if (groupSize > 0)
  10536. numChars += size / groupSize;
  10537. String s ((size_t) numChars, (int) 0);
  10538. juce_wchar* d = s.text;
  10539. for (int i = 0; i < size; ++i)
  10540. {
  10541. *d++ = hexDigits [(*data) >> 4];
  10542. *d++ = hexDigits [(*data) & 0xf];
  10543. ++data;
  10544. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10545. *d++ = ' ';
  10546. }
  10547. *d = 0;
  10548. return s;
  10549. }
  10550. int String::getHexValue32() const throw()
  10551. {
  10552. int result = 0;
  10553. const juce_wchar* c = text;
  10554. for (;;)
  10555. {
  10556. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10557. if (hexValue >= 0)
  10558. result = (result << 4) | hexValue;
  10559. else if (*c == 0)
  10560. break;
  10561. ++c;
  10562. }
  10563. return result;
  10564. }
  10565. int64 String::getHexValue64() const throw()
  10566. {
  10567. int64 result = 0;
  10568. const juce_wchar* c = text;
  10569. for (;;)
  10570. {
  10571. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10572. if (hexValue >= 0)
  10573. result = (result << 4) | hexValue;
  10574. else if (*c == 0)
  10575. break;
  10576. ++c;
  10577. }
  10578. return result;
  10579. }
  10580. const String String::createStringFromData (const void* const data_, const int size)
  10581. {
  10582. const char* const data = static_cast <const char*> (data_);
  10583. if (size <= 0 || data == 0)
  10584. {
  10585. return empty;
  10586. }
  10587. else if (size < 2)
  10588. {
  10589. return charToString (data[0]);
  10590. }
  10591. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10592. || (data[0] == (char)-1 && data[1] == (char)-2))
  10593. {
  10594. // assume it's 16-bit unicode
  10595. const bool bigEndian = (data[0] == (char)-2);
  10596. const int numChars = size / 2 - 1;
  10597. String result;
  10598. result.preallocateStorage (numChars + 2);
  10599. const uint16* const src = (const uint16*) (data + 2);
  10600. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10601. if (bigEndian)
  10602. {
  10603. for (int i = 0; i < numChars; ++i)
  10604. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10605. }
  10606. else
  10607. {
  10608. for (int i = 0; i < numChars; ++i)
  10609. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10610. }
  10611. dst [numChars] = 0;
  10612. return result;
  10613. }
  10614. else
  10615. {
  10616. return String::fromUTF8 (data, size);
  10617. }
  10618. }
  10619. const char* String::toUTF8() const
  10620. {
  10621. if (isEmpty())
  10622. {
  10623. return reinterpret_cast <const char*> (text);
  10624. }
  10625. else
  10626. {
  10627. const int currentLen = length() + 1;
  10628. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10629. String* const mutableThis = const_cast <String*> (this);
  10630. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10631. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10632. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10633. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10634. #endif
  10635. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10636. return otherCopy;
  10637. }
  10638. }
  10639. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10640. {
  10641. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10642. int num = 0, index = 0;
  10643. for (;;)
  10644. {
  10645. const uint32 c = (uint32) text [index++];
  10646. if (c >= 0x80)
  10647. {
  10648. int numExtraBytes = 1;
  10649. if (c >= 0x800)
  10650. {
  10651. ++numExtraBytes;
  10652. if (c >= 0x10000)
  10653. {
  10654. ++numExtraBytes;
  10655. if (c >= 0x200000)
  10656. {
  10657. ++numExtraBytes;
  10658. if (c >= 0x4000000)
  10659. ++numExtraBytes;
  10660. }
  10661. }
  10662. }
  10663. if (buffer != 0)
  10664. {
  10665. if (num + numExtraBytes >= maxBufferSizeBytes)
  10666. {
  10667. buffer [num++] = 0;
  10668. break;
  10669. }
  10670. else
  10671. {
  10672. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10673. while (--numExtraBytes >= 0)
  10674. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10675. }
  10676. }
  10677. else
  10678. {
  10679. num += numExtraBytes + 1;
  10680. }
  10681. }
  10682. else
  10683. {
  10684. if (buffer != 0)
  10685. {
  10686. if (num + 1 >= maxBufferSizeBytes)
  10687. {
  10688. buffer [num++] = 0;
  10689. break;
  10690. }
  10691. buffer [num] = (uint8) c;
  10692. }
  10693. ++num;
  10694. }
  10695. if (c == 0)
  10696. break;
  10697. }
  10698. return num;
  10699. }
  10700. int String::getNumBytesAsUTF8() const throw()
  10701. {
  10702. int num = 0;
  10703. const juce_wchar* t = text;
  10704. for (;;)
  10705. {
  10706. const uint32 c = (uint32) *t;
  10707. if (c >= 0x80)
  10708. {
  10709. ++num;
  10710. if (c >= 0x800)
  10711. {
  10712. ++num;
  10713. if (c >= 0x10000)
  10714. {
  10715. ++num;
  10716. if (c >= 0x200000)
  10717. {
  10718. ++num;
  10719. if (c >= 0x4000000)
  10720. ++num;
  10721. }
  10722. }
  10723. }
  10724. }
  10725. else if (c == 0)
  10726. break;
  10727. ++num;
  10728. ++t;
  10729. }
  10730. return num;
  10731. }
  10732. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10733. {
  10734. if (buffer == 0)
  10735. return empty;
  10736. if (bufferSizeBytes < 0)
  10737. bufferSizeBytes = std::numeric_limits<int>::max();
  10738. size_t numBytes;
  10739. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10740. if (buffer [numBytes] == 0)
  10741. break;
  10742. String result ((size_t) numBytes + 1, (int) 0);
  10743. juce_wchar* dest = result.text;
  10744. size_t i = 0;
  10745. while (i < numBytes)
  10746. {
  10747. const char c = buffer [i++];
  10748. if (c < 0)
  10749. {
  10750. unsigned int mask = 0x7f;
  10751. int bit = 0x40;
  10752. int numExtraValues = 0;
  10753. while (bit != 0 && (c & bit) != 0)
  10754. {
  10755. bit >>= 1;
  10756. mask >>= 1;
  10757. ++numExtraValues;
  10758. }
  10759. int n = (mask & (unsigned char) c);
  10760. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10761. {
  10762. const char nextByte = buffer[i];
  10763. if ((nextByte & 0xc0) != 0x80)
  10764. break;
  10765. n <<= 6;
  10766. n |= (nextByte & 0x3f);
  10767. ++i;
  10768. }
  10769. *dest++ = (juce_wchar) n;
  10770. }
  10771. else
  10772. {
  10773. *dest++ = (juce_wchar) c;
  10774. }
  10775. }
  10776. *dest = 0;
  10777. return result;
  10778. }
  10779. const char* String::toCString() const
  10780. {
  10781. if (isEmpty())
  10782. {
  10783. return reinterpret_cast <const char*> (text);
  10784. }
  10785. else
  10786. {
  10787. const int len = length();
  10788. String* const mutableThis = const_cast <String*> (this);
  10789. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  10790. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  10791. CharacterFunctions::copy (otherCopy, text, len);
  10792. otherCopy [len] = 0;
  10793. return otherCopy;
  10794. }
  10795. }
  10796. #if JUCE_MSVC
  10797. #pragma warning (push)
  10798. #pragma warning (disable: 4514 4996)
  10799. #endif
  10800. int String::getNumBytesAsCString() const throw()
  10801. {
  10802. return (int) wcstombs (0, text, 0);
  10803. }
  10804. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10805. {
  10806. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10807. if (destBuffer != 0 && numBytes >= 0)
  10808. destBuffer [numBytes] = 0;
  10809. return numBytes;
  10810. }
  10811. #if JUCE_MSVC
  10812. #pragma warning (pop)
  10813. #endif
  10814. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  10815. {
  10816. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  10817. }
  10818. String::Concatenator::Concatenator (String& stringToAppendTo)
  10819. : result (stringToAppendTo),
  10820. nextIndex (stringToAppendTo.length())
  10821. {
  10822. }
  10823. String::Concatenator::~Concatenator()
  10824. {
  10825. }
  10826. void String::Concatenator::append (const String& s)
  10827. {
  10828. const int len = s.length();
  10829. if (len > 0)
  10830. {
  10831. result.preallocateStorage (nextIndex + len);
  10832. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  10833. nextIndex += len;
  10834. }
  10835. }
  10836. END_JUCE_NAMESPACE
  10837. /*** End of inlined file: juce_String.cpp ***/
  10838. /*** Start of inlined file: juce_StringArray.cpp ***/
  10839. BEGIN_JUCE_NAMESPACE
  10840. StringArray::StringArray() throw()
  10841. {
  10842. }
  10843. StringArray::StringArray (const StringArray& other)
  10844. : strings (other.strings)
  10845. {
  10846. }
  10847. StringArray::StringArray (const String& firstValue)
  10848. {
  10849. strings.add (firstValue);
  10850. }
  10851. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  10852. const int numberOfStrings)
  10853. {
  10854. for (int i = 0; i < numberOfStrings; ++i)
  10855. strings.add (initialStrings [i]);
  10856. }
  10857. StringArray::StringArray (const char* const* const initialStrings,
  10858. const int numberOfStrings)
  10859. {
  10860. for (int i = 0; i < numberOfStrings; ++i)
  10861. strings.add (initialStrings [i]);
  10862. }
  10863. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  10864. {
  10865. int i = 0;
  10866. while (initialStrings[i] != 0)
  10867. strings.add (initialStrings [i++]);
  10868. }
  10869. StringArray::StringArray (const char* const* const initialStrings)
  10870. {
  10871. int i = 0;
  10872. while (initialStrings[i] != 0)
  10873. strings.add (initialStrings [i++]);
  10874. }
  10875. StringArray& StringArray::operator= (const StringArray& other)
  10876. {
  10877. strings = other.strings;
  10878. return *this;
  10879. }
  10880. StringArray::~StringArray()
  10881. {
  10882. }
  10883. bool StringArray::operator== (const StringArray& other) const throw()
  10884. {
  10885. if (other.size() != size())
  10886. return false;
  10887. for (int i = size(); --i >= 0;)
  10888. if (other.strings.getReference(i) != strings.getReference(i))
  10889. return false;
  10890. return true;
  10891. }
  10892. bool StringArray::operator!= (const StringArray& other) const throw()
  10893. {
  10894. return ! operator== (other);
  10895. }
  10896. void StringArray::clear()
  10897. {
  10898. strings.clear();
  10899. }
  10900. const String& StringArray::operator[] (const int index) const throw()
  10901. {
  10902. if (((unsigned int) index) < (unsigned int) strings.size())
  10903. return strings.getReference (index);
  10904. return String::empty;
  10905. }
  10906. String& StringArray::getReference (const int index) throw()
  10907. {
  10908. jassert (((unsigned int) index) < (unsigned int) strings.size());
  10909. return strings.getReference (index);
  10910. }
  10911. void StringArray::add (const String& newString)
  10912. {
  10913. strings.add (newString);
  10914. }
  10915. void StringArray::insert (const int index, const String& newString)
  10916. {
  10917. strings.insert (index, newString);
  10918. }
  10919. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10920. {
  10921. if (! contains (newString, ignoreCase))
  10922. add (newString);
  10923. }
  10924. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10925. {
  10926. if (startIndex < 0)
  10927. {
  10928. jassertfalse;
  10929. startIndex = 0;
  10930. }
  10931. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10932. numElementsToAdd = otherArray.size() - startIndex;
  10933. while (--numElementsToAdd >= 0)
  10934. strings.add (otherArray.strings.getReference (startIndex++));
  10935. }
  10936. void StringArray::set (const int index, const String& newString)
  10937. {
  10938. strings.set (index, newString);
  10939. }
  10940. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10941. {
  10942. if (ignoreCase)
  10943. {
  10944. for (int i = size(); --i >= 0;)
  10945. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10946. return true;
  10947. }
  10948. else
  10949. {
  10950. for (int i = size(); --i >= 0;)
  10951. if (stringToLookFor == strings.getReference(i))
  10952. return true;
  10953. }
  10954. return false;
  10955. }
  10956. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10957. {
  10958. if (i < 0)
  10959. i = 0;
  10960. const int numElements = size();
  10961. if (ignoreCase)
  10962. {
  10963. while (i < numElements)
  10964. {
  10965. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10966. return i;
  10967. ++i;
  10968. }
  10969. }
  10970. else
  10971. {
  10972. while (i < numElements)
  10973. {
  10974. if (stringToLookFor == strings.getReference (i))
  10975. return i;
  10976. ++i;
  10977. }
  10978. }
  10979. return -1;
  10980. }
  10981. void StringArray::remove (const int index)
  10982. {
  10983. strings.remove (index);
  10984. }
  10985. void StringArray::removeString (const String& stringToRemove,
  10986. const bool ignoreCase)
  10987. {
  10988. if (ignoreCase)
  10989. {
  10990. for (int i = size(); --i >= 0;)
  10991. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10992. strings.remove (i);
  10993. }
  10994. else
  10995. {
  10996. for (int i = size(); --i >= 0;)
  10997. if (stringToRemove == strings.getReference (i))
  10998. strings.remove (i);
  10999. }
  11000. }
  11001. void StringArray::removeRange (int startIndex, int numberToRemove)
  11002. {
  11003. strings.removeRange (startIndex, numberToRemove);
  11004. }
  11005. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11006. {
  11007. if (removeWhitespaceStrings)
  11008. {
  11009. for (int i = size(); --i >= 0;)
  11010. if (! strings.getReference(i).containsNonWhitespaceChars())
  11011. strings.remove (i);
  11012. }
  11013. else
  11014. {
  11015. for (int i = size(); --i >= 0;)
  11016. if (strings.getReference(i).isEmpty())
  11017. strings.remove (i);
  11018. }
  11019. }
  11020. void StringArray::trim()
  11021. {
  11022. for (int i = size(); --i >= 0;)
  11023. {
  11024. String& s = strings.getReference(i);
  11025. s = s.trim();
  11026. }
  11027. }
  11028. class InternalStringArrayComparator_CaseSensitive
  11029. {
  11030. public:
  11031. static int compareElements (String& first, String& second) { return first.compare (second); }
  11032. };
  11033. class InternalStringArrayComparator_CaseInsensitive
  11034. {
  11035. public:
  11036. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11037. };
  11038. void StringArray::sort (const bool ignoreCase)
  11039. {
  11040. if (ignoreCase)
  11041. {
  11042. InternalStringArrayComparator_CaseInsensitive comp;
  11043. strings.sort (comp);
  11044. }
  11045. else
  11046. {
  11047. InternalStringArrayComparator_CaseSensitive comp;
  11048. strings.sort (comp);
  11049. }
  11050. }
  11051. void StringArray::move (const int currentIndex, int newIndex) throw()
  11052. {
  11053. strings.move (currentIndex, newIndex);
  11054. }
  11055. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11056. {
  11057. const int last = (numberToJoin < 0) ? size()
  11058. : jmin (size(), start + numberToJoin);
  11059. if (start < 0)
  11060. start = 0;
  11061. if (start >= last)
  11062. return String::empty;
  11063. if (start == last - 1)
  11064. return strings.getReference (start);
  11065. const int separatorLen = separator.length();
  11066. int charsNeeded = separatorLen * (last - start - 1);
  11067. for (int i = start; i < last; ++i)
  11068. charsNeeded += strings.getReference(i).length();
  11069. String result;
  11070. result.preallocateStorage (charsNeeded);
  11071. juce_wchar* dest = result;
  11072. while (start < last)
  11073. {
  11074. const String& s = strings.getReference (start);
  11075. const int len = s.length();
  11076. if (len > 0)
  11077. {
  11078. s.copyToUnicode (dest, len);
  11079. dest += len;
  11080. }
  11081. if (++start < last && separatorLen > 0)
  11082. {
  11083. separator.copyToUnicode (dest, separatorLen);
  11084. dest += separatorLen;
  11085. }
  11086. }
  11087. *dest = 0;
  11088. return result;
  11089. }
  11090. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11091. {
  11092. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11093. }
  11094. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11095. {
  11096. int num = 0;
  11097. if (text.isNotEmpty())
  11098. {
  11099. bool insideQuotes = false;
  11100. juce_wchar currentQuoteChar = 0;
  11101. int i = 0;
  11102. int tokenStart = 0;
  11103. for (;;)
  11104. {
  11105. const juce_wchar c = text[i];
  11106. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11107. if (! isBreak)
  11108. {
  11109. if (quoteCharacters.containsChar (c))
  11110. {
  11111. if (insideQuotes)
  11112. {
  11113. // only break out of quotes-mode if we find a matching quote to the
  11114. // one that we opened with..
  11115. if (currentQuoteChar == c)
  11116. insideQuotes = false;
  11117. }
  11118. else
  11119. {
  11120. insideQuotes = true;
  11121. currentQuoteChar = c;
  11122. }
  11123. }
  11124. }
  11125. else
  11126. {
  11127. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11128. ++num;
  11129. tokenStart = i + 1;
  11130. }
  11131. if (c == 0)
  11132. break;
  11133. ++i;
  11134. }
  11135. }
  11136. return num;
  11137. }
  11138. int StringArray::addLines (const String& sourceText)
  11139. {
  11140. int numLines = 0;
  11141. const juce_wchar* text = sourceText;
  11142. while (*text != 0)
  11143. {
  11144. const juce_wchar* const startOfLine = text;
  11145. while (*text != 0)
  11146. {
  11147. if (*text == '\r')
  11148. {
  11149. ++text;
  11150. if (*text == '\n')
  11151. ++text;
  11152. break;
  11153. }
  11154. if (*text == '\n')
  11155. {
  11156. ++text;
  11157. break;
  11158. }
  11159. ++text;
  11160. }
  11161. const juce_wchar* endOfLine = text;
  11162. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11163. --endOfLine;
  11164. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11165. --endOfLine;
  11166. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11167. ++numLines;
  11168. }
  11169. return numLines;
  11170. }
  11171. void StringArray::removeDuplicates (const bool ignoreCase)
  11172. {
  11173. for (int i = 0; i < size() - 1; ++i)
  11174. {
  11175. const String s (strings.getReference(i));
  11176. int nextIndex = i + 1;
  11177. for (;;)
  11178. {
  11179. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11180. if (nextIndex < 0)
  11181. break;
  11182. strings.remove (nextIndex);
  11183. }
  11184. }
  11185. }
  11186. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11187. const bool appendNumberToFirstInstance,
  11188. const juce_wchar* preNumberString,
  11189. const juce_wchar* postNumberString)
  11190. {
  11191. if (preNumberString == 0)
  11192. preNumberString = L" (";
  11193. if (postNumberString == 0)
  11194. postNumberString = L")";
  11195. for (int i = 0; i < size() - 1; ++i)
  11196. {
  11197. String& s = strings.getReference(i);
  11198. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11199. if (nextIndex >= 0)
  11200. {
  11201. const String original (s);
  11202. int number = 0;
  11203. if (appendNumberToFirstInstance)
  11204. s = original + preNumberString + String (++number) + postNumberString;
  11205. else
  11206. ++number;
  11207. while (nextIndex >= 0)
  11208. {
  11209. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11210. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11211. }
  11212. }
  11213. }
  11214. }
  11215. void StringArray::minimiseStorageOverheads()
  11216. {
  11217. strings.minimiseStorageOverheads();
  11218. }
  11219. END_JUCE_NAMESPACE
  11220. /*** End of inlined file: juce_StringArray.cpp ***/
  11221. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11222. BEGIN_JUCE_NAMESPACE
  11223. StringPairArray::StringPairArray (const bool ignoreCase_)
  11224. : ignoreCase (ignoreCase_)
  11225. {
  11226. }
  11227. StringPairArray::StringPairArray (const StringPairArray& other)
  11228. : keys (other.keys),
  11229. values (other.values),
  11230. ignoreCase (other.ignoreCase)
  11231. {
  11232. }
  11233. StringPairArray::~StringPairArray()
  11234. {
  11235. }
  11236. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11237. {
  11238. keys = other.keys;
  11239. values = other.values;
  11240. return *this;
  11241. }
  11242. bool StringPairArray::operator== (const StringPairArray& other) const
  11243. {
  11244. for (int i = keys.size(); --i >= 0;)
  11245. if (other [keys[i]] != values[i])
  11246. return false;
  11247. return true;
  11248. }
  11249. bool StringPairArray::operator!= (const StringPairArray& other) const
  11250. {
  11251. return ! operator== (other);
  11252. }
  11253. const String& StringPairArray::operator[] (const String& key) const
  11254. {
  11255. return values [keys.indexOf (key, ignoreCase)];
  11256. }
  11257. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11258. {
  11259. const int i = keys.indexOf (key, ignoreCase);
  11260. if (i >= 0)
  11261. return values[i];
  11262. return defaultReturnValue;
  11263. }
  11264. void StringPairArray::set (const String& key, const String& value)
  11265. {
  11266. const int i = keys.indexOf (key, ignoreCase);
  11267. if (i >= 0)
  11268. {
  11269. values.set (i, value);
  11270. }
  11271. else
  11272. {
  11273. keys.add (key);
  11274. values.add (value);
  11275. }
  11276. }
  11277. void StringPairArray::addArray (const StringPairArray& other)
  11278. {
  11279. for (int i = 0; i < other.size(); ++i)
  11280. set (other.keys[i], other.values[i]);
  11281. }
  11282. void StringPairArray::clear()
  11283. {
  11284. keys.clear();
  11285. values.clear();
  11286. }
  11287. void StringPairArray::remove (const String& key)
  11288. {
  11289. remove (keys.indexOf (key, ignoreCase));
  11290. }
  11291. void StringPairArray::remove (const int index)
  11292. {
  11293. keys.remove (index);
  11294. values.remove (index);
  11295. }
  11296. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11297. {
  11298. ignoreCase = shouldIgnoreCase;
  11299. }
  11300. const String StringPairArray::getDescription() const
  11301. {
  11302. String s;
  11303. for (int i = 0; i < keys.size(); ++i)
  11304. {
  11305. s << keys[i] << " = " << values[i];
  11306. if (i < keys.size())
  11307. s << ", ";
  11308. }
  11309. return s;
  11310. }
  11311. void StringPairArray::minimiseStorageOverheads()
  11312. {
  11313. keys.minimiseStorageOverheads();
  11314. values.minimiseStorageOverheads();
  11315. }
  11316. END_JUCE_NAMESPACE
  11317. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11318. /*** Start of inlined file: juce_StringPool.cpp ***/
  11319. BEGIN_JUCE_NAMESPACE
  11320. StringPool::StringPool() throw() {}
  11321. StringPool::~StringPool() {}
  11322. template <class StringType>
  11323. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11324. {
  11325. int start = 0;
  11326. int end = strings.size();
  11327. for (;;)
  11328. {
  11329. if (start >= end)
  11330. {
  11331. jassert (start <= end);
  11332. strings.insert (start, newString);
  11333. return strings.getReference (start);
  11334. }
  11335. else
  11336. {
  11337. const String& startString = strings.getReference (start);
  11338. if (startString == newString)
  11339. return startString;
  11340. const int halfway = (start + end) >> 1;
  11341. if (halfway == start)
  11342. {
  11343. if (startString.compare (newString) < 0)
  11344. ++start;
  11345. strings.insert (start, newString);
  11346. return strings.getReference (start);
  11347. }
  11348. const int comp = strings.getReference (halfway).compare (newString);
  11349. if (comp == 0)
  11350. return strings.getReference (halfway);
  11351. else if (comp < 0)
  11352. start = halfway;
  11353. else
  11354. end = halfway;
  11355. }
  11356. }
  11357. }
  11358. const juce_wchar* StringPool::getPooledString (const String& s)
  11359. {
  11360. if (s.isEmpty())
  11361. return String::empty;
  11362. return getPooledStringFromArray (strings, s);
  11363. }
  11364. const juce_wchar* StringPool::getPooledString (const char* const s)
  11365. {
  11366. if (s == 0 || *s == 0)
  11367. return String::empty;
  11368. return getPooledStringFromArray (strings, s);
  11369. }
  11370. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11371. {
  11372. if (s == 0 || *s == 0)
  11373. return String::empty;
  11374. return getPooledStringFromArray (strings, s);
  11375. }
  11376. int StringPool::size() const throw()
  11377. {
  11378. return strings.size();
  11379. }
  11380. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11381. {
  11382. return strings [index];
  11383. }
  11384. END_JUCE_NAMESPACE
  11385. /*** End of inlined file: juce_StringPool.cpp ***/
  11386. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11387. BEGIN_JUCE_NAMESPACE
  11388. XmlDocument::XmlDocument (const String& documentText)
  11389. : originalText (documentText),
  11390. ignoreEmptyTextElements (true)
  11391. {
  11392. }
  11393. XmlDocument::XmlDocument (const File& file)
  11394. : ignoreEmptyTextElements (true)
  11395. {
  11396. inputSource = new FileInputSource (file);
  11397. }
  11398. XmlDocument::~XmlDocument()
  11399. {
  11400. }
  11401. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11402. {
  11403. inputSource = newSource;
  11404. }
  11405. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11406. {
  11407. ignoreEmptyTextElements = shouldBeIgnored;
  11408. }
  11409. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11410. {
  11411. return CharacterFunctions::isLetterOrDigit (c)
  11412. || c == '_' || c == '-' || c == ':' || c == '.';
  11413. }
  11414. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11415. {
  11416. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11417. : isXmlIdentifierCharSlow (c);
  11418. }
  11419. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11420. {
  11421. String textToParse (originalText);
  11422. if (textToParse.isEmpty() && inputSource != 0)
  11423. {
  11424. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11425. if (in != 0)
  11426. {
  11427. MemoryOutputStream data;
  11428. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11429. textToParse = data.toString();
  11430. if (! onlyReadOuterDocumentElement)
  11431. originalText = textToParse;
  11432. }
  11433. }
  11434. input = textToParse;
  11435. lastError = String::empty;
  11436. errorOccurred = false;
  11437. outOfData = false;
  11438. needToLoadDTD = true;
  11439. for (int i = 0; i < 128; ++i)
  11440. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11441. if (textToParse.isEmpty())
  11442. {
  11443. lastError = "not enough input";
  11444. }
  11445. else
  11446. {
  11447. skipHeader();
  11448. if (input != 0)
  11449. {
  11450. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11451. if (! errorOccurred)
  11452. return result.release();
  11453. }
  11454. else
  11455. {
  11456. lastError = "incorrect xml header";
  11457. }
  11458. }
  11459. return 0;
  11460. }
  11461. const String& XmlDocument::getLastParseError() const throw()
  11462. {
  11463. return lastError;
  11464. }
  11465. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11466. {
  11467. lastError = desc;
  11468. errorOccurred = ! carryOn;
  11469. }
  11470. const String XmlDocument::getFileContents (const String& filename) const
  11471. {
  11472. if (inputSource != 0)
  11473. {
  11474. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11475. if (in != 0)
  11476. return in->readEntireStreamAsString();
  11477. }
  11478. return String::empty;
  11479. }
  11480. juce_wchar XmlDocument::readNextChar() throw()
  11481. {
  11482. if (*input != 0)
  11483. {
  11484. return *input++;
  11485. }
  11486. else
  11487. {
  11488. outOfData = true;
  11489. return 0;
  11490. }
  11491. }
  11492. int XmlDocument::findNextTokenLength() throw()
  11493. {
  11494. int len = 0;
  11495. juce_wchar c = *input;
  11496. while (isXmlIdentifierChar (c))
  11497. c = input [++len];
  11498. return len;
  11499. }
  11500. void XmlDocument::skipHeader()
  11501. {
  11502. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11503. if (found != 0)
  11504. {
  11505. input = found;
  11506. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11507. if (input == 0)
  11508. return;
  11509. input += 2;
  11510. }
  11511. skipNextWhiteSpace();
  11512. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11513. if (docType == 0)
  11514. return;
  11515. input = docType + 9;
  11516. int n = 1;
  11517. while (n > 0)
  11518. {
  11519. const juce_wchar c = readNextChar();
  11520. if (outOfData)
  11521. return;
  11522. if (c == '<')
  11523. ++n;
  11524. else if (c == '>')
  11525. --n;
  11526. }
  11527. docType += 9;
  11528. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11529. }
  11530. void XmlDocument::skipNextWhiteSpace()
  11531. {
  11532. for (;;)
  11533. {
  11534. juce_wchar c = *input;
  11535. while (CharacterFunctions::isWhitespace (c))
  11536. c = *++input;
  11537. if (c == 0)
  11538. {
  11539. outOfData = true;
  11540. break;
  11541. }
  11542. else if (c == '<')
  11543. {
  11544. if (input[1] == '!'
  11545. && input[2] == '-'
  11546. && input[3] == '-')
  11547. {
  11548. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  11549. if (closeComment == 0)
  11550. {
  11551. outOfData = true;
  11552. break;
  11553. }
  11554. input = closeComment + 3;
  11555. continue;
  11556. }
  11557. else if (input[1] == '?')
  11558. {
  11559. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  11560. if (closeBracket == 0)
  11561. {
  11562. outOfData = true;
  11563. break;
  11564. }
  11565. input = closeBracket + 2;
  11566. continue;
  11567. }
  11568. }
  11569. break;
  11570. }
  11571. }
  11572. void XmlDocument::readQuotedString (String& result)
  11573. {
  11574. const juce_wchar quote = readNextChar();
  11575. while (! outOfData)
  11576. {
  11577. const juce_wchar c = readNextChar();
  11578. if (c == quote)
  11579. break;
  11580. if (c == '&')
  11581. {
  11582. --input;
  11583. readEntity (result);
  11584. }
  11585. else
  11586. {
  11587. --input;
  11588. const juce_wchar* const start = input;
  11589. for (;;)
  11590. {
  11591. const juce_wchar character = *input;
  11592. if (character == quote)
  11593. {
  11594. result.append (start, (int) (input - start));
  11595. ++input;
  11596. return;
  11597. }
  11598. else if (character == '&')
  11599. {
  11600. result.append (start, (int) (input - start));
  11601. break;
  11602. }
  11603. else if (character == 0)
  11604. {
  11605. outOfData = true;
  11606. setLastError ("unmatched quotes", false);
  11607. break;
  11608. }
  11609. ++input;
  11610. }
  11611. }
  11612. }
  11613. }
  11614. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11615. {
  11616. XmlElement* node = 0;
  11617. skipNextWhiteSpace();
  11618. if (outOfData)
  11619. return 0;
  11620. input = CharacterFunctions::find (input, JUCE_T("<"));
  11621. if (input != 0)
  11622. {
  11623. ++input;
  11624. int tagLen = findNextTokenLength();
  11625. if (tagLen == 0)
  11626. {
  11627. // no tag name - but allow for a gap after the '<' before giving an error
  11628. skipNextWhiteSpace();
  11629. tagLen = findNextTokenLength();
  11630. if (tagLen == 0)
  11631. {
  11632. setLastError ("tag name missing", false);
  11633. return node;
  11634. }
  11635. }
  11636. node = new XmlElement (String (input, tagLen));
  11637. input += tagLen;
  11638. XmlElement::XmlAttributeNode* lastAttribute = 0;
  11639. // look for attributes
  11640. for (;;)
  11641. {
  11642. skipNextWhiteSpace();
  11643. const juce_wchar c = *input;
  11644. // empty tag..
  11645. if (c == '/' && input[1] == '>')
  11646. {
  11647. input += 2;
  11648. break;
  11649. }
  11650. // parse the guts of the element..
  11651. if (c == '>')
  11652. {
  11653. ++input;
  11654. skipNextWhiteSpace();
  11655. if (alsoParseSubElements)
  11656. readChildElements (node);
  11657. break;
  11658. }
  11659. // get an attribute..
  11660. if (isXmlIdentifierChar (c))
  11661. {
  11662. const int attNameLen = findNextTokenLength();
  11663. if (attNameLen > 0)
  11664. {
  11665. const juce_wchar* attNameStart = input;
  11666. input += attNameLen;
  11667. skipNextWhiteSpace();
  11668. if (readNextChar() == '=')
  11669. {
  11670. skipNextWhiteSpace();
  11671. const juce_wchar nextChar = *input;
  11672. if (nextChar == '"' || nextChar == '\'')
  11673. {
  11674. XmlElement::XmlAttributeNode* const newAtt
  11675. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  11676. String::empty);
  11677. readQuotedString (newAtt->value);
  11678. if (lastAttribute == 0)
  11679. node->attributes = newAtt;
  11680. else
  11681. lastAttribute->next = newAtt;
  11682. lastAttribute = newAtt;
  11683. continue;
  11684. }
  11685. }
  11686. }
  11687. }
  11688. else
  11689. {
  11690. if (! outOfData)
  11691. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11692. }
  11693. break;
  11694. }
  11695. }
  11696. return node;
  11697. }
  11698. void XmlDocument::readChildElements (XmlElement* parent)
  11699. {
  11700. XmlElement* lastChildNode = 0;
  11701. for (;;)
  11702. {
  11703. skipNextWhiteSpace();
  11704. if (outOfData)
  11705. {
  11706. setLastError ("unmatched tags", false);
  11707. break;
  11708. }
  11709. if (*input == '<')
  11710. {
  11711. if (input[1] == '/')
  11712. {
  11713. // our close tag..
  11714. input = CharacterFunctions::find (input, JUCE_T(">"));
  11715. ++input;
  11716. break;
  11717. }
  11718. else if (input[1] == '!'
  11719. && input[2] == '['
  11720. && input[3] == 'C'
  11721. && input[4] == 'D'
  11722. && input[5] == 'A'
  11723. && input[6] == 'T'
  11724. && input[7] == 'A'
  11725. && input[8] == '[')
  11726. {
  11727. input += 9;
  11728. const juce_wchar* const inputStart = input;
  11729. int len = 0;
  11730. for (;;)
  11731. {
  11732. if (*input == 0)
  11733. {
  11734. setLastError ("unterminated CDATA section", false);
  11735. outOfData = true;
  11736. break;
  11737. }
  11738. else if (input[0] == ']'
  11739. && input[1] == ']'
  11740. && input[2] == '>')
  11741. {
  11742. input += 3;
  11743. break;
  11744. }
  11745. ++input;
  11746. ++len;
  11747. }
  11748. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  11749. if (lastChildNode != 0)
  11750. lastChildNode->nextElement = e;
  11751. else
  11752. parent->addChildElement (e);
  11753. lastChildNode = e;
  11754. }
  11755. else
  11756. {
  11757. // this is some other element, so parse and add it..
  11758. XmlElement* const n = readNextElement (true);
  11759. if (n != 0)
  11760. {
  11761. if (lastChildNode == 0)
  11762. parent->addChildElement (n);
  11763. else
  11764. lastChildNode->nextElement = n;
  11765. lastChildNode = n;
  11766. }
  11767. else
  11768. {
  11769. return;
  11770. }
  11771. }
  11772. }
  11773. else
  11774. {
  11775. // read character block..
  11776. XmlElement* const e = new XmlElement ((int)0);
  11777. if (lastChildNode != 0)
  11778. lastChildNode->nextElement = e;
  11779. else
  11780. parent->addChildElement (e);
  11781. lastChildNode = e;
  11782. String textElementContent;
  11783. for (;;)
  11784. {
  11785. const juce_wchar c = *input;
  11786. if (c == '<')
  11787. break;
  11788. if (c == 0)
  11789. {
  11790. setLastError ("unmatched tags", false);
  11791. outOfData = true;
  11792. return;
  11793. }
  11794. if (c == '&')
  11795. {
  11796. String entity;
  11797. readEntity (entity);
  11798. if (entity.startsWithChar ('<') && entity [1] != 0)
  11799. {
  11800. const juce_wchar* const oldInput = input;
  11801. const bool oldOutOfData = outOfData;
  11802. input = entity;
  11803. outOfData = false;
  11804. for (;;)
  11805. {
  11806. XmlElement* const n = readNextElement (true);
  11807. if (n == 0)
  11808. break;
  11809. if (lastChildNode == 0)
  11810. parent->addChildElement (n);
  11811. else
  11812. lastChildNode->nextElement = n;
  11813. lastChildNode = n;
  11814. }
  11815. input = oldInput;
  11816. outOfData = oldOutOfData;
  11817. }
  11818. else
  11819. {
  11820. textElementContent += entity;
  11821. }
  11822. }
  11823. else
  11824. {
  11825. const juce_wchar* start = input;
  11826. int len = 0;
  11827. for (;;)
  11828. {
  11829. const juce_wchar nextChar = *input;
  11830. if (nextChar == '<' || nextChar == '&')
  11831. {
  11832. break;
  11833. }
  11834. else if (nextChar == 0)
  11835. {
  11836. setLastError ("unmatched tags", false);
  11837. outOfData = true;
  11838. return;
  11839. }
  11840. ++input;
  11841. ++len;
  11842. }
  11843. textElementContent.append (start, len);
  11844. }
  11845. }
  11846. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11847. : textElementContent.isNotEmpty())
  11848. e->setText (textElementContent);
  11849. }
  11850. }
  11851. }
  11852. void XmlDocument::readEntity (String& result)
  11853. {
  11854. // skip over the ampersand
  11855. ++input;
  11856. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  11857. {
  11858. input += 4;
  11859. result += '&';
  11860. }
  11861. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  11862. {
  11863. input += 5;
  11864. result += '"';
  11865. }
  11866. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  11867. {
  11868. input += 5;
  11869. result += '\'';
  11870. }
  11871. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  11872. {
  11873. input += 3;
  11874. result += '<';
  11875. }
  11876. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  11877. {
  11878. input += 3;
  11879. result += '>';
  11880. }
  11881. else if (*input == '#')
  11882. {
  11883. int charCode = 0;
  11884. ++input;
  11885. if (*input == 'x' || *input == 'X')
  11886. {
  11887. ++input;
  11888. int numChars = 0;
  11889. while (input[0] != ';')
  11890. {
  11891. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11892. if (hexValue < 0 || ++numChars > 8)
  11893. {
  11894. setLastError ("illegal escape sequence", true);
  11895. break;
  11896. }
  11897. charCode = (charCode << 4) | hexValue;
  11898. ++input;
  11899. }
  11900. ++input;
  11901. }
  11902. else if (input[0] >= '0' && input[0] <= '9')
  11903. {
  11904. int numChars = 0;
  11905. while (input[0] != ';')
  11906. {
  11907. if (++numChars > 12)
  11908. {
  11909. setLastError ("illegal escape sequence", true);
  11910. break;
  11911. }
  11912. charCode = charCode * 10 + (input[0] - '0');
  11913. ++input;
  11914. }
  11915. ++input;
  11916. }
  11917. else
  11918. {
  11919. setLastError ("illegal escape sequence", true);
  11920. result += '&';
  11921. return;
  11922. }
  11923. result << (juce_wchar) charCode;
  11924. }
  11925. else
  11926. {
  11927. const juce_wchar* const entityNameStart = input;
  11928. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  11929. if (closingSemiColon == 0)
  11930. {
  11931. outOfData = true;
  11932. result += '&';
  11933. }
  11934. else
  11935. {
  11936. input = closingSemiColon + 1;
  11937. result += expandExternalEntity (String (entityNameStart,
  11938. (int) (closingSemiColon - entityNameStart)));
  11939. }
  11940. }
  11941. }
  11942. const String XmlDocument::expandEntity (const String& ent)
  11943. {
  11944. if (ent.equalsIgnoreCase ("amp"))
  11945. return String::charToString ('&');
  11946. if (ent.equalsIgnoreCase ("quot"))
  11947. return String::charToString ('"');
  11948. if (ent.equalsIgnoreCase ("apos"))
  11949. return String::charToString ('\'');
  11950. if (ent.equalsIgnoreCase ("lt"))
  11951. return String::charToString ('<');
  11952. if (ent.equalsIgnoreCase ("gt"))
  11953. return String::charToString ('>');
  11954. if (ent[0] == '#')
  11955. {
  11956. if (ent[1] == 'x' || ent[1] == 'X')
  11957. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  11958. if (ent[1] >= '0' && ent[1] <= '9')
  11959. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  11960. setLastError ("illegal escape sequence", false);
  11961. return String::charToString ('&');
  11962. }
  11963. return expandExternalEntity (ent);
  11964. }
  11965. const String XmlDocument::expandExternalEntity (const String& entity)
  11966. {
  11967. if (needToLoadDTD)
  11968. {
  11969. if (dtdText.isNotEmpty())
  11970. {
  11971. dtdText = dtdText.trimCharactersAtEnd (">");
  11972. tokenisedDTD.addTokens (dtdText, true);
  11973. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11974. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11975. {
  11976. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11977. tokenisedDTD.clear();
  11978. tokenisedDTD.addTokens (getFileContents (fn), true);
  11979. }
  11980. else
  11981. {
  11982. tokenisedDTD.clear();
  11983. const int openBracket = dtdText.indexOfChar ('[');
  11984. if (openBracket > 0)
  11985. {
  11986. const int closeBracket = dtdText.lastIndexOfChar (']');
  11987. if (closeBracket > openBracket)
  11988. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11989. closeBracket), true);
  11990. }
  11991. }
  11992. for (int i = tokenisedDTD.size(); --i >= 0;)
  11993. {
  11994. if (tokenisedDTD[i].startsWithChar ('%')
  11995. && tokenisedDTD[i].endsWithChar (';'))
  11996. {
  11997. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11998. StringArray newToks;
  11999. newToks.addTokens (parsed, true);
  12000. tokenisedDTD.remove (i);
  12001. for (int j = newToks.size(); --j >= 0;)
  12002. tokenisedDTD.insert (i, newToks[j]);
  12003. }
  12004. }
  12005. }
  12006. needToLoadDTD = false;
  12007. }
  12008. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12009. {
  12010. if (tokenisedDTD[i] == entity)
  12011. {
  12012. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12013. {
  12014. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12015. // check for sub-entities..
  12016. int ampersand = ent.indexOfChar ('&');
  12017. while (ampersand >= 0)
  12018. {
  12019. const int semiColon = ent.indexOf (i + 1, ";");
  12020. if (semiColon < 0)
  12021. {
  12022. setLastError ("entity without terminating semi-colon", false);
  12023. break;
  12024. }
  12025. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12026. ent = ent.substring (0, ampersand)
  12027. + resolved
  12028. + ent.substring (semiColon + 1);
  12029. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12030. }
  12031. return ent;
  12032. }
  12033. }
  12034. }
  12035. setLastError ("unknown entity", true);
  12036. return entity;
  12037. }
  12038. const String XmlDocument::getParameterEntity (const String& entity)
  12039. {
  12040. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12041. {
  12042. if (tokenisedDTD[i] == entity)
  12043. {
  12044. if (tokenisedDTD [i - 1] == "%"
  12045. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12046. {
  12047. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12048. if (ent.equalsIgnoreCase ("system"))
  12049. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12050. else
  12051. return ent.trim().unquoted();
  12052. }
  12053. }
  12054. }
  12055. return entity;
  12056. }
  12057. END_JUCE_NAMESPACE
  12058. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12059. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12060. BEGIN_JUCE_NAMESPACE
  12061. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12062. : name (other.name),
  12063. value (other.value),
  12064. next (0)
  12065. {
  12066. }
  12067. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12068. : name (name_),
  12069. value (value_),
  12070. next (0)
  12071. {
  12072. }
  12073. XmlElement::XmlElement (const String& tagName_) throw()
  12074. : tagName (tagName_),
  12075. firstChildElement (0),
  12076. nextElement (0),
  12077. attributes (0)
  12078. {
  12079. // the tag name mustn't be empty, or it'll look like a text element!
  12080. jassert (tagName_.containsNonWhitespaceChars())
  12081. // The tag can't contain spaces or other characters that would create invalid XML!
  12082. jassert (! tagName_.containsAnyOf (" <>/&"));
  12083. }
  12084. XmlElement::XmlElement (int /*dummy*/) throw()
  12085. : firstChildElement (0),
  12086. nextElement (0),
  12087. attributes (0)
  12088. {
  12089. }
  12090. XmlElement::XmlElement (const XmlElement& other)
  12091. : tagName (other.tagName),
  12092. firstChildElement (0),
  12093. nextElement (0),
  12094. attributes (0)
  12095. {
  12096. copyChildrenAndAttributesFrom (other);
  12097. }
  12098. XmlElement& XmlElement::operator= (const XmlElement& other)
  12099. {
  12100. if (this != &other)
  12101. {
  12102. removeAllAttributes();
  12103. deleteAllChildElements();
  12104. tagName = other.tagName;
  12105. copyChildrenAndAttributesFrom (other);
  12106. }
  12107. return *this;
  12108. }
  12109. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12110. {
  12111. XmlElement* child = other.firstChildElement;
  12112. XmlElement* lastChild = 0;
  12113. while (child != 0)
  12114. {
  12115. XmlElement* const copiedChild = new XmlElement (*child);
  12116. if (lastChild != 0)
  12117. lastChild->nextElement = copiedChild;
  12118. else
  12119. firstChildElement = copiedChild;
  12120. lastChild = copiedChild;
  12121. child = child->nextElement;
  12122. }
  12123. const XmlAttributeNode* att = other.attributes;
  12124. XmlAttributeNode* lastAtt = 0;
  12125. while (att != 0)
  12126. {
  12127. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12128. if (lastAtt != 0)
  12129. lastAtt->next = newAtt;
  12130. else
  12131. attributes = newAtt;
  12132. lastAtt = newAtt;
  12133. att = att->next;
  12134. }
  12135. }
  12136. XmlElement::~XmlElement() throw()
  12137. {
  12138. XmlElement* child = firstChildElement;
  12139. while (child != 0)
  12140. {
  12141. XmlElement* const nextChild = child->nextElement;
  12142. delete child;
  12143. child = nextChild;
  12144. }
  12145. XmlAttributeNode* att = attributes;
  12146. while (att != 0)
  12147. {
  12148. XmlAttributeNode* const nextAtt = att->next;
  12149. delete att;
  12150. att = nextAtt;
  12151. }
  12152. }
  12153. namespace XmlOutputFunctions
  12154. {
  12155. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12156. {
  12157. if ((character >= 'a' && character <= 'z')
  12158. || (character >= 'A' && character <= 'Z')
  12159. || (character >= '0' && character <= '9'))
  12160. return true;
  12161. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12162. do
  12163. {
  12164. if (((juce_wchar) (uint8) *t) == character)
  12165. return true;
  12166. }
  12167. while (*++t != 0);
  12168. return false;
  12169. }
  12170. static void generateLegalCharConstants()
  12171. {
  12172. uint8 n[32];
  12173. zerostruct (n);
  12174. for (int i = 0; i < 256; ++i)
  12175. if (isLegalXmlCharSlow (i))
  12176. n[i >> 3] |= (1 << (i & 7));
  12177. String s;
  12178. for (int i = 0; i < 32; ++i)
  12179. s << (int) n[i] << ", ";
  12180. DBG (s);
  12181. }*/
  12182. static bool isLegalXmlChar (const uint32 c) throw()
  12183. {
  12184. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12185. return c < sizeof (legalChars) * 8
  12186. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12187. }
  12188. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12189. {
  12190. const juce_wchar* t = text;
  12191. for (;;)
  12192. {
  12193. const juce_wchar character = *t++;
  12194. if (character == 0)
  12195. {
  12196. break;
  12197. }
  12198. else if (isLegalXmlChar ((uint32) character))
  12199. {
  12200. outputStream << (char) character;
  12201. }
  12202. else
  12203. {
  12204. switch (character)
  12205. {
  12206. case '&': outputStream << "&amp;"; break;
  12207. case '"': outputStream << "&quot;"; break;
  12208. case '>': outputStream << "&gt;"; break;
  12209. case '<': outputStream << "&lt;"; break;
  12210. case '\n':
  12211. if (changeNewLines)
  12212. outputStream << "&#10;";
  12213. else
  12214. outputStream << (char) character;
  12215. break;
  12216. case '\r':
  12217. if (changeNewLines)
  12218. outputStream << "&#13;";
  12219. else
  12220. outputStream << (char) character;
  12221. break;
  12222. default:
  12223. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12224. break;
  12225. }
  12226. }
  12227. }
  12228. }
  12229. static void writeSpaces (OutputStream& out, int numSpaces)
  12230. {
  12231. if (numSpaces > 0)
  12232. {
  12233. const char* const blanks = " ";
  12234. const int blankSize = (int) sizeof (blanks) - 1;
  12235. while (numSpaces > blankSize)
  12236. {
  12237. out.write (blanks, blankSize);
  12238. numSpaces -= blankSize;
  12239. }
  12240. out.write (blanks, numSpaces);
  12241. }
  12242. }
  12243. }
  12244. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12245. const int indentationLevel,
  12246. const int lineWrapLength) const
  12247. {
  12248. using namespace XmlOutputFunctions;
  12249. writeSpaces (outputStream, indentationLevel);
  12250. if (! isTextElement())
  12251. {
  12252. outputStream.writeByte ('<');
  12253. outputStream << tagName;
  12254. const int attIndent = indentationLevel + tagName.length() + 1;
  12255. int lineLen = 0;
  12256. const XmlAttributeNode* att = attributes;
  12257. while (att != 0)
  12258. {
  12259. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12260. {
  12261. outputStream.write ("\r\n", 2);
  12262. writeSpaces (outputStream, attIndent);
  12263. lineLen = 0;
  12264. }
  12265. const int64 startPos = outputStream.getPosition();
  12266. outputStream.writeByte (' ');
  12267. outputStream << att->name;
  12268. outputStream.write ("=\"", 2);
  12269. escapeIllegalXmlChars (outputStream, att->value, true);
  12270. outputStream.writeByte ('"');
  12271. lineLen += (int) (outputStream.getPosition() - startPos);
  12272. att = att->next;
  12273. }
  12274. if (firstChildElement != 0)
  12275. {
  12276. XmlElement* child = firstChildElement;
  12277. if (child->nextElement == 0 && child->isTextElement())
  12278. {
  12279. outputStream.writeByte ('>');
  12280. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12281. }
  12282. else
  12283. {
  12284. if (indentationLevel >= 0)
  12285. outputStream.write (">\r\n", 3);
  12286. else
  12287. outputStream.writeByte ('>');
  12288. bool lastWasTextNode = false;
  12289. while (child != 0)
  12290. {
  12291. if (child->isTextElement())
  12292. {
  12293. if ((! lastWasTextNode) && (indentationLevel >= 0))
  12294. writeSpaces (outputStream, indentationLevel + 2);
  12295. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12296. lastWasTextNode = true;
  12297. }
  12298. else
  12299. {
  12300. if (indentationLevel >= 0)
  12301. {
  12302. if (lastWasTextNode)
  12303. outputStream.write ("\r\n", 2);
  12304. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  12305. }
  12306. else
  12307. {
  12308. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  12309. }
  12310. lastWasTextNode = false;
  12311. }
  12312. child = child->nextElement;
  12313. }
  12314. if (indentationLevel >= 0)
  12315. {
  12316. if (lastWasTextNode)
  12317. outputStream.write ("\r\n", 2);
  12318. writeSpaces (outputStream, indentationLevel);
  12319. }
  12320. }
  12321. outputStream.write ("</", 2);
  12322. outputStream << tagName;
  12323. if (indentationLevel >= 0)
  12324. outputStream.write (">\r\n", 3);
  12325. else
  12326. outputStream.writeByte ('>');
  12327. }
  12328. else
  12329. {
  12330. if (indentationLevel >= 0)
  12331. outputStream.write ("/>\r\n", 4);
  12332. else
  12333. outputStream.write ("/>", 2);
  12334. }
  12335. }
  12336. else
  12337. {
  12338. if (indentationLevel >= 0)
  12339. writeSpaces (outputStream, indentationLevel + 2);
  12340. escapeIllegalXmlChars (outputStream, getText(), false);
  12341. }
  12342. }
  12343. const String XmlElement::createDocument (const String& dtdToUse,
  12344. const bool allOnOneLine,
  12345. const bool includeXmlHeader,
  12346. const String& encodingType,
  12347. const int lineWrapLength) const
  12348. {
  12349. MemoryOutputStream mem (2048);
  12350. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12351. return mem.toUTF8();
  12352. }
  12353. void XmlElement::writeToStream (OutputStream& output,
  12354. const String& dtdToUse,
  12355. const bool allOnOneLine,
  12356. const bool includeXmlHeader,
  12357. const String& encodingType,
  12358. const int lineWrapLength) const
  12359. {
  12360. if (includeXmlHeader)
  12361. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  12362. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  12363. if (dtdToUse.isNotEmpty())
  12364. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  12365. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12366. }
  12367. bool XmlElement::writeToFile (const File& file,
  12368. const String& dtdToUse,
  12369. const String& encodingType,
  12370. const int lineWrapLength) const
  12371. {
  12372. if (file.hasWriteAccess())
  12373. {
  12374. TemporaryFile tempFile (file);
  12375. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12376. if (out != 0)
  12377. {
  12378. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12379. out = 0;
  12380. return tempFile.overwriteTargetFileWithTemporary();
  12381. }
  12382. }
  12383. return false;
  12384. }
  12385. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12386. {
  12387. #if JUCE_DEBUG
  12388. // if debugging, check that the case is actually the same, because
  12389. // valid xml is case-sensitive, and although this lets it pass, it's
  12390. // better not to..
  12391. if (tagName.equalsIgnoreCase (tagNameWanted))
  12392. {
  12393. jassert (tagName == tagNameWanted);
  12394. return true;
  12395. }
  12396. else
  12397. {
  12398. return false;
  12399. }
  12400. #else
  12401. return tagName.equalsIgnoreCase (tagNameWanted);
  12402. #endif
  12403. }
  12404. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12405. {
  12406. XmlElement* e = nextElement;
  12407. while (e != 0 && ! e->hasTagName (requiredTagName))
  12408. e = e->nextElement;
  12409. return e;
  12410. }
  12411. int XmlElement::getNumAttributes() const throw()
  12412. {
  12413. const XmlAttributeNode* att = attributes;
  12414. int count = 0;
  12415. while (att != 0)
  12416. {
  12417. att = att->next;
  12418. ++count;
  12419. }
  12420. return count;
  12421. }
  12422. const String& XmlElement::getAttributeName (const int index) const throw()
  12423. {
  12424. const XmlAttributeNode* att = attributes;
  12425. int count = 0;
  12426. while (att != 0)
  12427. {
  12428. if (count == index)
  12429. return att->name;
  12430. att = att->next;
  12431. ++count;
  12432. }
  12433. return String::empty;
  12434. }
  12435. const String& XmlElement::getAttributeValue (const int index) const throw()
  12436. {
  12437. const XmlAttributeNode* att = attributes;
  12438. int count = 0;
  12439. while (att != 0)
  12440. {
  12441. if (count == index)
  12442. return att->value;
  12443. att = att->next;
  12444. ++count;
  12445. }
  12446. return String::empty;
  12447. }
  12448. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12449. {
  12450. const XmlAttributeNode* att = attributes;
  12451. while (att != 0)
  12452. {
  12453. if (att->name.equalsIgnoreCase (attributeName))
  12454. return true;
  12455. att = att->next;
  12456. }
  12457. return false;
  12458. }
  12459. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12460. {
  12461. const XmlAttributeNode* att = attributes;
  12462. while (att != 0)
  12463. {
  12464. if (att->name.equalsIgnoreCase (attributeName))
  12465. return att->value;
  12466. att = att->next;
  12467. }
  12468. return String::empty;
  12469. }
  12470. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12471. {
  12472. const XmlAttributeNode* att = attributes;
  12473. while (att != 0)
  12474. {
  12475. if (att->name.equalsIgnoreCase (attributeName))
  12476. return att->value;
  12477. att = att->next;
  12478. }
  12479. return defaultReturnValue;
  12480. }
  12481. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12482. {
  12483. const XmlAttributeNode* att = attributes;
  12484. while (att != 0)
  12485. {
  12486. if (att->name.equalsIgnoreCase (attributeName))
  12487. return att->value.getIntValue();
  12488. att = att->next;
  12489. }
  12490. return defaultReturnValue;
  12491. }
  12492. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12493. {
  12494. const XmlAttributeNode* att = attributes;
  12495. while (att != 0)
  12496. {
  12497. if (att->name.equalsIgnoreCase (attributeName))
  12498. return att->value.getDoubleValue();
  12499. att = att->next;
  12500. }
  12501. return defaultReturnValue;
  12502. }
  12503. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12504. {
  12505. const XmlAttributeNode* att = attributes;
  12506. while (att != 0)
  12507. {
  12508. if (att->name.equalsIgnoreCase (attributeName))
  12509. {
  12510. juce_wchar firstChar = att->value[0];
  12511. if (CharacterFunctions::isWhitespace (firstChar))
  12512. firstChar = att->value.trimStart() [0];
  12513. return firstChar == '1'
  12514. || firstChar == 't'
  12515. || firstChar == 'y'
  12516. || firstChar == 'T'
  12517. || firstChar == 'Y';
  12518. }
  12519. att = att->next;
  12520. }
  12521. return defaultReturnValue;
  12522. }
  12523. bool XmlElement::compareAttribute (const String& attributeName,
  12524. const String& stringToCompareAgainst,
  12525. const bool ignoreCase) const throw()
  12526. {
  12527. const XmlAttributeNode* att = attributes;
  12528. while (att != 0)
  12529. {
  12530. if (att->name.equalsIgnoreCase (attributeName))
  12531. {
  12532. if (ignoreCase)
  12533. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  12534. else
  12535. return att->value == stringToCompareAgainst;
  12536. }
  12537. att = att->next;
  12538. }
  12539. return false;
  12540. }
  12541. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12542. {
  12543. #if JUCE_DEBUG
  12544. // check the identifier being passed in is legal..
  12545. const juce_wchar* t = attributeName;
  12546. while (*t != 0)
  12547. {
  12548. jassert (CharacterFunctions::isLetterOrDigit (*t)
  12549. || *t == '_'
  12550. || *t == '-'
  12551. || *t == ':');
  12552. ++t;
  12553. }
  12554. #endif
  12555. if (attributes == 0)
  12556. {
  12557. attributes = new XmlAttributeNode (attributeName, value);
  12558. }
  12559. else
  12560. {
  12561. XmlAttributeNode* att = attributes;
  12562. for (;;)
  12563. {
  12564. if (att->name.equalsIgnoreCase (attributeName))
  12565. {
  12566. att->value = value;
  12567. break;
  12568. }
  12569. else if (att->next == 0)
  12570. {
  12571. att->next = new XmlAttributeNode (attributeName, value);
  12572. break;
  12573. }
  12574. att = att->next;
  12575. }
  12576. }
  12577. }
  12578. void XmlElement::setAttribute (const String& attributeName, const int number)
  12579. {
  12580. setAttribute (attributeName, String (number));
  12581. }
  12582. void XmlElement::setAttribute (const String& attributeName, const double number)
  12583. {
  12584. setAttribute (attributeName, String (number));
  12585. }
  12586. void XmlElement::removeAttribute (const String& attributeName) throw()
  12587. {
  12588. XmlAttributeNode* att = attributes;
  12589. XmlAttributeNode* lastAtt = 0;
  12590. while (att != 0)
  12591. {
  12592. if (att->name.equalsIgnoreCase (attributeName))
  12593. {
  12594. if (lastAtt == 0)
  12595. attributes = att->next;
  12596. else
  12597. lastAtt->next = att->next;
  12598. delete att;
  12599. break;
  12600. }
  12601. lastAtt = att;
  12602. att = att->next;
  12603. }
  12604. }
  12605. void XmlElement::removeAllAttributes() throw()
  12606. {
  12607. while (attributes != 0)
  12608. {
  12609. XmlAttributeNode* const nextAtt = attributes->next;
  12610. delete attributes;
  12611. attributes = nextAtt;
  12612. }
  12613. }
  12614. int XmlElement::getNumChildElements() const throw()
  12615. {
  12616. int count = 0;
  12617. const XmlElement* child = firstChildElement;
  12618. while (child != 0)
  12619. {
  12620. ++count;
  12621. child = child->nextElement;
  12622. }
  12623. return count;
  12624. }
  12625. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12626. {
  12627. int count = 0;
  12628. XmlElement* child = firstChildElement;
  12629. while (child != 0 && count < index)
  12630. {
  12631. child = child->nextElement;
  12632. ++count;
  12633. }
  12634. return child;
  12635. }
  12636. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12637. {
  12638. XmlElement* child = firstChildElement;
  12639. while (child != 0)
  12640. {
  12641. if (child->hasTagName (childName))
  12642. break;
  12643. child = child->nextElement;
  12644. }
  12645. return child;
  12646. }
  12647. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12648. {
  12649. if (newNode != 0)
  12650. {
  12651. if (firstChildElement == 0)
  12652. {
  12653. firstChildElement = newNode;
  12654. }
  12655. else
  12656. {
  12657. XmlElement* child = firstChildElement;
  12658. while (child->nextElement != 0)
  12659. child = child->nextElement;
  12660. child->nextElement = newNode;
  12661. // if this is non-zero, then something's probably
  12662. // gone wrong..
  12663. jassert (newNode->nextElement == 0);
  12664. }
  12665. }
  12666. }
  12667. void XmlElement::insertChildElement (XmlElement* const newNode,
  12668. int indexToInsertAt) throw()
  12669. {
  12670. if (newNode != 0)
  12671. {
  12672. removeChildElement (newNode, false);
  12673. if (indexToInsertAt == 0)
  12674. {
  12675. newNode->nextElement = firstChildElement;
  12676. firstChildElement = newNode;
  12677. }
  12678. else
  12679. {
  12680. if (firstChildElement == 0)
  12681. {
  12682. firstChildElement = newNode;
  12683. }
  12684. else
  12685. {
  12686. if (indexToInsertAt < 0)
  12687. indexToInsertAt = std::numeric_limits<int>::max();
  12688. XmlElement* child = firstChildElement;
  12689. while (child->nextElement != 0 && --indexToInsertAt > 0)
  12690. child = child->nextElement;
  12691. newNode->nextElement = child->nextElement;
  12692. child->nextElement = newNode;
  12693. }
  12694. }
  12695. }
  12696. }
  12697. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12698. {
  12699. XmlElement* const newElement = new XmlElement (childTagName);
  12700. addChildElement (newElement);
  12701. return newElement;
  12702. }
  12703. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12704. XmlElement* const newNode) throw()
  12705. {
  12706. if (newNode != 0)
  12707. {
  12708. XmlElement* child = firstChildElement;
  12709. XmlElement* previousNode = 0;
  12710. while (child != 0)
  12711. {
  12712. if (child == currentChildElement)
  12713. {
  12714. if (child != newNode)
  12715. {
  12716. if (previousNode == 0)
  12717. firstChildElement = newNode;
  12718. else
  12719. previousNode->nextElement = newNode;
  12720. newNode->nextElement = child->nextElement;
  12721. delete child;
  12722. }
  12723. return true;
  12724. }
  12725. previousNode = child;
  12726. child = child->nextElement;
  12727. }
  12728. }
  12729. return false;
  12730. }
  12731. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12732. const bool shouldDeleteTheChild) throw()
  12733. {
  12734. if (childToRemove != 0)
  12735. {
  12736. if (firstChildElement == childToRemove)
  12737. {
  12738. firstChildElement = childToRemove->nextElement;
  12739. childToRemove->nextElement = 0;
  12740. }
  12741. else
  12742. {
  12743. XmlElement* child = firstChildElement;
  12744. XmlElement* last = 0;
  12745. while (child != 0)
  12746. {
  12747. if (child == childToRemove)
  12748. {
  12749. if (last == 0)
  12750. firstChildElement = child->nextElement;
  12751. else
  12752. last->nextElement = child->nextElement;
  12753. childToRemove->nextElement = 0;
  12754. break;
  12755. }
  12756. last = child;
  12757. child = child->nextElement;
  12758. }
  12759. }
  12760. if (shouldDeleteTheChild)
  12761. delete childToRemove;
  12762. }
  12763. }
  12764. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12765. const bool ignoreOrderOfAttributes) const throw()
  12766. {
  12767. if (this != other)
  12768. {
  12769. if (other == 0 || tagName != other->tagName)
  12770. {
  12771. return false;
  12772. }
  12773. if (ignoreOrderOfAttributes)
  12774. {
  12775. int totalAtts = 0;
  12776. const XmlAttributeNode* att = attributes;
  12777. while (att != 0)
  12778. {
  12779. if (! other->compareAttribute (att->name, att->value))
  12780. return false;
  12781. att = att->next;
  12782. ++totalAtts;
  12783. }
  12784. if (totalAtts != other->getNumAttributes())
  12785. return false;
  12786. }
  12787. else
  12788. {
  12789. const XmlAttributeNode* thisAtt = attributes;
  12790. const XmlAttributeNode* otherAtt = other->attributes;
  12791. for (;;)
  12792. {
  12793. if (thisAtt == 0 || otherAtt == 0)
  12794. {
  12795. if (thisAtt == otherAtt) // both 0, so it's a match
  12796. break;
  12797. return false;
  12798. }
  12799. if (thisAtt->name != otherAtt->name
  12800. || thisAtt->value != otherAtt->value)
  12801. {
  12802. return false;
  12803. }
  12804. thisAtt = thisAtt->next;
  12805. otherAtt = otherAtt->next;
  12806. }
  12807. }
  12808. const XmlElement* thisChild = firstChildElement;
  12809. const XmlElement* otherChild = other->firstChildElement;
  12810. for (;;)
  12811. {
  12812. if (thisChild == 0 || otherChild == 0)
  12813. {
  12814. if (thisChild == otherChild) // both 0, so it's a match
  12815. break;
  12816. return false;
  12817. }
  12818. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12819. return false;
  12820. thisChild = thisChild->nextElement;
  12821. otherChild = otherChild->nextElement;
  12822. }
  12823. }
  12824. return true;
  12825. }
  12826. void XmlElement::deleteAllChildElements() throw()
  12827. {
  12828. while (firstChildElement != 0)
  12829. {
  12830. XmlElement* const nextChild = firstChildElement->nextElement;
  12831. delete firstChildElement;
  12832. firstChildElement = nextChild;
  12833. }
  12834. }
  12835. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12836. {
  12837. XmlElement* child = firstChildElement;
  12838. while (child != 0)
  12839. {
  12840. if (child->hasTagName (name))
  12841. {
  12842. XmlElement* const nextChild = child->nextElement;
  12843. removeChildElement (child, true);
  12844. child = nextChild;
  12845. }
  12846. else
  12847. {
  12848. child = child->nextElement;
  12849. }
  12850. }
  12851. }
  12852. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12853. {
  12854. const XmlElement* child = firstChildElement;
  12855. while (child != 0)
  12856. {
  12857. if (child == possibleChild)
  12858. return true;
  12859. child = child->nextElement;
  12860. }
  12861. return false;
  12862. }
  12863. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12864. {
  12865. if (this == elementToLookFor || elementToLookFor == 0)
  12866. return 0;
  12867. XmlElement* child = firstChildElement;
  12868. while (child != 0)
  12869. {
  12870. if (elementToLookFor == child)
  12871. return this;
  12872. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12873. if (found != 0)
  12874. return found;
  12875. child = child->nextElement;
  12876. }
  12877. return 0;
  12878. }
  12879. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12880. {
  12881. XmlElement* e = firstChildElement;
  12882. while (e != 0)
  12883. {
  12884. *elems++ = e;
  12885. e = e->nextElement;
  12886. }
  12887. }
  12888. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12889. {
  12890. XmlElement* e = firstChildElement = elems[0];
  12891. for (int i = 1; i < num; ++i)
  12892. {
  12893. e->nextElement = elems[i];
  12894. e = e->nextElement;
  12895. }
  12896. e->nextElement = 0;
  12897. }
  12898. bool XmlElement::isTextElement() const throw()
  12899. {
  12900. return tagName.isEmpty();
  12901. }
  12902. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  12903. const String& XmlElement::getText() const throw()
  12904. {
  12905. jassert (isTextElement()); // you're trying to get the text from an element that
  12906. // isn't actually a text element.. If this contains text sub-nodes, you
  12907. // probably want to use getAllSubText instead.
  12908. return getStringAttribute (juce_xmltextContentAttributeName);
  12909. }
  12910. void XmlElement::setText (const String& newText)
  12911. {
  12912. if (isTextElement())
  12913. setAttribute (juce_xmltextContentAttributeName, newText);
  12914. else
  12915. jassertfalse; // you can only change the text in a text element, not a normal one.
  12916. }
  12917. const String XmlElement::getAllSubText() const
  12918. {
  12919. String result;
  12920. String::Concatenator concatenator (result);
  12921. const XmlElement* child = firstChildElement;
  12922. while (child != 0)
  12923. {
  12924. if (child->isTextElement())
  12925. concatenator.append (child->getText());
  12926. child = child->nextElement;
  12927. }
  12928. return result;
  12929. }
  12930. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12931. const String& defaultReturnValue) const
  12932. {
  12933. const XmlElement* const child = getChildByName (childTagName);
  12934. if (child != 0)
  12935. return child->getAllSubText();
  12936. return defaultReturnValue;
  12937. }
  12938. XmlElement* XmlElement::createTextElement (const String& text)
  12939. {
  12940. XmlElement* const e = new XmlElement ((int) 0);
  12941. e->setAttribute (juce_xmltextContentAttributeName, text);
  12942. return e;
  12943. }
  12944. void XmlElement::addTextElement (const String& text)
  12945. {
  12946. addChildElement (createTextElement (text));
  12947. }
  12948. void XmlElement::deleteAllTextElements() throw()
  12949. {
  12950. XmlElement* child = firstChildElement;
  12951. while (child != 0)
  12952. {
  12953. XmlElement* const next = child->nextElement;
  12954. if (child->isTextElement())
  12955. removeChildElement (child, true);
  12956. child = next;
  12957. }
  12958. }
  12959. END_JUCE_NAMESPACE
  12960. /*** End of inlined file: juce_XmlElement.cpp ***/
  12961. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12962. BEGIN_JUCE_NAMESPACE
  12963. ReadWriteLock::ReadWriteLock() throw()
  12964. : numWaitingWriters (0),
  12965. numWriters (0),
  12966. writerThreadId (0)
  12967. {
  12968. }
  12969. ReadWriteLock::~ReadWriteLock() throw()
  12970. {
  12971. jassert (readerThreads.size() == 0);
  12972. jassert (numWriters == 0);
  12973. }
  12974. void ReadWriteLock::enterRead() const throw()
  12975. {
  12976. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12977. const ScopedLock sl (accessLock);
  12978. for (;;)
  12979. {
  12980. jassert (readerThreads.size() % 2 == 0);
  12981. int i;
  12982. for (i = 0; i < readerThreads.size(); i += 2)
  12983. if (readerThreads.getUnchecked(i) == threadId)
  12984. break;
  12985. if (i < readerThreads.size()
  12986. || numWriters + numWaitingWriters == 0
  12987. || (threadId == writerThreadId && numWriters > 0))
  12988. {
  12989. if (i < readerThreads.size())
  12990. {
  12991. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12992. }
  12993. else
  12994. {
  12995. readerThreads.add (threadId);
  12996. readerThreads.add ((Thread::ThreadID) 1);
  12997. }
  12998. return;
  12999. }
  13000. const ScopedUnlock ul (accessLock);
  13001. waitEvent.wait (100);
  13002. }
  13003. }
  13004. void ReadWriteLock::exitRead() const throw()
  13005. {
  13006. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13007. const ScopedLock sl (accessLock);
  13008. for (int i = 0; i < readerThreads.size(); i += 2)
  13009. {
  13010. if (readerThreads.getUnchecked(i) == threadId)
  13011. {
  13012. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13013. if (newCount == 0)
  13014. {
  13015. readerThreads.removeRange (i, 2);
  13016. waitEvent.signal();
  13017. }
  13018. else
  13019. {
  13020. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13021. }
  13022. return;
  13023. }
  13024. }
  13025. jassertfalse; // unlocking a lock that wasn't locked..
  13026. }
  13027. void ReadWriteLock::enterWrite() const throw()
  13028. {
  13029. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13030. const ScopedLock sl (accessLock);
  13031. for (;;)
  13032. {
  13033. if (readerThreads.size() + numWriters == 0
  13034. || threadId == writerThreadId
  13035. || (readerThreads.size() == 2
  13036. && readerThreads.getUnchecked(0) == threadId))
  13037. {
  13038. writerThreadId = threadId;
  13039. ++numWriters;
  13040. break;
  13041. }
  13042. ++numWaitingWriters;
  13043. accessLock.exit();
  13044. waitEvent.wait (100);
  13045. accessLock.enter();
  13046. --numWaitingWriters;
  13047. }
  13048. }
  13049. bool ReadWriteLock::tryEnterWrite() const throw()
  13050. {
  13051. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13052. const ScopedLock sl (accessLock);
  13053. if (readerThreads.size() + numWriters == 0
  13054. || threadId == writerThreadId
  13055. || (readerThreads.size() == 2
  13056. && readerThreads.getUnchecked(0) == threadId))
  13057. {
  13058. writerThreadId = threadId;
  13059. ++numWriters;
  13060. return true;
  13061. }
  13062. return false;
  13063. }
  13064. void ReadWriteLock::exitWrite() const throw()
  13065. {
  13066. const ScopedLock sl (accessLock);
  13067. // check this thread actually had the lock..
  13068. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13069. if (--numWriters == 0)
  13070. {
  13071. writerThreadId = 0;
  13072. waitEvent.signal();
  13073. }
  13074. }
  13075. END_JUCE_NAMESPACE
  13076. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13077. /*** Start of inlined file: juce_Thread.cpp ***/
  13078. BEGIN_JUCE_NAMESPACE
  13079. // these functions are implemented in the platform-specific code.
  13080. void* juce_createThread (void* userData);
  13081. void juce_killThread (void* handle);
  13082. bool juce_setThreadPriority (void* handle, int priority);
  13083. void juce_setCurrentThreadName (const String& name);
  13084. #if JUCE_WINDOWS
  13085. void juce_CloseThreadHandle (void* handle);
  13086. #endif
  13087. void Thread::threadEntryPoint (Thread* const thread)
  13088. {
  13089. {
  13090. const ScopedLock sl (runningThreadsLock);
  13091. runningThreads.add (thread);
  13092. }
  13093. JUCE_TRY
  13094. {
  13095. thread->threadId_ = Thread::getCurrentThreadId();
  13096. if (thread->threadName_.isNotEmpty())
  13097. juce_setCurrentThreadName (thread->threadName_);
  13098. if (thread->startSuspensionEvent_.wait (10000))
  13099. {
  13100. if (thread->affinityMask_ != 0)
  13101. setCurrentThreadAffinityMask (thread->affinityMask_);
  13102. thread->run();
  13103. }
  13104. }
  13105. JUCE_CATCH_ALL_ASSERT
  13106. {
  13107. const ScopedLock sl (runningThreadsLock);
  13108. jassert (runningThreads.contains (thread));
  13109. runningThreads.removeValue (thread);
  13110. }
  13111. #if JUCE_WINDOWS
  13112. juce_CloseThreadHandle (thread->threadHandle_);
  13113. #endif
  13114. thread->threadHandle_ = 0;
  13115. thread->threadId_ = 0;
  13116. }
  13117. // used to wrap the incoming call from the platform-specific code
  13118. void JUCE_API juce_threadEntryPoint (void* userData)
  13119. {
  13120. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13121. }
  13122. Thread::Thread (const String& threadName)
  13123. : threadName_ (threadName),
  13124. threadHandle_ (0),
  13125. threadPriority_ (5),
  13126. threadId_ (0),
  13127. affinityMask_ (0),
  13128. threadShouldExit_ (false)
  13129. {
  13130. }
  13131. Thread::~Thread()
  13132. {
  13133. stopThread (100);
  13134. }
  13135. void Thread::startThread()
  13136. {
  13137. const ScopedLock sl (startStopLock);
  13138. threadShouldExit_ = false;
  13139. if (threadHandle_ == 0)
  13140. {
  13141. threadHandle_ = juce_createThread (this);
  13142. juce_setThreadPriority (threadHandle_, threadPriority_);
  13143. startSuspensionEvent_.signal();
  13144. }
  13145. }
  13146. void Thread::startThread (const int priority)
  13147. {
  13148. const ScopedLock sl (startStopLock);
  13149. if (threadHandle_ == 0)
  13150. {
  13151. threadPriority_ = priority;
  13152. startThread();
  13153. }
  13154. else
  13155. {
  13156. setPriority (priority);
  13157. }
  13158. }
  13159. bool Thread::isThreadRunning() const
  13160. {
  13161. return threadHandle_ != 0;
  13162. }
  13163. void Thread::signalThreadShouldExit()
  13164. {
  13165. threadShouldExit_ = true;
  13166. }
  13167. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13168. {
  13169. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13170. jassert (getThreadId() != getCurrentThreadId());
  13171. const int sleepMsPerIteration = 5;
  13172. int count = timeOutMilliseconds / sleepMsPerIteration;
  13173. while (isThreadRunning())
  13174. {
  13175. if (timeOutMilliseconds > 0 && --count < 0)
  13176. return false;
  13177. sleep (sleepMsPerIteration);
  13178. }
  13179. return true;
  13180. }
  13181. void Thread::stopThread (const int timeOutMilliseconds)
  13182. {
  13183. // agh! You can't stop the thread that's calling this method! How on earth
  13184. // would that work??
  13185. jassert (getCurrentThreadId() != getThreadId());
  13186. const ScopedLock sl (startStopLock);
  13187. if (isThreadRunning())
  13188. {
  13189. signalThreadShouldExit();
  13190. notify();
  13191. if (timeOutMilliseconds != 0)
  13192. waitForThreadToExit (timeOutMilliseconds);
  13193. if (isThreadRunning())
  13194. {
  13195. // very bad karma if this point is reached, as
  13196. // there are bound to be locks and events left in
  13197. // silly states when a thread is killed by force..
  13198. jassertfalse;
  13199. Logger::writeToLog ("!! killing thread by force !!");
  13200. juce_killThread (threadHandle_);
  13201. threadHandle_ = 0;
  13202. threadId_ = 0;
  13203. const ScopedLock sl2 (runningThreadsLock);
  13204. runningThreads.removeValue (this);
  13205. }
  13206. }
  13207. }
  13208. bool Thread::setPriority (const int priority)
  13209. {
  13210. const ScopedLock sl (startStopLock);
  13211. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13212. if (worked)
  13213. threadPriority_ = priority;
  13214. return worked;
  13215. }
  13216. bool Thread::setCurrentThreadPriority (const int priority)
  13217. {
  13218. return juce_setThreadPriority (0, priority);
  13219. }
  13220. void Thread::setAffinityMask (const uint32 affinityMask)
  13221. {
  13222. affinityMask_ = affinityMask;
  13223. }
  13224. bool Thread::wait (const int timeOutMilliseconds) const
  13225. {
  13226. return defaultEvent_.wait (timeOutMilliseconds);
  13227. }
  13228. void Thread::notify() const
  13229. {
  13230. defaultEvent_.signal();
  13231. }
  13232. int Thread::getNumRunningThreads()
  13233. {
  13234. return runningThreads.size();
  13235. }
  13236. Thread* Thread::getCurrentThread()
  13237. {
  13238. const ThreadID thisId = getCurrentThreadId();
  13239. const ScopedLock sl (runningThreadsLock);
  13240. for (int i = runningThreads.size(); --i >= 0;)
  13241. {
  13242. Thread* const t = runningThreads.getUnchecked(i);
  13243. if (t->threadId_ == thisId)
  13244. return t;
  13245. }
  13246. return 0;
  13247. }
  13248. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13249. {
  13250. {
  13251. const ScopedLock sl (runningThreadsLock);
  13252. for (int i = runningThreads.size(); --i >= 0;)
  13253. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13254. }
  13255. for (;;)
  13256. {
  13257. Thread* firstThread;
  13258. {
  13259. const ScopedLock sl (runningThreadsLock);
  13260. firstThread = runningThreads.getFirst();
  13261. }
  13262. if (firstThread == 0)
  13263. break;
  13264. firstThread->stopThread (timeOutMilliseconds);
  13265. }
  13266. }
  13267. Array<Thread*> Thread::runningThreads;
  13268. CriticalSection Thread::runningThreadsLock;
  13269. END_JUCE_NAMESPACE
  13270. /*** End of inlined file: juce_Thread.cpp ***/
  13271. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13272. BEGIN_JUCE_NAMESPACE
  13273. ThreadPoolJob::ThreadPoolJob (const String& name)
  13274. : jobName (name),
  13275. pool (0),
  13276. shouldStop (false),
  13277. isActive (false),
  13278. shouldBeDeleted (false)
  13279. {
  13280. }
  13281. ThreadPoolJob::~ThreadPoolJob()
  13282. {
  13283. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13284. // to remove it first!
  13285. jassert (pool == 0 || ! pool->contains (this));
  13286. }
  13287. const String ThreadPoolJob::getJobName() const
  13288. {
  13289. return jobName;
  13290. }
  13291. void ThreadPoolJob::setJobName (const String& newName)
  13292. {
  13293. jobName = newName;
  13294. }
  13295. void ThreadPoolJob::signalJobShouldExit()
  13296. {
  13297. shouldStop = true;
  13298. }
  13299. class ThreadPool::ThreadPoolThread : public Thread
  13300. {
  13301. public:
  13302. ThreadPoolThread (ThreadPool& pool_)
  13303. : Thread ("Pool"),
  13304. pool (pool_),
  13305. busy (false)
  13306. {
  13307. }
  13308. ~ThreadPoolThread()
  13309. {
  13310. }
  13311. void run()
  13312. {
  13313. while (! threadShouldExit())
  13314. {
  13315. if (! pool.runNextJob())
  13316. wait (500);
  13317. }
  13318. }
  13319. private:
  13320. ThreadPool& pool;
  13321. bool volatile busy;
  13322. ThreadPoolThread (const ThreadPoolThread&);
  13323. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13324. };
  13325. ThreadPool::ThreadPool (const int numThreads,
  13326. const bool startThreadsOnlyWhenNeeded,
  13327. const int stopThreadsWhenNotUsedTimeoutMs)
  13328. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13329. priority (5)
  13330. {
  13331. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13332. for (int i = jmax (1, numThreads); --i >= 0;)
  13333. threads.add (new ThreadPoolThread (*this));
  13334. if (! startThreadsOnlyWhenNeeded)
  13335. for (int i = threads.size(); --i >= 0;)
  13336. threads.getUnchecked(i)->startThread (priority);
  13337. }
  13338. ThreadPool::~ThreadPool()
  13339. {
  13340. removeAllJobs (true, 4000);
  13341. int i;
  13342. for (i = threads.size(); --i >= 0;)
  13343. threads.getUnchecked(i)->signalThreadShouldExit();
  13344. for (i = threads.size(); --i >= 0;)
  13345. threads.getUnchecked(i)->stopThread (500);
  13346. }
  13347. void ThreadPool::addJob (ThreadPoolJob* const job)
  13348. {
  13349. jassert (job != 0);
  13350. jassert (job->pool == 0);
  13351. if (job->pool == 0)
  13352. {
  13353. job->pool = this;
  13354. job->shouldStop = false;
  13355. job->isActive = false;
  13356. {
  13357. const ScopedLock sl (lock);
  13358. jobs.add (job);
  13359. int numRunning = 0;
  13360. for (int i = threads.size(); --i >= 0;)
  13361. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13362. ++numRunning;
  13363. if (numRunning < threads.size())
  13364. {
  13365. bool startedOne = false;
  13366. int n = 1000;
  13367. while (--n >= 0 && ! startedOne)
  13368. {
  13369. for (int i = threads.size(); --i >= 0;)
  13370. {
  13371. if (! threads.getUnchecked(i)->isThreadRunning())
  13372. {
  13373. threads.getUnchecked(i)->startThread (priority);
  13374. startedOne = true;
  13375. break;
  13376. }
  13377. }
  13378. if (! startedOne)
  13379. Thread::sleep (2);
  13380. }
  13381. }
  13382. }
  13383. for (int i = threads.size(); --i >= 0;)
  13384. threads.getUnchecked(i)->notify();
  13385. }
  13386. }
  13387. int ThreadPool::getNumJobs() const
  13388. {
  13389. return jobs.size();
  13390. }
  13391. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13392. {
  13393. const ScopedLock sl (lock);
  13394. return jobs [index];
  13395. }
  13396. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13397. {
  13398. const ScopedLock sl (lock);
  13399. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13400. }
  13401. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13402. {
  13403. const ScopedLock sl (lock);
  13404. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13405. }
  13406. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13407. const int timeOutMs) const
  13408. {
  13409. if (job != 0)
  13410. {
  13411. const uint32 start = Time::getMillisecondCounter();
  13412. while (contains (job))
  13413. {
  13414. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13415. return false;
  13416. jobFinishedSignal.wait (2);
  13417. }
  13418. }
  13419. return true;
  13420. }
  13421. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13422. const bool interruptIfRunning,
  13423. const int timeOutMs)
  13424. {
  13425. bool dontWait = true;
  13426. if (job != 0)
  13427. {
  13428. const ScopedLock sl (lock);
  13429. if (jobs.contains (job))
  13430. {
  13431. if (job->isActive)
  13432. {
  13433. if (interruptIfRunning)
  13434. job->signalJobShouldExit();
  13435. dontWait = false;
  13436. }
  13437. else
  13438. {
  13439. jobs.removeValue (job);
  13440. job->pool = 0;
  13441. }
  13442. }
  13443. }
  13444. return dontWait || waitForJobToFinish (job, timeOutMs);
  13445. }
  13446. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13447. const int timeOutMs,
  13448. const bool deleteInactiveJobs,
  13449. ThreadPool::JobSelector* selectedJobsToRemove)
  13450. {
  13451. Array <ThreadPoolJob*> jobsToWaitFor;
  13452. {
  13453. const ScopedLock sl (lock);
  13454. for (int i = jobs.size(); --i >= 0;)
  13455. {
  13456. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13457. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13458. {
  13459. if (job->isActive)
  13460. {
  13461. jobsToWaitFor.add (job);
  13462. if (interruptRunningJobs)
  13463. job->signalJobShouldExit();
  13464. }
  13465. else
  13466. {
  13467. jobs.remove (i);
  13468. if (deleteInactiveJobs)
  13469. delete job;
  13470. else
  13471. job->pool = 0;
  13472. }
  13473. }
  13474. }
  13475. }
  13476. const uint32 start = Time::getMillisecondCounter();
  13477. for (;;)
  13478. {
  13479. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13480. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13481. jobsToWaitFor.remove (i);
  13482. if (jobsToWaitFor.size() == 0)
  13483. break;
  13484. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13485. return false;
  13486. jobFinishedSignal.wait (20);
  13487. }
  13488. return true;
  13489. }
  13490. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13491. {
  13492. StringArray s;
  13493. const ScopedLock sl (lock);
  13494. for (int i = 0; i < jobs.size(); ++i)
  13495. {
  13496. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13497. if (job->isActive || ! onlyReturnActiveJobs)
  13498. s.add (job->getJobName());
  13499. }
  13500. return s;
  13501. }
  13502. bool ThreadPool::setThreadPriorities (const int newPriority)
  13503. {
  13504. bool ok = true;
  13505. if (priority != newPriority)
  13506. {
  13507. priority = newPriority;
  13508. for (int i = threads.size(); --i >= 0;)
  13509. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13510. ok = false;
  13511. }
  13512. return ok;
  13513. }
  13514. bool ThreadPool::runNextJob()
  13515. {
  13516. ThreadPoolJob* job = 0;
  13517. {
  13518. const ScopedLock sl (lock);
  13519. for (int i = 0; i < jobs.size(); ++i)
  13520. {
  13521. job = jobs[i];
  13522. if (job != 0 && ! (job->isActive || job->shouldStop))
  13523. break;
  13524. job = 0;
  13525. }
  13526. if (job != 0)
  13527. job->isActive = true;
  13528. }
  13529. if (job != 0)
  13530. {
  13531. JUCE_TRY
  13532. {
  13533. ThreadPoolJob::JobStatus result = job->runJob();
  13534. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13535. const ScopedLock sl (lock);
  13536. if (jobs.contains (job))
  13537. {
  13538. job->isActive = false;
  13539. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13540. {
  13541. job->pool = 0;
  13542. job->shouldStop = true;
  13543. jobs.removeValue (job);
  13544. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13545. delete job;
  13546. jobFinishedSignal.signal();
  13547. }
  13548. else
  13549. {
  13550. // move the job to the end of the queue if it wants another go
  13551. jobs.move (jobs.indexOf (job), -1);
  13552. }
  13553. }
  13554. }
  13555. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13556. catch (...)
  13557. {
  13558. const ScopedLock sl (lock);
  13559. jobs.removeValue (job);
  13560. }
  13561. #endif
  13562. }
  13563. else
  13564. {
  13565. if (threadStopTimeout > 0
  13566. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13567. {
  13568. const ScopedLock sl (lock);
  13569. if (jobs.size() == 0)
  13570. for (int i = threads.size(); --i >= 0;)
  13571. threads.getUnchecked(i)->signalThreadShouldExit();
  13572. }
  13573. else
  13574. {
  13575. return false;
  13576. }
  13577. }
  13578. return true;
  13579. }
  13580. END_JUCE_NAMESPACE
  13581. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13582. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13583. BEGIN_JUCE_NAMESPACE
  13584. TimeSliceThread::TimeSliceThread (const String& threadName)
  13585. : Thread (threadName),
  13586. index (0),
  13587. clientBeingCalled (0),
  13588. clientsChanged (false)
  13589. {
  13590. }
  13591. TimeSliceThread::~TimeSliceThread()
  13592. {
  13593. stopThread (2000);
  13594. }
  13595. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  13596. {
  13597. const ScopedLock sl (listLock);
  13598. clients.addIfNotAlreadyThere (client);
  13599. clientsChanged = true;
  13600. notify();
  13601. }
  13602. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13603. {
  13604. const ScopedLock sl1 (listLock);
  13605. clientsChanged = true;
  13606. // if there's a chance we're in the middle of calling this client, we need to
  13607. // also lock the outer lock..
  13608. if (clientBeingCalled == client)
  13609. {
  13610. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13611. const ScopedLock sl2 (callbackLock);
  13612. const ScopedLock sl3 (listLock);
  13613. clients.removeValue (client);
  13614. }
  13615. else
  13616. {
  13617. clients.removeValue (client);
  13618. }
  13619. }
  13620. int TimeSliceThread::getNumClients() const
  13621. {
  13622. return clients.size();
  13623. }
  13624. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13625. {
  13626. const ScopedLock sl (listLock);
  13627. return clients [i];
  13628. }
  13629. void TimeSliceThread::run()
  13630. {
  13631. int numCallsSinceBusy = 0;
  13632. while (! threadShouldExit())
  13633. {
  13634. int timeToWait = 500;
  13635. {
  13636. const ScopedLock sl (callbackLock);
  13637. {
  13638. const ScopedLock sl2 (listLock);
  13639. if (clients.size() > 0)
  13640. {
  13641. index = (index + 1) % clients.size();
  13642. clientBeingCalled = clients [index];
  13643. }
  13644. else
  13645. {
  13646. index = 0;
  13647. clientBeingCalled = 0;
  13648. }
  13649. if (clientsChanged)
  13650. {
  13651. clientsChanged = false;
  13652. numCallsSinceBusy = 0;
  13653. }
  13654. }
  13655. if (clientBeingCalled != 0)
  13656. {
  13657. if (clientBeingCalled->useTimeSlice())
  13658. numCallsSinceBusy = 0;
  13659. else
  13660. ++numCallsSinceBusy;
  13661. if (numCallsSinceBusy >= clients.size())
  13662. timeToWait = 500;
  13663. else if (index == 0)
  13664. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  13665. else
  13666. timeToWait = 0;
  13667. }
  13668. }
  13669. if (timeToWait > 0)
  13670. wait (timeToWait);
  13671. }
  13672. }
  13673. END_JUCE_NAMESPACE
  13674. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13675. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13676. BEGIN_JUCE_NAMESPACE
  13677. DeletedAtShutdown::DeletedAtShutdown()
  13678. {
  13679. const ScopedLock sl (getLock());
  13680. getObjects().add (this);
  13681. }
  13682. DeletedAtShutdown::~DeletedAtShutdown()
  13683. {
  13684. const ScopedLock sl (getLock());
  13685. getObjects().removeValue (this);
  13686. }
  13687. void DeletedAtShutdown::deleteAll()
  13688. {
  13689. // make a local copy of the array, so it can't get into a loop if something
  13690. // creates another DeletedAtShutdown object during its destructor.
  13691. Array <DeletedAtShutdown*> localCopy;
  13692. {
  13693. const ScopedLock sl (getLock());
  13694. localCopy = getObjects();
  13695. }
  13696. for (int i = localCopy.size(); --i >= 0;)
  13697. {
  13698. JUCE_TRY
  13699. {
  13700. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13701. // double-check that it's not already been deleted during another object's destructor.
  13702. {
  13703. const ScopedLock sl (getLock());
  13704. if (! getObjects().contains (deletee))
  13705. deletee = 0;
  13706. }
  13707. delete deletee;
  13708. }
  13709. JUCE_CATCH_EXCEPTION
  13710. }
  13711. // if no objects got re-created during shutdown, this should have been emptied by their
  13712. // destructors
  13713. jassert (getObjects().size() == 0);
  13714. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13715. }
  13716. CriticalSection& DeletedAtShutdown::getLock()
  13717. {
  13718. static CriticalSection lock;
  13719. return lock;
  13720. }
  13721. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13722. {
  13723. static Array <DeletedAtShutdown*> objects;
  13724. return objects;
  13725. }
  13726. END_JUCE_NAMESPACE
  13727. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13728. #endif
  13729. #if JUCE_BUILD_MISC
  13730. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13731. BEGIN_JUCE_NAMESPACE
  13732. class ValueTree::SetPropertyAction : public UndoableAction
  13733. {
  13734. public:
  13735. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13736. const var& newValue_, const var& oldValue_,
  13737. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13738. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13739. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13740. {
  13741. }
  13742. ~SetPropertyAction() {}
  13743. bool perform()
  13744. {
  13745. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13746. if (isDeletingProperty)
  13747. target->removeProperty (name, 0);
  13748. else
  13749. target->setProperty (name, newValue, 0);
  13750. return true;
  13751. }
  13752. bool undo()
  13753. {
  13754. if (isAddingNewProperty)
  13755. target->removeProperty (name, 0);
  13756. else
  13757. target->setProperty (name, oldValue, 0);
  13758. return true;
  13759. }
  13760. int getSizeInUnits()
  13761. {
  13762. return (int) sizeof (*this); //xxx should be more accurate
  13763. }
  13764. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13765. {
  13766. if (! (isAddingNewProperty || isDeletingProperty))
  13767. {
  13768. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13769. if (next != 0 && next->target == target && next->name == name
  13770. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13771. {
  13772. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13773. }
  13774. }
  13775. return 0;
  13776. }
  13777. private:
  13778. const SharedObjectPtr target;
  13779. const Identifier name;
  13780. const var newValue;
  13781. var oldValue;
  13782. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13783. SetPropertyAction (const SetPropertyAction&);
  13784. SetPropertyAction& operator= (const SetPropertyAction&);
  13785. };
  13786. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13787. {
  13788. public:
  13789. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13790. const SharedObjectPtr& newChild_)
  13791. : target (target_),
  13792. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13793. childIndex (childIndex_),
  13794. isDeleting (newChild_ == 0)
  13795. {
  13796. jassert (child != 0);
  13797. }
  13798. ~AddOrRemoveChildAction() {}
  13799. bool perform()
  13800. {
  13801. if (isDeleting)
  13802. target->removeChild (childIndex, 0);
  13803. else
  13804. target->addChild (child, childIndex, 0);
  13805. return true;
  13806. }
  13807. bool undo()
  13808. {
  13809. if (isDeleting)
  13810. {
  13811. target->addChild (child, childIndex, 0);
  13812. }
  13813. else
  13814. {
  13815. // If you hit this, it seems that your object's state is getting confused - probably
  13816. // because you've interleaved some undoable and non-undoable operations?
  13817. jassert (childIndex < target->children.size());
  13818. target->removeChild (childIndex, 0);
  13819. }
  13820. return true;
  13821. }
  13822. int getSizeInUnits()
  13823. {
  13824. return (int) sizeof (*this); //xxx should be more accurate
  13825. }
  13826. private:
  13827. const SharedObjectPtr target, child;
  13828. const int childIndex;
  13829. const bool isDeleting;
  13830. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  13831. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  13832. };
  13833. class ValueTree::MoveChildAction : public UndoableAction
  13834. {
  13835. public:
  13836. MoveChildAction (const SharedObjectPtr& parent_,
  13837. const int startIndex_, const int endIndex_)
  13838. : parent (parent_),
  13839. startIndex (startIndex_),
  13840. endIndex (endIndex_)
  13841. {
  13842. }
  13843. ~MoveChildAction() {}
  13844. bool perform()
  13845. {
  13846. parent->moveChild (startIndex, endIndex, 0);
  13847. return true;
  13848. }
  13849. bool undo()
  13850. {
  13851. parent->moveChild (endIndex, startIndex, 0);
  13852. return true;
  13853. }
  13854. int getSizeInUnits()
  13855. {
  13856. return (int) sizeof (*this); //xxx should be more accurate
  13857. }
  13858. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13859. {
  13860. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13861. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13862. return new MoveChildAction (parent, startIndex, next->endIndex);
  13863. return 0;
  13864. }
  13865. private:
  13866. const SharedObjectPtr parent;
  13867. const int startIndex, endIndex;
  13868. MoveChildAction (const MoveChildAction&);
  13869. MoveChildAction& operator= (const MoveChildAction&);
  13870. };
  13871. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13872. : type (type_), parent (0)
  13873. {
  13874. }
  13875. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13876. : type (other.type), properties (other.properties), parent (0)
  13877. {
  13878. for (int i = 0; i < other.children.size(); ++i)
  13879. {
  13880. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13881. child->parent = this;
  13882. children.add (child);
  13883. }
  13884. }
  13885. ValueTree::SharedObject::~SharedObject()
  13886. {
  13887. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13888. for (int i = children.size(); --i >= 0;)
  13889. {
  13890. const SharedObjectPtr c (children.getUnchecked(i));
  13891. c->parent = 0;
  13892. children.remove (i);
  13893. c->sendParentChangeMessage();
  13894. }
  13895. }
  13896. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13897. {
  13898. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13899. {
  13900. ValueTree* const v = valueTreesWithListeners[i];
  13901. if (v != 0)
  13902. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13903. }
  13904. }
  13905. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13906. {
  13907. ValueTree tree (this);
  13908. ValueTree::SharedObject* t = this;
  13909. while (t != 0)
  13910. {
  13911. t->sendPropertyChangeMessage (tree, property);
  13912. t = t->parent;
  13913. }
  13914. }
  13915. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  13916. {
  13917. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13918. {
  13919. ValueTree* const v = valueTreesWithListeners[i];
  13920. if (v != 0)
  13921. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  13922. }
  13923. }
  13924. void ValueTree::SharedObject::sendChildChangeMessage()
  13925. {
  13926. ValueTree tree (this);
  13927. ValueTree::SharedObject* t = this;
  13928. while (t != 0)
  13929. {
  13930. t->sendChildChangeMessage (tree);
  13931. t = t->parent;
  13932. }
  13933. }
  13934. void ValueTree::SharedObject::sendParentChangeMessage()
  13935. {
  13936. ValueTree tree (this);
  13937. int i;
  13938. for (i = children.size(); --i >= 0;)
  13939. {
  13940. SharedObject* const t = children[i];
  13941. if (t != 0)
  13942. t->sendParentChangeMessage();
  13943. }
  13944. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13945. {
  13946. ValueTree* const v = valueTreesWithListeners[i];
  13947. if (v != 0)
  13948. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  13949. }
  13950. }
  13951. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  13952. {
  13953. return properties [name];
  13954. }
  13955. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13956. {
  13957. return properties.getWithDefault (name, defaultReturnValue);
  13958. }
  13959. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13960. {
  13961. if (undoManager == 0)
  13962. {
  13963. if (properties.set (name, newValue))
  13964. sendPropertyChangeMessage (name);
  13965. }
  13966. else
  13967. {
  13968. var* const existingValue = properties.getItem (name);
  13969. if (existingValue != 0)
  13970. {
  13971. if (*existingValue != newValue)
  13972. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  13973. }
  13974. else
  13975. {
  13976. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  13977. }
  13978. }
  13979. }
  13980. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  13981. {
  13982. return properties.contains (name);
  13983. }
  13984. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13985. {
  13986. if (undoManager == 0)
  13987. {
  13988. if (properties.remove (name))
  13989. sendPropertyChangeMessage (name);
  13990. }
  13991. else
  13992. {
  13993. if (properties.contains (name))
  13994. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  13995. }
  13996. }
  13997. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  13998. {
  13999. if (undoManager == 0)
  14000. {
  14001. while (properties.size() > 0)
  14002. {
  14003. const Identifier name (properties.getName (properties.size() - 1));
  14004. properties.remove (name);
  14005. sendPropertyChangeMessage (name);
  14006. }
  14007. }
  14008. else
  14009. {
  14010. for (int i = properties.size(); --i >= 0;)
  14011. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14012. }
  14013. }
  14014. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14015. {
  14016. for (int i = 0; i < children.size(); ++i)
  14017. if (children.getUnchecked(i)->type == typeToMatch)
  14018. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14019. return ValueTree::invalid;
  14020. }
  14021. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14022. {
  14023. for (int i = 0; i < children.size(); ++i)
  14024. if (children.getUnchecked(i)->type == typeToMatch)
  14025. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14026. SharedObject* const newObject = new SharedObject (typeToMatch);
  14027. addChild (newObject, -1, undoManager);
  14028. return ValueTree (newObject);
  14029. }
  14030. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14031. {
  14032. for (int i = 0; i < children.size(); ++i)
  14033. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14034. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14035. return ValueTree::invalid;
  14036. }
  14037. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14038. {
  14039. const SharedObject* p = parent;
  14040. while (p != 0)
  14041. {
  14042. if (p == possibleParent)
  14043. return true;
  14044. p = p->parent;
  14045. }
  14046. return false;
  14047. }
  14048. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14049. {
  14050. return children.indexOf (child.object);
  14051. }
  14052. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14053. {
  14054. if (child != 0 && child->parent != this)
  14055. {
  14056. if (child != this && ! isAChildOf (child))
  14057. {
  14058. // You should always make sure that a child is removed from its previous parent before
  14059. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14060. // undomanager should be used when removing it from its current parent..
  14061. jassert (child->parent == 0);
  14062. if (child->parent != 0)
  14063. {
  14064. jassert (child->parent->children.indexOf (child) >= 0);
  14065. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14066. }
  14067. if (undoManager == 0)
  14068. {
  14069. children.insert (index, child);
  14070. child->parent = this;
  14071. sendChildChangeMessage();
  14072. child->sendParentChangeMessage();
  14073. }
  14074. else
  14075. {
  14076. if (index < 0)
  14077. index = children.size();
  14078. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14079. }
  14080. }
  14081. else
  14082. {
  14083. // You're attempting to create a recursive loop! A node
  14084. // can't be a child of one of its own children!
  14085. jassertfalse;
  14086. }
  14087. }
  14088. }
  14089. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14090. {
  14091. const SharedObjectPtr child (children [childIndex]);
  14092. if (child != 0)
  14093. {
  14094. if (undoManager == 0)
  14095. {
  14096. children.remove (childIndex);
  14097. child->parent = 0;
  14098. sendChildChangeMessage();
  14099. child->sendParentChangeMessage();
  14100. }
  14101. else
  14102. {
  14103. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14104. }
  14105. }
  14106. }
  14107. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14108. {
  14109. while (children.size() > 0)
  14110. removeChild (children.size() - 1, undoManager);
  14111. }
  14112. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14113. {
  14114. // The source index must be a valid index!
  14115. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14116. if (currentIndex != newIndex
  14117. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14118. {
  14119. if (undoManager == 0)
  14120. {
  14121. children.move (currentIndex, newIndex);
  14122. sendChildChangeMessage();
  14123. }
  14124. else
  14125. {
  14126. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14127. newIndex = children.size() - 1;
  14128. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14129. }
  14130. }
  14131. }
  14132. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14133. {
  14134. if (type != other.type
  14135. || properties.size() != other.properties.size()
  14136. || children.size() != other.children.size()
  14137. || properties != other.properties)
  14138. return false;
  14139. for (int i = 0; i < children.size(); ++i)
  14140. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14141. return false;
  14142. return true;
  14143. }
  14144. ValueTree::ValueTree() throw()
  14145. : object (0)
  14146. {
  14147. }
  14148. const ValueTree ValueTree::invalid;
  14149. ValueTree::ValueTree (const Identifier& type_)
  14150. : object (new ValueTree::SharedObject (type_))
  14151. {
  14152. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14153. }
  14154. ValueTree::ValueTree (SharedObject* const object_)
  14155. : object (object_)
  14156. {
  14157. }
  14158. ValueTree::ValueTree (const ValueTree& other)
  14159. : object (other.object)
  14160. {
  14161. }
  14162. ValueTree& ValueTree::operator= (const ValueTree& other)
  14163. {
  14164. if (listeners.size() > 0)
  14165. {
  14166. if (object != 0)
  14167. object->valueTreesWithListeners.removeValue (this);
  14168. if (other.object != 0)
  14169. other.object->valueTreesWithListeners.add (this);
  14170. }
  14171. object = other.object;
  14172. return *this;
  14173. }
  14174. ValueTree::~ValueTree()
  14175. {
  14176. if (listeners.size() > 0 && object != 0)
  14177. object->valueTreesWithListeners.removeValue (this);
  14178. }
  14179. bool ValueTree::operator== (const ValueTree& other) const throw()
  14180. {
  14181. return object == other.object;
  14182. }
  14183. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14184. {
  14185. return object != other.object;
  14186. }
  14187. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14188. {
  14189. return object == other.object
  14190. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14191. }
  14192. ValueTree ValueTree::createCopy() const
  14193. {
  14194. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14195. }
  14196. bool ValueTree::hasType (const Identifier& typeName) const
  14197. {
  14198. return object != 0 && object->type == typeName;
  14199. }
  14200. const Identifier ValueTree::getType() const
  14201. {
  14202. return object != 0 ? object->type : Identifier();
  14203. }
  14204. ValueTree ValueTree::getParent() const
  14205. {
  14206. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14207. }
  14208. ValueTree ValueTree::getSibling (const int delta) const
  14209. {
  14210. if (object == 0 || object->parent == 0)
  14211. return invalid;
  14212. const int index = object->parent->indexOf (*this) + delta;
  14213. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14214. }
  14215. const var& ValueTree::operator[] (const Identifier& name) const
  14216. {
  14217. return object == 0 ? var::null : object->getProperty (name);
  14218. }
  14219. const var& ValueTree::getProperty (const Identifier& name) const
  14220. {
  14221. return object == 0 ? var::null : object->getProperty (name);
  14222. }
  14223. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14224. {
  14225. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14226. }
  14227. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14228. {
  14229. jassert (name.toString().isNotEmpty());
  14230. if (object != 0 && name.toString().isNotEmpty())
  14231. object->setProperty (name, newValue, undoManager);
  14232. }
  14233. bool ValueTree::hasProperty (const Identifier& name) const
  14234. {
  14235. return object != 0 && object->hasProperty (name);
  14236. }
  14237. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14238. {
  14239. if (object != 0)
  14240. object->removeProperty (name, undoManager);
  14241. }
  14242. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14243. {
  14244. if (object != 0)
  14245. object->removeAllProperties (undoManager);
  14246. }
  14247. int ValueTree::getNumProperties() const
  14248. {
  14249. return object == 0 ? 0 : object->properties.size();
  14250. }
  14251. const Identifier ValueTree::getPropertyName (const int index) const
  14252. {
  14253. return object == 0 ? Identifier()
  14254. : object->properties.getName (index);
  14255. }
  14256. class ValueTreePropertyValueSource : public Value::ValueSource,
  14257. public ValueTree::Listener
  14258. {
  14259. public:
  14260. ValueTreePropertyValueSource (const ValueTree& tree_,
  14261. const Identifier& property_,
  14262. UndoManager* const undoManager_)
  14263. : tree (tree_),
  14264. property (property_),
  14265. undoManager (undoManager_)
  14266. {
  14267. tree.addListener (this);
  14268. }
  14269. ~ValueTreePropertyValueSource()
  14270. {
  14271. tree.removeListener (this);
  14272. }
  14273. const var getValue() const
  14274. {
  14275. return tree [property];
  14276. }
  14277. void setValue (const var& newValue)
  14278. {
  14279. tree.setProperty (property, newValue, undoManager);
  14280. }
  14281. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14282. {
  14283. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14284. sendChangeMessage (false);
  14285. }
  14286. void valueTreeChildrenChanged (ValueTree&) {}
  14287. void valueTreeParentChanged (ValueTree&) {}
  14288. private:
  14289. ValueTree tree;
  14290. const Identifier property;
  14291. UndoManager* const undoManager;
  14292. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14293. };
  14294. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14295. {
  14296. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14297. }
  14298. int ValueTree::getNumChildren() const
  14299. {
  14300. return object == 0 ? 0 : object->children.size();
  14301. }
  14302. ValueTree ValueTree::getChild (int index) const
  14303. {
  14304. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14305. }
  14306. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14307. {
  14308. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14309. }
  14310. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14311. {
  14312. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14313. }
  14314. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14315. {
  14316. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14317. }
  14318. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14319. {
  14320. return object != 0 && object->isAChildOf (possibleParent.object);
  14321. }
  14322. int ValueTree::indexOf (const ValueTree& child) const
  14323. {
  14324. return object != 0 ? object->indexOf (child) : -1;
  14325. }
  14326. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14327. {
  14328. if (object != 0)
  14329. object->addChild (child.object, index, undoManager);
  14330. }
  14331. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14332. {
  14333. if (object != 0)
  14334. object->removeChild (childIndex, undoManager);
  14335. }
  14336. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14337. {
  14338. if (object != 0)
  14339. object->removeChild (object->children.indexOf (child.object), undoManager);
  14340. }
  14341. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14342. {
  14343. if (object != 0)
  14344. object->removeAllChildren (undoManager);
  14345. }
  14346. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14347. {
  14348. if (object != 0)
  14349. object->moveChild (currentIndex, newIndex, undoManager);
  14350. }
  14351. void ValueTree::addListener (Listener* listener)
  14352. {
  14353. if (listener != 0)
  14354. {
  14355. if (listeners.size() == 0 && object != 0)
  14356. object->valueTreesWithListeners.add (this);
  14357. listeners.add (listener);
  14358. }
  14359. }
  14360. void ValueTree::removeListener (Listener* listener)
  14361. {
  14362. listeners.remove (listener);
  14363. if (listeners.size() == 0 && object != 0)
  14364. object->valueTreesWithListeners.removeValue (this);
  14365. }
  14366. XmlElement* ValueTree::SharedObject::createXml() const
  14367. {
  14368. XmlElement* xml = new XmlElement (type.toString());
  14369. int i;
  14370. for (i = 0; i < properties.size(); ++i)
  14371. {
  14372. Identifier name (properties.getName(i));
  14373. const var& v = properties [name];
  14374. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  14375. xml->setAttribute (name.toString(), v.toString());
  14376. }
  14377. for (i = 0; i < children.size(); ++i)
  14378. xml->addChildElement (children.getUnchecked(i)->createXml());
  14379. return xml;
  14380. }
  14381. XmlElement* ValueTree::createXml() const
  14382. {
  14383. return object != 0 ? object->createXml() : 0;
  14384. }
  14385. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14386. {
  14387. ValueTree v (xml.getTagName());
  14388. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  14389. for (int i = 0; i < numAtts; ++i)
  14390. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  14391. forEachXmlChildElement (xml, e)
  14392. {
  14393. v.addChild (fromXml (*e), -1, 0);
  14394. }
  14395. return v;
  14396. }
  14397. void ValueTree::writeToStream (OutputStream& output)
  14398. {
  14399. output.writeString (getType().toString());
  14400. const int numProps = getNumProperties();
  14401. output.writeCompressedInt (numProps);
  14402. int i;
  14403. for (i = 0; i < numProps; ++i)
  14404. {
  14405. const Identifier name (getPropertyName(i));
  14406. output.writeString (name.toString());
  14407. getProperty(name).writeToStream (output);
  14408. }
  14409. const int numChildren = getNumChildren();
  14410. output.writeCompressedInt (numChildren);
  14411. for (i = 0; i < numChildren; ++i)
  14412. getChild (i).writeToStream (output);
  14413. }
  14414. ValueTree ValueTree::readFromStream (InputStream& input)
  14415. {
  14416. const String type (input.readString());
  14417. if (type.isEmpty())
  14418. return ValueTree::invalid;
  14419. ValueTree v (type);
  14420. const int numProps = input.readCompressedInt();
  14421. if (numProps < 0)
  14422. {
  14423. jassertfalse; // trying to read corrupted data!
  14424. return v;
  14425. }
  14426. int i;
  14427. for (i = 0; i < numProps; ++i)
  14428. {
  14429. const String name (input.readString());
  14430. jassert (name.isNotEmpty());
  14431. const var value (var::readFromStream (input));
  14432. v.setProperty (name, value, 0);
  14433. }
  14434. const int numChildren = input.readCompressedInt();
  14435. for (i = 0; i < numChildren; ++i)
  14436. v.addChild (readFromStream (input), -1, 0);
  14437. return v;
  14438. }
  14439. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14440. {
  14441. MemoryInputStream in (data, numBytes, false);
  14442. return readFromStream (in);
  14443. }
  14444. END_JUCE_NAMESPACE
  14445. /*** End of inlined file: juce_ValueTree.cpp ***/
  14446. /*** Start of inlined file: juce_Value.cpp ***/
  14447. BEGIN_JUCE_NAMESPACE
  14448. Value::ValueSource::ValueSource()
  14449. {
  14450. }
  14451. Value::ValueSource::~ValueSource()
  14452. {
  14453. }
  14454. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14455. {
  14456. if (synchronous)
  14457. {
  14458. for (int i = valuesWithListeners.size(); --i >= 0;)
  14459. {
  14460. Value* const v = valuesWithListeners[i];
  14461. if (v != 0)
  14462. v->callListeners();
  14463. }
  14464. }
  14465. else
  14466. {
  14467. triggerAsyncUpdate();
  14468. }
  14469. }
  14470. void Value::ValueSource::handleAsyncUpdate()
  14471. {
  14472. sendChangeMessage (true);
  14473. }
  14474. class SimpleValueSource : public Value::ValueSource
  14475. {
  14476. public:
  14477. SimpleValueSource()
  14478. {
  14479. }
  14480. SimpleValueSource (const var& initialValue)
  14481. : value (initialValue)
  14482. {
  14483. }
  14484. ~SimpleValueSource()
  14485. {
  14486. }
  14487. const var getValue() const
  14488. {
  14489. return value;
  14490. }
  14491. void setValue (const var& newValue)
  14492. {
  14493. if (newValue != value)
  14494. {
  14495. value = newValue;
  14496. sendChangeMessage (false);
  14497. }
  14498. }
  14499. private:
  14500. var value;
  14501. SimpleValueSource (const SimpleValueSource&);
  14502. SimpleValueSource& operator= (const SimpleValueSource&);
  14503. };
  14504. Value::Value()
  14505. : value (new SimpleValueSource())
  14506. {
  14507. }
  14508. Value::Value (ValueSource* const value_)
  14509. : value (value_)
  14510. {
  14511. jassert (value_ != 0);
  14512. }
  14513. Value::Value (const var& initialValue)
  14514. : value (new SimpleValueSource (initialValue))
  14515. {
  14516. }
  14517. Value::Value (const Value& other)
  14518. : value (other.value)
  14519. {
  14520. }
  14521. Value& Value::operator= (const Value& other)
  14522. {
  14523. value = other.value;
  14524. return *this;
  14525. }
  14526. Value::~Value()
  14527. {
  14528. if (listeners.size() > 0)
  14529. value->valuesWithListeners.removeValue (this);
  14530. }
  14531. const var Value::getValue() const
  14532. {
  14533. return value->getValue();
  14534. }
  14535. Value::operator const var() const
  14536. {
  14537. return getValue();
  14538. }
  14539. void Value::setValue (const var& newValue)
  14540. {
  14541. value->setValue (newValue);
  14542. }
  14543. const String Value::toString() const
  14544. {
  14545. return value->getValue().toString();
  14546. }
  14547. Value& Value::operator= (const var& newValue)
  14548. {
  14549. value->setValue (newValue);
  14550. return *this;
  14551. }
  14552. void Value::referTo (const Value& valueToReferTo)
  14553. {
  14554. if (valueToReferTo.value != value)
  14555. {
  14556. if (listeners.size() > 0)
  14557. {
  14558. value->valuesWithListeners.removeValue (this);
  14559. valueToReferTo.value->valuesWithListeners.add (this);
  14560. }
  14561. value = valueToReferTo.value;
  14562. callListeners();
  14563. }
  14564. }
  14565. bool Value::refersToSameSourceAs (const Value& other) const
  14566. {
  14567. return value == other.value;
  14568. }
  14569. bool Value::operator== (const Value& other) const
  14570. {
  14571. return value == other.value || value->getValue() == other.getValue();
  14572. }
  14573. bool Value::operator!= (const Value& other) const
  14574. {
  14575. return value != other.value && value->getValue() != other.getValue();
  14576. }
  14577. void Value::addListener (Listener* const listener)
  14578. {
  14579. if (listener != 0)
  14580. {
  14581. if (listeners.size() == 0)
  14582. value->valuesWithListeners.add (this);
  14583. listeners.add (listener);
  14584. }
  14585. }
  14586. void Value::removeListener (Listener* const listener)
  14587. {
  14588. listeners.remove (listener);
  14589. if (listeners.size() == 0)
  14590. value->valuesWithListeners.removeValue (this);
  14591. }
  14592. void Value::callListeners()
  14593. {
  14594. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14595. listeners.call (&Value::Listener::valueChanged, v);
  14596. }
  14597. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14598. {
  14599. return stream << value.toString();
  14600. }
  14601. END_JUCE_NAMESPACE
  14602. /*** End of inlined file: juce_Value.cpp ***/
  14603. /*** Start of inlined file: juce_Application.cpp ***/
  14604. BEGIN_JUCE_NAMESPACE
  14605. #if JUCE_MAC
  14606. extern void juce_initialiseMacMainMenu();
  14607. #endif
  14608. JUCEApplication::JUCEApplication()
  14609. : appReturnValue (0),
  14610. stillInitialising (true)
  14611. {
  14612. jassert (isStandaloneApp() && appInstance == 0);
  14613. appInstance = this;
  14614. }
  14615. JUCEApplication::~JUCEApplication()
  14616. {
  14617. if (appLock != 0)
  14618. {
  14619. appLock->exit();
  14620. appLock = 0;
  14621. }
  14622. jassert (appInstance == this);
  14623. appInstance = 0;
  14624. }
  14625. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  14626. JUCEApplication* JUCEApplication::appInstance = 0;
  14627. bool JUCEApplication::moreThanOneInstanceAllowed()
  14628. {
  14629. return true;
  14630. }
  14631. void JUCEApplication::anotherInstanceStarted (const String&)
  14632. {
  14633. }
  14634. void JUCEApplication::systemRequestedQuit()
  14635. {
  14636. quit();
  14637. }
  14638. void JUCEApplication::quit()
  14639. {
  14640. MessageManager::getInstance()->stopDispatchLoop();
  14641. }
  14642. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  14643. {
  14644. appReturnValue = newReturnValue;
  14645. }
  14646. void JUCEApplication::actionListenerCallback (const String& message)
  14647. {
  14648. if (message.startsWith (getApplicationName() + "/"))
  14649. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  14650. }
  14651. void JUCEApplication::unhandledException (const std::exception*,
  14652. const String&,
  14653. const int)
  14654. {
  14655. jassertfalse;
  14656. }
  14657. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  14658. const char* const sourceFile,
  14659. const int lineNumber)
  14660. {
  14661. if (appInstance != 0)
  14662. appInstance->unhandledException (e, sourceFile, lineNumber);
  14663. }
  14664. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  14665. {
  14666. return 0;
  14667. }
  14668. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  14669. {
  14670. commands.add (StandardApplicationCommandIDs::quit);
  14671. }
  14672. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  14673. {
  14674. if (commandID == StandardApplicationCommandIDs::quit)
  14675. {
  14676. result.setInfo (TRANS("Quit"),
  14677. TRANS("Quits the application"),
  14678. "Application",
  14679. 0);
  14680. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  14681. }
  14682. }
  14683. bool JUCEApplication::perform (const InvocationInfo& info)
  14684. {
  14685. if (info.commandID == StandardApplicationCommandIDs::quit)
  14686. {
  14687. systemRequestedQuit();
  14688. return true;
  14689. }
  14690. return false;
  14691. }
  14692. bool JUCEApplication::initialiseApp (const String& commandLine)
  14693. {
  14694. commandLineParameters = commandLine.trim();
  14695. #if ! JUCE_IOS
  14696. jassert (appLock == 0); // initialiseApp must only be called once!
  14697. if (! moreThanOneInstanceAllowed())
  14698. {
  14699. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  14700. if (! appLock->enter(0))
  14701. {
  14702. appLock = 0;
  14703. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  14704. DBG ("Another instance is running - quitting...");
  14705. return false;
  14706. }
  14707. }
  14708. #endif
  14709. // let the app do its setting-up..
  14710. initialise (commandLineParameters);
  14711. #if JUCE_MAC
  14712. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  14713. #endif
  14714. // register for broadcast new app messages
  14715. MessageManager::getInstance()->registerBroadcastListener (this);
  14716. stillInitialising = false;
  14717. return true;
  14718. }
  14719. int JUCEApplication::shutdownApp()
  14720. {
  14721. jassert (appInstance == this);
  14722. MessageManager::getInstance()->deregisterBroadcastListener (this);
  14723. JUCE_TRY
  14724. {
  14725. // give the app a chance to clean up..
  14726. shutdown();
  14727. }
  14728. JUCE_CATCH_EXCEPTION
  14729. return getApplicationReturnValue();
  14730. }
  14731. int JUCEApplication::main (const String& commandLine)
  14732. {
  14733. ScopedJuceInitialiser_GUI libraryInitialiser;
  14734. jassert (createInstance != 0);
  14735. const ScopedPointer<JUCEApplication> app (createInstance());
  14736. if (! app->initialiseApp (commandLine))
  14737. return 0;
  14738. JUCE_TRY
  14739. {
  14740. // loop until a quit message is received..
  14741. MessageManager::getInstance()->runDispatchLoop();
  14742. }
  14743. JUCE_CATCH_EXCEPTION
  14744. return app->shutdownApp();
  14745. }
  14746. #if JUCE_IOS
  14747. extern int juce_iOSMain (int argc, const char* argv[]);
  14748. #endif
  14749. #if ! JUCE_WINDOWS
  14750. extern const char* juce_Argv0;
  14751. #endif
  14752. int JUCEApplication::main (int argc, const char* argv[])
  14753. {
  14754. JUCE_AUTORELEASEPOOL
  14755. #if ! JUCE_WINDOWS
  14756. jassert (createInstance != 0);
  14757. juce_Argv0 = argv[0];
  14758. #endif
  14759. #if JUCE_IOS
  14760. return juce_iOSMain (argc, argv);
  14761. #else
  14762. String cmd;
  14763. for (int i = 1; i < argc; ++i)
  14764. cmd << argv[i] << ' ';
  14765. return JUCEApplication::main (cmd);
  14766. #endif
  14767. }
  14768. END_JUCE_NAMESPACE
  14769. /*** End of inlined file: juce_Application.cpp ***/
  14770. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14771. BEGIN_JUCE_NAMESPACE
  14772. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14773. : commandID (commandID_),
  14774. flags (0)
  14775. {
  14776. }
  14777. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14778. const String& description_,
  14779. const String& categoryName_,
  14780. const int flags_) throw()
  14781. {
  14782. shortName = shortName_;
  14783. description = description_;
  14784. categoryName = categoryName_;
  14785. flags = flags_;
  14786. }
  14787. void ApplicationCommandInfo::setActive (const bool b) throw()
  14788. {
  14789. if (b)
  14790. flags &= ~isDisabled;
  14791. else
  14792. flags |= isDisabled;
  14793. }
  14794. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14795. {
  14796. if (b)
  14797. flags |= isTicked;
  14798. else
  14799. flags &= ~isTicked;
  14800. }
  14801. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14802. {
  14803. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14804. }
  14805. END_JUCE_NAMESPACE
  14806. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14807. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14808. BEGIN_JUCE_NAMESPACE
  14809. ApplicationCommandManager::ApplicationCommandManager()
  14810. : firstTarget (0)
  14811. {
  14812. keyMappings = new KeyPressMappingSet (this);
  14813. Desktop::getInstance().addFocusChangeListener (this);
  14814. }
  14815. ApplicationCommandManager::~ApplicationCommandManager()
  14816. {
  14817. Desktop::getInstance().removeFocusChangeListener (this);
  14818. keyMappings = 0;
  14819. }
  14820. void ApplicationCommandManager::clearCommands()
  14821. {
  14822. commands.clear();
  14823. keyMappings->clearAllKeyPresses();
  14824. triggerAsyncUpdate();
  14825. }
  14826. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14827. {
  14828. // zero isn't a valid command ID!
  14829. jassert (newCommand.commandID != 0);
  14830. // the name isn't optional!
  14831. jassert (newCommand.shortName.isNotEmpty());
  14832. if (getCommandForID (newCommand.commandID) == 0)
  14833. {
  14834. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14835. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14836. commands.add (newInfo);
  14837. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14838. triggerAsyncUpdate();
  14839. }
  14840. else
  14841. {
  14842. // trying to re-register the same command with different parameters?
  14843. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14844. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14845. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14846. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14847. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14848. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14849. }
  14850. }
  14851. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14852. {
  14853. if (target != 0)
  14854. {
  14855. Array <CommandID> commandIDs;
  14856. target->getAllCommands (commandIDs);
  14857. for (int i = 0; i < commandIDs.size(); ++i)
  14858. {
  14859. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14860. target->getCommandInfo (info.commandID, info);
  14861. registerCommand (info);
  14862. }
  14863. }
  14864. }
  14865. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14866. {
  14867. for (int i = commands.size(); --i >= 0;)
  14868. {
  14869. if (commands.getUnchecked (i)->commandID == commandID)
  14870. {
  14871. commands.remove (i);
  14872. triggerAsyncUpdate();
  14873. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14874. for (int j = keys.size(); --j >= 0;)
  14875. keyMappings->removeKeyPress (keys.getReference (j));
  14876. }
  14877. }
  14878. }
  14879. void ApplicationCommandManager::commandStatusChanged()
  14880. {
  14881. triggerAsyncUpdate();
  14882. }
  14883. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14884. {
  14885. for (int i = commands.size(); --i >= 0;)
  14886. if (commands.getUnchecked(i)->commandID == commandID)
  14887. return commands.getUnchecked(i);
  14888. return 0;
  14889. }
  14890. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14891. {
  14892. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14893. return (ci != 0) ? ci->shortName : String::empty;
  14894. }
  14895. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14896. {
  14897. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14898. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14899. : String::empty;
  14900. }
  14901. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14902. {
  14903. StringArray s;
  14904. for (int i = 0; i < commands.size(); ++i)
  14905. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14906. return s;
  14907. }
  14908. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14909. {
  14910. Array <CommandID> results;
  14911. for (int i = 0; i < commands.size(); ++i)
  14912. if (commands.getUnchecked(i)->categoryName == categoryName)
  14913. results.add (commands.getUnchecked(i)->commandID);
  14914. return results;
  14915. }
  14916. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14917. {
  14918. ApplicationCommandTarget::InvocationInfo info (commandID);
  14919. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14920. return invoke (info, asynchronously);
  14921. }
  14922. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14923. {
  14924. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14925. // manager first..
  14926. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14927. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14928. if (target == 0)
  14929. return false;
  14930. ApplicationCommandInfo commandInfo (0);
  14931. target->getCommandInfo (info_.commandID, commandInfo);
  14932. ApplicationCommandTarget::InvocationInfo info (info_);
  14933. info.commandFlags = commandInfo.flags;
  14934. sendListenerInvokeCallback (info);
  14935. const bool ok = target->invoke (info, asynchronously);
  14936. commandStatusChanged();
  14937. return ok;
  14938. }
  14939. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14940. {
  14941. return firstTarget != 0 ? firstTarget
  14942. : findDefaultComponentTarget();
  14943. }
  14944. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14945. {
  14946. firstTarget = newTarget;
  14947. }
  14948. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14949. ApplicationCommandInfo& upToDateInfo)
  14950. {
  14951. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14952. if (target == 0)
  14953. target = JUCEApplication::getInstance();
  14954. if (target != 0)
  14955. target = target->getTargetForCommand (commandID);
  14956. if (target != 0)
  14957. target->getCommandInfo (commandID, upToDateInfo);
  14958. return target;
  14959. }
  14960. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14961. {
  14962. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14963. if (target == 0 && c != 0)
  14964. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14965. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14966. return target;
  14967. }
  14968. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14969. {
  14970. Component* c = Component::getCurrentlyFocusedComponent();
  14971. if (c == 0)
  14972. {
  14973. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14974. if (activeWindow != 0)
  14975. {
  14976. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14977. if (c == 0)
  14978. c = activeWindow;
  14979. }
  14980. }
  14981. if (c == 0 && Process::isForegroundProcess())
  14982. {
  14983. // getting a bit desperate now - try all desktop comps..
  14984. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14985. {
  14986. ApplicationCommandTarget* const target
  14987. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14988. ->getPeer()->getLastFocusedSubcomponent());
  14989. if (target != 0)
  14990. return target;
  14991. }
  14992. }
  14993. if (c != 0)
  14994. {
  14995. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14996. // if we're focused on a ResizableWindow, chances are that it's the content
  14997. // component that really should get the event. And if not, the event will
  14998. // still be passed up to the top level window anyway, so let's send it to the
  14999. // content comp.
  15000. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15001. c = resizableWindow->getContentComponent();
  15002. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15003. if (target != 0)
  15004. return target;
  15005. }
  15006. return JUCEApplication::getInstance();
  15007. }
  15008. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  15009. {
  15010. listeners.add (listener);
  15011. }
  15012. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  15013. {
  15014. listeners.remove (listener);
  15015. }
  15016. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15017. {
  15018. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15019. }
  15020. void ApplicationCommandManager::handleAsyncUpdate()
  15021. {
  15022. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15023. }
  15024. void ApplicationCommandManager::globalFocusChanged (Component*)
  15025. {
  15026. commandStatusChanged();
  15027. }
  15028. END_JUCE_NAMESPACE
  15029. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15030. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15031. BEGIN_JUCE_NAMESPACE
  15032. ApplicationCommandTarget::ApplicationCommandTarget()
  15033. {
  15034. }
  15035. ApplicationCommandTarget::~ApplicationCommandTarget()
  15036. {
  15037. messageInvoker = 0;
  15038. }
  15039. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15040. {
  15041. if (isCommandActive (info.commandID))
  15042. {
  15043. if (async)
  15044. {
  15045. if (messageInvoker == 0)
  15046. messageInvoker = new CommandTargetMessageInvoker (this);
  15047. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15048. return true;
  15049. }
  15050. else
  15051. {
  15052. const bool success = perform (info);
  15053. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15054. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15055. // returns the command's info.
  15056. return success;
  15057. }
  15058. }
  15059. return false;
  15060. }
  15061. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15062. {
  15063. Component* c = dynamic_cast <Component*> (this);
  15064. if (c != 0)
  15065. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15066. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15067. return 0;
  15068. }
  15069. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15070. {
  15071. ApplicationCommandTarget* target = this;
  15072. int depth = 0;
  15073. while (target != 0)
  15074. {
  15075. Array <CommandID> commandIDs;
  15076. target->getAllCommands (commandIDs);
  15077. if (commandIDs.contains (commandID))
  15078. return target;
  15079. target = target->getNextCommandTarget();
  15080. ++depth;
  15081. jassert (depth < 100); // could be a recursive command chain??
  15082. jassert (target != this); // definitely a recursive command chain!
  15083. if (depth > 100 || target == this)
  15084. break;
  15085. }
  15086. if (target == 0)
  15087. {
  15088. target = JUCEApplication::getInstance();
  15089. if (target != 0)
  15090. {
  15091. Array <CommandID> commandIDs;
  15092. target->getAllCommands (commandIDs);
  15093. if (commandIDs.contains (commandID))
  15094. return target;
  15095. }
  15096. }
  15097. return 0;
  15098. }
  15099. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15100. {
  15101. ApplicationCommandInfo info (commandID);
  15102. info.flags = ApplicationCommandInfo::isDisabled;
  15103. getCommandInfo (commandID, info);
  15104. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15105. }
  15106. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15107. {
  15108. ApplicationCommandTarget* target = this;
  15109. int depth = 0;
  15110. while (target != 0)
  15111. {
  15112. if (target->tryToInvoke (info, async))
  15113. return true;
  15114. target = target->getNextCommandTarget();
  15115. ++depth;
  15116. jassert (depth < 100); // could be a recursive command chain??
  15117. jassert (target != this); // definitely a recursive command chain!
  15118. if (depth > 100 || target == this)
  15119. break;
  15120. }
  15121. if (target == 0)
  15122. {
  15123. target = JUCEApplication::getInstance();
  15124. if (target != 0)
  15125. return target->tryToInvoke (info, async);
  15126. }
  15127. return false;
  15128. }
  15129. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15130. {
  15131. ApplicationCommandTarget::InvocationInfo info (commandID);
  15132. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15133. return invoke (info, asynchronously);
  15134. }
  15135. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  15136. : commandID (commandID_),
  15137. commandFlags (0),
  15138. invocationMethod (direct),
  15139. originatingComponent (0),
  15140. isKeyDown (false),
  15141. millisecsSinceKeyPressed (0)
  15142. {
  15143. }
  15144. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15145. : owner (owner_)
  15146. {
  15147. }
  15148. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15149. {
  15150. }
  15151. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15152. {
  15153. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15154. owner->tryToInvoke (*info, false);
  15155. }
  15156. END_JUCE_NAMESPACE
  15157. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15158. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15159. BEGIN_JUCE_NAMESPACE
  15160. juce_ImplementSingleton (ApplicationProperties)
  15161. ApplicationProperties::ApplicationProperties()
  15162. : msBeforeSaving (3000),
  15163. options (PropertiesFile::storeAsBinary),
  15164. commonSettingsAreReadOnly (0),
  15165. processLock (0)
  15166. {
  15167. }
  15168. ApplicationProperties::~ApplicationProperties()
  15169. {
  15170. closeFiles();
  15171. clearSingletonInstance();
  15172. }
  15173. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15174. const String& fileNameSuffix,
  15175. const String& folderName_,
  15176. const int millisecondsBeforeSaving,
  15177. const int propertiesFileOptions,
  15178. InterProcessLock* processLock_)
  15179. {
  15180. appName = applicationName;
  15181. fileSuffix = fileNameSuffix;
  15182. folderName = folderName_;
  15183. msBeforeSaving = millisecondsBeforeSaving;
  15184. options = propertiesFileOptions;
  15185. processLock = processLock_;
  15186. }
  15187. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15188. const bool testCommonSettings,
  15189. const bool showWarningDialogOnFailure)
  15190. {
  15191. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15192. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15193. if (! (userOk && commonOk))
  15194. {
  15195. if (showWarningDialogOnFailure)
  15196. {
  15197. String filenames;
  15198. if (userProps != 0 && ! userOk)
  15199. filenames << '\n' << userProps->getFile().getFullPathName();
  15200. if (commonProps != 0 && ! commonOk)
  15201. filenames << '\n' << commonProps->getFile().getFullPathName();
  15202. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15203. appName + TRANS(" - Unable to save settings"),
  15204. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15205. + appName + TRANS(" needs to be able to write to the following files:\n")
  15206. + filenames
  15207. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15208. }
  15209. return false;
  15210. }
  15211. return true;
  15212. }
  15213. void ApplicationProperties::openFiles()
  15214. {
  15215. // You need to call setStorageParameters() before trying to get hold of the
  15216. // properties!
  15217. jassert (appName.isNotEmpty());
  15218. if (appName.isNotEmpty())
  15219. {
  15220. if (userProps == 0)
  15221. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15222. false, msBeforeSaving, options, processLock);
  15223. if (commonProps == 0)
  15224. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15225. true, msBeforeSaving, options, processLock);
  15226. userProps->setFallbackPropertySet (commonProps);
  15227. }
  15228. }
  15229. PropertiesFile* ApplicationProperties::getUserSettings()
  15230. {
  15231. if (userProps == 0)
  15232. openFiles();
  15233. return userProps;
  15234. }
  15235. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15236. {
  15237. if (commonProps == 0)
  15238. openFiles();
  15239. if (returnUserPropsIfReadOnly)
  15240. {
  15241. if (commonSettingsAreReadOnly == 0)
  15242. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15243. if (commonSettingsAreReadOnly > 0)
  15244. return userProps;
  15245. }
  15246. return commonProps;
  15247. }
  15248. bool ApplicationProperties::saveIfNeeded()
  15249. {
  15250. return (userProps == 0 || userProps->saveIfNeeded())
  15251. && (commonProps == 0 || commonProps->saveIfNeeded());
  15252. }
  15253. void ApplicationProperties::closeFiles()
  15254. {
  15255. userProps = 0;
  15256. commonProps = 0;
  15257. }
  15258. END_JUCE_NAMESPACE
  15259. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15260. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15261. BEGIN_JUCE_NAMESPACE
  15262. namespace PropertyFileConstants
  15263. {
  15264. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15265. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15266. static const char* const fileTag = "PROPERTIES";
  15267. static const char* const valueTag = "VALUE";
  15268. static const char* const nameAttribute = "name";
  15269. static const char* const valueAttribute = "val";
  15270. }
  15271. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15272. const int options_, InterProcessLock* const processLock_)
  15273. : PropertySet (ignoreCaseOfKeyNames),
  15274. file (f),
  15275. timerInterval (millisecondsBeforeSaving),
  15276. options (options_),
  15277. loadedOk (false),
  15278. needsWriting (false),
  15279. processLock (processLock_)
  15280. {
  15281. // You need to correctly specify just one storage format for the file
  15282. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15283. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15284. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15285. ProcessScopedLock pl (createProcessLock());
  15286. if (pl != 0 && ! pl->isLocked())
  15287. return; // locking failure..
  15288. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15289. if (fileStream != 0)
  15290. {
  15291. int magicNumber = fileStream->readInt();
  15292. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15293. {
  15294. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15295. magicNumber = PropertyFileConstants::magicNumber;
  15296. }
  15297. if (magicNumber == PropertyFileConstants::magicNumber)
  15298. {
  15299. loadedOk = true;
  15300. BufferedInputStream in (fileStream.release(), 2048, true);
  15301. int numValues = in.readInt();
  15302. while (--numValues >= 0 && ! in.isExhausted())
  15303. {
  15304. const String key (in.readString());
  15305. const String value (in.readString());
  15306. jassert (key.isNotEmpty());
  15307. if (key.isNotEmpty())
  15308. getAllProperties().set (key, value);
  15309. }
  15310. }
  15311. else
  15312. {
  15313. // Not a binary props file - let's see if it's XML..
  15314. fileStream = 0;
  15315. XmlDocument parser (f);
  15316. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15317. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15318. {
  15319. doc = parser.getDocumentElement();
  15320. if (doc != 0)
  15321. {
  15322. loadedOk = true;
  15323. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15324. {
  15325. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15326. if (name.isNotEmpty())
  15327. {
  15328. getAllProperties().set (name,
  15329. e->getFirstChildElement() != 0
  15330. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15331. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15332. }
  15333. }
  15334. }
  15335. else
  15336. {
  15337. // must be a pretty broken XML file we're trying to parse here,
  15338. // or a sign that this object needs an InterProcessLock,
  15339. // or just a failure reading the file. This last reason is why
  15340. // we don't jassertfalse here.
  15341. }
  15342. }
  15343. }
  15344. }
  15345. else
  15346. {
  15347. loadedOk = ! f.exists();
  15348. }
  15349. }
  15350. PropertiesFile::~PropertiesFile()
  15351. {
  15352. if (! saveIfNeeded())
  15353. jassertfalse;
  15354. }
  15355. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15356. {
  15357. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15358. }
  15359. bool PropertiesFile::saveIfNeeded()
  15360. {
  15361. const ScopedLock sl (getLock());
  15362. return (! needsWriting) || save();
  15363. }
  15364. bool PropertiesFile::needsToBeSaved() const
  15365. {
  15366. const ScopedLock sl (getLock());
  15367. return needsWriting;
  15368. }
  15369. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15370. {
  15371. const ScopedLock sl (getLock());
  15372. needsWriting = needsToBeSaved_;
  15373. }
  15374. bool PropertiesFile::save()
  15375. {
  15376. const ScopedLock sl (getLock());
  15377. stopTimer();
  15378. if (file == File::nonexistent
  15379. || file.isDirectory()
  15380. || ! file.getParentDirectory().createDirectory())
  15381. return false;
  15382. if ((options & storeAsXML) != 0)
  15383. {
  15384. XmlElement doc (PropertyFileConstants::fileTag);
  15385. for (int i = 0; i < getAllProperties().size(); ++i)
  15386. {
  15387. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15388. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15389. // if the value seems to contain xml, store it as such..
  15390. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  15391. XmlElement* const childElement = xmlContent.getDocumentElement();
  15392. if (childElement != 0)
  15393. e->addChildElement (childElement);
  15394. else
  15395. e->setAttribute (PropertyFileConstants::valueAttribute,
  15396. getAllProperties().getAllValues() [i]);
  15397. }
  15398. ProcessScopedLock pl (createProcessLock());
  15399. if (pl != 0 && ! pl->isLocked())
  15400. return false; // locking failure..
  15401. if (doc.writeToFile (file, String::empty))
  15402. {
  15403. needsWriting = false;
  15404. return true;
  15405. }
  15406. }
  15407. else
  15408. {
  15409. ProcessScopedLock pl (createProcessLock());
  15410. if (pl != 0 && ! pl->isLocked())
  15411. return false; // locking failure..
  15412. TemporaryFile tempFile (file);
  15413. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15414. if (out != 0)
  15415. {
  15416. if ((options & storeAsCompressedBinary) != 0)
  15417. {
  15418. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15419. out->flush();
  15420. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15421. }
  15422. else
  15423. {
  15424. // have you set up the storage option flags correctly?
  15425. jassert ((options & storeAsBinary) != 0);
  15426. out->writeInt (PropertyFileConstants::magicNumber);
  15427. }
  15428. const int numProperties = getAllProperties().size();
  15429. out->writeInt (numProperties);
  15430. for (int i = 0; i < numProperties; ++i)
  15431. {
  15432. out->writeString (getAllProperties().getAllKeys() [i]);
  15433. out->writeString (getAllProperties().getAllValues() [i]);
  15434. }
  15435. out = 0;
  15436. if (tempFile.overwriteTargetFileWithTemporary())
  15437. {
  15438. needsWriting = false;
  15439. return true;
  15440. }
  15441. }
  15442. }
  15443. return false;
  15444. }
  15445. void PropertiesFile::timerCallback()
  15446. {
  15447. saveIfNeeded();
  15448. }
  15449. void PropertiesFile::propertyChanged()
  15450. {
  15451. sendChangeMessage (this);
  15452. needsWriting = true;
  15453. if (timerInterval > 0)
  15454. startTimer (timerInterval);
  15455. else if (timerInterval == 0)
  15456. saveIfNeeded();
  15457. }
  15458. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15459. const String& fileNameSuffix,
  15460. const String& folderName,
  15461. const bool commonToAllUsers)
  15462. {
  15463. // mustn't have illegal characters in this name..
  15464. jassert (applicationName == File::createLegalFileName (applicationName));
  15465. #if JUCE_MAC || JUCE_IOS
  15466. File dir (commonToAllUsers ? "/Library/Preferences"
  15467. : "~/Library/Preferences");
  15468. if (folderName.isNotEmpty())
  15469. dir = dir.getChildFile (folderName);
  15470. #endif
  15471. #ifdef JUCE_LINUX
  15472. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15473. + (folderName.isNotEmpty() ? folderName
  15474. : ("." + applicationName)));
  15475. #endif
  15476. #if JUCE_WINDOWS
  15477. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15478. : File::userApplicationDataDirectory));
  15479. if (dir == File::nonexistent)
  15480. return File::nonexistent;
  15481. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15482. : applicationName);
  15483. #endif
  15484. return dir.getChildFile (applicationName)
  15485. .withFileExtension (fileNameSuffix);
  15486. }
  15487. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15488. const String& fileNameSuffix,
  15489. const String& folderName,
  15490. const bool commonToAllUsers,
  15491. const int millisecondsBeforeSaving,
  15492. const int propertiesFileOptions,
  15493. InterProcessLock* processLock_)
  15494. {
  15495. const File file (getDefaultAppSettingsFile (applicationName,
  15496. fileNameSuffix,
  15497. folderName,
  15498. commonToAllUsers));
  15499. jassert (file != File::nonexistent);
  15500. if (file == File::nonexistent)
  15501. return 0;
  15502. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15503. }
  15504. END_JUCE_NAMESPACE
  15505. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15506. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15507. BEGIN_JUCE_NAMESPACE
  15508. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15509. const String& fileWildcard_,
  15510. const String& openFileDialogTitle_,
  15511. const String& saveFileDialogTitle_)
  15512. : changedSinceSave (false),
  15513. fileExtension (fileExtension_),
  15514. fileWildcard (fileWildcard_),
  15515. openFileDialogTitle (openFileDialogTitle_),
  15516. saveFileDialogTitle (saveFileDialogTitle_)
  15517. {
  15518. }
  15519. FileBasedDocument::~FileBasedDocument()
  15520. {
  15521. }
  15522. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15523. {
  15524. if (changedSinceSave != hasChanged)
  15525. {
  15526. changedSinceSave = hasChanged;
  15527. sendChangeMessage (this);
  15528. }
  15529. }
  15530. void FileBasedDocument::changed()
  15531. {
  15532. changedSinceSave = true;
  15533. sendChangeMessage (this);
  15534. }
  15535. void FileBasedDocument::setFile (const File& newFile)
  15536. {
  15537. if (documentFile != newFile)
  15538. {
  15539. documentFile = newFile;
  15540. changed();
  15541. }
  15542. }
  15543. bool FileBasedDocument::loadFrom (const File& newFile,
  15544. const bool showMessageOnFailure)
  15545. {
  15546. MouseCursor::showWaitCursor();
  15547. const File oldFile (documentFile);
  15548. documentFile = newFile;
  15549. String error;
  15550. if (newFile.existsAsFile())
  15551. {
  15552. error = loadDocument (newFile);
  15553. if (error.isEmpty())
  15554. {
  15555. setChangedFlag (false);
  15556. MouseCursor::hideWaitCursor();
  15557. setLastDocumentOpened (newFile);
  15558. return true;
  15559. }
  15560. }
  15561. else
  15562. {
  15563. error = "The file doesn't exist";
  15564. }
  15565. documentFile = oldFile;
  15566. MouseCursor::hideWaitCursor();
  15567. if (showMessageOnFailure)
  15568. {
  15569. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15570. TRANS("Failed to open file..."),
  15571. TRANS("There was an error while trying to load the file:\n\n")
  15572. + newFile.getFullPathName()
  15573. + "\n\n"
  15574. + error);
  15575. }
  15576. return false;
  15577. }
  15578. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15579. {
  15580. FileChooser fc (openFileDialogTitle,
  15581. getLastDocumentOpened(),
  15582. fileWildcard);
  15583. if (fc.browseForFileToOpen())
  15584. return loadFrom (fc.getResult(), showMessageOnFailure);
  15585. return false;
  15586. }
  15587. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15588. const bool showMessageOnFailure)
  15589. {
  15590. return saveAs (documentFile,
  15591. false,
  15592. askUserForFileIfNotSpecified,
  15593. showMessageOnFailure);
  15594. }
  15595. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  15596. const bool warnAboutOverwritingExistingFiles,
  15597. const bool askUserForFileIfNotSpecified,
  15598. const bool showMessageOnFailure)
  15599. {
  15600. if (newFile == File::nonexistent)
  15601. {
  15602. if (askUserForFileIfNotSpecified)
  15603. {
  15604. return saveAsInteractive (true);
  15605. }
  15606. else
  15607. {
  15608. // can't save to an unspecified file
  15609. jassertfalse;
  15610. return failedToWriteToFile;
  15611. }
  15612. }
  15613. if (warnAboutOverwritingExistingFiles && newFile.exists())
  15614. {
  15615. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15616. TRANS("File already exists"),
  15617. TRANS("There's already a file called:\n\n")
  15618. + newFile.getFullPathName()
  15619. + TRANS("\n\nAre you sure you want to overwrite it?"),
  15620. TRANS("overwrite"),
  15621. TRANS("cancel")))
  15622. {
  15623. return userCancelledSave;
  15624. }
  15625. }
  15626. MouseCursor::showWaitCursor();
  15627. const File oldFile (documentFile);
  15628. documentFile = newFile;
  15629. String error (saveDocument (newFile));
  15630. if (error.isEmpty())
  15631. {
  15632. setChangedFlag (false);
  15633. MouseCursor::hideWaitCursor();
  15634. return savedOk;
  15635. }
  15636. documentFile = oldFile;
  15637. MouseCursor::hideWaitCursor();
  15638. if (showMessageOnFailure)
  15639. {
  15640. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15641. TRANS("Error writing to file..."),
  15642. TRANS("An error occurred while trying to save \"")
  15643. + getDocumentTitle()
  15644. + TRANS("\" to the file:\n\n")
  15645. + newFile.getFullPathName()
  15646. + "\n\n"
  15647. + error);
  15648. }
  15649. return failedToWriteToFile;
  15650. }
  15651. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  15652. {
  15653. if (! hasChangedSinceSaved())
  15654. return savedOk;
  15655. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  15656. TRANS("Closing document..."),
  15657. TRANS("Do you want to save the changes to \"")
  15658. + getDocumentTitle() + "\"?",
  15659. TRANS("save"),
  15660. TRANS("discard changes"),
  15661. TRANS("cancel"));
  15662. if (r == 1)
  15663. {
  15664. // save changes
  15665. return save (true, true);
  15666. }
  15667. else if (r == 2)
  15668. {
  15669. // discard changes
  15670. return savedOk;
  15671. }
  15672. return userCancelledSave;
  15673. }
  15674. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  15675. {
  15676. File f;
  15677. if (documentFile.existsAsFile())
  15678. f = documentFile;
  15679. else
  15680. f = getLastDocumentOpened();
  15681. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  15682. if (legalFilename.isEmpty())
  15683. legalFilename = "unnamed";
  15684. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  15685. f = f.getSiblingFile (legalFilename);
  15686. else
  15687. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  15688. f = f.withFileExtension (fileExtension)
  15689. .getNonexistentSibling (true);
  15690. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  15691. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  15692. {
  15693. File chosen (fc.getResult());
  15694. if (chosen.getFileExtension().isEmpty())
  15695. {
  15696. chosen = chosen.withFileExtension (fileExtension);
  15697. if (chosen.exists())
  15698. {
  15699. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15700. TRANS("File already exists"),
  15701. TRANS("There's already a file called:")
  15702. + "\n\n" + chosen.getFullPathName()
  15703. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  15704. TRANS("overwrite"),
  15705. TRANS("cancel")))
  15706. {
  15707. return userCancelledSave;
  15708. }
  15709. }
  15710. }
  15711. setLastDocumentOpened (chosen);
  15712. return saveAs (chosen, false, false, true);
  15713. }
  15714. return userCancelledSave;
  15715. }
  15716. END_JUCE_NAMESPACE
  15717. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  15718. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15719. BEGIN_JUCE_NAMESPACE
  15720. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  15721. : maxNumberOfItems (10)
  15722. {
  15723. }
  15724. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  15725. {
  15726. }
  15727. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  15728. {
  15729. maxNumberOfItems = jmax (1, newMaxNumber);
  15730. while (getNumFiles() > maxNumberOfItems)
  15731. files.remove (getNumFiles() - 1);
  15732. }
  15733. int RecentlyOpenedFilesList::getNumFiles() const
  15734. {
  15735. return files.size();
  15736. }
  15737. const File RecentlyOpenedFilesList::getFile (const int index) const
  15738. {
  15739. return File (files [index]);
  15740. }
  15741. void RecentlyOpenedFilesList::clear()
  15742. {
  15743. files.clear();
  15744. }
  15745. void RecentlyOpenedFilesList::addFile (const File& file)
  15746. {
  15747. const String path (file.getFullPathName());
  15748. files.removeString (path, true);
  15749. files.insert (0, path);
  15750. setMaxNumberOfItems (maxNumberOfItems);
  15751. }
  15752. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15753. {
  15754. for (int i = getNumFiles(); --i >= 0;)
  15755. if (! getFile(i).exists())
  15756. files.remove (i);
  15757. }
  15758. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15759. const int baseItemId,
  15760. const bool showFullPaths,
  15761. const bool dontAddNonExistentFiles,
  15762. const File** filesToAvoid)
  15763. {
  15764. int num = 0;
  15765. for (int i = 0; i < getNumFiles(); ++i)
  15766. {
  15767. const File f (getFile(i));
  15768. if ((! dontAddNonExistentFiles) || f.exists())
  15769. {
  15770. bool needsAvoiding = false;
  15771. if (filesToAvoid != 0)
  15772. {
  15773. const File** avoid = filesToAvoid;
  15774. while (*avoid != 0)
  15775. {
  15776. if (f == **avoid)
  15777. {
  15778. needsAvoiding = true;
  15779. break;
  15780. }
  15781. ++avoid;
  15782. }
  15783. }
  15784. if (! needsAvoiding)
  15785. {
  15786. menuToAddTo.addItem (baseItemId + i,
  15787. showFullPaths ? f.getFullPathName()
  15788. : f.getFileName());
  15789. ++num;
  15790. }
  15791. }
  15792. }
  15793. return num;
  15794. }
  15795. const String RecentlyOpenedFilesList::toString() const
  15796. {
  15797. return files.joinIntoString ("\n");
  15798. }
  15799. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15800. {
  15801. clear();
  15802. files.addLines (stringifiedVersion);
  15803. setMaxNumberOfItems (maxNumberOfItems);
  15804. }
  15805. END_JUCE_NAMESPACE
  15806. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15807. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15808. BEGIN_JUCE_NAMESPACE
  15809. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15810. const int minimumTransactions)
  15811. : totalUnitsStored (0),
  15812. nextIndex (0),
  15813. newTransaction (true),
  15814. reentrancyCheck (false)
  15815. {
  15816. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15817. minimumTransactions);
  15818. }
  15819. UndoManager::~UndoManager()
  15820. {
  15821. clearUndoHistory();
  15822. }
  15823. void UndoManager::clearUndoHistory()
  15824. {
  15825. transactions.clear();
  15826. transactionNames.clear();
  15827. totalUnitsStored = 0;
  15828. nextIndex = 0;
  15829. sendChangeMessage (this);
  15830. }
  15831. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15832. {
  15833. return totalUnitsStored;
  15834. }
  15835. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15836. const int minimumTransactions)
  15837. {
  15838. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15839. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15840. }
  15841. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15842. {
  15843. if (command_ != 0)
  15844. {
  15845. ScopedPointer<UndoableAction> command (command_);
  15846. if (actionName.isNotEmpty())
  15847. currentTransactionName = actionName;
  15848. if (reentrancyCheck)
  15849. {
  15850. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15851. // undo() methods, or else these actions won't actually get done.
  15852. return false;
  15853. }
  15854. else if (command->perform())
  15855. {
  15856. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15857. if (commandSet != 0 && ! newTransaction)
  15858. {
  15859. UndoableAction* lastAction = commandSet->getLast();
  15860. if (lastAction != 0)
  15861. {
  15862. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15863. if (coalescedAction != 0)
  15864. {
  15865. command = coalescedAction;
  15866. totalUnitsStored -= lastAction->getSizeInUnits();
  15867. commandSet->removeLast();
  15868. }
  15869. }
  15870. }
  15871. else
  15872. {
  15873. commandSet = new OwnedArray<UndoableAction>();
  15874. transactions.insert (nextIndex, commandSet);
  15875. transactionNames.insert (nextIndex, currentTransactionName);
  15876. ++nextIndex;
  15877. }
  15878. totalUnitsStored += command->getSizeInUnits();
  15879. commandSet->add (command.release());
  15880. newTransaction = false;
  15881. while (nextIndex < transactions.size())
  15882. {
  15883. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15884. for (int i = lastSet->size(); --i >= 0;)
  15885. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15886. transactions.removeLast();
  15887. transactionNames.remove (transactionNames.size() - 1);
  15888. }
  15889. while (nextIndex > 0
  15890. && totalUnitsStored > maxNumUnitsToKeep
  15891. && transactions.size() > minimumTransactionsToKeep)
  15892. {
  15893. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15894. for (int i = firstSet->size(); --i >= 0;)
  15895. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15896. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15897. transactions.remove (0);
  15898. transactionNames.remove (0);
  15899. --nextIndex;
  15900. }
  15901. sendChangeMessage (this);
  15902. return true;
  15903. }
  15904. }
  15905. return false;
  15906. }
  15907. void UndoManager::beginNewTransaction (const String& actionName)
  15908. {
  15909. newTransaction = true;
  15910. currentTransactionName = actionName;
  15911. }
  15912. void UndoManager::setCurrentTransactionName (const String& newName)
  15913. {
  15914. currentTransactionName = newName;
  15915. }
  15916. bool UndoManager::canUndo() const
  15917. {
  15918. return nextIndex > 0;
  15919. }
  15920. bool UndoManager::canRedo() const
  15921. {
  15922. return nextIndex < transactions.size();
  15923. }
  15924. const String UndoManager::getUndoDescription() const
  15925. {
  15926. return transactionNames [nextIndex - 1];
  15927. }
  15928. const String UndoManager::getRedoDescription() const
  15929. {
  15930. return transactionNames [nextIndex];
  15931. }
  15932. bool UndoManager::undo()
  15933. {
  15934. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15935. if (commandSet == 0)
  15936. return false;
  15937. reentrancyCheck = true;
  15938. bool failed = false;
  15939. for (int i = commandSet->size(); --i >= 0;)
  15940. {
  15941. if (! commandSet->getUnchecked(i)->undo())
  15942. {
  15943. jassertfalse;
  15944. failed = true;
  15945. break;
  15946. }
  15947. }
  15948. reentrancyCheck = false;
  15949. if (failed)
  15950. clearUndoHistory();
  15951. else
  15952. --nextIndex;
  15953. beginNewTransaction();
  15954. sendChangeMessage (this);
  15955. return true;
  15956. }
  15957. bool UndoManager::redo()
  15958. {
  15959. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15960. if (commandSet == 0)
  15961. return false;
  15962. reentrancyCheck = true;
  15963. bool failed = false;
  15964. for (int i = 0; i < commandSet->size(); ++i)
  15965. {
  15966. if (! commandSet->getUnchecked(i)->perform())
  15967. {
  15968. jassertfalse;
  15969. failed = true;
  15970. break;
  15971. }
  15972. }
  15973. reentrancyCheck = false;
  15974. if (failed)
  15975. clearUndoHistory();
  15976. else
  15977. ++nextIndex;
  15978. beginNewTransaction();
  15979. sendChangeMessage (this);
  15980. return true;
  15981. }
  15982. bool UndoManager::undoCurrentTransactionOnly()
  15983. {
  15984. return newTransaction ? false : undo();
  15985. }
  15986. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15987. {
  15988. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15989. if (commandSet != 0 && ! newTransaction)
  15990. {
  15991. for (int i = 0; i < commandSet->size(); ++i)
  15992. actionsFound.add (commandSet->getUnchecked(i));
  15993. }
  15994. }
  15995. int UndoManager::getNumActionsInCurrentTransaction() const
  15996. {
  15997. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15998. if (commandSet != 0 && ! newTransaction)
  15999. return commandSet->size();
  16000. return 0;
  16001. }
  16002. END_JUCE_NAMESPACE
  16003. /*** End of inlined file: juce_UndoManager.cpp ***/
  16004. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16005. BEGIN_JUCE_NAMESPACE
  16006. static const char* const aiffFormatName = "AIFF file";
  16007. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16008. class AiffAudioFormatReader : public AudioFormatReader
  16009. {
  16010. public:
  16011. int bytesPerFrame;
  16012. int64 dataChunkStart;
  16013. bool littleEndian;
  16014. AiffAudioFormatReader (InputStream* in)
  16015. : AudioFormatReader (in, TRANS (aiffFormatName))
  16016. {
  16017. if (input->readInt() == chunkName ("FORM"))
  16018. {
  16019. const int len = input->readIntBigEndian();
  16020. const int64 end = input->getPosition() + len;
  16021. const int nextType = input->readInt();
  16022. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16023. {
  16024. bool hasGotVer = false;
  16025. bool hasGotData = false;
  16026. bool hasGotType = false;
  16027. while (input->getPosition() < end)
  16028. {
  16029. const int type = input->readInt();
  16030. const uint32 length = (uint32) input->readIntBigEndian();
  16031. const int64 chunkEnd = input->getPosition() + length;
  16032. if (type == chunkName ("FVER"))
  16033. {
  16034. hasGotVer = true;
  16035. const int ver = input->readIntBigEndian();
  16036. if (ver != 0 && ver != (int)0xa2805140)
  16037. break;
  16038. }
  16039. else if (type == chunkName ("COMM"))
  16040. {
  16041. hasGotType = true;
  16042. numChannels = (unsigned int)input->readShortBigEndian();
  16043. lengthInSamples = input->readIntBigEndian();
  16044. bitsPerSample = input->readShortBigEndian();
  16045. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16046. unsigned char sampleRateBytes[10];
  16047. input->read (sampleRateBytes, 10);
  16048. const int byte0 = sampleRateBytes[0];
  16049. if ((byte0 & 0x80) != 0
  16050. || byte0 <= 0x3F || byte0 > 0x40
  16051. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16052. break;
  16053. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16054. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16055. sampleRate = (int) sampRate;
  16056. if (length <= 18)
  16057. {
  16058. // some types don't have a chunk large enough to include a compression
  16059. // type, so assume it's just big-endian pcm
  16060. littleEndian = false;
  16061. }
  16062. else
  16063. {
  16064. const int compType = input->readInt();
  16065. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16066. {
  16067. littleEndian = false;
  16068. }
  16069. else if (compType == chunkName ("sowt"))
  16070. {
  16071. littleEndian = true;
  16072. }
  16073. else
  16074. {
  16075. sampleRate = 0;
  16076. break;
  16077. }
  16078. }
  16079. }
  16080. else if (type == chunkName ("SSND"))
  16081. {
  16082. hasGotData = true;
  16083. const int offset = input->readIntBigEndian();
  16084. dataChunkStart = input->getPosition() + 4 + offset;
  16085. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16086. }
  16087. else if ((hasGotVer && hasGotData && hasGotType)
  16088. || chunkEnd < input->getPosition()
  16089. || input->isExhausted())
  16090. {
  16091. break;
  16092. }
  16093. input->setPosition (chunkEnd);
  16094. }
  16095. }
  16096. }
  16097. }
  16098. ~AiffAudioFormatReader()
  16099. {
  16100. }
  16101. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16102. int64 startSampleInFile, int numSamples)
  16103. {
  16104. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16105. if (samplesAvailable < numSamples)
  16106. {
  16107. for (int i = numDestChannels; --i >= 0;)
  16108. if (destSamples[i] != 0)
  16109. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16110. numSamples = (int) samplesAvailable;
  16111. }
  16112. if (numSamples <= 0)
  16113. return true;
  16114. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16115. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16116. char tempBuffer [tempBufSize];
  16117. while (numSamples > 0)
  16118. {
  16119. int* left = destSamples[0];
  16120. if (left != 0)
  16121. left += startOffsetInDestBuffer;
  16122. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  16123. if (right != 0)
  16124. right += startOffsetInDestBuffer;
  16125. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16126. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16127. if (bytesRead < numThisTime * bytesPerFrame)
  16128. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16129. if (bitsPerSample == 16)
  16130. {
  16131. if (littleEndian)
  16132. {
  16133. const short* src = reinterpret_cast <const short*> (tempBuffer);
  16134. if (numChannels > 1)
  16135. {
  16136. if (left == 0)
  16137. {
  16138. for (int i = numThisTime; --i >= 0;)
  16139. {
  16140. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16141. ++src;
  16142. }
  16143. }
  16144. else if (right == 0)
  16145. {
  16146. for (int i = numThisTime; --i >= 0;)
  16147. {
  16148. ++src;
  16149. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16150. }
  16151. }
  16152. else
  16153. {
  16154. for (int i = numThisTime; --i >= 0;)
  16155. {
  16156. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16157. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16158. }
  16159. }
  16160. }
  16161. else
  16162. {
  16163. for (int i = numThisTime; --i >= 0;)
  16164. {
  16165. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16166. }
  16167. }
  16168. }
  16169. else
  16170. {
  16171. const char* src = tempBuffer;
  16172. if (numChannels > 1)
  16173. {
  16174. if (left == 0)
  16175. {
  16176. for (int i = numThisTime; --i >= 0;)
  16177. {
  16178. *right++ = ByteOrder::bigEndianShort (src) << 16;
  16179. src += 4;
  16180. }
  16181. }
  16182. else if (right == 0)
  16183. {
  16184. for (int i = numThisTime; --i >= 0;)
  16185. {
  16186. src += 2;
  16187. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16188. src += 2;
  16189. }
  16190. }
  16191. else
  16192. {
  16193. for (int i = numThisTime; --i >= 0;)
  16194. {
  16195. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16196. src += 2;
  16197. *right++ = ByteOrder::bigEndianShort (src) << 16;
  16198. src += 2;
  16199. }
  16200. }
  16201. }
  16202. else
  16203. {
  16204. for (int i = numThisTime; --i >= 0;)
  16205. {
  16206. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16207. src += 2;
  16208. }
  16209. }
  16210. }
  16211. }
  16212. else if (bitsPerSample == 24)
  16213. {
  16214. const char* src = (const char*)tempBuffer;
  16215. if (littleEndian)
  16216. {
  16217. if (numChannels > 1)
  16218. {
  16219. if (left == 0)
  16220. {
  16221. for (int i = numThisTime; --i >= 0;)
  16222. {
  16223. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  16224. src += 6;
  16225. }
  16226. }
  16227. else if (right == 0)
  16228. {
  16229. for (int i = numThisTime; --i >= 0;)
  16230. {
  16231. src += 3;
  16232. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16233. src += 3;
  16234. }
  16235. }
  16236. else
  16237. {
  16238. for (int i = numThisTime; --i >= 0;)
  16239. {
  16240. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16241. src += 3;
  16242. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  16243. src += 3;
  16244. }
  16245. }
  16246. }
  16247. else
  16248. {
  16249. for (int i = numThisTime; --i >= 0;)
  16250. {
  16251. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16252. src += 3;
  16253. }
  16254. }
  16255. }
  16256. else
  16257. {
  16258. if (numChannels > 1)
  16259. {
  16260. if (left == 0)
  16261. {
  16262. for (int i = numThisTime; --i >= 0;)
  16263. {
  16264. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  16265. src += 6;
  16266. }
  16267. }
  16268. else if (right == 0)
  16269. {
  16270. for (int i = numThisTime; --i >= 0;)
  16271. {
  16272. src += 3;
  16273. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16274. src += 3;
  16275. }
  16276. }
  16277. else
  16278. {
  16279. for (int i = numThisTime; --i >= 0;)
  16280. {
  16281. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16282. src += 3;
  16283. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  16284. src += 3;
  16285. }
  16286. }
  16287. }
  16288. else
  16289. {
  16290. for (int i = numThisTime; --i >= 0;)
  16291. {
  16292. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16293. src += 3;
  16294. }
  16295. }
  16296. }
  16297. }
  16298. else if (bitsPerSample == 32)
  16299. {
  16300. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  16301. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  16302. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  16303. if (littleEndian)
  16304. {
  16305. if (numChannels > 1)
  16306. {
  16307. if (l == 0)
  16308. {
  16309. for (int i = numThisTime; --i >= 0;)
  16310. {
  16311. ++src;
  16312. *r++ = ByteOrder::swapIfBigEndian (*src++);
  16313. }
  16314. }
  16315. else if (r == 0)
  16316. {
  16317. for (int i = numThisTime; --i >= 0;)
  16318. {
  16319. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16320. ++src;
  16321. }
  16322. }
  16323. else
  16324. {
  16325. for (int i = numThisTime; --i >= 0;)
  16326. {
  16327. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16328. *r++ = ByteOrder::swapIfBigEndian (*src++);
  16329. }
  16330. }
  16331. }
  16332. else
  16333. {
  16334. for (int i = numThisTime; --i >= 0;)
  16335. {
  16336. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16337. }
  16338. }
  16339. }
  16340. else
  16341. {
  16342. if (numChannels > 1)
  16343. {
  16344. if (l == 0)
  16345. {
  16346. for (int i = numThisTime; --i >= 0;)
  16347. {
  16348. ++src;
  16349. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  16350. }
  16351. }
  16352. else if (r == 0)
  16353. {
  16354. for (int i = numThisTime; --i >= 0;)
  16355. {
  16356. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16357. ++src;
  16358. }
  16359. }
  16360. else
  16361. {
  16362. for (int i = numThisTime; --i >= 0;)
  16363. {
  16364. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16365. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  16366. }
  16367. }
  16368. }
  16369. else
  16370. {
  16371. for (int i = numThisTime; --i >= 0;)
  16372. {
  16373. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16374. }
  16375. }
  16376. }
  16377. left = reinterpret_cast <int*> (l);
  16378. right = reinterpret_cast <int*> (r);
  16379. }
  16380. else if (bitsPerSample == 8)
  16381. {
  16382. const char* src = tempBuffer;
  16383. if (numChannels > 1)
  16384. {
  16385. if (left == 0)
  16386. {
  16387. for (int i = numThisTime; --i >= 0;)
  16388. {
  16389. *right++ = ((int) *src++) << 24;
  16390. ++src;
  16391. }
  16392. }
  16393. else if (right == 0)
  16394. {
  16395. for (int i = numThisTime; --i >= 0;)
  16396. {
  16397. ++src;
  16398. *left++ = ((int) *src++) << 24;
  16399. }
  16400. }
  16401. else
  16402. {
  16403. for (int i = numThisTime; --i >= 0;)
  16404. {
  16405. *left++ = ((int) *src++) << 24;
  16406. *right++ = ((int) *src++) << 24;
  16407. }
  16408. }
  16409. }
  16410. else
  16411. {
  16412. for (int i = numThisTime; --i >= 0;)
  16413. {
  16414. *left++ = ((int) *src++) << 24;
  16415. }
  16416. }
  16417. }
  16418. startOffsetInDestBuffer += numThisTime;
  16419. numSamples -= numThisTime;
  16420. }
  16421. if (numSamples > 0)
  16422. {
  16423. for (int i = numDestChannels; --i >= 0;)
  16424. if (destSamples[i] != 0)
  16425. zeromem (destSamples[i] + startOffsetInDestBuffer,
  16426. sizeof (int) * numSamples);
  16427. }
  16428. return true;
  16429. }
  16430. juce_UseDebuggingNewOperator
  16431. private:
  16432. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16433. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16434. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16435. };
  16436. class AiffAudioFormatWriter : public AudioFormatWriter
  16437. {
  16438. MemoryBlock tempBlock;
  16439. uint32 lengthInSamples, bytesWritten;
  16440. int64 headerPosition;
  16441. bool writeFailed;
  16442. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16443. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16444. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16445. void writeHeader()
  16446. {
  16447. const bool couldSeekOk = output->setPosition (headerPosition);
  16448. (void) couldSeekOk;
  16449. // if this fails, you've given it an output stream that can't seek! It needs
  16450. // to be able to seek back to write the header
  16451. jassert (couldSeekOk);
  16452. const int headerLen = 54;
  16453. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16454. audioBytes += (audioBytes & 1);
  16455. output->writeInt (chunkName ("FORM"));
  16456. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16457. output->writeInt (chunkName ("AIFF"));
  16458. output->writeInt (chunkName ("COMM"));
  16459. output->writeIntBigEndian (18);
  16460. output->writeShortBigEndian ((short) numChannels);
  16461. output->writeIntBigEndian (lengthInSamples);
  16462. output->writeShortBigEndian ((short) bitsPerSample);
  16463. uint8 sampleRateBytes[10];
  16464. zeromem (sampleRateBytes, 10);
  16465. if (sampleRate <= 1)
  16466. {
  16467. sampleRateBytes[0] = 0x3f;
  16468. sampleRateBytes[1] = 0xff;
  16469. sampleRateBytes[2] = 0x80;
  16470. }
  16471. else
  16472. {
  16473. int mask = 0x40000000;
  16474. sampleRateBytes[0] = 0x40;
  16475. if (sampleRate >= mask)
  16476. {
  16477. jassertfalse;
  16478. sampleRateBytes[1] = 0x1d;
  16479. }
  16480. else
  16481. {
  16482. int n = (int) sampleRate;
  16483. int i;
  16484. for (i = 0; i <= 32 ; ++i)
  16485. {
  16486. if ((n & mask) != 0)
  16487. break;
  16488. mask >>= 1;
  16489. }
  16490. n = n << (i + 1);
  16491. sampleRateBytes[1] = (uint8) (29 - i);
  16492. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16493. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16494. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16495. sampleRateBytes[5] = (uint8) (n & 0xff);
  16496. }
  16497. }
  16498. output->write (sampleRateBytes, 10);
  16499. output->writeInt (chunkName ("SSND"));
  16500. output->writeIntBigEndian (audioBytes + 8);
  16501. output->writeInt (0);
  16502. output->writeInt (0);
  16503. jassert (output->getPosition() == headerLen);
  16504. }
  16505. public:
  16506. AiffAudioFormatWriter (OutputStream* out,
  16507. const double sampleRate_,
  16508. const unsigned int chans,
  16509. const int bits)
  16510. : AudioFormatWriter (out,
  16511. TRANS (aiffFormatName),
  16512. sampleRate_,
  16513. chans,
  16514. bits),
  16515. lengthInSamples (0),
  16516. bytesWritten (0),
  16517. writeFailed (false)
  16518. {
  16519. headerPosition = out->getPosition();
  16520. writeHeader();
  16521. }
  16522. ~AiffAudioFormatWriter()
  16523. {
  16524. if ((bytesWritten & 1) != 0)
  16525. output->writeByte (0);
  16526. writeHeader();
  16527. }
  16528. bool write (const int** data, int numSamples)
  16529. {
  16530. if (writeFailed)
  16531. return false;
  16532. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16533. tempBlock.ensureSize (bytes, false);
  16534. char* buffer = static_cast <char*> (tempBlock.getData());
  16535. const int* left = data[0];
  16536. const int* right = data[1];
  16537. if (right == 0)
  16538. right = left;
  16539. if (bitsPerSample == 16)
  16540. {
  16541. short* b = reinterpret_cast <short*> (buffer);
  16542. if (numChannels > 1)
  16543. {
  16544. for (int i = numSamples; --i >= 0;)
  16545. {
  16546. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  16547. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  16548. }
  16549. }
  16550. else
  16551. {
  16552. for (int i = numSamples; --i >= 0;)
  16553. {
  16554. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  16555. }
  16556. }
  16557. }
  16558. else if (bitsPerSample == 24)
  16559. {
  16560. char* b = buffer;
  16561. if (numChannels > 1)
  16562. {
  16563. for (int i = numSamples; --i >= 0;)
  16564. {
  16565. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  16566. b += 3;
  16567. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  16568. b += 3;
  16569. }
  16570. }
  16571. else
  16572. {
  16573. for (int i = numSamples; --i >= 0;)
  16574. {
  16575. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  16576. b += 3;
  16577. }
  16578. }
  16579. }
  16580. else if (bitsPerSample == 32)
  16581. {
  16582. uint32* b = reinterpret_cast <uint32*> (buffer);
  16583. if (numChannels > 1)
  16584. {
  16585. for (int i = numSamples; --i >= 0;)
  16586. {
  16587. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  16588. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  16589. }
  16590. }
  16591. else
  16592. {
  16593. for (int i = numSamples; --i >= 0;)
  16594. {
  16595. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  16596. }
  16597. }
  16598. }
  16599. else if (bitsPerSample == 8)
  16600. {
  16601. char* b = buffer;
  16602. if (numChannels > 1)
  16603. {
  16604. for (int i = numSamples; --i >= 0;)
  16605. {
  16606. *b++ = (char) (*left++ >> 24);
  16607. *b++ = (char) (*right++ >> 24);
  16608. }
  16609. }
  16610. else
  16611. {
  16612. for (int i = numSamples; --i >= 0;)
  16613. {
  16614. *b++ = (char) (*left++ >> 24);
  16615. }
  16616. }
  16617. }
  16618. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16619. || ! output->write (buffer, bytes))
  16620. {
  16621. // failed to write to disk, so let's try writing the header.
  16622. // If it's just run out of disk space, then if it does manage
  16623. // to write the header, we'll still have a useable file..
  16624. writeHeader();
  16625. writeFailed = true;
  16626. return false;
  16627. }
  16628. else
  16629. {
  16630. bytesWritten += bytes;
  16631. lengthInSamples += numSamples;
  16632. return true;
  16633. }
  16634. }
  16635. juce_UseDebuggingNewOperator
  16636. };
  16637. AiffAudioFormat::AiffAudioFormat()
  16638. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16639. {
  16640. }
  16641. AiffAudioFormat::~AiffAudioFormat()
  16642. {
  16643. }
  16644. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16645. {
  16646. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16647. return Array <int> (rates);
  16648. }
  16649. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16650. {
  16651. const int depths[] = { 8, 16, 24, 0 };
  16652. return Array <int> (depths);
  16653. }
  16654. bool AiffAudioFormat::canDoStereo()
  16655. {
  16656. return true;
  16657. }
  16658. bool AiffAudioFormat::canDoMono()
  16659. {
  16660. return true;
  16661. }
  16662. #if JUCE_MAC
  16663. bool AiffAudioFormat::canHandleFile (const File& f)
  16664. {
  16665. if (AudioFormat::canHandleFile (f))
  16666. return true;
  16667. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16668. return type == 'AIFF' || type == 'AIFC'
  16669. || type == 'aiff' || type == 'aifc';
  16670. }
  16671. #endif
  16672. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  16673. const bool deleteStreamIfOpeningFails)
  16674. {
  16675. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16676. if (w->sampleRate != 0)
  16677. return w.release();
  16678. if (! deleteStreamIfOpeningFails)
  16679. w->input = 0;
  16680. return 0;
  16681. }
  16682. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16683. double sampleRate,
  16684. unsigned int chans,
  16685. int bitsPerSample,
  16686. const StringPairArray& /*metadataValues*/,
  16687. int /*qualityOptionIndex*/)
  16688. {
  16689. if (getPossibleBitDepths().contains (bitsPerSample))
  16690. {
  16691. return new AiffAudioFormatWriter (out,
  16692. sampleRate,
  16693. chans,
  16694. bitsPerSample);
  16695. }
  16696. return 0;
  16697. }
  16698. END_JUCE_NAMESPACE
  16699. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16700. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16701. BEGIN_JUCE_NAMESPACE
  16702. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16703. const String& formatName_)
  16704. : sampleRate (0),
  16705. bitsPerSample (0),
  16706. lengthInSamples (0),
  16707. numChannels (0),
  16708. usesFloatingPointData (false),
  16709. input (in),
  16710. formatName (formatName_)
  16711. {
  16712. }
  16713. AudioFormatReader::~AudioFormatReader()
  16714. {
  16715. delete input;
  16716. }
  16717. bool AudioFormatReader::read (int** destSamples,
  16718. int numDestChannels,
  16719. int64 startSampleInSource,
  16720. int numSamplesToRead,
  16721. const bool fillLeftoverChannelsWithCopies)
  16722. {
  16723. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16724. int startOffsetInDestBuffer = 0;
  16725. if (startSampleInSource < 0)
  16726. {
  16727. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16728. for (int i = numDestChannels; --i >= 0;)
  16729. if (destSamples[i] != 0)
  16730. zeromem (destSamples[i], sizeof (int) * silence);
  16731. startOffsetInDestBuffer += silence;
  16732. numSamplesToRead -= silence;
  16733. startSampleInSource = 0;
  16734. }
  16735. if (numSamplesToRead <= 0)
  16736. return true;
  16737. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16738. startSampleInSource, numSamplesToRead))
  16739. return false;
  16740. if (numDestChannels > (int) numChannels)
  16741. {
  16742. if (fillLeftoverChannelsWithCopies)
  16743. {
  16744. int* lastFullChannel = destSamples[0];
  16745. for (int i = (int) numChannels; --i > 0;)
  16746. {
  16747. if (destSamples[i] != 0)
  16748. {
  16749. lastFullChannel = destSamples[i];
  16750. break;
  16751. }
  16752. }
  16753. if (lastFullChannel != 0)
  16754. for (int i = numChannels; i < numDestChannels; ++i)
  16755. if (destSamples[i] != 0)
  16756. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16757. }
  16758. else
  16759. {
  16760. for (int i = numChannels; i < numDestChannels; ++i)
  16761. if (destSamples[i] != 0)
  16762. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16763. }
  16764. }
  16765. return true;
  16766. }
  16767. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16768. {
  16769. float mn = buffer[0];
  16770. float mx = mn;
  16771. for (int i = 1; i < num; ++i)
  16772. {
  16773. const float s = buffer[i];
  16774. if (s > mx) mx = s;
  16775. if (s < mn) mn = s;
  16776. }
  16777. maxVal = mx;
  16778. minVal = mn;
  16779. }
  16780. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16781. int64 numSamples,
  16782. float& lowestLeft, float& highestLeft,
  16783. float& lowestRight, float& highestRight)
  16784. {
  16785. if (numSamples <= 0)
  16786. {
  16787. lowestLeft = 0;
  16788. lowestRight = 0;
  16789. highestLeft = 0;
  16790. highestRight = 0;
  16791. return;
  16792. }
  16793. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16794. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16795. int* tempBuffer[3];
  16796. tempBuffer[0] = (int*) tempSpace.getData();
  16797. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16798. tempBuffer[2] = 0;
  16799. if (usesFloatingPointData)
  16800. {
  16801. float lmin = 1.0e6f;
  16802. float lmax = -lmin;
  16803. float rmin = lmin;
  16804. float rmax = lmax;
  16805. while (numSamples > 0)
  16806. {
  16807. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16808. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16809. numSamples -= numToDo;
  16810. startSampleInFile += numToDo;
  16811. float bufmin, bufmax;
  16812. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16813. lmin = jmin (lmin, bufmin);
  16814. lmax = jmax (lmax, bufmax);
  16815. if (numChannels > 1)
  16816. {
  16817. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16818. rmin = jmin (rmin, bufmin);
  16819. rmax = jmax (rmax, bufmax);
  16820. }
  16821. }
  16822. if (numChannels <= 1)
  16823. {
  16824. rmax = lmax;
  16825. rmin = lmin;
  16826. }
  16827. lowestLeft = lmin;
  16828. highestLeft = lmax;
  16829. lowestRight = rmin;
  16830. highestRight = rmax;
  16831. }
  16832. else
  16833. {
  16834. int lmax = std::numeric_limits<int>::min();
  16835. int lmin = std::numeric_limits<int>::max();
  16836. int rmax = std::numeric_limits<int>::min();
  16837. int rmin = std::numeric_limits<int>::max();
  16838. while (numSamples > 0)
  16839. {
  16840. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16841. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16842. numSamples -= numToDo;
  16843. startSampleInFile += numToDo;
  16844. for (int j = numChannels; --j >= 0;)
  16845. {
  16846. int bufMax = std::numeric_limits<int>::min();
  16847. int bufMin = std::numeric_limits<int>::max();
  16848. const int* const b = tempBuffer[j];
  16849. for (int i = 0; i < numToDo; ++i)
  16850. {
  16851. const int samp = b[i];
  16852. if (samp < bufMin)
  16853. bufMin = samp;
  16854. if (samp > bufMax)
  16855. bufMax = samp;
  16856. }
  16857. if (j == 0)
  16858. {
  16859. lmax = jmax (lmax, bufMax);
  16860. lmin = jmin (lmin, bufMin);
  16861. }
  16862. else
  16863. {
  16864. rmax = jmax (rmax, bufMax);
  16865. rmin = jmin (rmin, bufMin);
  16866. }
  16867. }
  16868. }
  16869. if (numChannels <= 1)
  16870. {
  16871. rmax = lmax;
  16872. rmin = lmin;
  16873. }
  16874. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16875. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16876. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16877. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16878. }
  16879. }
  16880. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16881. int64 numSamplesToSearch,
  16882. const double magnitudeRangeMinimum,
  16883. const double magnitudeRangeMaximum,
  16884. const int minimumConsecutiveSamples)
  16885. {
  16886. if (numSamplesToSearch == 0)
  16887. return -1;
  16888. const int bufferSize = 4096;
  16889. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16890. int* tempBuffer[3];
  16891. tempBuffer[0] = (int*) tempSpace.getData();
  16892. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16893. tempBuffer[2] = 0;
  16894. int consecutive = 0;
  16895. int64 firstMatchPos = -1;
  16896. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16897. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16898. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16899. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16900. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16901. while (numSamplesToSearch != 0)
  16902. {
  16903. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16904. int64 bufferStart = startSample;
  16905. if (numSamplesToSearch < 0)
  16906. bufferStart -= numThisTime;
  16907. if (bufferStart >= (int) lengthInSamples)
  16908. break;
  16909. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16910. int num = numThisTime;
  16911. while (--num >= 0)
  16912. {
  16913. if (numSamplesToSearch < 0)
  16914. --startSample;
  16915. bool matches = false;
  16916. const int index = (int) (startSample - bufferStart);
  16917. if (usesFloatingPointData)
  16918. {
  16919. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16920. if (sample1 >= magnitudeRangeMinimum
  16921. && sample1 <= magnitudeRangeMaximum)
  16922. {
  16923. matches = true;
  16924. }
  16925. else if (numChannels > 1)
  16926. {
  16927. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16928. matches = (sample2 >= magnitudeRangeMinimum
  16929. && sample2 <= magnitudeRangeMaximum);
  16930. }
  16931. }
  16932. else
  16933. {
  16934. const int sample1 = abs (tempBuffer[0] [index]);
  16935. if (sample1 >= intMagnitudeRangeMinimum
  16936. && sample1 <= intMagnitudeRangeMaximum)
  16937. {
  16938. matches = true;
  16939. }
  16940. else if (numChannels > 1)
  16941. {
  16942. const int sample2 = abs (tempBuffer[1][index]);
  16943. matches = (sample2 >= intMagnitudeRangeMinimum
  16944. && sample2 <= intMagnitudeRangeMaximum);
  16945. }
  16946. }
  16947. if (matches)
  16948. {
  16949. if (firstMatchPos < 0)
  16950. firstMatchPos = startSample;
  16951. if (++consecutive >= minimumConsecutiveSamples)
  16952. {
  16953. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16954. return -1;
  16955. return firstMatchPos;
  16956. }
  16957. }
  16958. else
  16959. {
  16960. consecutive = 0;
  16961. firstMatchPos = -1;
  16962. }
  16963. if (numSamplesToSearch > 0)
  16964. ++startSample;
  16965. }
  16966. if (numSamplesToSearch > 0)
  16967. numSamplesToSearch -= numThisTime;
  16968. else
  16969. numSamplesToSearch += numThisTime;
  16970. }
  16971. return -1;
  16972. }
  16973. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16974. const String& formatName_,
  16975. const double rate,
  16976. const unsigned int numChannels_,
  16977. const unsigned int bitsPerSample_)
  16978. : sampleRate (rate),
  16979. numChannels (numChannels_),
  16980. bitsPerSample (bitsPerSample_),
  16981. usesFloatingPointData (false),
  16982. output (out),
  16983. formatName (formatName_)
  16984. {
  16985. }
  16986. AudioFormatWriter::~AudioFormatWriter()
  16987. {
  16988. delete output;
  16989. }
  16990. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16991. int64 startSample,
  16992. int64 numSamplesToRead)
  16993. {
  16994. const int bufferSize = 16384;
  16995. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16996. int* buffers [128];
  16997. zerostruct (buffers);
  16998. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16999. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  17000. if (numSamplesToRead < 0)
  17001. numSamplesToRead = reader.lengthInSamples;
  17002. while (numSamplesToRead > 0)
  17003. {
  17004. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17005. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17006. return false;
  17007. if (reader.usesFloatingPointData != isFloatingPoint())
  17008. {
  17009. int** bufferChan = buffers;
  17010. while (*bufferChan != 0)
  17011. {
  17012. int* b = *bufferChan++;
  17013. if (isFloatingPoint())
  17014. {
  17015. // int -> float
  17016. const double factor = 1.0 / std::numeric_limits<int>::max();
  17017. for (int i = 0; i < numToDo; ++i)
  17018. ((float*) b)[i] = (float) (factor * b[i]);
  17019. }
  17020. else
  17021. {
  17022. // float -> int
  17023. for (int i = 0; i < numToDo; ++i)
  17024. {
  17025. const double samp = *(const float*) b;
  17026. if (samp <= -1.0)
  17027. *b++ = std::numeric_limits<int>::min();
  17028. else if (samp >= 1.0)
  17029. *b++ = std::numeric_limits<int>::max();
  17030. else
  17031. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17032. }
  17033. }
  17034. }
  17035. }
  17036. if (! write ((const int**) buffers, numToDo))
  17037. return false;
  17038. numSamplesToRead -= numToDo;
  17039. startSample += numToDo;
  17040. }
  17041. return true;
  17042. }
  17043. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  17044. int numSamplesToRead,
  17045. const int samplesPerBlock)
  17046. {
  17047. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17048. int* buffers [128];
  17049. zerostruct (buffers);
  17050. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17051. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  17052. while (numSamplesToRead > 0)
  17053. {
  17054. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17055. AudioSourceChannelInfo info;
  17056. info.buffer = &tempBuffer;
  17057. info.startSample = 0;
  17058. info.numSamples = numToDo;
  17059. info.clearActiveBufferRegion();
  17060. source.getNextAudioBlock (info);
  17061. if (! isFloatingPoint())
  17062. {
  17063. int** bufferChan = buffers;
  17064. while (*bufferChan != 0)
  17065. {
  17066. int* b = *bufferChan++;
  17067. // float -> int
  17068. for (int j = numToDo; --j >= 0;)
  17069. {
  17070. const double samp = *(const float*) b;
  17071. if (samp <= -1.0)
  17072. *b++ = std::numeric_limits<int>::min();
  17073. else if (samp >= 1.0)
  17074. *b++ = std::numeric_limits<int>::max();
  17075. else
  17076. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17077. }
  17078. }
  17079. }
  17080. if (! write ((const int**) buffers, numToDo))
  17081. return false;
  17082. numSamplesToRead -= numToDo;
  17083. }
  17084. return true;
  17085. }
  17086. AudioFormat::AudioFormat (const String& name,
  17087. const StringArray& extensions)
  17088. : formatName (name),
  17089. fileExtensions (extensions)
  17090. {
  17091. }
  17092. AudioFormat::~AudioFormat()
  17093. {
  17094. }
  17095. const String& AudioFormat::getFormatName() const
  17096. {
  17097. return formatName;
  17098. }
  17099. const StringArray& AudioFormat::getFileExtensions() const
  17100. {
  17101. return fileExtensions;
  17102. }
  17103. bool AudioFormat::canHandleFile (const File& f)
  17104. {
  17105. for (int i = 0; i < fileExtensions.size(); ++i)
  17106. if (f.hasFileExtension (fileExtensions[i]))
  17107. return true;
  17108. return false;
  17109. }
  17110. bool AudioFormat::isCompressed()
  17111. {
  17112. return false;
  17113. }
  17114. const StringArray AudioFormat::getQualityOptions()
  17115. {
  17116. return StringArray();
  17117. }
  17118. END_JUCE_NAMESPACE
  17119. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17120. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17121. BEGIN_JUCE_NAMESPACE
  17122. AudioFormatManager::AudioFormatManager()
  17123. : defaultFormatIndex (0)
  17124. {
  17125. }
  17126. AudioFormatManager::~AudioFormatManager()
  17127. {
  17128. clearFormats();
  17129. clearSingletonInstance();
  17130. }
  17131. juce_ImplementSingleton (AudioFormatManager);
  17132. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17133. const bool makeThisTheDefaultFormat)
  17134. {
  17135. jassert (newFormat != 0);
  17136. if (newFormat != 0)
  17137. {
  17138. #if JUCE_DEBUG
  17139. for (int i = getNumKnownFormats(); --i >= 0;)
  17140. {
  17141. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17142. {
  17143. jassertfalse; // trying to add the same format twice!
  17144. }
  17145. }
  17146. #endif
  17147. if (makeThisTheDefaultFormat)
  17148. defaultFormatIndex = getNumKnownFormats();
  17149. knownFormats.add (newFormat);
  17150. }
  17151. }
  17152. void AudioFormatManager::registerBasicFormats()
  17153. {
  17154. #if JUCE_MAC
  17155. registerFormat (new AiffAudioFormat(), true);
  17156. registerFormat (new WavAudioFormat(), false);
  17157. #else
  17158. registerFormat (new WavAudioFormat(), true);
  17159. registerFormat (new AiffAudioFormat(), false);
  17160. #endif
  17161. #if JUCE_USE_FLAC
  17162. registerFormat (new FlacAudioFormat(), false);
  17163. #endif
  17164. #if JUCE_USE_OGGVORBIS
  17165. registerFormat (new OggVorbisAudioFormat(), false);
  17166. #endif
  17167. }
  17168. void AudioFormatManager::clearFormats()
  17169. {
  17170. knownFormats.clear();
  17171. defaultFormatIndex = 0;
  17172. }
  17173. int AudioFormatManager::getNumKnownFormats() const
  17174. {
  17175. return knownFormats.size();
  17176. }
  17177. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17178. {
  17179. return knownFormats [index];
  17180. }
  17181. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17182. {
  17183. return getKnownFormat (defaultFormatIndex);
  17184. }
  17185. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17186. {
  17187. String e (fileExtension);
  17188. if (! e.startsWithChar ('.'))
  17189. e = "." + e;
  17190. for (int i = 0; i < getNumKnownFormats(); ++i)
  17191. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17192. return getKnownFormat(i);
  17193. return 0;
  17194. }
  17195. const String AudioFormatManager::getWildcardForAllFormats() const
  17196. {
  17197. StringArray allExtensions;
  17198. int i;
  17199. for (i = 0; i < getNumKnownFormats(); ++i)
  17200. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17201. allExtensions.trim();
  17202. allExtensions.removeEmptyStrings();
  17203. String s;
  17204. for (i = 0; i < allExtensions.size(); ++i)
  17205. {
  17206. s << '*';
  17207. if (! allExtensions[i].startsWithChar ('.'))
  17208. s << '.';
  17209. s << allExtensions[i];
  17210. if (i < allExtensions.size() - 1)
  17211. s << ';';
  17212. }
  17213. return s;
  17214. }
  17215. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17216. {
  17217. // you need to actually register some formats before the manager can
  17218. // use them to open a file!
  17219. jassert (getNumKnownFormats() > 0);
  17220. for (int i = 0; i < getNumKnownFormats(); ++i)
  17221. {
  17222. AudioFormat* const af = getKnownFormat(i);
  17223. if (af->canHandleFile (file))
  17224. {
  17225. InputStream* const in = file.createInputStream();
  17226. if (in != 0)
  17227. {
  17228. AudioFormatReader* const r = af->createReaderFor (in, true);
  17229. if (r != 0)
  17230. return r;
  17231. }
  17232. }
  17233. }
  17234. return 0;
  17235. }
  17236. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17237. {
  17238. // you need to actually register some formats before the manager can
  17239. // use them to open a file!
  17240. jassert (getNumKnownFormats() > 0);
  17241. ScopedPointer <InputStream> in (audioFileStream);
  17242. if (in != 0)
  17243. {
  17244. const int64 originalStreamPos = in->getPosition();
  17245. for (int i = 0; i < getNumKnownFormats(); ++i)
  17246. {
  17247. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17248. if (r != 0)
  17249. {
  17250. in.release();
  17251. return r;
  17252. }
  17253. in->setPosition (originalStreamPos);
  17254. // the stream that is passed-in must be capable of being repositioned so
  17255. // that all the formats can have a go at opening it.
  17256. jassert (in->getPosition() == originalStreamPos);
  17257. }
  17258. }
  17259. return 0;
  17260. }
  17261. END_JUCE_NAMESPACE
  17262. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17263. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17264. BEGIN_JUCE_NAMESPACE
  17265. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17266. const int64 startSample_,
  17267. const int64 length_,
  17268. const bool deleteSourceWhenDeleted_)
  17269. : AudioFormatReader (0, source_->getFormatName()),
  17270. source (source_),
  17271. startSample (startSample_),
  17272. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17273. {
  17274. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17275. sampleRate = source->sampleRate;
  17276. bitsPerSample = source->bitsPerSample;
  17277. lengthInSamples = length;
  17278. numChannels = source->numChannels;
  17279. usesFloatingPointData = source->usesFloatingPointData;
  17280. }
  17281. AudioSubsectionReader::~AudioSubsectionReader()
  17282. {
  17283. if (deleteSourceWhenDeleted)
  17284. delete source;
  17285. }
  17286. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17287. int64 startSampleInFile, int numSamples)
  17288. {
  17289. if (startSampleInFile + numSamples > length)
  17290. {
  17291. for (int i = numDestChannels; --i >= 0;)
  17292. if (destSamples[i] != 0)
  17293. zeromem (destSamples[i], sizeof (int) * numSamples);
  17294. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17295. if (numSamples <= 0)
  17296. return true;
  17297. }
  17298. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17299. startSampleInFile + startSample, numSamples);
  17300. }
  17301. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17302. int64 numSamples,
  17303. float& lowestLeft,
  17304. float& highestLeft,
  17305. float& lowestRight,
  17306. float& highestRight)
  17307. {
  17308. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17309. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17310. source->readMaxLevels (startSampleInFile + startSample,
  17311. numSamples,
  17312. lowestLeft,
  17313. highestLeft,
  17314. lowestRight,
  17315. highestRight);
  17316. }
  17317. END_JUCE_NAMESPACE
  17318. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17319. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17320. BEGIN_JUCE_NAMESPACE
  17321. const int timeBeforeDeletingReader = 2000;
  17322. struct AudioThumbnailDataFormat
  17323. {
  17324. char thumbnailMagic[4];
  17325. int samplesPerThumbSample;
  17326. int64 totalSamples; // source samples
  17327. int64 numFinishedSamples; // source samples
  17328. int numThumbnailSamples;
  17329. int numChannels;
  17330. int sampleRate;
  17331. char future[16];
  17332. char data[1];
  17333. void swapEndiannessIfNeeded() throw()
  17334. {
  17335. #if JUCE_BIG_ENDIAN
  17336. flip (samplesPerThumbSample);
  17337. flip (totalSamples);
  17338. flip (numFinishedSamples);
  17339. flip (numThumbnailSamples);
  17340. flip (numChannels);
  17341. flip (sampleRate);
  17342. #endif
  17343. }
  17344. private:
  17345. #if JUCE_BIG_ENDIAN
  17346. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  17347. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  17348. #endif
  17349. };
  17350. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17351. AudioFormatManager& formatManagerToUse_,
  17352. AudioThumbnailCache& cacheToUse)
  17353. : formatManagerToUse (formatManagerToUse_),
  17354. cache (cacheToUse),
  17355. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  17356. {
  17357. clear();
  17358. }
  17359. AudioThumbnail::~AudioThumbnail()
  17360. {
  17361. cache.removeThumbnail (this);
  17362. const ScopedLock sl (readerLock);
  17363. reader = 0;
  17364. }
  17365. void AudioThumbnail::setSource (InputSource* const newSource)
  17366. {
  17367. cache.removeThumbnail (this);
  17368. timerCallback(); // stops the timer and deletes the reader
  17369. source = newSource;
  17370. clear();
  17371. if (newSource != 0
  17372. && ! (cache.loadThumb (*this, newSource->hashCode())
  17373. && isFullyLoaded()))
  17374. {
  17375. {
  17376. const ScopedLock sl (readerLock);
  17377. reader = createReader();
  17378. }
  17379. if (reader != 0)
  17380. {
  17381. initialiseFromAudioFile (*reader);
  17382. cache.addThumbnail (this);
  17383. }
  17384. }
  17385. sendChangeMessage (this);
  17386. }
  17387. bool AudioThumbnail::useTimeSlice()
  17388. {
  17389. const ScopedLock sl (readerLock);
  17390. if (isFullyLoaded())
  17391. {
  17392. if (reader != 0)
  17393. startTimer (timeBeforeDeletingReader);
  17394. cache.removeThumbnail (this);
  17395. return false;
  17396. }
  17397. if (reader == 0)
  17398. reader = createReader();
  17399. if (reader != 0)
  17400. {
  17401. readNextBlockFromAudioFile (*reader);
  17402. stopTimer();
  17403. sendChangeMessage (this);
  17404. const bool justFinished = isFullyLoaded();
  17405. if (justFinished)
  17406. cache.storeThumb (*this, source->hashCode());
  17407. return ! justFinished;
  17408. }
  17409. return false;
  17410. }
  17411. AudioFormatReader* AudioThumbnail::createReader() const
  17412. {
  17413. if (source != 0)
  17414. {
  17415. InputStream* const audioFileStream = source->createInputStream();
  17416. if (audioFileStream != 0)
  17417. return formatManagerToUse.createReaderFor (audioFileStream);
  17418. }
  17419. return 0;
  17420. }
  17421. void AudioThumbnail::timerCallback()
  17422. {
  17423. stopTimer();
  17424. const ScopedLock sl (readerLock);
  17425. reader = 0;
  17426. }
  17427. void AudioThumbnail::clear()
  17428. {
  17429. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  17430. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  17431. d->thumbnailMagic[0] = 'j';
  17432. d->thumbnailMagic[1] = 'a';
  17433. d->thumbnailMagic[2] = 't';
  17434. d->thumbnailMagic[3] = 'm';
  17435. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17436. d->totalSamples = 0;
  17437. d->numFinishedSamples = 0;
  17438. d->numThumbnailSamples = 0;
  17439. d->numChannels = 0;
  17440. d->sampleRate = 0;
  17441. numSamplesCached = 0;
  17442. cacheNeedsRefilling = true;
  17443. }
  17444. void AudioThumbnail::loadFrom (InputStream& input)
  17445. {
  17446. const ScopedLock sl (readerLock);
  17447. data.setSize (0);
  17448. input.readIntoMemoryBlock (data);
  17449. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  17450. d->swapEndiannessIfNeeded();
  17451. if (! (d->thumbnailMagic[0] == 'j'
  17452. && d->thumbnailMagic[1] == 'a'
  17453. && d->thumbnailMagic[2] == 't'
  17454. && d->thumbnailMagic[3] == 'm'))
  17455. {
  17456. clear();
  17457. }
  17458. numSamplesCached = 0;
  17459. cacheNeedsRefilling = true;
  17460. }
  17461. void AudioThumbnail::saveTo (OutputStream& output) const
  17462. {
  17463. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  17464. d->swapEndiannessIfNeeded();
  17465. output.write (data.getData(), (int) data.getSize());
  17466. d->swapEndiannessIfNeeded();
  17467. }
  17468. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17469. {
  17470. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  17471. d->totalSamples = fileReader.lengthInSamples;
  17472. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17473. d->numFinishedSamples = 0;
  17474. d->sampleRate = roundToInt (fileReader.sampleRate);
  17475. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17476. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17477. d = (AudioThumbnailDataFormat*) data.getData();
  17478. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  17479. return d->totalSamples > 0;
  17480. }
  17481. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17482. {
  17483. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  17484. if (d->numFinishedSamples < d->totalSamples)
  17485. {
  17486. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17487. generateSection (fileReader,
  17488. d->numFinishedSamples,
  17489. numToDo);
  17490. d->numFinishedSamples += numToDo;
  17491. }
  17492. cacheNeedsRefilling = true;
  17493. return (d->numFinishedSamples < d->totalSamples);
  17494. }
  17495. int AudioThumbnail::getNumChannels() const throw()
  17496. {
  17497. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  17498. jassert (d != 0);
  17499. return d->numChannels;
  17500. }
  17501. double AudioThumbnail::getTotalLength() const throw()
  17502. {
  17503. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  17504. jassert (d != 0);
  17505. if (d->sampleRate > 0)
  17506. return d->totalSamples / (double)d->sampleRate;
  17507. else
  17508. return 0.0;
  17509. }
  17510. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17511. int64 startSample,
  17512. int numSamples)
  17513. {
  17514. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  17515. jassert (d != 0);
  17516. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17517. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17518. char* l = getChannelData (0);
  17519. char* r = getChannelData (1);
  17520. for (int i = firstDataPos; i < lastDataPos; ++i)
  17521. {
  17522. const int sourceStart = i * d->samplesPerThumbSample;
  17523. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17524. float lowestLeft, highestLeft, lowestRight, highestRight;
  17525. fileReader.readMaxLevels (sourceStart,
  17526. sourceEnd - sourceStart,
  17527. lowestLeft,
  17528. highestLeft,
  17529. lowestRight,
  17530. highestRight);
  17531. int n = i * 2;
  17532. if (r != 0)
  17533. {
  17534. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17535. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17536. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17537. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17538. }
  17539. else
  17540. {
  17541. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17542. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17543. }
  17544. }
  17545. }
  17546. char* AudioThumbnail::getChannelData (int channel) const
  17547. {
  17548. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  17549. jassert (d != 0);
  17550. if (channel >= 0 && channel < d->numChannels)
  17551. return d->data + (channel * 2 * d->numThumbnailSamples);
  17552. return 0;
  17553. }
  17554. bool AudioThumbnail::isFullyLoaded() const throw()
  17555. {
  17556. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  17557. jassert (d != 0);
  17558. return d->numFinishedSamples >= d->totalSamples;
  17559. }
  17560. void AudioThumbnail::refillCache (const int numSamples,
  17561. double startTime,
  17562. const double timePerPixel)
  17563. {
  17564. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  17565. jassert (d != 0);
  17566. if (numSamples <= 0
  17567. || timePerPixel <= 0.0
  17568. || d->sampleRate <= 0)
  17569. {
  17570. numSamplesCached = 0;
  17571. cacheNeedsRefilling = true;
  17572. return;
  17573. }
  17574. if (numSamples == numSamplesCached
  17575. && numChannelsCached == d->numChannels
  17576. && startTime == cachedStart
  17577. && timePerPixel == cachedTimePerPixel
  17578. && ! cacheNeedsRefilling)
  17579. {
  17580. return;
  17581. }
  17582. numSamplesCached = numSamples;
  17583. numChannelsCached = d->numChannels;
  17584. cachedStart = startTime;
  17585. cachedTimePerPixel = timePerPixel;
  17586. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17587. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17588. const ScopedLock sl (readerLock);
  17589. cacheNeedsRefilling = false;
  17590. if (needExtraDetail && reader == 0)
  17591. reader = createReader();
  17592. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17593. {
  17594. startTimer (timeBeforeDeletingReader);
  17595. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17596. int sample = roundToInt (startTime * d->sampleRate);
  17597. for (int i = numSamples; --i >= 0;)
  17598. {
  17599. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17600. if (sample >= 0)
  17601. {
  17602. if (sample >= reader->lengthInSamples)
  17603. break;
  17604. float lmin, lmax, rmin, rmax;
  17605. reader->readMaxLevels (sample,
  17606. jmax (1, nextSample - sample),
  17607. lmin, lmax, rmin, rmax);
  17608. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17609. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17610. if (numChannelsCached > 1)
  17611. {
  17612. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17613. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17614. }
  17615. cacheData += 2 * numChannelsCached;
  17616. }
  17617. startTime += timePerPixel;
  17618. sample = nextSample;
  17619. }
  17620. }
  17621. else
  17622. {
  17623. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17624. {
  17625. char* const channelData = getChannelData (channelNum);
  17626. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17627. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17628. startTime = cachedStart;
  17629. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17630. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17631. for (int i = numSamples; --i >= 0;)
  17632. {
  17633. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17634. if (sample >= 0 && channelData != 0)
  17635. {
  17636. char mx = -128;
  17637. char mn = 127;
  17638. while (sample <= nextSample)
  17639. {
  17640. if (sample >= numFinished)
  17641. break;
  17642. const int n = sample << 1;
  17643. const char sampMin = channelData [n];
  17644. const char sampMax = channelData [n + 1];
  17645. if (sampMin < mn)
  17646. mn = sampMin;
  17647. if (sampMax > mx)
  17648. mx = sampMax;
  17649. ++sample;
  17650. }
  17651. if (mn <= mx)
  17652. {
  17653. cacheData[0] = mn;
  17654. cacheData[1] = mx;
  17655. }
  17656. else
  17657. {
  17658. cacheData[0] = 1;
  17659. cacheData[1] = 0;
  17660. }
  17661. }
  17662. else
  17663. {
  17664. cacheData[0] = 1;
  17665. cacheData[1] = 0;
  17666. }
  17667. cacheData += numChannelsCached * 2;
  17668. startTime += timePerPixel;
  17669. sample = nextSample;
  17670. }
  17671. }
  17672. }
  17673. }
  17674. void AudioThumbnail::drawChannel (Graphics& g,
  17675. int x, int y, int w, int h,
  17676. double startTime,
  17677. double endTime,
  17678. int channelNum,
  17679. const float verticalZoomFactor)
  17680. {
  17681. refillCache (w, startTime, (endTime - startTime) / w);
  17682. if (numSamplesCached >= w
  17683. && channelNum >= 0
  17684. && channelNum < numChannelsCached)
  17685. {
  17686. const float topY = (float) y;
  17687. const float bottomY = topY + h;
  17688. const float midY = topY + h * 0.5f;
  17689. const float vscale = verticalZoomFactor * h / 256.0f;
  17690. const Rectangle<int> clip (g.getClipBounds());
  17691. const int skipLeft = jlimit (0, w, clip.getX() - x);
  17692. w -= skipLeft;
  17693. x += skipLeft;
  17694. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  17695. + (channelNum << 1)
  17696. + skipLeft * (numChannelsCached << 1);
  17697. while (--w >= 0)
  17698. {
  17699. const char mn = cacheData[0];
  17700. const char mx = cacheData[1];
  17701. cacheData += numChannelsCached << 1;
  17702. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  17703. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  17704. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  17705. ++x;
  17706. if (x >= clip.getRight())
  17707. break;
  17708. }
  17709. }
  17710. }
  17711. END_JUCE_NAMESPACE
  17712. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17713. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17714. BEGIN_JUCE_NAMESPACE
  17715. struct ThumbnailCacheEntry
  17716. {
  17717. int64 hash;
  17718. uint32 lastUsed;
  17719. MemoryBlock data;
  17720. juce_UseDebuggingNewOperator
  17721. };
  17722. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  17723. : TimeSliceThread ("thumb cache"),
  17724. maxNumThumbsToStore (maxNumThumbsToStore_)
  17725. {
  17726. startThread (2);
  17727. }
  17728. AudioThumbnailCache::~AudioThumbnailCache()
  17729. {
  17730. }
  17731. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  17732. {
  17733. for (int i = thumbs.size(); --i >= 0;)
  17734. {
  17735. if (thumbs[i]->hash == hashCode)
  17736. {
  17737. MemoryInputStream in (thumbs[i]->data, false);
  17738. thumb.loadFrom (in);
  17739. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  17740. return true;
  17741. }
  17742. }
  17743. return false;
  17744. }
  17745. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17746. const int64 hashCode)
  17747. {
  17748. MemoryOutputStream out;
  17749. thumb.saveTo (out);
  17750. ThumbnailCacheEntry* te = 0;
  17751. for (int i = thumbs.size(); --i >= 0;)
  17752. {
  17753. if (thumbs[i]->hash == hashCode)
  17754. {
  17755. te = thumbs[i];
  17756. break;
  17757. }
  17758. }
  17759. if (te == 0)
  17760. {
  17761. te = new ThumbnailCacheEntry();
  17762. te->hash = hashCode;
  17763. if (thumbs.size() < maxNumThumbsToStore)
  17764. {
  17765. thumbs.add (te);
  17766. }
  17767. else
  17768. {
  17769. int oldest = 0;
  17770. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17771. int i;
  17772. for (i = thumbs.size(); --i >= 0;)
  17773. if (thumbs[i]->lastUsed < oldestTime)
  17774. oldest = i;
  17775. thumbs.set (i, te);
  17776. }
  17777. }
  17778. te->lastUsed = Time::getMillisecondCounter();
  17779. te->data.setSize (0);
  17780. te->data.append (out.getData(), out.getDataSize());
  17781. }
  17782. void AudioThumbnailCache::clear()
  17783. {
  17784. thumbs.clear();
  17785. }
  17786. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17787. {
  17788. addTimeSliceClient (thumb);
  17789. }
  17790. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17791. {
  17792. removeTimeSliceClient (thumb);
  17793. }
  17794. END_JUCE_NAMESPACE
  17795. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17796. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17797. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17798. #if ! JUCE_WINDOWS
  17799. #include <QuickTime/Movies.h>
  17800. #include <QuickTime/QTML.h>
  17801. #include <QuickTime/QuickTimeComponents.h>
  17802. #include <QuickTime/MediaHandlers.h>
  17803. #include <QuickTime/ImageCodec.h>
  17804. #else
  17805. #if JUCE_MSVC
  17806. #pragma warning (push)
  17807. #pragma warning (disable : 4100)
  17808. #endif
  17809. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17810. add its header directory to your include path.
  17811. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17812. flag in juce_Config.h
  17813. */
  17814. #include <Movies.h>
  17815. #include <QTML.h>
  17816. #include <QuickTimeComponents.h>
  17817. #include <MediaHandlers.h>
  17818. #include <ImageCodec.h>
  17819. #if JUCE_MSVC
  17820. #pragma warning (pop)
  17821. #endif
  17822. #endif
  17823. BEGIN_JUCE_NAMESPACE
  17824. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17825. static const char* const quickTimeFormatName = "QuickTime file";
  17826. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17827. class QTAudioReader : public AudioFormatReader
  17828. {
  17829. public:
  17830. QTAudioReader (InputStream* const input_, const int trackNum_)
  17831. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17832. ok (false),
  17833. movie (0),
  17834. trackNum (trackNum_),
  17835. lastSampleRead (0),
  17836. lastThreadId (0),
  17837. extractor (0),
  17838. dataHandle (0)
  17839. {
  17840. bufferList.calloc (256, 1);
  17841. #if JUCE_WINDOWS
  17842. if (InitializeQTML (0) != noErr)
  17843. return;
  17844. #endif
  17845. if (EnterMovies() != noErr)
  17846. return;
  17847. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17848. if (! opened)
  17849. return;
  17850. {
  17851. const int numTracks = GetMovieTrackCount (movie);
  17852. int trackCount = 0;
  17853. for (int i = 1; i <= numTracks; ++i)
  17854. {
  17855. track = GetMovieIndTrack (movie, i);
  17856. media = GetTrackMedia (track);
  17857. OSType mediaType;
  17858. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17859. if (mediaType == SoundMediaType
  17860. && trackCount++ == trackNum_)
  17861. {
  17862. ok = true;
  17863. break;
  17864. }
  17865. }
  17866. }
  17867. if (! ok)
  17868. return;
  17869. ok = false;
  17870. lengthInSamples = GetMediaDecodeDuration (media);
  17871. usesFloatingPointData = false;
  17872. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17873. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17874. / GetMediaTimeScale (media);
  17875. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17876. unsigned long output_layout_size;
  17877. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17878. kQTPropertyClass_MovieAudioExtraction_Audio,
  17879. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17880. 0, &output_layout_size, 0);
  17881. if (err != noErr)
  17882. return;
  17883. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17884. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17885. err = MovieAudioExtractionGetProperty (extractor,
  17886. kQTPropertyClass_MovieAudioExtraction_Audio,
  17887. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17888. output_layout_size, qt_audio_channel_layout, 0);
  17889. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17890. err = MovieAudioExtractionSetProperty (extractor,
  17891. kQTPropertyClass_MovieAudioExtraction_Audio,
  17892. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17893. output_layout_size,
  17894. qt_audio_channel_layout);
  17895. err = MovieAudioExtractionGetProperty (extractor,
  17896. kQTPropertyClass_MovieAudioExtraction_Audio,
  17897. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17898. sizeof (inputStreamDesc),
  17899. &inputStreamDesc, 0);
  17900. if (err != noErr)
  17901. return;
  17902. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17903. | kAudioFormatFlagIsPacked
  17904. | kAudioFormatFlagsNativeEndian;
  17905. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17906. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17907. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17908. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17909. err = MovieAudioExtractionSetProperty (extractor,
  17910. kQTPropertyClass_MovieAudioExtraction_Audio,
  17911. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17912. sizeof (inputStreamDesc),
  17913. &inputStreamDesc);
  17914. if (err != noErr)
  17915. return;
  17916. Boolean allChannelsDiscrete = false;
  17917. err = MovieAudioExtractionSetProperty (extractor,
  17918. kQTPropertyClass_MovieAudioExtraction_Movie,
  17919. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17920. sizeof (allChannelsDiscrete),
  17921. &allChannelsDiscrete);
  17922. if (err != noErr)
  17923. return;
  17924. bufferList->mNumberBuffers = 1;
  17925. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17926. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17927. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17928. bufferList->mBuffers[0].mData = dataBuffer;
  17929. sampleRate = inputStreamDesc.mSampleRate;
  17930. bitsPerSample = 16;
  17931. numChannels = inputStreamDesc.mChannelsPerFrame;
  17932. detachThread();
  17933. ok = true;
  17934. }
  17935. ~QTAudioReader()
  17936. {
  17937. if (dataHandle != 0)
  17938. DisposeHandle (dataHandle);
  17939. if (extractor != 0)
  17940. {
  17941. MovieAudioExtractionEnd (extractor);
  17942. extractor = 0;
  17943. }
  17944. checkThreadIsAttached();
  17945. DisposeMovie (movie);
  17946. #if JUCE_MAC
  17947. ExitMoviesOnThread ();
  17948. #endif
  17949. }
  17950. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17951. int64 startSampleInFile, int numSamples)
  17952. {
  17953. checkThreadIsAttached();
  17954. while (numSamples > 0)
  17955. {
  17956. if (! loadFrame ((int) startSampleInFile))
  17957. return false;
  17958. const int numToDo = jmin (numSamples, samplesPerFrame);
  17959. for (int j = numDestChannels; --j >= 0;)
  17960. {
  17961. if (destSamples[j] != 0)
  17962. {
  17963. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17964. for (int i = 0; i < numToDo; ++i)
  17965. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17966. }
  17967. }
  17968. startOffsetInDestBuffer += numToDo;
  17969. startSampleInFile += numToDo;
  17970. numSamples -= numToDo;
  17971. }
  17972. detachThread();
  17973. return true;
  17974. }
  17975. bool loadFrame (const int sampleNum)
  17976. {
  17977. if (lastSampleRead != sampleNum)
  17978. {
  17979. TimeRecord time;
  17980. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17981. time.base = 0;
  17982. time.value.hi = 0;
  17983. time.value.lo = (UInt32) sampleNum;
  17984. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17985. kQTPropertyClass_MovieAudioExtraction_Movie,
  17986. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17987. sizeof (time), &time);
  17988. if (err != noErr)
  17989. return false;
  17990. }
  17991. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17992. UInt32 outFlags = 0;
  17993. UInt32 actualNumSamples = samplesPerFrame;
  17994. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17995. bufferList, &outFlags);
  17996. lastSampleRead = sampleNum + samplesPerFrame;
  17997. return err == noErr;
  17998. }
  17999. juce_UseDebuggingNewOperator
  18000. bool ok;
  18001. private:
  18002. Movie movie;
  18003. Media media;
  18004. Track track;
  18005. const int trackNum;
  18006. double trackUnitsPerFrame;
  18007. int samplesPerFrame;
  18008. int lastSampleRead;
  18009. Thread::ThreadID lastThreadId;
  18010. MovieAudioExtractionRef extractor;
  18011. AudioStreamBasicDescription inputStreamDesc;
  18012. HeapBlock <AudioBufferList> bufferList;
  18013. HeapBlock <char> dataBuffer;
  18014. Handle dataHandle;
  18015. void checkThreadIsAttached()
  18016. {
  18017. #if JUCE_MAC
  18018. if (Thread::getCurrentThreadId() != lastThreadId)
  18019. EnterMoviesOnThread (0);
  18020. AttachMovieToCurrentThread (movie);
  18021. #endif
  18022. }
  18023. void detachThread()
  18024. {
  18025. #if JUCE_MAC
  18026. DetachMovieFromCurrentThread (movie);
  18027. #endif
  18028. }
  18029. QTAudioReader (const QTAudioReader&);
  18030. QTAudioReader& operator= (const QTAudioReader&);
  18031. };
  18032. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18033. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18034. {
  18035. }
  18036. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18037. {
  18038. }
  18039. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  18040. {
  18041. return Array<int>();
  18042. }
  18043. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  18044. {
  18045. return Array<int>();
  18046. }
  18047. bool QuickTimeAudioFormat::canDoStereo()
  18048. {
  18049. return true;
  18050. }
  18051. bool QuickTimeAudioFormat::canDoMono()
  18052. {
  18053. return true;
  18054. }
  18055. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18056. const bool deleteStreamIfOpeningFails)
  18057. {
  18058. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18059. if (r->ok)
  18060. return r.release();
  18061. if (! deleteStreamIfOpeningFails)
  18062. r->input = 0;
  18063. return 0;
  18064. }
  18065. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18066. double /*sampleRateToUse*/,
  18067. unsigned int /*numberOfChannels*/,
  18068. int /*bitsPerSample*/,
  18069. const StringPairArray& /*metadataValues*/,
  18070. int /*qualityOptionIndex*/)
  18071. {
  18072. jassertfalse; // not yet implemented!
  18073. return 0;
  18074. }
  18075. END_JUCE_NAMESPACE
  18076. #endif
  18077. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18078. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18079. BEGIN_JUCE_NAMESPACE
  18080. static const char* const wavFormatName = "WAV file";
  18081. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18082. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18083. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18084. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18085. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18086. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18087. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18088. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18089. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18090. const String& originator,
  18091. const String& originatorRef,
  18092. const Time& date,
  18093. const int64 timeReferenceSamples,
  18094. const String& codingHistory)
  18095. {
  18096. StringPairArray m;
  18097. m.set (bwavDescription, description);
  18098. m.set (bwavOriginator, originator);
  18099. m.set (bwavOriginatorRef, originatorRef);
  18100. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18101. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18102. m.set (bwavTimeReference, String (timeReferenceSamples));
  18103. m.set (bwavCodingHistory, codingHistory);
  18104. return m;
  18105. }
  18106. #if JUCE_MSVC
  18107. #pragma pack (push, 1)
  18108. #define PACKED
  18109. #elif JUCE_GCC
  18110. #define PACKED __attribute__((packed))
  18111. #else
  18112. #define PACKED
  18113. #endif
  18114. struct BWAVChunk
  18115. {
  18116. char description [256];
  18117. char originator [32];
  18118. char originatorRef [32];
  18119. char originationDate [10];
  18120. char originationTime [8];
  18121. uint32 timeRefLow;
  18122. uint32 timeRefHigh;
  18123. uint16 version;
  18124. uint8 umid[64];
  18125. uint8 reserved[190];
  18126. char codingHistory[1];
  18127. void copyTo (StringPairArray& values) const
  18128. {
  18129. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18130. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18131. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18132. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18133. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18134. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18135. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18136. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18137. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18138. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18139. }
  18140. static MemoryBlock createFrom (const StringPairArray& values)
  18141. {
  18142. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18143. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18144. data.fillWith (0);
  18145. BWAVChunk* b = (BWAVChunk*) data.getData();
  18146. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18147. // as they get called in the right order..
  18148. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18149. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18150. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18151. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18152. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18153. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18154. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18155. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18156. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18157. if (b->description[0] != 0
  18158. || b->originator[0] != 0
  18159. || b->originationDate[0] != 0
  18160. || b->originationTime[0] != 0
  18161. || b->codingHistory[0] != 0
  18162. || time != 0)
  18163. {
  18164. return data;
  18165. }
  18166. return MemoryBlock();
  18167. }
  18168. } PACKED;
  18169. struct SMPLChunk
  18170. {
  18171. struct SampleLoop
  18172. {
  18173. uint32 identifier;
  18174. uint32 type;
  18175. uint32 start;
  18176. uint32 end;
  18177. uint32 fraction;
  18178. uint32 playCount;
  18179. } PACKED;
  18180. uint32 manufacturer;
  18181. uint32 product;
  18182. uint32 samplePeriod;
  18183. uint32 midiUnityNote;
  18184. uint32 midiPitchFraction;
  18185. uint32 smpteFormat;
  18186. uint32 smpteOffset;
  18187. uint32 numSampleLoops;
  18188. uint32 samplerData;
  18189. SampleLoop loops[1];
  18190. void copyTo (StringPairArray& values, const int totalSize) const
  18191. {
  18192. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18193. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18194. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18195. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18196. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18197. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18198. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18199. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18200. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18201. for (uint32 i = 0; i < numSampleLoops; ++i)
  18202. {
  18203. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18204. break;
  18205. const String prefix ("Loop" + String(i));
  18206. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18207. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18208. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18209. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18210. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18211. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18212. }
  18213. }
  18214. static MemoryBlock createFrom (const StringPairArray& values)
  18215. {
  18216. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18217. if (numLoops <= 0)
  18218. return MemoryBlock();
  18219. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18220. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18221. data.fillWith (0);
  18222. SMPLChunk* s = (SMPLChunk*) data.getData();
  18223. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18224. // as they get called in the right order..
  18225. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18226. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18227. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18228. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18229. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18230. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18231. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18232. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18233. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18234. for (int i = 0; i < numLoops; ++i)
  18235. {
  18236. const String prefix ("Loop" + String(i));
  18237. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18238. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18239. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18240. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18241. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18242. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18243. }
  18244. return data;
  18245. }
  18246. } PACKED;
  18247. struct ExtensibleWavSubFormat
  18248. {
  18249. uint32 data1;
  18250. uint16 data2;
  18251. uint16 data3;
  18252. uint8 data4[8];
  18253. } PACKED;
  18254. #if JUCE_MSVC
  18255. #pragma pack (pop)
  18256. #endif
  18257. #undef PACKED
  18258. class WavAudioFormatReader : public AudioFormatReader
  18259. {
  18260. int bytesPerFrame;
  18261. int64 dataChunkStart, dataLength;
  18262. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18263. WavAudioFormatReader (const WavAudioFormatReader&);
  18264. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18265. public:
  18266. int64 bwavChunkStart, bwavSize;
  18267. WavAudioFormatReader (InputStream* const in)
  18268. : AudioFormatReader (in, TRANS (wavFormatName)),
  18269. dataLength (0),
  18270. bwavChunkStart (0),
  18271. bwavSize (0)
  18272. {
  18273. if (input->readInt() == chunkName ("RIFF"))
  18274. {
  18275. const uint32 len = (uint32) input->readInt();
  18276. const int64 end = input->getPosition() + len;
  18277. bool hasGotType = false;
  18278. bool hasGotData = false;
  18279. if (input->readInt() == chunkName ("WAVE"))
  18280. {
  18281. while (input->getPosition() < end
  18282. && ! input->isExhausted())
  18283. {
  18284. const int chunkType = input->readInt();
  18285. uint32 length = (uint32) input->readInt();
  18286. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18287. if (chunkType == chunkName ("fmt "))
  18288. {
  18289. // read the format chunk
  18290. const unsigned short format = input->readShort();
  18291. const short numChans = input->readShort();
  18292. sampleRate = input->readInt();
  18293. const int bytesPerSec = input->readInt();
  18294. numChannels = numChans;
  18295. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18296. bitsPerSample = 8 * bytesPerFrame / numChans;
  18297. if (format == 3)
  18298. {
  18299. usesFloatingPointData = true;
  18300. }
  18301. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18302. {
  18303. if (length < 40) // too short
  18304. {
  18305. bytesPerFrame = 0;
  18306. }
  18307. else
  18308. {
  18309. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18310. ExtensibleWavSubFormat subFormat;
  18311. subFormat.data1 = input->readInt();
  18312. subFormat.data2 = input->readShort();
  18313. subFormat.data3 = input->readShort();
  18314. input->read (subFormat.data4, sizeof (subFormat.data4));
  18315. const ExtensibleWavSubFormat pcmFormat
  18316. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18317. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18318. {
  18319. const ExtensibleWavSubFormat ambisonicFormat
  18320. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18321. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18322. bytesPerFrame = 0;
  18323. }
  18324. }
  18325. }
  18326. else if (format != 1)
  18327. {
  18328. bytesPerFrame = 0;
  18329. }
  18330. hasGotType = true;
  18331. }
  18332. else if (chunkType == chunkName ("data"))
  18333. {
  18334. // get the data chunk's position
  18335. dataLength = length;
  18336. dataChunkStart = input->getPosition();
  18337. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18338. hasGotData = true;
  18339. }
  18340. else if (chunkType == chunkName ("bext"))
  18341. {
  18342. bwavChunkStart = input->getPosition();
  18343. bwavSize = length;
  18344. // Broadcast-wav extension chunk..
  18345. HeapBlock <BWAVChunk> bwav;
  18346. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18347. input->read (bwav, length);
  18348. bwav->copyTo (metadataValues);
  18349. }
  18350. else if (chunkType == chunkName ("smpl"))
  18351. {
  18352. HeapBlock <SMPLChunk> smpl;
  18353. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18354. input->read (smpl, length);
  18355. smpl->copyTo (metadataValues, length);
  18356. }
  18357. else if (chunkEnd <= input->getPosition())
  18358. {
  18359. break;
  18360. }
  18361. input->setPosition (chunkEnd);
  18362. }
  18363. }
  18364. }
  18365. }
  18366. ~WavAudioFormatReader()
  18367. {
  18368. }
  18369. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18370. int64 startSampleInFile, int numSamples)
  18371. {
  18372. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18373. if (samplesAvailable < numSamples)
  18374. {
  18375. for (int i = numDestChannels; --i >= 0;)
  18376. if (destSamples[i] != 0)
  18377. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18378. numSamples = (int) samplesAvailable;
  18379. }
  18380. if (numSamples <= 0)
  18381. return true;
  18382. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18383. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18384. char tempBuffer [tempBufSize];
  18385. while (numSamples > 0)
  18386. {
  18387. int* left = destSamples[0];
  18388. if (left != 0)
  18389. left += startOffsetInDestBuffer;
  18390. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  18391. if (right != 0)
  18392. right += startOffsetInDestBuffer;
  18393. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18394. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18395. if (bytesRead < numThisTime * bytesPerFrame)
  18396. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18397. if (bitsPerSample == 16)
  18398. {
  18399. const short* src = reinterpret_cast <const short*> (tempBuffer);
  18400. if (numChannels > 1)
  18401. {
  18402. if (left == 0)
  18403. {
  18404. for (int i = numThisTime; --i >= 0;)
  18405. {
  18406. ++src;
  18407. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18408. }
  18409. }
  18410. else if (right == 0)
  18411. {
  18412. for (int i = numThisTime; --i >= 0;)
  18413. {
  18414. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18415. ++src;
  18416. }
  18417. }
  18418. else
  18419. {
  18420. for (int i = numThisTime; --i >= 0;)
  18421. {
  18422. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18423. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18424. }
  18425. }
  18426. }
  18427. else
  18428. {
  18429. for (int i = numThisTime; --i >= 0;)
  18430. {
  18431. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18432. }
  18433. }
  18434. }
  18435. else if (bitsPerSample == 24)
  18436. {
  18437. const char* src = tempBuffer;
  18438. if (numChannels > 1)
  18439. {
  18440. if (left == 0)
  18441. {
  18442. for (int i = numThisTime; --i >= 0;)
  18443. {
  18444. src += 3;
  18445. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  18446. src += 3;
  18447. }
  18448. }
  18449. else if (right == 0)
  18450. {
  18451. for (int i = numThisTime; --i >= 0;)
  18452. {
  18453. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18454. src += 6;
  18455. }
  18456. }
  18457. else
  18458. {
  18459. for (int i = 0; i < numThisTime; ++i)
  18460. {
  18461. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18462. src += 3;
  18463. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  18464. src += 3;
  18465. }
  18466. }
  18467. }
  18468. else
  18469. {
  18470. for (int i = 0; i < numThisTime; ++i)
  18471. {
  18472. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18473. src += 3;
  18474. }
  18475. }
  18476. }
  18477. else if (bitsPerSample == 32)
  18478. {
  18479. const unsigned int* src = (const unsigned int*) tempBuffer;
  18480. unsigned int* l = (unsigned int*) left;
  18481. unsigned int* r = (unsigned int*) right;
  18482. if (numChannels > 1)
  18483. {
  18484. if (l == 0)
  18485. {
  18486. for (int i = numThisTime; --i >= 0;)
  18487. {
  18488. ++src;
  18489. *r++ = ByteOrder::swapIfBigEndian (*src++);
  18490. }
  18491. }
  18492. else if (r == 0)
  18493. {
  18494. for (int i = numThisTime; --i >= 0;)
  18495. {
  18496. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18497. ++src;
  18498. }
  18499. }
  18500. else
  18501. {
  18502. for (int i = numThisTime; --i >= 0;)
  18503. {
  18504. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18505. *r++ = ByteOrder::swapIfBigEndian (*src++);
  18506. }
  18507. }
  18508. }
  18509. else
  18510. {
  18511. for (int i = numThisTime; --i >= 0;)
  18512. {
  18513. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18514. }
  18515. }
  18516. left = (int*)l;
  18517. right = (int*)r;
  18518. }
  18519. else if (bitsPerSample == 8)
  18520. {
  18521. const unsigned char* src = (const unsigned char*) tempBuffer;
  18522. if (numChannels > 1)
  18523. {
  18524. if (left == 0)
  18525. {
  18526. for (int i = numThisTime; --i >= 0;)
  18527. {
  18528. ++src;
  18529. *right++ = ((int) *src++ - 128) << 24;
  18530. }
  18531. }
  18532. else if (right == 0)
  18533. {
  18534. for (int i = numThisTime; --i >= 0;)
  18535. {
  18536. *left++ = ((int) *src++ - 128) << 24;
  18537. ++src;
  18538. }
  18539. }
  18540. else
  18541. {
  18542. for (int i = numThisTime; --i >= 0;)
  18543. {
  18544. *left++ = ((int) *src++ - 128) << 24;
  18545. *right++ = ((int) *src++ - 128) << 24;
  18546. }
  18547. }
  18548. }
  18549. else
  18550. {
  18551. for (int i = numThisTime; --i >= 0;)
  18552. {
  18553. *left++ = ((int)*src++ - 128) << 24;
  18554. }
  18555. }
  18556. }
  18557. startOffsetInDestBuffer += numThisTime;
  18558. numSamples -= numThisTime;
  18559. }
  18560. if (numSamples > 0)
  18561. {
  18562. for (int i = numDestChannels; --i >= 0;)
  18563. if (destSamples[i] != 0)
  18564. zeromem (destSamples[i] + startOffsetInDestBuffer,
  18565. sizeof (int) * numSamples);
  18566. }
  18567. return true;
  18568. }
  18569. juce_UseDebuggingNewOperator
  18570. };
  18571. class WavAudioFormatWriter : public AudioFormatWriter
  18572. {
  18573. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18574. uint32 lengthInSamples, bytesWritten;
  18575. int64 headerPosition;
  18576. bool writeFailed;
  18577. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18578. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18579. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18580. void writeHeader()
  18581. {
  18582. const bool seekedOk = output->setPosition (headerPosition);
  18583. (void) seekedOk;
  18584. // if this fails, you've given it an output stream that can't seek! It needs
  18585. // to be able to seek back to write the header
  18586. jassert (seekedOk);
  18587. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18588. output->writeInt (chunkName ("RIFF"));
  18589. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18590. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18591. output->writeInt (chunkName ("WAVE"));
  18592. output->writeInt (chunkName ("fmt "));
  18593. output->writeInt (16);
  18594. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18595. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18596. output->writeShort ((short) numChannels);
  18597. output->writeInt ((int) sampleRate);
  18598. output->writeInt (bytesPerFrame * (int) sampleRate);
  18599. output->writeShort ((short) bytesPerFrame);
  18600. output->writeShort ((short) bitsPerSample);
  18601. if (bwavChunk.getSize() > 0)
  18602. {
  18603. output->writeInt (chunkName ("bext"));
  18604. output->writeInt ((int) bwavChunk.getSize());
  18605. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18606. }
  18607. if (smplChunk.getSize() > 0)
  18608. {
  18609. output->writeInt (chunkName ("smpl"));
  18610. output->writeInt ((int) smplChunk.getSize());
  18611. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18612. }
  18613. output->writeInt (chunkName ("data"));
  18614. output->writeInt (lengthInSamples * bytesPerFrame);
  18615. usesFloatingPointData = (bitsPerSample == 32);
  18616. }
  18617. public:
  18618. WavAudioFormatWriter (OutputStream* const out,
  18619. const double sampleRate_,
  18620. const unsigned int numChannels_,
  18621. const int bits,
  18622. const StringPairArray& metadataValues)
  18623. : AudioFormatWriter (out,
  18624. TRANS (wavFormatName),
  18625. sampleRate_,
  18626. numChannels_,
  18627. bits),
  18628. lengthInSamples (0),
  18629. bytesWritten (0),
  18630. writeFailed (false)
  18631. {
  18632. if (metadataValues.size() > 0)
  18633. {
  18634. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18635. smplChunk = SMPLChunk::createFrom (metadataValues);
  18636. }
  18637. headerPosition = out->getPosition();
  18638. writeHeader();
  18639. }
  18640. ~WavAudioFormatWriter()
  18641. {
  18642. writeHeader();
  18643. }
  18644. bool write (const int** data, int numSamples)
  18645. {
  18646. if (writeFailed)
  18647. return false;
  18648. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18649. tempBlock.ensureSize (bytes, false);
  18650. char* buffer = static_cast <char*> (tempBlock.getData());
  18651. const int* left = data[0];
  18652. const int* right = data[1];
  18653. if (right == 0)
  18654. right = left;
  18655. if (bitsPerSample == 16)
  18656. {
  18657. short* b = (short*) buffer;
  18658. if (numChannels > 1)
  18659. {
  18660. for (int i = numSamples; --i >= 0;)
  18661. {
  18662. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  18663. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  18664. }
  18665. }
  18666. else
  18667. {
  18668. for (int i = numSamples; --i >= 0;)
  18669. {
  18670. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  18671. }
  18672. }
  18673. }
  18674. else if (bitsPerSample == 24)
  18675. {
  18676. char* b = buffer;
  18677. if (numChannels > 1)
  18678. {
  18679. for (int i = numSamples; --i >= 0;)
  18680. {
  18681. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  18682. b += 3;
  18683. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  18684. b += 3;
  18685. }
  18686. }
  18687. else
  18688. {
  18689. for (int i = numSamples; --i >= 0;)
  18690. {
  18691. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  18692. b += 3;
  18693. }
  18694. }
  18695. }
  18696. else if (bitsPerSample == 32)
  18697. {
  18698. unsigned int* b = (unsigned int*) buffer;
  18699. if (numChannels > 1)
  18700. {
  18701. for (int i = numSamples; --i >= 0;)
  18702. {
  18703. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  18704. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  18705. }
  18706. }
  18707. else
  18708. {
  18709. for (int i = numSamples; --i >= 0;)
  18710. {
  18711. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  18712. }
  18713. }
  18714. }
  18715. else if (bitsPerSample == 8)
  18716. {
  18717. unsigned char* b = (unsigned char*) buffer;
  18718. if (numChannels > 1)
  18719. {
  18720. for (int i = numSamples; --i >= 0;)
  18721. {
  18722. *b++ = (unsigned char) (128 + (*left++ >> 24));
  18723. *b++ = (unsigned char) (128 + (*right++ >> 24));
  18724. }
  18725. }
  18726. else
  18727. {
  18728. for (int i = numSamples; --i >= 0;)
  18729. {
  18730. *b++ = (unsigned char) (128 + (*left++ >> 24));
  18731. }
  18732. }
  18733. }
  18734. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18735. || ! output->write (buffer, bytes))
  18736. {
  18737. // failed to write to disk, so let's try writing the header.
  18738. // If it's just run out of disk space, then if it does manage
  18739. // to write the header, we'll still have a useable file..
  18740. writeHeader();
  18741. writeFailed = true;
  18742. return false;
  18743. }
  18744. else
  18745. {
  18746. bytesWritten += bytes;
  18747. lengthInSamples += numSamples;
  18748. return true;
  18749. }
  18750. }
  18751. juce_UseDebuggingNewOperator
  18752. };
  18753. WavAudioFormat::WavAudioFormat()
  18754. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18755. {
  18756. }
  18757. WavAudioFormat::~WavAudioFormat()
  18758. {
  18759. }
  18760. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18761. {
  18762. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18763. return Array <int> (rates);
  18764. }
  18765. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18766. {
  18767. const int depths[] = { 8, 16, 24, 32, 0 };
  18768. return Array <int> (depths);
  18769. }
  18770. bool WavAudioFormat::canDoStereo()
  18771. {
  18772. return true;
  18773. }
  18774. bool WavAudioFormat::canDoMono()
  18775. {
  18776. return true;
  18777. }
  18778. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18779. const bool deleteStreamIfOpeningFails)
  18780. {
  18781. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18782. if (r->sampleRate != 0)
  18783. return r.release();
  18784. if (! deleteStreamIfOpeningFails)
  18785. r->input = 0;
  18786. return 0;
  18787. }
  18788. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18789. double sampleRate,
  18790. unsigned int numChannels,
  18791. int bitsPerSample,
  18792. const StringPairArray& metadataValues,
  18793. int /*qualityOptionIndex*/)
  18794. {
  18795. if (getPossibleBitDepths().contains (bitsPerSample))
  18796. {
  18797. return new WavAudioFormatWriter (out,
  18798. sampleRate,
  18799. numChannels,
  18800. bitsPerSample,
  18801. metadataValues);
  18802. }
  18803. return 0;
  18804. }
  18805. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18806. {
  18807. TemporaryFile tempFile (file);
  18808. WavAudioFormat wav;
  18809. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18810. if (reader != 0)
  18811. {
  18812. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18813. if (outStream != 0)
  18814. {
  18815. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18816. reader->numChannels, reader->bitsPerSample,
  18817. metadata, 0));
  18818. if (writer != 0)
  18819. {
  18820. outStream.release();
  18821. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18822. writer = 0;
  18823. reader = 0;
  18824. return ok && tempFile.overwriteTargetFileWithTemporary();
  18825. }
  18826. }
  18827. }
  18828. return false;
  18829. }
  18830. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18831. {
  18832. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18833. if (reader != 0)
  18834. {
  18835. const int64 bwavPos = reader->bwavChunkStart;
  18836. const int64 bwavSize = reader->bwavSize;
  18837. reader = 0;
  18838. if (bwavSize > 0)
  18839. {
  18840. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18841. if (chunk.getSize() <= (size_t) bwavSize)
  18842. {
  18843. // the new one will fit in the space available, so write it directly..
  18844. const int64 oldSize = wavFile.getSize();
  18845. {
  18846. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18847. out->setPosition (bwavPos);
  18848. out->write (chunk.getData(), (int) chunk.getSize());
  18849. out->setPosition (oldSize);
  18850. }
  18851. jassert (wavFile.getSize() == oldSize);
  18852. return true;
  18853. }
  18854. }
  18855. }
  18856. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18857. }
  18858. END_JUCE_NAMESPACE
  18859. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18860. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18861. #if JUCE_USE_CDREADER
  18862. BEGIN_JUCE_NAMESPACE
  18863. int AudioCDReader::getNumTracks() const
  18864. {
  18865. return trackStartSamples.size() - 1;
  18866. }
  18867. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18868. {
  18869. return trackStartSamples [trackNum];
  18870. }
  18871. const Array<int>& AudioCDReader::getTrackOffsets() const
  18872. {
  18873. return trackStartSamples;
  18874. }
  18875. int AudioCDReader::getCDDBId()
  18876. {
  18877. int checksum = 0;
  18878. const int numTracks = getNumTracks();
  18879. for (int i = 0; i < numTracks; ++i)
  18880. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18881. checksum += offset % 10;
  18882. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18883. // CCLLLLTT: checksum, length, tracks
  18884. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18885. }
  18886. END_JUCE_NAMESPACE
  18887. #endif
  18888. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18889. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18890. BEGIN_JUCE_NAMESPACE
  18891. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18892. const bool deleteReaderWhenThisIsDeleted)
  18893. : reader (reader_),
  18894. deleteReader (deleteReaderWhenThisIsDeleted),
  18895. nextPlayPos (0),
  18896. looping (false)
  18897. {
  18898. jassert (reader != 0);
  18899. }
  18900. AudioFormatReaderSource::~AudioFormatReaderSource()
  18901. {
  18902. releaseResources();
  18903. if (deleteReader)
  18904. delete reader;
  18905. }
  18906. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18907. {
  18908. nextPlayPos = newPosition;
  18909. }
  18910. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18911. {
  18912. looping = shouldLoop;
  18913. }
  18914. int AudioFormatReaderSource::getNextReadPosition() const
  18915. {
  18916. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18917. : nextPlayPos;
  18918. }
  18919. int AudioFormatReaderSource::getTotalLength() const
  18920. {
  18921. return (int) reader->lengthInSamples;
  18922. }
  18923. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18924. double /*sampleRate*/)
  18925. {
  18926. }
  18927. void AudioFormatReaderSource::releaseResources()
  18928. {
  18929. }
  18930. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18931. {
  18932. if (info.numSamples > 0)
  18933. {
  18934. const int start = nextPlayPos;
  18935. if (looping)
  18936. {
  18937. const int newStart = start % (int) reader->lengthInSamples;
  18938. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18939. if (newEnd > newStart)
  18940. {
  18941. info.buffer->readFromAudioReader (reader,
  18942. info.startSample,
  18943. newEnd - newStart,
  18944. newStart,
  18945. true, true);
  18946. }
  18947. else
  18948. {
  18949. const int endSamps = (int) reader->lengthInSamples - newStart;
  18950. info.buffer->readFromAudioReader (reader,
  18951. info.startSample,
  18952. endSamps,
  18953. newStart,
  18954. true, true);
  18955. info.buffer->readFromAudioReader (reader,
  18956. info.startSample + endSamps,
  18957. newEnd,
  18958. 0,
  18959. true, true);
  18960. }
  18961. nextPlayPos = newEnd;
  18962. }
  18963. else
  18964. {
  18965. info.buffer->readFromAudioReader (reader,
  18966. info.startSample,
  18967. info.numSamples,
  18968. start,
  18969. true, true);
  18970. nextPlayPos += info.numSamples;
  18971. }
  18972. }
  18973. }
  18974. END_JUCE_NAMESPACE
  18975. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18976. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18977. BEGIN_JUCE_NAMESPACE
  18978. AudioSourcePlayer::AudioSourcePlayer()
  18979. : source (0),
  18980. sampleRate (0),
  18981. bufferSize (0),
  18982. tempBuffer (2, 8),
  18983. lastGain (1.0f),
  18984. gain (1.0f)
  18985. {
  18986. }
  18987. AudioSourcePlayer::~AudioSourcePlayer()
  18988. {
  18989. setSource (0);
  18990. }
  18991. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18992. {
  18993. if (source != newSource)
  18994. {
  18995. AudioSource* const oldSource = source;
  18996. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18997. newSource->prepareToPlay (bufferSize, sampleRate);
  18998. {
  18999. const ScopedLock sl (readLock);
  19000. source = newSource;
  19001. }
  19002. if (oldSource != 0)
  19003. oldSource->releaseResources();
  19004. }
  19005. }
  19006. void AudioSourcePlayer::setGain (const float newGain) throw()
  19007. {
  19008. gain = newGain;
  19009. }
  19010. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19011. int totalNumInputChannels,
  19012. float** outputChannelData,
  19013. int totalNumOutputChannels,
  19014. int numSamples)
  19015. {
  19016. // these should have been prepared by audioDeviceAboutToStart()...
  19017. jassert (sampleRate > 0 && bufferSize > 0);
  19018. const ScopedLock sl (readLock);
  19019. if (source != 0)
  19020. {
  19021. AudioSourceChannelInfo info;
  19022. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19023. // messy stuff needed to compact the channels down into an array
  19024. // of non-zero pointers..
  19025. for (i = 0; i < totalNumInputChannels; ++i)
  19026. {
  19027. if (inputChannelData[i] != 0)
  19028. {
  19029. inputChans [numInputs++] = inputChannelData[i];
  19030. if (numInputs >= numElementsInArray (inputChans))
  19031. break;
  19032. }
  19033. }
  19034. for (i = 0; i < totalNumOutputChannels; ++i)
  19035. {
  19036. if (outputChannelData[i] != 0)
  19037. {
  19038. outputChans [numOutputs++] = outputChannelData[i];
  19039. if (numOutputs >= numElementsInArray (outputChans))
  19040. break;
  19041. }
  19042. }
  19043. if (numInputs > numOutputs)
  19044. {
  19045. // if there aren't enough output channels for the number of
  19046. // inputs, we need to create some temporary extra ones (can't
  19047. // use the input data in case it gets written to)
  19048. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19049. false, false, true);
  19050. for (i = 0; i < numOutputs; ++i)
  19051. {
  19052. channels[numActiveChans] = outputChans[i];
  19053. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19054. ++numActiveChans;
  19055. }
  19056. for (i = numOutputs; i < numInputs; ++i)
  19057. {
  19058. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19059. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19060. ++numActiveChans;
  19061. }
  19062. }
  19063. else
  19064. {
  19065. for (i = 0; i < numInputs; ++i)
  19066. {
  19067. channels[numActiveChans] = outputChans[i];
  19068. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19069. ++numActiveChans;
  19070. }
  19071. for (i = numInputs; i < numOutputs; ++i)
  19072. {
  19073. channels[numActiveChans] = outputChans[i];
  19074. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19075. ++numActiveChans;
  19076. }
  19077. }
  19078. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19079. info.buffer = &buffer;
  19080. info.startSample = 0;
  19081. info.numSamples = numSamples;
  19082. source->getNextAudioBlock (info);
  19083. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19084. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19085. lastGain = gain;
  19086. }
  19087. else
  19088. {
  19089. for (int i = 0; i < totalNumOutputChannels; ++i)
  19090. if (outputChannelData[i] != 0)
  19091. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19092. }
  19093. }
  19094. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19095. {
  19096. sampleRate = device->getCurrentSampleRate();
  19097. bufferSize = device->getCurrentBufferSizeSamples();
  19098. zeromem (channels, sizeof (channels));
  19099. if (source != 0)
  19100. source->prepareToPlay (bufferSize, sampleRate);
  19101. }
  19102. void AudioSourcePlayer::audioDeviceStopped()
  19103. {
  19104. if (source != 0)
  19105. source->releaseResources();
  19106. sampleRate = 0.0;
  19107. bufferSize = 0;
  19108. tempBuffer.setSize (2, 8);
  19109. }
  19110. END_JUCE_NAMESPACE
  19111. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19112. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19113. BEGIN_JUCE_NAMESPACE
  19114. AudioTransportSource::AudioTransportSource()
  19115. : source (0),
  19116. resamplerSource (0),
  19117. bufferingSource (0),
  19118. positionableSource (0),
  19119. masterSource (0),
  19120. gain (1.0f),
  19121. lastGain (1.0f),
  19122. playing (false),
  19123. stopped (true),
  19124. sampleRate (44100.0),
  19125. sourceSampleRate (0.0),
  19126. blockSize (128),
  19127. readAheadBufferSize (0),
  19128. isPrepared (false),
  19129. inputStreamEOF (false)
  19130. {
  19131. }
  19132. AudioTransportSource::~AudioTransportSource()
  19133. {
  19134. setSource (0);
  19135. releaseResources();
  19136. }
  19137. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19138. int readAheadBufferSize_,
  19139. double sourceSampleRateToCorrectFor)
  19140. {
  19141. if (source == newSource)
  19142. {
  19143. if (source == 0)
  19144. return;
  19145. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19146. }
  19147. readAheadBufferSize = readAheadBufferSize_;
  19148. sourceSampleRate = sourceSampleRateToCorrectFor;
  19149. ResamplingAudioSource* newResamplerSource = 0;
  19150. BufferingAudioSource* newBufferingSource = 0;
  19151. PositionableAudioSource* newPositionableSource = 0;
  19152. AudioSource* newMasterSource = 0;
  19153. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19154. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19155. AudioSource* oldMasterSource = masterSource;
  19156. if (newSource != 0)
  19157. {
  19158. newPositionableSource = newSource;
  19159. if (readAheadBufferSize_ > 0)
  19160. newPositionableSource = newBufferingSource
  19161. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19162. newPositionableSource->setNextReadPosition (0);
  19163. if (sourceSampleRateToCorrectFor != 0)
  19164. newMasterSource = newResamplerSource
  19165. = new ResamplingAudioSource (newPositionableSource, false);
  19166. else
  19167. newMasterSource = newPositionableSource;
  19168. if (isPrepared)
  19169. {
  19170. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19171. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19172. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19173. }
  19174. }
  19175. {
  19176. const ScopedLock sl (callbackLock);
  19177. source = newSource;
  19178. resamplerSource = newResamplerSource;
  19179. bufferingSource = newBufferingSource;
  19180. masterSource = newMasterSource;
  19181. positionableSource = newPositionableSource;
  19182. playing = false;
  19183. }
  19184. if (oldMasterSource != 0)
  19185. oldMasterSource->releaseResources();
  19186. }
  19187. void AudioTransportSource::start()
  19188. {
  19189. if ((! playing) && masterSource != 0)
  19190. {
  19191. {
  19192. const ScopedLock sl (callbackLock);
  19193. playing = true;
  19194. stopped = false;
  19195. inputStreamEOF = false;
  19196. }
  19197. sendChangeMessage (this);
  19198. }
  19199. }
  19200. void AudioTransportSource::stop()
  19201. {
  19202. if (playing)
  19203. {
  19204. {
  19205. const ScopedLock sl (callbackLock);
  19206. playing = false;
  19207. }
  19208. int n = 500;
  19209. while (--n >= 0 && ! stopped)
  19210. Thread::sleep (2);
  19211. sendChangeMessage (this);
  19212. }
  19213. }
  19214. void AudioTransportSource::setPosition (double newPosition)
  19215. {
  19216. if (sampleRate > 0.0)
  19217. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19218. }
  19219. double AudioTransportSource::getCurrentPosition() const
  19220. {
  19221. if (sampleRate > 0.0)
  19222. return getNextReadPosition() / sampleRate;
  19223. else
  19224. return 0.0;
  19225. }
  19226. void AudioTransportSource::setNextReadPosition (int newPosition)
  19227. {
  19228. if (positionableSource != 0)
  19229. {
  19230. if (sampleRate > 0 && sourceSampleRate > 0)
  19231. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19232. positionableSource->setNextReadPosition (newPosition);
  19233. }
  19234. }
  19235. int AudioTransportSource::getNextReadPosition() const
  19236. {
  19237. if (positionableSource != 0)
  19238. {
  19239. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19240. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19241. }
  19242. return 0;
  19243. }
  19244. int AudioTransportSource::getTotalLength() const
  19245. {
  19246. const ScopedLock sl (callbackLock);
  19247. if (positionableSource != 0)
  19248. {
  19249. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19250. return roundToInt (positionableSource->getTotalLength() * ratio);
  19251. }
  19252. return 0;
  19253. }
  19254. bool AudioTransportSource::isLooping() const
  19255. {
  19256. const ScopedLock sl (callbackLock);
  19257. return positionableSource != 0
  19258. && positionableSource->isLooping();
  19259. }
  19260. void AudioTransportSource::setGain (const float newGain) throw()
  19261. {
  19262. gain = newGain;
  19263. }
  19264. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19265. double sampleRate_)
  19266. {
  19267. const ScopedLock sl (callbackLock);
  19268. sampleRate = sampleRate_;
  19269. blockSize = samplesPerBlockExpected;
  19270. if (masterSource != 0)
  19271. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19272. if (resamplerSource != 0 && sourceSampleRate != 0)
  19273. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19274. isPrepared = true;
  19275. }
  19276. void AudioTransportSource::releaseResources()
  19277. {
  19278. const ScopedLock sl (callbackLock);
  19279. if (masterSource != 0)
  19280. masterSource->releaseResources();
  19281. isPrepared = false;
  19282. }
  19283. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19284. {
  19285. const ScopedLock sl (callbackLock);
  19286. inputStreamEOF = false;
  19287. if (masterSource != 0 && ! stopped)
  19288. {
  19289. masterSource->getNextAudioBlock (info);
  19290. if (! playing)
  19291. {
  19292. // just stopped playing, so fade out the last block..
  19293. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19294. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19295. if (info.numSamples > 256)
  19296. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19297. }
  19298. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19299. && ! positionableSource->isLooping())
  19300. {
  19301. playing = false;
  19302. inputStreamEOF = true;
  19303. sendChangeMessage (this);
  19304. }
  19305. stopped = ! playing;
  19306. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19307. {
  19308. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19309. lastGain, gain);
  19310. }
  19311. }
  19312. else
  19313. {
  19314. info.clearActiveBufferRegion();
  19315. stopped = true;
  19316. }
  19317. lastGain = gain;
  19318. }
  19319. END_JUCE_NAMESPACE
  19320. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19321. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19322. BEGIN_JUCE_NAMESPACE
  19323. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19324. public Thread,
  19325. private Timer
  19326. {
  19327. public:
  19328. SharedBufferingAudioSourceThread()
  19329. : Thread ("Audio Buffer")
  19330. {
  19331. }
  19332. ~SharedBufferingAudioSourceThread()
  19333. {
  19334. stopThread (10000);
  19335. clearSingletonInstance();
  19336. }
  19337. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19338. void addSource (BufferingAudioSource* source)
  19339. {
  19340. const ScopedLock sl (lock);
  19341. if (! sources.contains (source))
  19342. {
  19343. sources.add (source);
  19344. startThread();
  19345. stopTimer();
  19346. }
  19347. notify();
  19348. }
  19349. void removeSource (BufferingAudioSource* source)
  19350. {
  19351. const ScopedLock sl (lock);
  19352. sources.removeValue (source);
  19353. if (sources.size() == 0)
  19354. startTimer (5000);
  19355. }
  19356. private:
  19357. Array <BufferingAudioSource*> sources;
  19358. CriticalSection lock;
  19359. void run()
  19360. {
  19361. while (! threadShouldExit())
  19362. {
  19363. bool busy = false;
  19364. for (int i = sources.size(); --i >= 0;)
  19365. {
  19366. if (threadShouldExit())
  19367. return;
  19368. const ScopedLock sl (lock);
  19369. BufferingAudioSource* const b = sources[i];
  19370. if (b != 0 && b->readNextBufferChunk())
  19371. busy = true;
  19372. }
  19373. if (! busy)
  19374. wait (500);
  19375. }
  19376. }
  19377. void timerCallback()
  19378. {
  19379. stopTimer();
  19380. if (sources.size() == 0)
  19381. deleteInstance();
  19382. }
  19383. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19384. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19385. };
  19386. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19387. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19388. const bool deleteSourceWhenDeleted_,
  19389. int numberOfSamplesToBuffer_)
  19390. : source (source_),
  19391. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19392. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19393. buffer (2, 0),
  19394. bufferValidStart (0),
  19395. bufferValidEnd (0),
  19396. nextPlayPos (0),
  19397. wasSourceLooping (false)
  19398. {
  19399. jassert (source_ != 0);
  19400. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19401. // not using a larger buffer..
  19402. }
  19403. BufferingAudioSource::~BufferingAudioSource()
  19404. {
  19405. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19406. if (thread != 0)
  19407. thread->removeSource (this);
  19408. if (deleteSourceWhenDeleted)
  19409. delete source;
  19410. }
  19411. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19412. {
  19413. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19414. sampleRate = sampleRate_;
  19415. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19416. buffer.clear();
  19417. bufferValidStart = 0;
  19418. bufferValidEnd = 0;
  19419. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19420. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19421. buffer.getNumSamples() / 2))
  19422. {
  19423. SharedBufferingAudioSourceThread::getInstance()->notify();
  19424. Thread::sleep (5);
  19425. }
  19426. }
  19427. void BufferingAudioSource::releaseResources()
  19428. {
  19429. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19430. if (thread != 0)
  19431. thread->removeSource (this);
  19432. buffer.setSize (2, 0);
  19433. source->releaseResources();
  19434. }
  19435. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19436. {
  19437. const ScopedLock sl (bufferStartPosLock);
  19438. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19439. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19440. if (validStart == validEnd)
  19441. {
  19442. // total cache miss
  19443. info.clearActiveBufferRegion();
  19444. }
  19445. else
  19446. {
  19447. if (validStart > 0)
  19448. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19449. if (validEnd < info.numSamples)
  19450. info.buffer->clear (info.startSample + validEnd,
  19451. info.numSamples - validEnd); // partial cache miss at end
  19452. if (validStart < validEnd)
  19453. {
  19454. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19455. {
  19456. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19457. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19458. if (startBufferIndex < endBufferIndex)
  19459. {
  19460. info.buffer->copyFrom (chan, info.startSample + validStart,
  19461. buffer,
  19462. chan, startBufferIndex,
  19463. validEnd - validStart);
  19464. }
  19465. else
  19466. {
  19467. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19468. info.buffer->copyFrom (chan, info.startSample + validStart,
  19469. buffer,
  19470. chan, startBufferIndex,
  19471. initialSize);
  19472. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19473. buffer,
  19474. chan, 0,
  19475. (validEnd - validStart) - initialSize);
  19476. }
  19477. }
  19478. }
  19479. nextPlayPos += info.numSamples;
  19480. if (source->isLooping() && nextPlayPos > 0)
  19481. nextPlayPos %= source->getTotalLength();
  19482. }
  19483. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19484. if (thread != 0)
  19485. thread->notify();
  19486. }
  19487. int BufferingAudioSource::getNextReadPosition() const
  19488. {
  19489. return (source->isLooping() && nextPlayPos > 0)
  19490. ? nextPlayPos % source->getTotalLength()
  19491. : nextPlayPos;
  19492. }
  19493. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19494. {
  19495. const ScopedLock sl (bufferStartPosLock);
  19496. nextPlayPos = newPosition;
  19497. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19498. if (thread != 0)
  19499. thread->notify();
  19500. }
  19501. bool BufferingAudioSource::readNextBufferChunk()
  19502. {
  19503. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19504. {
  19505. const ScopedLock sl (bufferStartPosLock);
  19506. if (wasSourceLooping != isLooping())
  19507. {
  19508. wasSourceLooping = isLooping();
  19509. bufferValidStart = 0;
  19510. bufferValidEnd = 0;
  19511. }
  19512. newBVS = jmax (0, nextPlayPos);
  19513. newBVE = newBVS + buffer.getNumSamples() - 4;
  19514. sectionToReadStart = 0;
  19515. sectionToReadEnd = 0;
  19516. const int maxChunkSize = 2048;
  19517. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19518. {
  19519. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19520. sectionToReadStart = newBVS;
  19521. sectionToReadEnd = newBVE;
  19522. bufferValidStart = 0;
  19523. bufferValidEnd = 0;
  19524. }
  19525. else if (abs (newBVS - bufferValidStart) > 512
  19526. || abs (newBVE - bufferValidEnd) > 512)
  19527. {
  19528. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19529. sectionToReadStart = bufferValidEnd;
  19530. sectionToReadEnd = newBVE;
  19531. bufferValidStart = newBVS;
  19532. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19533. }
  19534. }
  19535. if (sectionToReadStart != sectionToReadEnd)
  19536. {
  19537. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19538. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19539. if (bufferIndexStart < bufferIndexEnd)
  19540. {
  19541. readBufferSection (sectionToReadStart,
  19542. sectionToReadEnd - sectionToReadStart,
  19543. bufferIndexStart);
  19544. }
  19545. else
  19546. {
  19547. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19548. readBufferSection (sectionToReadStart,
  19549. initialSize,
  19550. bufferIndexStart);
  19551. readBufferSection (sectionToReadStart + initialSize,
  19552. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19553. 0);
  19554. }
  19555. const ScopedLock sl2 (bufferStartPosLock);
  19556. bufferValidStart = newBVS;
  19557. bufferValidEnd = newBVE;
  19558. return true;
  19559. }
  19560. else
  19561. {
  19562. return false;
  19563. }
  19564. }
  19565. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19566. {
  19567. if (source->getNextReadPosition() != start)
  19568. source->setNextReadPosition (start);
  19569. AudioSourceChannelInfo info;
  19570. info.buffer = &buffer;
  19571. info.startSample = bufferOffset;
  19572. info.numSamples = length;
  19573. source->getNextAudioBlock (info);
  19574. }
  19575. END_JUCE_NAMESPACE
  19576. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19577. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19578. BEGIN_JUCE_NAMESPACE
  19579. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19580. const bool deleteSourceWhenDeleted_)
  19581. : requiredNumberOfChannels (2),
  19582. source (source_),
  19583. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19584. buffer (2, 16)
  19585. {
  19586. remappedInfo.buffer = &buffer;
  19587. remappedInfo.startSample = 0;
  19588. }
  19589. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19590. {
  19591. if (deleteSourceWhenDeleted)
  19592. delete source;
  19593. }
  19594. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19595. {
  19596. const ScopedLock sl (lock);
  19597. requiredNumberOfChannels = requiredNumberOfChannels_;
  19598. }
  19599. void ChannelRemappingAudioSource::clearAllMappings()
  19600. {
  19601. const ScopedLock sl (lock);
  19602. remappedInputs.clear();
  19603. remappedOutputs.clear();
  19604. }
  19605. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19606. {
  19607. const ScopedLock sl (lock);
  19608. while (remappedInputs.size() < destIndex)
  19609. remappedInputs.add (-1);
  19610. remappedInputs.set (destIndex, sourceIndex);
  19611. }
  19612. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19613. {
  19614. const ScopedLock sl (lock);
  19615. while (remappedOutputs.size() < sourceIndex)
  19616. remappedOutputs.add (-1);
  19617. remappedOutputs.set (sourceIndex, destIndex);
  19618. }
  19619. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19620. {
  19621. const ScopedLock sl (lock);
  19622. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19623. return remappedInputs.getUnchecked (inputChannelIndex);
  19624. return -1;
  19625. }
  19626. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19627. {
  19628. const ScopedLock sl (lock);
  19629. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19630. return remappedOutputs .getUnchecked (outputChannelIndex);
  19631. return -1;
  19632. }
  19633. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19634. {
  19635. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19636. }
  19637. void ChannelRemappingAudioSource::releaseResources()
  19638. {
  19639. source->releaseResources();
  19640. }
  19641. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19642. {
  19643. const ScopedLock sl (lock);
  19644. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19645. const int numChans = bufferToFill.buffer->getNumChannels();
  19646. int i;
  19647. for (i = 0; i < buffer.getNumChannels(); ++i)
  19648. {
  19649. const int remappedChan = getRemappedInputChannel (i);
  19650. if (remappedChan >= 0 && remappedChan < numChans)
  19651. {
  19652. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19653. remappedChan,
  19654. bufferToFill.startSample,
  19655. bufferToFill.numSamples);
  19656. }
  19657. else
  19658. {
  19659. buffer.clear (i, 0, bufferToFill.numSamples);
  19660. }
  19661. }
  19662. remappedInfo.numSamples = bufferToFill.numSamples;
  19663. source->getNextAudioBlock (remappedInfo);
  19664. bufferToFill.clearActiveBufferRegion();
  19665. for (i = 0; i < requiredNumberOfChannels; ++i)
  19666. {
  19667. const int remappedChan = getRemappedOutputChannel (i);
  19668. if (remappedChan >= 0 && remappedChan < numChans)
  19669. {
  19670. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19671. buffer, i, 0, bufferToFill.numSamples);
  19672. }
  19673. }
  19674. }
  19675. XmlElement* ChannelRemappingAudioSource::createXml() const
  19676. {
  19677. XmlElement* e = new XmlElement ("MAPPINGS");
  19678. String ins, outs;
  19679. int i;
  19680. const ScopedLock sl (lock);
  19681. for (i = 0; i < remappedInputs.size(); ++i)
  19682. ins << remappedInputs.getUnchecked(i) << ' ';
  19683. for (i = 0; i < remappedOutputs.size(); ++i)
  19684. outs << remappedOutputs.getUnchecked(i) << ' ';
  19685. e->setAttribute ("inputs", ins.trimEnd());
  19686. e->setAttribute ("outputs", outs.trimEnd());
  19687. return e;
  19688. }
  19689. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19690. {
  19691. if (e.hasTagName ("MAPPINGS"))
  19692. {
  19693. const ScopedLock sl (lock);
  19694. clearAllMappings();
  19695. StringArray ins, outs;
  19696. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19697. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19698. int i;
  19699. for (i = 0; i < ins.size(); ++i)
  19700. remappedInputs.add (ins[i].getIntValue());
  19701. for (i = 0; i < outs.size(); ++i)
  19702. remappedOutputs.add (outs[i].getIntValue());
  19703. }
  19704. }
  19705. END_JUCE_NAMESPACE
  19706. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19707. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19708. BEGIN_JUCE_NAMESPACE
  19709. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19710. const bool deleteInputWhenDeleted_)
  19711. : input (inputSource),
  19712. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19713. {
  19714. jassert (inputSource != 0);
  19715. for (int i = 2; --i >= 0;)
  19716. iirFilters.add (new IIRFilter());
  19717. }
  19718. IIRFilterAudioSource::~IIRFilterAudioSource()
  19719. {
  19720. if (deleteInputWhenDeleted)
  19721. delete input;
  19722. }
  19723. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19724. {
  19725. for (int i = iirFilters.size(); --i >= 0;)
  19726. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19727. }
  19728. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19729. {
  19730. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19731. for (int i = iirFilters.size(); --i >= 0;)
  19732. iirFilters.getUnchecked(i)->reset();
  19733. }
  19734. void IIRFilterAudioSource::releaseResources()
  19735. {
  19736. input->releaseResources();
  19737. }
  19738. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19739. {
  19740. input->getNextAudioBlock (bufferToFill);
  19741. const int numChannels = bufferToFill.buffer->getNumChannels();
  19742. while (numChannels > iirFilters.size())
  19743. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19744. for (int i = 0; i < numChannels; ++i)
  19745. iirFilters.getUnchecked(i)
  19746. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19747. bufferToFill.numSamples);
  19748. }
  19749. END_JUCE_NAMESPACE
  19750. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19751. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19752. BEGIN_JUCE_NAMESPACE
  19753. MixerAudioSource::MixerAudioSource()
  19754. : tempBuffer (2, 0),
  19755. currentSampleRate (0.0),
  19756. bufferSizeExpected (0)
  19757. {
  19758. }
  19759. MixerAudioSource::~MixerAudioSource()
  19760. {
  19761. removeAllInputs();
  19762. }
  19763. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19764. {
  19765. if (input != 0 && ! inputs.contains (input))
  19766. {
  19767. double localRate;
  19768. int localBufferSize;
  19769. {
  19770. const ScopedLock sl (lock);
  19771. localRate = currentSampleRate;
  19772. localBufferSize = bufferSizeExpected;
  19773. }
  19774. if (localRate != 0.0)
  19775. input->prepareToPlay (localBufferSize, localRate);
  19776. const ScopedLock sl (lock);
  19777. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19778. inputs.add (input);
  19779. }
  19780. }
  19781. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19782. {
  19783. if (input != 0)
  19784. {
  19785. int index;
  19786. {
  19787. const ScopedLock sl (lock);
  19788. index = inputs.indexOf (input);
  19789. if (index >= 0)
  19790. {
  19791. inputsToDelete.shiftBits (index, 1);
  19792. inputs.remove (index);
  19793. }
  19794. }
  19795. if (index >= 0)
  19796. {
  19797. input->releaseResources();
  19798. if (deleteInput)
  19799. delete input;
  19800. }
  19801. }
  19802. }
  19803. void MixerAudioSource::removeAllInputs()
  19804. {
  19805. OwnedArray<AudioSource> toDelete;
  19806. {
  19807. const ScopedLock sl (lock);
  19808. for (int i = inputs.size(); --i >= 0;)
  19809. if (inputsToDelete[i])
  19810. toDelete.add (inputs.getUnchecked(i));
  19811. }
  19812. }
  19813. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19814. {
  19815. tempBuffer.setSize (2, samplesPerBlockExpected);
  19816. const ScopedLock sl (lock);
  19817. currentSampleRate = sampleRate;
  19818. bufferSizeExpected = samplesPerBlockExpected;
  19819. for (int i = inputs.size(); --i >= 0;)
  19820. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19821. }
  19822. void MixerAudioSource::releaseResources()
  19823. {
  19824. const ScopedLock sl (lock);
  19825. for (int i = inputs.size(); --i >= 0;)
  19826. inputs.getUnchecked(i)->releaseResources();
  19827. tempBuffer.setSize (2, 0);
  19828. currentSampleRate = 0;
  19829. bufferSizeExpected = 0;
  19830. }
  19831. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19832. {
  19833. const ScopedLock sl (lock);
  19834. if (inputs.size() > 0)
  19835. {
  19836. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19837. if (inputs.size() > 1)
  19838. {
  19839. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19840. info.buffer->getNumSamples());
  19841. AudioSourceChannelInfo info2;
  19842. info2.buffer = &tempBuffer;
  19843. info2.numSamples = info.numSamples;
  19844. info2.startSample = 0;
  19845. for (int i = 1; i < inputs.size(); ++i)
  19846. {
  19847. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19848. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19849. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19850. }
  19851. }
  19852. }
  19853. else
  19854. {
  19855. info.clearActiveBufferRegion();
  19856. }
  19857. }
  19858. END_JUCE_NAMESPACE
  19859. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19860. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19861. BEGIN_JUCE_NAMESPACE
  19862. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19863. const bool deleteInputWhenDeleted_,
  19864. const int numChannels_)
  19865. : input (inputSource),
  19866. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19867. ratio (1.0),
  19868. lastRatio (1.0),
  19869. buffer (numChannels_, 0),
  19870. sampsInBuffer (0),
  19871. numChannels (numChannels_)
  19872. {
  19873. jassert (input != 0);
  19874. }
  19875. ResamplingAudioSource::~ResamplingAudioSource()
  19876. {
  19877. if (deleteInputWhenDeleted)
  19878. delete input;
  19879. }
  19880. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19881. {
  19882. jassert (samplesInPerOutputSample > 0);
  19883. const ScopedLock sl (ratioLock);
  19884. ratio = jmax (0.0, samplesInPerOutputSample);
  19885. }
  19886. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19887. double sampleRate)
  19888. {
  19889. const ScopedLock sl (ratioLock);
  19890. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19891. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19892. buffer.clear();
  19893. sampsInBuffer = 0;
  19894. bufferPos = 0;
  19895. subSampleOffset = 0.0;
  19896. filterStates.calloc (numChannels);
  19897. srcBuffers.calloc (numChannels);
  19898. destBuffers.calloc (numChannels);
  19899. createLowPass (ratio);
  19900. resetFilters();
  19901. }
  19902. void ResamplingAudioSource::releaseResources()
  19903. {
  19904. input->releaseResources();
  19905. buffer.setSize (numChannels, 0);
  19906. }
  19907. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19908. {
  19909. const ScopedLock sl (ratioLock);
  19910. if (lastRatio != ratio)
  19911. {
  19912. createLowPass (ratio);
  19913. lastRatio = ratio;
  19914. }
  19915. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19916. int bufferSize = buffer.getNumSamples();
  19917. if (bufferSize < sampsNeeded + 8)
  19918. {
  19919. bufferPos %= bufferSize;
  19920. bufferSize = sampsNeeded + 32;
  19921. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19922. }
  19923. bufferPos %= bufferSize;
  19924. int endOfBufferPos = bufferPos + sampsInBuffer;
  19925. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19926. while (sampsNeeded > sampsInBuffer)
  19927. {
  19928. endOfBufferPos %= bufferSize;
  19929. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19930. bufferSize - endOfBufferPos);
  19931. AudioSourceChannelInfo readInfo;
  19932. readInfo.buffer = &buffer;
  19933. readInfo.numSamples = numToDo;
  19934. readInfo.startSample = endOfBufferPos;
  19935. input->getNextAudioBlock (readInfo);
  19936. if (ratio > 1.0001)
  19937. {
  19938. // for down-sampling, pre-apply the filter..
  19939. for (int i = channelsToProcess; --i >= 0;)
  19940. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19941. }
  19942. sampsInBuffer += numToDo;
  19943. endOfBufferPos += numToDo;
  19944. }
  19945. for (int channel = 0; channel < channelsToProcess; ++channel)
  19946. {
  19947. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19948. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19949. }
  19950. int nextPos = (bufferPos + 1) % bufferSize;
  19951. for (int m = info.numSamples; --m >= 0;)
  19952. {
  19953. const float alpha = (float) subSampleOffset;
  19954. const float invAlpha = 1.0f - alpha;
  19955. for (int channel = 0; channel < channelsToProcess; ++channel)
  19956. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19957. subSampleOffset += ratio;
  19958. jassert (sampsInBuffer > 0);
  19959. while (subSampleOffset >= 1.0)
  19960. {
  19961. if (++bufferPos >= bufferSize)
  19962. bufferPos = 0;
  19963. --sampsInBuffer;
  19964. nextPos = (bufferPos + 1) % bufferSize;
  19965. subSampleOffset -= 1.0;
  19966. }
  19967. }
  19968. if (ratio < 0.9999)
  19969. {
  19970. // for up-sampling, apply the filter after transposing..
  19971. for (int i = channelsToProcess; --i >= 0;)
  19972. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19973. }
  19974. else if (ratio <= 1.0001)
  19975. {
  19976. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19977. for (int i = channelsToProcess; --i >= 0;)
  19978. {
  19979. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19980. FilterState& fs = filterStates[i];
  19981. if (info.numSamples > 1)
  19982. {
  19983. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19984. }
  19985. else
  19986. {
  19987. fs.y2 = fs.y1;
  19988. fs.x2 = fs.x1;
  19989. }
  19990. fs.y1 = fs.x1 = *endOfBuffer;
  19991. }
  19992. }
  19993. jassert (sampsInBuffer >= 0);
  19994. }
  19995. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19996. {
  19997. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19998. : 0.5 * frequencyRatio;
  19999. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20000. const double nSquared = n * n;
  20001. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20002. setFilterCoefficients (c1,
  20003. c1 * 2.0f,
  20004. c1,
  20005. 1.0,
  20006. c1 * 2.0 * (1.0 - nSquared),
  20007. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20008. }
  20009. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20010. {
  20011. const double a = 1.0 / c4;
  20012. c1 *= a;
  20013. c2 *= a;
  20014. c3 *= a;
  20015. c5 *= a;
  20016. c6 *= a;
  20017. coefficients[0] = c1;
  20018. coefficients[1] = c2;
  20019. coefficients[2] = c3;
  20020. coefficients[3] = c4;
  20021. coefficients[4] = c5;
  20022. coefficients[5] = c6;
  20023. }
  20024. void ResamplingAudioSource::resetFilters()
  20025. {
  20026. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20027. }
  20028. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20029. {
  20030. while (--num >= 0)
  20031. {
  20032. const double in = *samples;
  20033. double out = coefficients[0] * in
  20034. + coefficients[1] * fs.x1
  20035. + coefficients[2] * fs.x2
  20036. - coefficients[4] * fs.y1
  20037. - coefficients[5] * fs.y2;
  20038. #if JUCE_INTEL
  20039. if (! (out < -1.0e-8 || out > 1.0e-8))
  20040. out = 0;
  20041. #endif
  20042. fs.x2 = fs.x1;
  20043. fs.x1 = in;
  20044. fs.y2 = fs.y1;
  20045. fs.y1 = out;
  20046. *samples++ = (float) out;
  20047. }
  20048. }
  20049. END_JUCE_NAMESPACE
  20050. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20051. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20052. BEGIN_JUCE_NAMESPACE
  20053. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20054. : frequency (1000.0),
  20055. sampleRate (44100.0),
  20056. currentPhase (0.0),
  20057. phasePerSample (0.0),
  20058. amplitude (0.5f)
  20059. {
  20060. }
  20061. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20062. {
  20063. }
  20064. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20065. {
  20066. amplitude = newAmplitude;
  20067. }
  20068. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20069. {
  20070. frequency = newFrequencyHz;
  20071. phasePerSample = 0.0;
  20072. }
  20073. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20074. double sampleRate_)
  20075. {
  20076. currentPhase = 0.0;
  20077. phasePerSample = 0.0;
  20078. sampleRate = sampleRate_;
  20079. }
  20080. void ToneGeneratorAudioSource::releaseResources()
  20081. {
  20082. }
  20083. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20084. {
  20085. if (phasePerSample == 0.0)
  20086. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20087. for (int i = 0; i < info.numSamples; ++i)
  20088. {
  20089. const float sample = amplitude * (float) std::sin (currentPhase);
  20090. currentPhase += phasePerSample;
  20091. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20092. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20093. }
  20094. }
  20095. END_JUCE_NAMESPACE
  20096. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20097. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20098. BEGIN_JUCE_NAMESPACE
  20099. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20100. : sampleRate (0),
  20101. bufferSize (0),
  20102. useDefaultInputChannels (true),
  20103. useDefaultOutputChannels (true)
  20104. {
  20105. }
  20106. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20107. {
  20108. return outputDeviceName == other.outputDeviceName
  20109. && inputDeviceName == other.inputDeviceName
  20110. && sampleRate == other.sampleRate
  20111. && bufferSize == other.bufferSize
  20112. && inputChannels == other.inputChannels
  20113. && useDefaultInputChannels == other.useDefaultInputChannels
  20114. && outputChannels == other.outputChannels
  20115. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20116. }
  20117. AudioDeviceManager::AudioDeviceManager()
  20118. : currentAudioDevice (0),
  20119. numInputChansNeeded (0),
  20120. numOutputChansNeeded (2),
  20121. listNeedsScanning (true),
  20122. useInputNames (false),
  20123. inputLevelMeasurementEnabledCount (0),
  20124. inputLevel (0),
  20125. tempBuffer (2, 2),
  20126. defaultMidiOutput (0),
  20127. cpuUsageMs (0),
  20128. timeToCpuScale (0)
  20129. {
  20130. callbackHandler.owner = this;
  20131. }
  20132. AudioDeviceManager::~AudioDeviceManager()
  20133. {
  20134. currentAudioDevice = 0;
  20135. defaultMidiOutput = 0;
  20136. }
  20137. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20138. {
  20139. if (availableDeviceTypes.size() == 0)
  20140. {
  20141. createAudioDeviceTypes (availableDeviceTypes);
  20142. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20143. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20144. if (availableDeviceTypes.size() > 0)
  20145. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20146. }
  20147. }
  20148. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20149. {
  20150. scanDevicesIfNeeded();
  20151. return availableDeviceTypes;
  20152. }
  20153. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20154. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20155. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20156. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20157. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20158. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20159. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20160. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20161. {
  20162. (void) list; // (to avoid 'unused param' warnings)
  20163. #if JUCE_WINDOWS
  20164. #if JUCE_WASAPI
  20165. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20166. list.add (juce_createAudioIODeviceType_WASAPI());
  20167. #endif
  20168. #if JUCE_DIRECTSOUND
  20169. list.add (juce_createAudioIODeviceType_DirectSound());
  20170. #endif
  20171. #if JUCE_ASIO
  20172. list.add (juce_createAudioIODeviceType_ASIO());
  20173. #endif
  20174. #endif
  20175. #if JUCE_MAC
  20176. list.add (juce_createAudioIODeviceType_CoreAudio());
  20177. #endif
  20178. #if JUCE_IOS
  20179. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20180. #endif
  20181. #if JUCE_LINUX && JUCE_ALSA
  20182. list.add (juce_createAudioIODeviceType_ALSA());
  20183. #endif
  20184. #if JUCE_LINUX && JUCE_JACK
  20185. list.add (juce_createAudioIODeviceType_JACK());
  20186. #endif
  20187. }
  20188. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20189. const int numOutputChannelsNeeded,
  20190. const XmlElement* const e,
  20191. const bool selectDefaultDeviceOnFailure,
  20192. const String& preferredDefaultDeviceName,
  20193. const AudioDeviceSetup* preferredSetupOptions)
  20194. {
  20195. scanDevicesIfNeeded();
  20196. numInputChansNeeded = numInputChannelsNeeded;
  20197. numOutputChansNeeded = numOutputChannelsNeeded;
  20198. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20199. {
  20200. lastExplicitSettings = new XmlElement (*e);
  20201. String error;
  20202. AudioDeviceSetup setup;
  20203. if (preferredSetupOptions != 0)
  20204. setup = *preferredSetupOptions;
  20205. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20206. {
  20207. setup.inputDeviceName = setup.outputDeviceName
  20208. = e->getStringAttribute ("audioDeviceName");
  20209. }
  20210. else
  20211. {
  20212. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20213. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20214. }
  20215. currentDeviceType = e->getStringAttribute ("deviceType");
  20216. if (currentDeviceType.isEmpty())
  20217. {
  20218. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20219. if (type != 0)
  20220. currentDeviceType = type->getTypeName();
  20221. else if (availableDeviceTypes.size() > 0)
  20222. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20223. }
  20224. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20225. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20226. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20227. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20228. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20229. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20230. error = setAudioDeviceSetup (setup, true);
  20231. midiInsFromXml.clear();
  20232. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20233. midiInsFromXml.add (c->getStringAttribute ("name"));
  20234. const StringArray allMidiIns (MidiInput::getDevices());
  20235. for (int i = allMidiIns.size(); --i >= 0;)
  20236. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20237. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20238. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20239. false, preferredDefaultDeviceName);
  20240. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20241. return error;
  20242. }
  20243. else
  20244. {
  20245. AudioDeviceSetup setup;
  20246. if (preferredSetupOptions != 0)
  20247. {
  20248. setup = *preferredSetupOptions;
  20249. }
  20250. else if (preferredDefaultDeviceName.isNotEmpty())
  20251. {
  20252. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20253. {
  20254. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20255. StringArray outs (type->getDeviceNames (false));
  20256. int i;
  20257. for (i = 0; i < outs.size(); ++i)
  20258. {
  20259. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20260. {
  20261. setup.outputDeviceName = outs[i];
  20262. break;
  20263. }
  20264. }
  20265. StringArray ins (type->getDeviceNames (true));
  20266. for (i = 0; i < ins.size(); ++i)
  20267. {
  20268. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20269. {
  20270. setup.inputDeviceName = ins[i];
  20271. break;
  20272. }
  20273. }
  20274. }
  20275. }
  20276. insertDefaultDeviceNames (setup);
  20277. return setAudioDeviceSetup (setup, false);
  20278. }
  20279. }
  20280. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20281. {
  20282. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20283. if (type != 0)
  20284. {
  20285. if (setup.outputDeviceName.isEmpty())
  20286. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20287. if (setup.inputDeviceName.isEmpty())
  20288. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20289. }
  20290. }
  20291. XmlElement* AudioDeviceManager::createStateXml() const
  20292. {
  20293. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20294. }
  20295. void AudioDeviceManager::scanDevicesIfNeeded()
  20296. {
  20297. if (listNeedsScanning)
  20298. {
  20299. listNeedsScanning = false;
  20300. createDeviceTypesIfNeeded();
  20301. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20302. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20303. }
  20304. }
  20305. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20306. {
  20307. scanDevicesIfNeeded();
  20308. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20309. {
  20310. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20311. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20312. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20313. {
  20314. return type;
  20315. }
  20316. }
  20317. return 0;
  20318. }
  20319. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20320. {
  20321. setup = currentSetup;
  20322. }
  20323. void AudioDeviceManager::deleteCurrentDevice()
  20324. {
  20325. currentAudioDevice = 0;
  20326. currentSetup.inputDeviceName = String::empty;
  20327. currentSetup.outputDeviceName = String::empty;
  20328. }
  20329. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20330. const bool treatAsChosenDevice)
  20331. {
  20332. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20333. {
  20334. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20335. && currentDeviceType != type)
  20336. {
  20337. currentDeviceType = type;
  20338. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20339. insertDefaultDeviceNames (s);
  20340. setAudioDeviceSetup (s, treatAsChosenDevice);
  20341. sendChangeMessage (this);
  20342. break;
  20343. }
  20344. }
  20345. }
  20346. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20347. {
  20348. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20349. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20350. return availableDeviceTypes[i];
  20351. return availableDeviceTypes[0];
  20352. }
  20353. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20354. const bool treatAsChosenDevice)
  20355. {
  20356. jassert (&newSetup != &currentSetup); // this will have no effect
  20357. if (newSetup == currentSetup && currentAudioDevice != 0)
  20358. return String::empty;
  20359. if (! (newSetup == currentSetup))
  20360. sendChangeMessage (this);
  20361. stopDevice();
  20362. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20363. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20364. String error;
  20365. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20366. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20367. {
  20368. deleteCurrentDevice();
  20369. if (treatAsChosenDevice)
  20370. updateXml();
  20371. return String::empty;
  20372. }
  20373. if (currentSetup.inputDeviceName != newInputDeviceName
  20374. || currentSetup.outputDeviceName != newOutputDeviceName
  20375. || currentAudioDevice == 0)
  20376. {
  20377. deleteCurrentDevice();
  20378. scanDevicesIfNeeded();
  20379. if (newOutputDeviceName.isNotEmpty()
  20380. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20381. {
  20382. return "No such device: " + newOutputDeviceName;
  20383. }
  20384. if (newInputDeviceName.isNotEmpty()
  20385. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20386. {
  20387. return "No such device: " + newInputDeviceName;
  20388. }
  20389. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20390. if (currentAudioDevice == 0)
  20391. 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!";
  20392. else
  20393. error = currentAudioDevice->getLastError();
  20394. if (error.isNotEmpty())
  20395. {
  20396. deleteCurrentDevice();
  20397. return error;
  20398. }
  20399. if (newSetup.useDefaultInputChannels)
  20400. {
  20401. inputChannels.clear();
  20402. inputChannels.setRange (0, numInputChansNeeded, true);
  20403. }
  20404. if (newSetup.useDefaultOutputChannels)
  20405. {
  20406. outputChannels.clear();
  20407. outputChannels.setRange (0, numOutputChansNeeded, true);
  20408. }
  20409. if (newInputDeviceName.isEmpty())
  20410. inputChannels.clear();
  20411. if (newOutputDeviceName.isEmpty())
  20412. outputChannels.clear();
  20413. }
  20414. if (! newSetup.useDefaultInputChannels)
  20415. inputChannels = newSetup.inputChannels;
  20416. if (! newSetup.useDefaultOutputChannels)
  20417. outputChannels = newSetup.outputChannels;
  20418. currentSetup = newSetup;
  20419. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20420. error = currentAudioDevice->open (inputChannels,
  20421. outputChannels,
  20422. currentSetup.sampleRate,
  20423. currentSetup.bufferSize);
  20424. if (error.isEmpty())
  20425. {
  20426. currentDeviceType = currentAudioDevice->getTypeName();
  20427. currentAudioDevice->start (&callbackHandler);
  20428. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20429. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20430. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20431. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20432. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20433. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20434. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20435. if (treatAsChosenDevice)
  20436. updateXml();
  20437. }
  20438. else
  20439. {
  20440. deleteCurrentDevice();
  20441. }
  20442. return error;
  20443. }
  20444. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20445. {
  20446. jassert (currentAudioDevice != 0);
  20447. if (rate > 0)
  20448. {
  20449. bool ok = false;
  20450. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20451. {
  20452. const double sr = currentAudioDevice->getSampleRate (i);
  20453. if (sr == rate)
  20454. ok = true;
  20455. }
  20456. if (! ok)
  20457. rate = 0;
  20458. }
  20459. if (rate == 0)
  20460. {
  20461. double lowestAbove44 = 0.0;
  20462. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20463. {
  20464. const double sr = currentAudioDevice->getSampleRate (i);
  20465. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20466. lowestAbove44 = sr;
  20467. }
  20468. if (lowestAbove44 == 0.0)
  20469. rate = currentAudioDevice->getSampleRate (0);
  20470. else
  20471. rate = lowestAbove44;
  20472. }
  20473. return rate;
  20474. }
  20475. void AudioDeviceManager::stopDevice()
  20476. {
  20477. if (currentAudioDevice != 0)
  20478. currentAudioDevice->stop();
  20479. testSound = 0;
  20480. }
  20481. void AudioDeviceManager::closeAudioDevice()
  20482. {
  20483. stopDevice();
  20484. currentAudioDevice = 0;
  20485. }
  20486. void AudioDeviceManager::restartLastAudioDevice()
  20487. {
  20488. if (currentAudioDevice == 0)
  20489. {
  20490. if (currentSetup.inputDeviceName.isEmpty()
  20491. && currentSetup.outputDeviceName.isEmpty())
  20492. {
  20493. // This method will only reload the last device that was running
  20494. // before closeAudioDevice() was called - you need to actually open
  20495. // one first, with setAudioDevice().
  20496. jassertfalse;
  20497. return;
  20498. }
  20499. AudioDeviceSetup s (currentSetup);
  20500. setAudioDeviceSetup (s, false);
  20501. }
  20502. }
  20503. void AudioDeviceManager::updateXml()
  20504. {
  20505. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20506. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20507. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20508. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20509. if (currentAudioDevice != 0)
  20510. {
  20511. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20512. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20513. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20514. if (! currentSetup.useDefaultInputChannels)
  20515. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20516. if (! currentSetup.useDefaultOutputChannels)
  20517. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20518. }
  20519. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20520. {
  20521. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20522. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20523. }
  20524. if (midiInsFromXml.size() > 0)
  20525. {
  20526. // Add any midi devices that have been enabled before, but which aren't currently
  20527. // open because the device has been disconnected.
  20528. const StringArray availableMidiDevices (MidiInput::getDevices());
  20529. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20530. {
  20531. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20532. {
  20533. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20534. m->setAttribute ("name", midiInsFromXml[i]);
  20535. }
  20536. }
  20537. }
  20538. if (defaultMidiOutputName.isNotEmpty())
  20539. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20540. }
  20541. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20542. {
  20543. {
  20544. const ScopedLock sl (audioCallbackLock);
  20545. if (callbacks.contains (newCallback))
  20546. return;
  20547. }
  20548. if (currentAudioDevice != 0 && newCallback != 0)
  20549. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20550. const ScopedLock sl (audioCallbackLock);
  20551. callbacks.add (newCallback);
  20552. }
  20553. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20554. {
  20555. if (callback != 0)
  20556. {
  20557. bool needsDeinitialising = currentAudioDevice != 0;
  20558. {
  20559. const ScopedLock sl (audioCallbackLock);
  20560. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20561. callbacks.removeValue (callback);
  20562. }
  20563. if (needsDeinitialising)
  20564. callback->audioDeviceStopped();
  20565. }
  20566. }
  20567. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20568. int numInputChannels,
  20569. float** outputChannelData,
  20570. int numOutputChannels,
  20571. int numSamples)
  20572. {
  20573. const ScopedLock sl (audioCallbackLock);
  20574. if (inputLevelMeasurementEnabledCount > 0)
  20575. {
  20576. for (int j = 0; j < numSamples; ++j)
  20577. {
  20578. float s = 0;
  20579. for (int i = 0; i < numInputChannels; ++i)
  20580. s += std::abs (inputChannelData[i][j]);
  20581. s /= numInputChannels;
  20582. const double decayFactor = 0.99992;
  20583. if (s > inputLevel)
  20584. inputLevel = s;
  20585. else if (inputLevel > 0.001f)
  20586. inputLevel *= decayFactor;
  20587. else
  20588. inputLevel = 0;
  20589. }
  20590. }
  20591. if (callbacks.size() > 0)
  20592. {
  20593. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20594. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20595. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20596. outputChannelData, numOutputChannels, numSamples);
  20597. float** const tempChans = tempBuffer.getArrayOfChannels();
  20598. for (int i = callbacks.size(); --i > 0;)
  20599. {
  20600. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20601. tempChans, numOutputChannels, numSamples);
  20602. for (int chan = 0; chan < numOutputChannels; ++chan)
  20603. {
  20604. const float* const src = tempChans [chan];
  20605. float* const dst = outputChannelData [chan];
  20606. if (src != 0 && dst != 0)
  20607. for (int j = 0; j < numSamples; ++j)
  20608. dst[j] += src[j];
  20609. }
  20610. }
  20611. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20612. const double filterAmount = 0.2;
  20613. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20614. }
  20615. else
  20616. {
  20617. for (int i = 0; i < numOutputChannels; ++i)
  20618. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20619. }
  20620. if (testSound != 0)
  20621. {
  20622. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20623. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20624. for (int i = 0; i < numOutputChannels; ++i)
  20625. for (int j = 0; j < numSamps; ++j)
  20626. outputChannelData [i][j] += src[j];
  20627. testSoundPosition += numSamps;
  20628. if (testSoundPosition >= testSound->getNumSamples())
  20629. testSound = 0;
  20630. }
  20631. }
  20632. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20633. {
  20634. cpuUsageMs = 0;
  20635. const double sampleRate = device->getCurrentSampleRate();
  20636. const int blockSize = device->getCurrentBufferSizeSamples();
  20637. if (sampleRate > 0.0 && blockSize > 0)
  20638. {
  20639. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20640. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20641. }
  20642. {
  20643. const ScopedLock sl (audioCallbackLock);
  20644. for (int i = callbacks.size(); --i >= 0;)
  20645. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20646. }
  20647. sendChangeMessage (this);
  20648. }
  20649. void AudioDeviceManager::audioDeviceStoppedInt()
  20650. {
  20651. cpuUsageMs = 0;
  20652. timeToCpuScale = 0;
  20653. sendChangeMessage (this);
  20654. const ScopedLock sl (audioCallbackLock);
  20655. for (int i = callbacks.size(); --i >= 0;)
  20656. callbacks.getUnchecked(i)->audioDeviceStopped();
  20657. }
  20658. double AudioDeviceManager::getCpuUsage() const
  20659. {
  20660. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20661. }
  20662. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20663. const bool enabled)
  20664. {
  20665. if (enabled != isMidiInputEnabled (name))
  20666. {
  20667. if (enabled)
  20668. {
  20669. const int index = MidiInput::getDevices().indexOf (name);
  20670. if (index >= 0)
  20671. {
  20672. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20673. if (min != 0)
  20674. {
  20675. enabledMidiInputs.add (min);
  20676. min->start();
  20677. }
  20678. }
  20679. }
  20680. else
  20681. {
  20682. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20683. if (enabledMidiInputs[i]->getName() == name)
  20684. enabledMidiInputs.remove (i);
  20685. }
  20686. updateXml();
  20687. sendChangeMessage (this);
  20688. }
  20689. }
  20690. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20691. {
  20692. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20693. if (enabledMidiInputs[i]->getName() == name)
  20694. return true;
  20695. return false;
  20696. }
  20697. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20698. MidiInputCallback* callback)
  20699. {
  20700. removeMidiInputCallback (name, callback);
  20701. if (name.isEmpty())
  20702. {
  20703. midiCallbacks.add (callback);
  20704. midiCallbackDevices.add (0);
  20705. }
  20706. else
  20707. {
  20708. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20709. {
  20710. if (enabledMidiInputs[i]->getName() == name)
  20711. {
  20712. const ScopedLock sl (midiCallbackLock);
  20713. midiCallbacks.add (callback);
  20714. midiCallbackDevices.add (enabledMidiInputs[i]);
  20715. break;
  20716. }
  20717. }
  20718. }
  20719. }
  20720. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20721. MidiInputCallback* /*callback*/)
  20722. {
  20723. const ScopedLock sl (midiCallbackLock);
  20724. for (int i = midiCallbacks.size(); --i >= 0;)
  20725. {
  20726. String devName;
  20727. if (midiCallbackDevices.getUnchecked(i) != 0)
  20728. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20729. if (devName == name)
  20730. {
  20731. midiCallbacks.remove (i);
  20732. midiCallbackDevices.remove (i);
  20733. }
  20734. }
  20735. }
  20736. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20737. const MidiMessage& message)
  20738. {
  20739. if (! message.isActiveSense())
  20740. {
  20741. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20742. const ScopedLock sl (midiCallbackLock);
  20743. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20744. {
  20745. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20746. if (md == source || (md == 0 && isDefaultSource))
  20747. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20748. }
  20749. }
  20750. }
  20751. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20752. {
  20753. if (defaultMidiOutputName != deviceName)
  20754. {
  20755. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20756. {
  20757. const ScopedLock sl (audioCallbackLock);
  20758. oldCallbacks = callbacks;
  20759. callbacks.clear();
  20760. }
  20761. if (currentAudioDevice != 0)
  20762. for (int i = oldCallbacks.size(); --i >= 0;)
  20763. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20764. defaultMidiOutput = 0;
  20765. defaultMidiOutputName = deviceName;
  20766. if (deviceName.isNotEmpty())
  20767. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20768. if (currentAudioDevice != 0)
  20769. for (int i = oldCallbacks.size(); --i >= 0;)
  20770. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20771. {
  20772. const ScopedLock sl (audioCallbackLock);
  20773. callbacks = oldCallbacks;
  20774. }
  20775. updateXml();
  20776. sendChangeMessage (this);
  20777. }
  20778. }
  20779. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20780. int numInputChannels,
  20781. float** outputChannelData,
  20782. int numOutputChannels,
  20783. int numSamples)
  20784. {
  20785. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20786. }
  20787. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20788. {
  20789. owner->audioDeviceAboutToStartInt (device);
  20790. }
  20791. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20792. {
  20793. owner->audioDeviceStoppedInt();
  20794. }
  20795. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20796. {
  20797. owner->handleIncomingMidiMessageInt (source, message);
  20798. }
  20799. void AudioDeviceManager::playTestSound()
  20800. {
  20801. { // cunningly nested to swap, unlock and delete in that order.
  20802. ScopedPointer <AudioSampleBuffer> oldSound;
  20803. {
  20804. const ScopedLock sl (audioCallbackLock);
  20805. oldSound = testSound;
  20806. }
  20807. }
  20808. testSoundPosition = 0;
  20809. if (currentAudioDevice != 0)
  20810. {
  20811. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20812. const int soundLength = (int) sampleRate;
  20813. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20814. float* samples = newSound->getSampleData (0);
  20815. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20816. const float amplitude = 0.5f;
  20817. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20818. for (int i = 0; i < soundLength; ++i)
  20819. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20820. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20821. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20822. const ScopedLock sl (audioCallbackLock);
  20823. testSound = newSound;
  20824. }
  20825. }
  20826. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20827. {
  20828. const ScopedLock sl (audioCallbackLock);
  20829. if (enableMeasurement)
  20830. ++inputLevelMeasurementEnabledCount;
  20831. else
  20832. --inputLevelMeasurementEnabledCount;
  20833. inputLevel = 0;
  20834. }
  20835. double AudioDeviceManager::getCurrentInputLevel() const
  20836. {
  20837. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20838. return inputLevel;
  20839. }
  20840. END_JUCE_NAMESPACE
  20841. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20842. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20843. BEGIN_JUCE_NAMESPACE
  20844. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20845. : name (deviceName),
  20846. typeName (typeName_)
  20847. {
  20848. }
  20849. AudioIODevice::~AudioIODevice()
  20850. {
  20851. }
  20852. bool AudioIODevice::hasControlPanel() const
  20853. {
  20854. return false;
  20855. }
  20856. bool AudioIODevice::showControlPanel()
  20857. {
  20858. jassertfalse; // this should only be called for devices which return true from
  20859. // their hasControlPanel() method.
  20860. return false;
  20861. }
  20862. END_JUCE_NAMESPACE
  20863. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20864. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20865. BEGIN_JUCE_NAMESPACE
  20866. AudioIODeviceType::AudioIODeviceType (const String& name)
  20867. : typeName (name)
  20868. {
  20869. }
  20870. AudioIODeviceType::~AudioIODeviceType()
  20871. {
  20872. }
  20873. END_JUCE_NAMESPACE
  20874. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20875. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20876. BEGIN_JUCE_NAMESPACE
  20877. MidiOutput::MidiOutput()
  20878. : Thread ("midi out"),
  20879. internal (0),
  20880. firstMessage (0)
  20881. {
  20882. }
  20883. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20884. const double sampleNumber)
  20885. : message (data, len, sampleNumber)
  20886. {
  20887. }
  20888. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20889. const double millisecondCounterToStartAt,
  20890. double samplesPerSecondForBuffer)
  20891. {
  20892. // You've got to call startBackgroundThread() for this to actually work..
  20893. jassert (isThreadRunning());
  20894. // this needs to be a value in the future - RTFM for this method!
  20895. jassert (millisecondCounterToStartAt > 0);
  20896. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20897. MidiBuffer::Iterator i (buffer);
  20898. const uint8* data;
  20899. int len, time;
  20900. while (i.getNextEvent (data, len, time))
  20901. {
  20902. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20903. PendingMessage* const m
  20904. = new PendingMessage (data, len, eventTime);
  20905. const ScopedLock sl (lock);
  20906. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20907. {
  20908. m->next = firstMessage;
  20909. firstMessage = m;
  20910. }
  20911. else
  20912. {
  20913. PendingMessage* mm = firstMessage;
  20914. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20915. mm = mm->next;
  20916. m->next = mm->next;
  20917. mm->next = m;
  20918. }
  20919. }
  20920. notify();
  20921. }
  20922. void MidiOutput::clearAllPendingMessages()
  20923. {
  20924. const ScopedLock sl (lock);
  20925. while (firstMessage != 0)
  20926. {
  20927. PendingMessage* const m = firstMessage;
  20928. firstMessage = firstMessage->next;
  20929. delete m;
  20930. }
  20931. }
  20932. void MidiOutput::startBackgroundThread()
  20933. {
  20934. startThread (9);
  20935. }
  20936. void MidiOutput::stopBackgroundThread()
  20937. {
  20938. stopThread (5000);
  20939. }
  20940. void MidiOutput::run()
  20941. {
  20942. while (! threadShouldExit())
  20943. {
  20944. uint32 now = Time::getMillisecondCounter();
  20945. uint32 eventTime = 0;
  20946. uint32 timeToWait = 500;
  20947. PendingMessage* message;
  20948. {
  20949. const ScopedLock sl (lock);
  20950. message = firstMessage;
  20951. if (message != 0)
  20952. {
  20953. eventTime = roundToInt (message->message.getTimeStamp());
  20954. if (eventTime > now + 20)
  20955. {
  20956. timeToWait = eventTime - (now + 20);
  20957. message = 0;
  20958. }
  20959. else
  20960. {
  20961. firstMessage = message->next;
  20962. }
  20963. }
  20964. }
  20965. if (message != 0)
  20966. {
  20967. if (eventTime > now)
  20968. {
  20969. Time::waitForMillisecondCounter (eventTime);
  20970. if (threadShouldExit())
  20971. break;
  20972. }
  20973. if (eventTime > now - 200)
  20974. sendMessageNow (message->message);
  20975. delete message;
  20976. }
  20977. else
  20978. {
  20979. jassert (timeToWait < 1000 * 30);
  20980. wait (timeToWait);
  20981. }
  20982. }
  20983. clearAllPendingMessages();
  20984. }
  20985. END_JUCE_NAMESPACE
  20986. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20987. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20988. BEGIN_JUCE_NAMESPACE
  20989. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20990. {
  20991. const double maxVal = (double) 0x7fff;
  20992. char* intData = static_cast <char*> (dest);
  20993. if (dest != (void*) source || destBytesPerSample <= 4)
  20994. {
  20995. for (int i = 0; i < numSamples; ++i)
  20996. {
  20997. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20998. intData += destBytesPerSample;
  20999. }
  21000. }
  21001. else
  21002. {
  21003. intData += destBytesPerSample * numSamples;
  21004. for (int i = numSamples; --i >= 0;)
  21005. {
  21006. intData -= destBytesPerSample;
  21007. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21008. }
  21009. }
  21010. }
  21011. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21012. {
  21013. const double maxVal = (double) 0x7fff;
  21014. char* intData = static_cast <char*> (dest);
  21015. if (dest != (void*) source || destBytesPerSample <= 4)
  21016. {
  21017. for (int i = 0; i < numSamples; ++i)
  21018. {
  21019. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21020. intData += destBytesPerSample;
  21021. }
  21022. }
  21023. else
  21024. {
  21025. intData += destBytesPerSample * numSamples;
  21026. for (int i = numSamples; --i >= 0;)
  21027. {
  21028. intData -= destBytesPerSample;
  21029. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21030. }
  21031. }
  21032. }
  21033. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21034. {
  21035. const double maxVal = (double) 0x7fffff;
  21036. char* intData = static_cast <char*> (dest);
  21037. if (dest != (void*) source || destBytesPerSample <= 4)
  21038. {
  21039. for (int i = 0; i < numSamples; ++i)
  21040. {
  21041. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21042. intData += destBytesPerSample;
  21043. }
  21044. }
  21045. else
  21046. {
  21047. intData += destBytesPerSample * numSamples;
  21048. for (int i = numSamples; --i >= 0;)
  21049. {
  21050. intData -= destBytesPerSample;
  21051. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21052. }
  21053. }
  21054. }
  21055. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21056. {
  21057. const double maxVal = (double) 0x7fffff;
  21058. char* intData = static_cast <char*> (dest);
  21059. if (dest != (void*) source || destBytesPerSample <= 4)
  21060. {
  21061. for (int i = 0; i < numSamples; ++i)
  21062. {
  21063. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21064. intData += destBytesPerSample;
  21065. }
  21066. }
  21067. else
  21068. {
  21069. intData += destBytesPerSample * numSamples;
  21070. for (int i = numSamples; --i >= 0;)
  21071. {
  21072. intData -= destBytesPerSample;
  21073. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21074. }
  21075. }
  21076. }
  21077. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21078. {
  21079. const double maxVal = (double) 0x7fffffff;
  21080. char* intData = static_cast <char*> (dest);
  21081. if (dest != (void*) source || destBytesPerSample <= 4)
  21082. {
  21083. for (int i = 0; i < numSamples; ++i)
  21084. {
  21085. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21086. intData += destBytesPerSample;
  21087. }
  21088. }
  21089. else
  21090. {
  21091. intData += destBytesPerSample * numSamples;
  21092. for (int i = numSamples; --i >= 0;)
  21093. {
  21094. intData -= destBytesPerSample;
  21095. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21096. }
  21097. }
  21098. }
  21099. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21100. {
  21101. const double maxVal = (double) 0x7fffffff;
  21102. char* intData = static_cast <char*> (dest);
  21103. if (dest != (void*) source || destBytesPerSample <= 4)
  21104. {
  21105. for (int i = 0; i < numSamples; ++i)
  21106. {
  21107. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21108. intData += destBytesPerSample;
  21109. }
  21110. }
  21111. else
  21112. {
  21113. intData += destBytesPerSample * numSamples;
  21114. for (int i = numSamples; --i >= 0;)
  21115. {
  21116. intData -= destBytesPerSample;
  21117. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21118. }
  21119. }
  21120. }
  21121. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21122. {
  21123. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21124. char* d = static_cast <char*> (dest);
  21125. for (int i = 0; i < numSamples; ++i)
  21126. {
  21127. *(float*) d = source[i];
  21128. #if JUCE_BIG_ENDIAN
  21129. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21130. #endif
  21131. d += destBytesPerSample;
  21132. }
  21133. }
  21134. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21135. {
  21136. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21137. char* d = static_cast <char*> (dest);
  21138. for (int i = 0; i < numSamples; ++i)
  21139. {
  21140. *(float*) d = source[i];
  21141. #if JUCE_LITTLE_ENDIAN
  21142. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21143. #endif
  21144. d += destBytesPerSample;
  21145. }
  21146. }
  21147. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21148. {
  21149. const float scale = 1.0f / 0x7fff;
  21150. const char* intData = static_cast <const char*> (source);
  21151. if (source != (void*) dest || srcBytesPerSample >= 4)
  21152. {
  21153. for (int i = 0; i < numSamples; ++i)
  21154. {
  21155. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21156. intData += srcBytesPerSample;
  21157. }
  21158. }
  21159. else
  21160. {
  21161. intData += srcBytesPerSample * numSamples;
  21162. for (int i = numSamples; --i >= 0;)
  21163. {
  21164. intData -= srcBytesPerSample;
  21165. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21166. }
  21167. }
  21168. }
  21169. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21170. {
  21171. const float scale = 1.0f / 0x7fff;
  21172. const char* intData = static_cast <const char*> (source);
  21173. if (source != (void*) dest || srcBytesPerSample >= 4)
  21174. {
  21175. for (int i = 0; i < numSamples; ++i)
  21176. {
  21177. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21178. intData += srcBytesPerSample;
  21179. }
  21180. }
  21181. else
  21182. {
  21183. intData += srcBytesPerSample * numSamples;
  21184. for (int i = numSamples; --i >= 0;)
  21185. {
  21186. intData -= srcBytesPerSample;
  21187. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21188. }
  21189. }
  21190. }
  21191. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21192. {
  21193. const float scale = 1.0f / 0x7fffff;
  21194. const char* intData = static_cast <const char*> (source);
  21195. if (source != (void*) dest || srcBytesPerSample >= 4)
  21196. {
  21197. for (int i = 0; i < numSamples; ++i)
  21198. {
  21199. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21200. intData += srcBytesPerSample;
  21201. }
  21202. }
  21203. else
  21204. {
  21205. intData += srcBytesPerSample * numSamples;
  21206. for (int i = numSamples; --i >= 0;)
  21207. {
  21208. intData -= srcBytesPerSample;
  21209. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21210. }
  21211. }
  21212. }
  21213. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21214. {
  21215. const float scale = 1.0f / 0x7fffff;
  21216. const char* intData = static_cast <const char*> (source);
  21217. if (source != (void*) dest || srcBytesPerSample >= 4)
  21218. {
  21219. for (int i = 0; i < numSamples; ++i)
  21220. {
  21221. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21222. intData += srcBytesPerSample;
  21223. }
  21224. }
  21225. else
  21226. {
  21227. intData += srcBytesPerSample * numSamples;
  21228. for (int i = numSamples; --i >= 0;)
  21229. {
  21230. intData -= srcBytesPerSample;
  21231. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21232. }
  21233. }
  21234. }
  21235. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21236. {
  21237. const float scale = 1.0f / 0x7fffffff;
  21238. const char* intData = static_cast <const char*> (source);
  21239. if (source != (void*) dest || srcBytesPerSample >= 4)
  21240. {
  21241. for (int i = 0; i < numSamples; ++i)
  21242. {
  21243. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21244. intData += srcBytesPerSample;
  21245. }
  21246. }
  21247. else
  21248. {
  21249. intData += srcBytesPerSample * numSamples;
  21250. for (int i = numSamples; --i >= 0;)
  21251. {
  21252. intData -= srcBytesPerSample;
  21253. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21254. }
  21255. }
  21256. }
  21257. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21258. {
  21259. const float scale = 1.0f / 0x7fffffff;
  21260. const char* intData = static_cast <const char*> (source);
  21261. if (source != (void*) dest || srcBytesPerSample >= 4)
  21262. {
  21263. for (int i = 0; i < numSamples; ++i)
  21264. {
  21265. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21266. intData += srcBytesPerSample;
  21267. }
  21268. }
  21269. else
  21270. {
  21271. intData += srcBytesPerSample * numSamples;
  21272. for (int i = numSamples; --i >= 0;)
  21273. {
  21274. intData -= srcBytesPerSample;
  21275. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21276. }
  21277. }
  21278. }
  21279. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21280. {
  21281. const char* s = static_cast <const char*> (source);
  21282. for (int i = 0; i < numSamples; ++i)
  21283. {
  21284. dest[i] = *(float*)s;
  21285. #if JUCE_BIG_ENDIAN
  21286. uint32* const d = (uint32*) (dest + i);
  21287. *d = ByteOrder::swap (*d);
  21288. #endif
  21289. s += srcBytesPerSample;
  21290. }
  21291. }
  21292. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21293. {
  21294. const char* s = static_cast <const char*> (source);
  21295. for (int i = 0; i < numSamples; ++i)
  21296. {
  21297. dest[i] = *(float*)s;
  21298. #if JUCE_LITTLE_ENDIAN
  21299. uint32* const d = (uint32*) (dest + i);
  21300. *d = ByteOrder::swap (*d);
  21301. #endif
  21302. s += srcBytesPerSample;
  21303. }
  21304. }
  21305. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21306. const float* const source,
  21307. void* const dest,
  21308. const int numSamples)
  21309. {
  21310. switch (destFormat)
  21311. {
  21312. case int16LE:
  21313. convertFloatToInt16LE (source, dest, numSamples);
  21314. break;
  21315. case int16BE:
  21316. convertFloatToInt16BE (source, dest, numSamples);
  21317. break;
  21318. case int24LE:
  21319. convertFloatToInt24LE (source, dest, numSamples);
  21320. break;
  21321. case int24BE:
  21322. convertFloatToInt24BE (source, dest, numSamples);
  21323. break;
  21324. case int32LE:
  21325. convertFloatToInt32LE (source, dest, numSamples);
  21326. break;
  21327. case int32BE:
  21328. convertFloatToInt32BE (source, dest, numSamples);
  21329. break;
  21330. case float32LE:
  21331. convertFloatToFloat32LE (source, dest, numSamples);
  21332. break;
  21333. case float32BE:
  21334. convertFloatToFloat32BE (source, dest, numSamples);
  21335. break;
  21336. default:
  21337. jassertfalse;
  21338. break;
  21339. }
  21340. }
  21341. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21342. const void* const source,
  21343. float* const dest,
  21344. const int numSamples)
  21345. {
  21346. switch (sourceFormat)
  21347. {
  21348. case int16LE:
  21349. convertInt16LEToFloat (source, dest, numSamples);
  21350. break;
  21351. case int16BE:
  21352. convertInt16BEToFloat (source, dest, numSamples);
  21353. break;
  21354. case int24LE:
  21355. convertInt24LEToFloat (source, dest, numSamples);
  21356. break;
  21357. case int24BE:
  21358. convertInt24BEToFloat (source, dest, numSamples);
  21359. break;
  21360. case int32LE:
  21361. convertInt32LEToFloat (source, dest, numSamples);
  21362. break;
  21363. case int32BE:
  21364. convertInt32BEToFloat (source, dest, numSamples);
  21365. break;
  21366. case float32LE:
  21367. convertFloat32LEToFloat (source, dest, numSamples);
  21368. break;
  21369. case float32BE:
  21370. convertFloat32BEToFloat (source, dest, numSamples);
  21371. break;
  21372. default:
  21373. jassertfalse;
  21374. break;
  21375. }
  21376. }
  21377. void AudioDataConverters::interleaveSamples (const float** const source,
  21378. float* const dest,
  21379. const int numSamples,
  21380. const int numChannels)
  21381. {
  21382. for (int chan = 0; chan < numChannels; ++chan)
  21383. {
  21384. int i = chan;
  21385. const float* src = source [chan];
  21386. for (int j = 0; j < numSamples; ++j)
  21387. {
  21388. dest [i] = src [j];
  21389. i += numChannels;
  21390. }
  21391. }
  21392. }
  21393. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21394. float** const dest,
  21395. const int numSamples,
  21396. const int numChannels)
  21397. {
  21398. for (int chan = 0; chan < numChannels; ++chan)
  21399. {
  21400. int i = chan;
  21401. float* dst = dest [chan];
  21402. for (int j = 0; j < numSamples; ++j)
  21403. {
  21404. dst [j] = source [i];
  21405. i += numChannels;
  21406. }
  21407. }
  21408. }
  21409. END_JUCE_NAMESPACE
  21410. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21411. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21412. BEGIN_JUCE_NAMESPACE
  21413. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21414. const int numSamples) throw()
  21415. : numChannels (numChannels_),
  21416. size (numSamples)
  21417. {
  21418. jassert (numSamples >= 0);
  21419. jassert (numChannels_ > 0);
  21420. allocateData();
  21421. }
  21422. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21423. : numChannels (other.numChannels),
  21424. size (other.size)
  21425. {
  21426. allocateData();
  21427. const size_t numBytes = size * sizeof (float);
  21428. for (int i = 0; i < numChannels; ++i)
  21429. memcpy (channels[i], other.channels[i], numBytes);
  21430. }
  21431. void AudioSampleBuffer::allocateData()
  21432. {
  21433. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21434. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21435. allocatedData.malloc (allocatedBytes);
  21436. channels = reinterpret_cast <float**> (allocatedData.getData());
  21437. float* chan = (float*) (allocatedData + channelListSize);
  21438. for (int i = 0; i < numChannels; ++i)
  21439. {
  21440. channels[i] = chan;
  21441. chan += size;
  21442. }
  21443. channels [numChannels] = 0;
  21444. }
  21445. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21446. const int numChannels_,
  21447. const int numSamples) throw()
  21448. : numChannels (numChannels_),
  21449. size (numSamples),
  21450. allocatedBytes (0)
  21451. {
  21452. jassert (numChannels_ > 0);
  21453. allocateChannels (dataToReferTo);
  21454. }
  21455. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21456. const int newNumChannels,
  21457. const int newNumSamples) throw()
  21458. {
  21459. jassert (newNumChannels > 0);
  21460. allocatedBytes = 0;
  21461. allocatedData.free();
  21462. numChannels = newNumChannels;
  21463. size = newNumSamples;
  21464. allocateChannels (dataToReferTo);
  21465. }
  21466. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21467. {
  21468. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21469. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21470. {
  21471. channels = static_cast <float**> (preallocatedChannelSpace);
  21472. }
  21473. else
  21474. {
  21475. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21476. channels = reinterpret_cast <float**> (allocatedData.getData());
  21477. }
  21478. for (int i = 0; i < numChannels; ++i)
  21479. {
  21480. // you have to pass in the same number of valid pointers as numChannels
  21481. jassert (dataToReferTo[i] != 0);
  21482. channels[i] = dataToReferTo[i];
  21483. }
  21484. channels [numChannels] = 0;
  21485. }
  21486. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21487. {
  21488. if (this != &other)
  21489. {
  21490. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21491. const size_t numBytes = size * sizeof (float);
  21492. for (int i = 0; i < numChannels; ++i)
  21493. memcpy (channels[i], other.channels[i], numBytes);
  21494. }
  21495. return *this;
  21496. }
  21497. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21498. {
  21499. }
  21500. void AudioSampleBuffer::setSize (const int newNumChannels,
  21501. const int newNumSamples,
  21502. const bool keepExistingContent,
  21503. const bool clearExtraSpace,
  21504. const bool avoidReallocating) throw()
  21505. {
  21506. jassert (newNumChannels > 0);
  21507. if (newNumSamples != size || newNumChannels != numChannels)
  21508. {
  21509. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21510. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21511. if (keepExistingContent)
  21512. {
  21513. HeapBlock <char> newData;
  21514. newData.allocate (newTotalBytes, clearExtraSpace);
  21515. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21516. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21517. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21518. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21519. for (int i = 0; i < numChansToCopy; ++i)
  21520. {
  21521. memcpy (newChan, channels[i], numBytesToCopy);
  21522. newChannels[i] = newChan;
  21523. newChan += newNumSamples;
  21524. }
  21525. allocatedData.swapWith (newData);
  21526. allocatedBytes = (int) newTotalBytes;
  21527. channels = newChannels;
  21528. }
  21529. else
  21530. {
  21531. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21532. {
  21533. if (clearExtraSpace)
  21534. zeromem (allocatedData, newTotalBytes);
  21535. }
  21536. else
  21537. {
  21538. allocatedBytes = newTotalBytes;
  21539. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21540. channels = reinterpret_cast <float**> (allocatedData.getData());
  21541. }
  21542. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21543. for (int i = 0; i < newNumChannels; ++i)
  21544. {
  21545. channels[i] = chan;
  21546. chan += newNumSamples;
  21547. }
  21548. }
  21549. channels [newNumChannels] = 0;
  21550. size = newNumSamples;
  21551. numChannels = newNumChannels;
  21552. }
  21553. }
  21554. void AudioSampleBuffer::clear() throw()
  21555. {
  21556. for (int i = 0; i < numChannels; ++i)
  21557. zeromem (channels[i], size * sizeof (float));
  21558. }
  21559. void AudioSampleBuffer::clear (const int startSample,
  21560. const int numSamples) throw()
  21561. {
  21562. jassert (startSample >= 0 && startSample + numSamples <= size);
  21563. for (int i = 0; i < numChannels; ++i)
  21564. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21565. }
  21566. void AudioSampleBuffer::clear (const int channel,
  21567. const int startSample,
  21568. const int numSamples) throw()
  21569. {
  21570. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21571. jassert (startSample >= 0 && startSample + numSamples <= size);
  21572. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21573. }
  21574. void AudioSampleBuffer::applyGain (const int channel,
  21575. const int startSample,
  21576. int numSamples,
  21577. const float gain) throw()
  21578. {
  21579. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21580. jassert (startSample >= 0 && startSample + numSamples <= size);
  21581. if (gain != 1.0f)
  21582. {
  21583. float* d = channels [channel] + startSample;
  21584. if (gain == 0.0f)
  21585. {
  21586. zeromem (d, sizeof (float) * numSamples);
  21587. }
  21588. else
  21589. {
  21590. while (--numSamples >= 0)
  21591. *d++ *= gain;
  21592. }
  21593. }
  21594. }
  21595. void AudioSampleBuffer::applyGainRamp (const int channel,
  21596. const int startSample,
  21597. int numSamples,
  21598. float startGain,
  21599. float endGain) throw()
  21600. {
  21601. if (startGain == endGain)
  21602. {
  21603. applyGain (channel, startSample, numSamples, startGain);
  21604. }
  21605. else
  21606. {
  21607. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21608. jassert (startSample >= 0 && startSample + numSamples <= size);
  21609. const float increment = (endGain - startGain) / numSamples;
  21610. float* d = channels [channel] + startSample;
  21611. while (--numSamples >= 0)
  21612. {
  21613. *d++ *= startGain;
  21614. startGain += increment;
  21615. }
  21616. }
  21617. }
  21618. void AudioSampleBuffer::applyGain (const int startSample,
  21619. const int numSamples,
  21620. const float gain) throw()
  21621. {
  21622. for (int i = 0; i < numChannels; ++i)
  21623. applyGain (i, startSample, numSamples, gain);
  21624. }
  21625. void AudioSampleBuffer::addFrom (const int destChannel,
  21626. const int destStartSample,
  21627. const AudioSampleBuffer& source,
  21628. const int sourceChannel,
  21629. const int sourceStartSample,
  21630. int numSamples,
  21631. const float gain) throw()
  21632. {
  21633. jassert (&source != this || sourceChannel != destChannel);
  21634. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21635. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21636. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21637. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21638. if (gain != 0.0f && numSamples > 0)
  21639. {
  21640. float* d = channels [destChannel] + destStartSample;
  21641. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21642. if (gain != 1.0f)
  21643. {
  21644. while (--numSamples >= 0)
  21645. *d++ += gain * *s++;
  21646. }
  21647. else
  21648. {
  21649. while (--numSamples >= 0)
  21650. *d++ += *s++;
  21651. }
  21652. }
  21653. }
  21654. void AudioSampleBuffer::addFrom (const int destChannel,
  21655. const int destStartSample,
  21656. const float* source,
  21657. int numSamples,
  21658. const float gain) throw()
  21659. {
  21660. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21661. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21662. jassert (source != 0);
  21663. if (gain != 0.0f && numSamples > 0)
  21664. {
  21665. float* d = channels [destChannel] + destStartSample;
  21666. if (gain != 1.0f)
  21667. {
  21668. while (--numSamples >= 0)
  21669. *d++ += gain * *source++;
  21670. }
  21671. else
  21672. {
  21673. while (--numSamples >= 0)
  21674. *d++ += *source++;
  21675. }
  21676. }
  21677. }
  21678. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21679. const int destStartSample,
  21680. const float* source,
  21681. int numSamples,
  21682. float startGain,
  21683. const float endGain) throw()
  21684. {
  21685. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21686. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21687. jassert (source != 0);
  21688. if (startGain == endGain)
  21689. {
  21690. addFrom (destChannel,
  21691. destStartSample,
  21692. source,
  21693. numSamples,
  21694. startGain);
  21695. }
  21696. else
  21697. {
  21698. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21699. {
  21700. const float increment = (endGain - startGain) / numSamples;
  21701. float* d = channels [destChannel] + destStartSample;
  21702. while (--numSamples >= 0)
  21703. {
  21704. *d++ += startGain * *source++;
  21705. startGain += increment;
  21706. }
  21707. }
  21708. }
  21709. }
  21710. void AudioSampleBuffer::copyFrom (const int destChannel,
  21711. const int destStartSample,
  21712. const AudioSampleBuffer& source,
  21713. const int sourceChannel,
  21714. const int sourceStartSample,
  21715. int numSamples) throw()
  21716. {
  21717. jassert (&source != this || sourceChannel != destChannel);
  21718. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21719. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21720. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21721. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21722. if (numSamples > 0)
  21723. {
  21724. memcpy (channels [destChannel] + destStartSample,
  21725. source.channels [sourceChannel] + sourceStartSample,
  21726. sizeof (float) * numSamples);
  21727. }
  21728. }
  21729. void AudioSampleBuffer::copyFrom (const int destChannel,
  21730. const int destStartSample,
  21731. const float* source,
  21732. int numSamples) throw()
  21733. {
  21734. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21735. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21736. jassert (source != 0);
  21737. if (numSamples > 0)
  21738. {
  21739. memcpy (channels [destChannel] + destStartSample,
  21740. source,
  21741. sizeof (float) * numSamples);
  21742. }
  21743. }
  21744. void AudioSampleBuffer::copyFrom (const int destChannel,
  21745. const int destStartSample,
  21746. const float* source,
  21747. int numSamples,
  21748. const float gain) throw()
  21749. {
  21750. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21751. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21752. jassert (source != 0);
  21753. if (numSamples > 0)
  21754. {
  21755. float* d = channels [destChannel] + destStartSample;
  21756. if (gain != 1.0f)
  21757. {
  21758. if (gain == 0)
  21759. {
  21760. zeromem (d, sizeof (float) * numSamples);
  21761. }
  21762. else
  21763. {
  21764. while (--numSamples >= 0)
  21765. *d++ = gain * *source++;
  21766. }
  21767. }
  21768. else
  21769. {
  21770. memcpy (d, source, sizeof (float) * numSamples);
  21771. }
  21772. }
  21773. }
  21774. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21775. const int destStartSample,
  21776. const float* source,
  21777. int numSamples,
  21778. float startGain,
  21779. float endGain) throw()
  21780. {
  21781. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21782. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21783. jassert (source != 0);
  21784. if (startGain == endGain)
  21785. {
  21786. copyFrom (destChannel,
  21787. destStartSample,
  21788. source,
  21789. numSamples,
  21790. startGain);
  21791. }
  21792. else
  21793. {
  21794. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21795. {
  21796. const float increment = (endGain - startGain) / numSamples;
  21797. float* d = channels [destChannel] + destStartSample;
  21798. while (--numSamples >= 0)
  21799. {
  21800. *d++ = startGain * *source++;
  21801. startGain += increment;
  21802. }
  21803. }
  21804. }
  21805. }
  21806. void AudioSampleBuffer::findMinMax (const int channel,
  21807. const int startSample,
  21808. int numSamples,
  21809. float& minVal,
  21810. float& maxVal) const throw()
  21811. {
  21812. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21813. jassert (startSample >= 0 && startSample + numSamples <= size);
  21814. if (numSamples <= 0)
  21815. {
  21816. minVal = 0.0f;
  21817. maxVal = 0.0f;
  21818. }
  21819. else
  21820. {
  21821. const float* d = channels [channel] + startSample;
  21822. float mn = *d++;
  21823. float mx = mn;
  21824. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21825. {
  21826. const float samp = *d++;
  21827. if (samp > mx)
  21828. mx = samp;
  21829. if (samp < mn)
  21830. mn = samp;
  21831. }
  21832. maxVal = mx;
  21833. minVal = mn;
  21834. }
  21835. }
  21836. float AudioSampleBuffer::getMagnitude (const int channel,
  21837. const int startSample,
  21838. const int numSamples) const throw()
  21839. {
  21840. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21841. jassert (startSample >= 0 && startSample + numSamples <= size);
  21842. float mn, mx;
  21843. findMinMax (channel, startSample, numSamples, mn, mx);
  21844. return jmax (mn, -mn, mx, -mx);
  21845. }
  21846. float AudioSampleBuffer::getMagnitude (const int startSample,
  21847. const int numSamples) const throw()
  21848. {
  21849. float mag = 0.0f;
  21850. for (int i = 0; i < numChannels; ++i)
  21851. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21852. return mag;
  21853. }
  21854. float AudioSampleBuffer::getRMSLevel (const int channel,
  21855. const int startSample,
  21856. const int numSamples) const throw()
  21857. {
  21858. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21859. jassert (startSample >= 0 && startSample + numSamples <= size);
  21860. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21861. return 0.0f;
  21862. const float* const data = channels [channel] + startSample;
  21863. double sum = 0.0;
  21864. for (int i = 0; i < numSamples; ++i)
  21865. {
  21866. const float sample = data [i];
  21867. sum += sample * sample;
  21868. }
  21869. return (float) std::sqrt (sum / numSamples);
  21870. }
  21871. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21872. const int startSample,
  21873. const int numSamples,
  21874. const int readerStartSample,
  21875. const bool useLeftChan,
  21876. const bool useRightChan)
  21877. {
  21878. jassert (reader != 0);
  21879. jassert (startSample >= 0 && startSample + numSamples <= size);
  21880. if (numSamples > 0)
  21881. {
  21882. int* chans[3];
  21883. if (useLeftChan == useRightChan)
  21884. {
  21885. chans[0] = (int*) getSampleData (0, startSample);
  21886. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21887. }
  21888. else if (useLeftChan || (reader->numChannels == 1))
  21889. {
  21890. chans[0] = (int*) getSampleData (0, startSample);
  21891. chans[1] = 0;
  21892. }
  21893. else if (useRightChan)
  21894. {
  21895. chans[0] = 0;
  21896. chans[1] = (int*) getSampleData (0, startSample);
  21897. }
  21898. chans[2] = 0;
  21899. reader->read (chans, 2, readerStartSample, numSamples, true);
  21900. if (! reader->usesFloatingPointData)
  21901. {
  21902. for (int j = 0; j < 2; ++j)
  21903. {
  21904. float* const d = reinterpret_cast <float*> (chans[j]);
  21905. if (d != 0)
  21906. {
  21907. const float multiplier = 1.0f / 0x7fffffff;
  21908. for (int i = 0; i < numSamples; ++i)
  21909. d[i] = *(int*)(d + i) * multiplier;
  21910. }
  21911. }
  21912. }
  21913. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21914. {
  21915. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21916. memcpy (getSampleData (1, startSample),
  21917. getSampleData (0, startSample),
  21918. sizeof (float) * numSamples);
  21919. }
  21920. }
  21921. }
  21922. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21923. const int startSample,
  21924. const int numSamples) const
  21925. {
  21926. jassert (startSample >= 0 && startSample + numSamples <= size && numChannels > 0);
  21927. if (numSamples > 0)
  21928. {
  21929. HeapBlock<int> tempBuffer;
  21930. HeapBlock<int*> chans (numChannels + 1);
  21931. chans [numChannels] = 0;
  21932. if (writer->isFloatingPoint())
  21933. {
  21934. for (int i = numChannels; --i >= 0;)
  21935. chans[i] = (int*) channels[i] + startSample;
  21936. }
  21937. else
  21938. {
  21939. tempBuffer.malloc (numSamples * numChannels);
  21940. for (int j = 0; j < numChannels; ++j)
  21941. {
  21942. int* const dest = tempBuffer + j * numSamples;
  21943. const float* const src = channels[j] + startSample;
  21944. chans[j] = dest;
  21945. for (int i = 0; i < numSamples; ++i)
  21946. {
  21947. const double samp = src[i];
  21948. if (samp <= -1.0)
  21949. dest[i] = std::numeric_limits<int>::min();
  21950. else if (samp >= 1.0)
  21951. dest[i] = std::numeric_limits<int>::max();
  21952. else
  21953. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21954. }
  21955. }
  21956. }
  21957. writer->write ((const int**) chans.getData(), numSamples);
  21958. }
  21959. }
  21960. END_JUCE_NAMESPACE
  21961. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21962. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21963. BEGIN_JUCE_NAMESPACE
  21964. IIRFilter::IIRFilter()
  21965. : active (false)
  21966. {
  21967. reset();
  21968. }
  21969. IIRFilter::IIRFilter (const IIRFilter& other)
  21970. : active (other.active)
  21971. {
  21972. const ScopedLock sl (other.processLock);
  21973. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21974. reset();
  21975. }
  21976. IIRFilter::~IIRFilter()
  21977. {
  21978. }
  21979. void IIRFilter::reset() throw()
  21980. {
  21981. const ScopedLock sl (processLock);
  21982. x1 = 0;
  21983. x2 = 0;
  21984. y1 = 0;
  21985. y2 = 0;
  21986. }
  21987. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21988. {
  21989. float out = coefficients[0] * in
  21990. + coefficients[1] * x1
  21991. + coefficients[2] * x2
  21992. - coefficients[4] * y1
  21993. - coefficients[5] * y2;
  21994. #if JUCE_INTEL
  21995. if (! (out < -1.0e-8 || out > 1.0e-8))
  21996. out = 0;
  21997. #endif
  21998. x2 = x1;
  21999. x1 = in;
  22000. y2 = y1;
  22001. y1 = out;
  22002. return out;
  22003. }
  22004. void IIRFilter::processSamples (float* const samples,
  22005. const int numSamples) throw()
  22006. {
  22007. const ScopedLock sl (processLock);
  22008. if (active)
  22009. {
  22010. for (int i = 0; i < numSamples; ++i)
  22011. {
  22012. const float in = samples[i];
  22013. float out = coefficients[0] * in
  22014. + coefficients[1] * x1
  22015. + coefficients[2] * x2
  22016. - coefficients[4] * y1
  22017. - coefficients[5] * y2;
  22018. #if JUCE_INTEL
  22019. if (! (out < -1.0e-8 || out > 1.0e-8))
  22020. out = 0;
  22021. #endif
  22022. x2 = x1;
  22023. x1 = in;
  22024. y2 = y1;
  22025. y1 = out;
  22026. samples[i] = out;
  22027. }
  22028. }
  22029. }
  22030. void IIRFilter::makeLowPass (const double sampleRate,
  22031. const double frequency) throw()
  22032. {
  22033. jassert (sampleRate > 0);
  22034. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22035. const double nSquared = n * n;
  22036. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22037. setCoefficients (c1,
  22038. c1 * 2.0f,
  22039. c1,
  22040. 1.0,
  22041. c1 * 2.0 * (1.0 - nSquared),
  22042. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22043. }
  22044. void IIRFilter::makeHighPass (const double sampleRate,
  22045. const double frequency) throw()
  22046. {
  22047. const double n = tan (double_Pi * frequency / sampleRate);
  22048. const double nSquared = n * n;
  22049. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22050. setCoefficients (c1,
  22051. c1 * -2.0f,
  22052. c1,
  22053. 1.0,
  22054. c1 * 2.0 * (nSquared - 1.0),
  22055. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22056. }
  22057. void IIRFilter::makeLowShelf (const double sampleRate,
  22058. const double cutOffFrequency,
  22059. const double Q,
  22060. const float gainFactor) throw()
  22061. {
  22062. jassert (sampleRate > 0);
  22063. jassert (Q > 0);
  22064. const double A = jmax (0.0f, gainFactor);
  22065. const double aminus1 = A - 1.0;
  22066. const double aplus1 = A + 1.0;
  22067. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22068. const double coso = std::cos (omega);
  22069. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22070. const double aminus1TimesCoso = aminus1 * coso;
  22071. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22072. A * 2.0 * (aminus1 - aplus1 * coso),
  22073. A * (aplus1 - aminus1TimesCoso - beta),
  22074. aplus1 + aminus1TimesCoso + beta,
  22075. -2.0 * (aminus1 + aplus1 * coso),
  22076. aplus1 + aminus1TimesCoso - beta);
  22077. }
  22078. void IIRFilter::makeHighShelf (const double sampleRate,
  22079. const double cutOffFrequency,
  22080. const double Q,
  22081. const float gainFactor) throw()
  22082. {
  22083. jassert (sampleRate > 0);
  22084. jassert (Q > 0);
  22085. const double A = jmax (0.0f, gainFactor);
  22086. const double aminus1 = A - 1.0;
  22087. const double aplus1 = A + 1.0;
  22088. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22089. const double coso = std::cos (omega);
  22090. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22091. const double aminus1TimesCoso = aminus1 * coso;
  22092. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22093. A * -2.0 * (aminus1 + aplus1 * coso),
  22094. A * (aplus1 + aminus1TimesCoso - beta),
  22095. aplus1 - aminus1TimesCoso + beta,
  22096. 2.0 * (aminus1 - aplus1 * coso),
  22097. aplus1 - aminus1TimesCoso - beta);
  22098. }
  22099. void IIRFilter::makeBandPass (const double sampleRate,
  22100. const double centreFrequency,
  22101. const double Q,
  22102. const float gainFactor) throw()
  22103. {
  22104. jassert (sampleRate > 0);
  22105. jassert (Q > 0);
  22106. const double A = jmax (0.0f, gainFactor);
  22107. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22108. const double alpha = 0.5 * std::sin (omega) / Q;
  22109. const double c2 = -2.0 * std::cos (omega);
  22110. const double alphaTimesA = alpha * A;
  22111. const double alphaOverA = alpha / A;
  22112. setCoefficients (1.0 + alphaTimesA,
  22113. c2,
  22114. 1.0 - alphaTimesA,
  22115. 1.0 + alphaOverA,
  22116. c2,
  22117. 1.0 - alphaOverA);
  22118. }
  22119. void IIRFilter::makeInactive() throw()
  22120. {
  22121. const ScopedLock sl (processLock);
  22122. active = false;
  22123. }
  22124. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22125. {
  22126. const ScopedLock sl (processLock);
  22127. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22128. active = other.active;
  22129. }
  22130. void IIRFilter::setCoefficients (double c1,
  22131. double c2,
  22132. double c3,
  22133. double c4,
  22134. double c5,
  22135. double c6) throw()
  22136. {
  22137. const double a = 1.0 / c4;
  22138. c1 *= a;
  22139. c2 *= a;
  22140. c3 *= a;
  22141. c5 *= a;
  22142. c6 *= a;
  22143. const ScopedLock sl (processLock);
  22144. coefficients[0] = (float) c1;
  22145. coefficients[1] = (float) c2;
  22146. coefficients[2] = (float) c3;
  22147. coefficients[3] = (float) c4;
  22148. coefficients[4] = (float) c5;
  22149. coefficients[5] = (float) c6;
  22150. active = true;
  22151. }
  22152. END_JUCE_NAMESPACE
  22153. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22154. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22155. BEGIN_JUCE_NAMESPACE
  22156. MidiBuffer::MidiBuffer() throw()
  22157. : bytesUsed (0)
  22158. {
  22159. }
  22160. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22161. : bytesUsed (0)
  22162. {
  22163. addEvent (message, 0);
  22164. }
  22165. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22166. : data (other.data),
  22167. bytesUsed (other.bytesUsed)
  22168. {
  22169. }
  22170. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22171. {
  22172. bytesUsed = other.bytesUsed;
  22173. data = other.data;
  22174. return *this;
  22175. }
  22176. void MidiBuffer::swapWith (MidiBuffer& other)
  22177. {
  22178. data.swapWith (other.data);
  22179. swapVariables <int> (bytesUsed, other.bytesUsed);
  22180. }
  22181. MidiBuffer::~MidiBuffer()
  22182. {
  22183. }
  22184. inline uint8* MidiBuffer::getData() const throw()
  22185. {
  22186. return static_cast <uint8*> (data.getData());
  22187. }
  22188. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22189. {
  22190. return *static_cast <const int*> (d);
  22191. }
  22192. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22193. {
  22194. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22195. }
  22196. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22197. {
  22198. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22199. }
  22200. void MidiBuffer::clear() throw()
  22201. {
  22202. bytesUsed = 0;
  22203. }
  22204. void MidiBuffer::clear (const int startSample, const int numSamples)
  22205. {
  22206. uint8* const start = findEventAfter (getData(), startSample - 1);
  22207. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22208. if (end > start)
  22209. {
  22210. const int bytesToMove = bytesUsed - (int) (end - getData());
  22211. if (bytesToMove > 0)
  22212. memmove (start, end, bytesToMove);
  22213. bytesUsed -= (int) (end - start);
  22214. }
  22215. }
  22216. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22217. {
  22218. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22219. }
  22220. static int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22221. {
  22222. unsigned int byte = (unsigned int) *data;
  22223. int size = 0;
  22224. if (byte == 0xf0 || byte == 0xf7)
  22225. {
  22226. const uint8* d = data + 1;
  22227. while (d < data + maxBytes)
  22228. if (*d++ == 0xf7)
  22229. break;
  22230. size = (int) (d - data);
  22231. }
  22232. else if (byte == 0xff)
  22233. {
  22234. int n;
  22235. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22236. size = jmin (maxBytes, n + 2 + bytesLeft);
  22237. }
  22238. else if (byte >= 0x80)
  22239. {
  22240. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22241. }
  22242. return size;
  22243. }
  22244. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22245. {
  22246. const int numBytes = findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22247. if (numBytes > 0)
  22248. {
  22249. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22250. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22251. uint8* d = findEventAfter (getData(), sampleNumber);
  22252. const int bytesToMove = bytesUsed - (int) (d - getData());
  22253. if (bytesToMove > 0)
  22254. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22255. *reinterpret_cast <int*> (d) = sampleNumber;
  22256. d += sizeof (int);
  22257. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22258. d += sizeof (uint16);
  22259. memcpy (d, newData, numBytes);
  22260. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22261. }
  22262. }
  22263. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22264. const int startSample,
  22265. const int numSamples,
  22266. const int sampleDeltaToAdd)
  22267. {
  22268. Iterator i (otherBuffer);
  22269. i.setNextSamplePosition (startSample);
  22270. const uint8* eventData;
  22271. int eventSize, position;
  22272. while (i.getNextEvent (eventData, eventSize, position)
  22273. && (position < startSample + numSamples || numSamples < 0))
  22274. {
  22275. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22276. }
  22277. }
  22278. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22279. {
  22280. data.ensureSize (minimumNumBytes);
  22281. }
  22282. bool MidiBuffer::isEmpty() const throw()
  22283. {
  22284. return bytesUsed == 0;
  22285. }
  22286. int MidiBuffer::getNumEvents() const throw()
  22287. {
  22288. int n = 0;
  22289. const uint8* d = getData();
  22290. const uint8* const end = d + bytesUsed;
  22291. while (d < end)
  22292. {
  22293. d += getEventTotalSize (d);
  22294. ++n;
  22295. }
  22296. return n;
  22297. }
  22298. int MidiBuffer::getFirstEventTime() const throw()
  22299. {
  22300. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22301. }
  22302. int MidiBuffer::getLastEventTime() const throw()
  22303. {
  22304. if (bytesUsed == 0)
  22305. return 0;
  22306. const uint8* d = getData();
  22307. const uint8* const endData = d + bytesUsed;
  22308. for (;;)
  22309. {
  22310. const uint8* const nextOne = d + getEventTotalSize (d);
  22311. if (nextOne >= endData)
  22312. return getEventTime (d);
  22313. d = nextOne;
  22314. }
  22315. }
  22316. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22317. {
  22318. const uint8* const endData = getData() + bytesUsed;
  22319. while (d < endData && getEventTime (d) <= samplePosition)
  22320. d += getEventTotalSize (d);
  22321. return d;
  22322. }
  22323. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22324. : buffer (buffer_),
  22325. data (buffer_.getData())
  22326. {
  22327. }
  22328. MidiBuffer::Iterator::~Iterator() throw()
  22329. {
  22330. }
  22331. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22332. {
  22333. data = buffer.getData();
  22334. const uint8* dataEnd = data + buffer.bytesUsed;
  22335. while (data < dataEnd && getEventTime (data) < samplePosition)
  22336. data += getEventTotalSize (data);
  22337. }
  22338. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22339. {
  22340. if (data >= buffer.getData() + buffer.bytesUsed)
  22341. return false;
  22342. samplePosition = getEventTime (data);
  22343. numBytes = getEventDataSize (data);
  22344. data += sizeof (int) + sizeof (uint16);
  22345. midiData = data;
  22346. data += numBytes;
  22347. return true;
  22348. }
  22349. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22350. {
  22351. if (data >= buffer.getData() + buffer.bytesUsed)
  22352. return false;
  22353. samplePosition = getEventTime (data);
  22354. const int numBytes = getEventDataSize (data);
  22355. data += sizeof (int) + sizeof (uint16);
  22356. result = MidiMessage (data, numBytes, samplePosition);
  22357. data += numBytes;
  22358. return true;
  22359. }
  22360. END_JUCE_NAMESPACE
  22361. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22362. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22363. BEGIN_JUCE_NAMESPACE
  22364. namespace MidiFileHelpers
  22365. {
  22366. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22367. {
  22368. unsigned int buffer = v & 0x7F;
  22369. while ((v >>= 7) != 0)
  22370. {
  22371. buffer <<= 8;
  22372. buffer |= ((v & 0x7F) | 0x80);
  22373. }
  22374. for (;;)
  22375. {
  22376. out.writeByte ((char) buffer);
  22377. if (buffer & 0x80)
  22378. buffer >>= 8;
  22379. else
  22380. break;
  22381. }
  22382. }
  22383. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22384. {
  22385. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22386. data += 4;
  22387. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22388. {
  22389. bool ok = false;
  22390. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22391. {
  22392. for (int i = 0; i < 8; ++i)
  22393. {
  22394. ch = ByteOrder::bigEndianInt (data);
  22395. data += 4;
  22396. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22397. {
  22398. ok = true;
  22399. break;
  22400. }
  22401. }
  22402. }
  22403. if (! ok)
  22404. return false;
  22405. }
  22406. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22407. data += 4;
  22408. fileType = (short) ByteOrder::bigEndianShort (data);
  22409. data += 2;
  22410. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22411. data += 2;
  22412. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22413. data += 2;
  22414. bytesRemaining -= 6;
  22415. data += bytesRemaining;
  22416. return true;
  22417. }
  22418. static double convertTicksToSeconds (const double time,
  22419. const MidiMessageSequence& tempoEvents,
  22420. const int timeFormat)
  22421. {
  22422. if (timeFormat > 0)
  22423. {
  22424. int numer = 4, denom = 4;
  22425. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22426. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22427. double secsPerTick = 0.5 * tickLen;
  22428. const int numEvents = tempoEvents.getNumEvents();
  22429. for (int i = 0; i < numEvents; ++i)
  22430. {
  22431. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22432. if (time <= m.getTimeStamp())
  22433. break;
  22434. if (timeFormat > 0)
  22435. {
  22436. correctedTempoTime = correctedTempoTime
  22437. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22438. }
  22439. else
  22440. {
  22441. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22442. }
  22443. tempoTime = m.getTimeStamp();
  22444. if (m.isTempoMetaEvent())
  22445. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22446. else if (m.isTimeSignatureMetaEvent())
  22447. m.getTimeSignatureInfo (numer, denom);
  22448. while (i + 1 < numEvents)
  22449. {
  22450. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22451. if (m2.getTimeStamp() == tempoTime)
  22452. {
  22453. ++i;
  22454. if (m2.isTempoMetaEvent())
  22455. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22456. else if (m2.isTimeSignatureMetaEvent())
  22457. m2.getTimeSignatureInfo (numer, denom);
  22458. }
  22459. else
  22460. {
  22461. break;
  22462. }
  22463. }
  22464. }
  22465. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22466. }
  22467. else
  22468. {
  22469. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22470. }
  22471. }
  22472. // a comparator that puts all the note-offs before note-ons that have the same time
  22473. struct Sorter
  22474. {
  22475. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22476. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22477. {
  22478. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22479. if (diff == 0)
  22480. {
  22481. if (first->message.isNoteOff() && second->message.isNoteOn())
  22482. return -1;
  22483. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22484. return 1;
  22485. else
  22486. return 0;
  22487. }
  22488. else
  22489. {
  22490. return (diff > 0) ? 1 : -1;
  22491. }
  22492. }
  22493. };
  22494. }
  22495. MidiFile::MidiFile()
  22496. : timeFormat ((short) (unsigned short) 0xe728)
  22497. {
  22498. }
  22499. MidiFile::~MidiFile()
  22500. {
  22501. clear();
  22502. }
  22503. void MidiFile::clear()
  22504. {
  22505. tracks.clear();
  22506. }
  22507. int MidiFile::getNumTracks() const throw()
  22508. {
  22509. return tracks.size();
  22510. }
  22511. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22512. {
  22513. return tracks [index];
  22514. }
  22515. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22516. {
  22517. tracks.add (new MidiMessageSequence (trackSequence));
  22518. }
  22519. short MidiFile::getTimeFormat() const throw()
  22520. {
  22521. return timeFormat;
  22522. }
  22523. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22524. {
  22525. timeFormat = (short) ticks;
  22526. }
  22527. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22528. const int subframeResolution) throw()
  22529. {
  22530. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22531. }
  22532. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22533. {
  22534. for (int i = tracks.size(); --i >= 0;)
  22535. {
  22536. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22537. for (int j = 0; j < numEvents; ++j)
  22538. {
  22539. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22540. if (m.isTempoMetaEvent())
  22541. tempoChangeEvents.addEvent (m);
  22542. }
  22543. }
  22544. }
  22545. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22546. {
  22547. for (int i = tracks.size(); --i >= 0;)
  22548. {
  22549. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22550. for (int j = 0; j < numEvents; ++j)
  22551. {
  22552. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22553. if (m.isTimeSignatureMetaEvent())
  22554. timeSigEvents.addEvent (m);
  22555. }
  22556. }
  22557. }
  22558. double MidiFile::getLastTimestamp() const
  22559. {
  22560. double t = 0.0;
  22561. for (int i = tracks.size(); --i >= 0;)
  22562. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22563. return t;
  22564. }
  22565. bool MidiFile::readFrom (InputStream& sourceStream)
  22566. {
  22567. clear();
  22568. MemoryBlock data;
  22569. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22570. // (put a sanity-check on the file size, as midi files are generally small)
  22571. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22572. {
  22573. size_t size = data.getSize();
  22574. const uint8* d = static_cast <const uint8*> (data.getData());
  22575. short fileType, expectedTracks;
  22576. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22577. {
  22578. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22579. int track = 0;
  22580. while (size > 0 && track < expectedTracks)
  22581. {
  22582. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22583. d += 4;
  22584. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22585. d += 4;
  22586. if (chunkSize <= 0)
  22587. break;
  22588. if (size < 0)
  22589. return false;
  22590. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22591. {
  22592. readNextTrack (d, chunkSize);
  22593. }
  22594. size -= chunkSize + 8;
  22595. d += chunkSize;
  22596. ++track;
  22597. }
  22598. return true;
  22599. }
  22600. }
  22601. return false;
  22602. }
  22603. void MidiFile::readNextTrack (const uint8* data, int size)
  22604. {
  22605. double time = 0;
  22606. char lastStatusByte = 0;
  22607. MidiMessageSequence result;
  22608. while (size > 0)
  22609. {
  22610. int bytesUsed;
  22611. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22612. data += bytesUsed;
  22613. size -= bytesUsed;
  22614. time += delay;
  22615. int messSize = 0;
  22616. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22617. if (messSize <= 0)
  22618. break;
  22619. size -= messSize;
  22620. data += messSize;
  22621. result.addEvent (mm);
  22622. const char firstByte = *(mm.getRawData());
  22623. if ((firstByte & 0xf0) != 0xf0)
  22624. lastStatusByte = firstByte;
  22625. }
  22626. // use a sort that puts all the note-offs before note-ons that have the same time
  22627. MidiFileHelpers::Sorter sorter;
  22628. result.list.sort (sorter, true);
  22629. result.updateMatchedPairs();
  22630. addTrack (result);
  22631. }
  22632. void MidiFile::convertTimestampTicksToSeconds()
  22633. {
  22634. MidiMessageSequence tempoEvents;
  22635. findAllTempoEvents (tempoEvents);
  22636. findAllTimeSigEvents (tempoEvents);
  22637. for (int i = 0; i < tracks.size(); ++i)
  22638. {
  22639. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22640. for (int j = ms.getNumEvents(); --j >= 0;)
  22641. {
  22642. MidiMessage& m = ms.getEventPointer(j)->message;
  22643. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22644. tempoEvents,
  22645. timeFormat));
  22646. }
  22647. }
  22648. }
  22649. bool MidiFile::writeTo (OutputStream& out)
  22650. {
  22651. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22652. out.writeIntBigEndian (6);
  22653. out.writeShortBigEndian (1); // type
  22654. out.writeShortBigEndian ((short) tracks.size());
  22655. out.writeShortBigEndian (timeFormat);
  22656. for (int i = 0; i < tracks.size(); ++i)
  22657. writeTrack (out, i);
  22658. out.flush();
  22659. return true;
  22660. }
  22661. void MidiFile::writeTrack (OutputStream& mainOut,
  22662. const int trackNum)
  22663. {
  22664. MemoryOutputStream out;
  22665. const MidiMessageSequence& ms = *tracks[trackNum];
  22666. int lastTick = 0;
  22667. char lastStatusByte = 0;
  22668. for (int i = 0; i < ms.getNumEvents(); ++i)
  22669. {
  22670. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22671. const int tick = roundToInt (mm.getTimeStamp());
  22672. const int delta = jmax (0, tick - lastTick);
  22673. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22674. lastTick = tick;
  22675. const char statusByte = *(mm.getRawData());
  22676. if ((statusByte == lastStatusByte)
  22677. && ((statusByte & 0xf0) != 0xf0)
  22678. && i > 0
  22679. && mm.getRawDataSize() > 1)
  22680. {
  22681. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22682. }
  22683. else
  22684. {
  22685. out.write (mm.getRawData(), mm.getRawDataSize());
  22686. }
  22687. lastStatusByte = statusByte;
  22688. }
  22689. out.writeByte (0);
  22690. const MidiMessage m (MidiMessage::endOfTrack());
  22691. out.write (m.getRawData(),
  22692. m.getRawDataSize());
  22693. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22694. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22695. mainOut.write (out.getData(), (int) out.getDataSize());
  22696. }
  22697. END_JUCE_NAMESPACE
  22698. /*** End of inlined file: juce_MidiFile.cpp ***/
  22699. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22700. BEGIN_JUCE_NAMESPACE
  22701. MidiKeyboardState::MidiKeyboardState()
  22702. {
  22703. zerostruct (noteStates);
  22704. }
  22705. MidiKeyboardState::~MidiKeyboardState()
  22706. {
  22707. }
  22708. void MidiKeyboardState::reset()
  22709. {
  22710. const ScopedLock sl (lock);
  22711. zerostruct (noteStates);
  22712. eventsToAdd.clear();
  22713. }
  22714. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22715. {
  22716. jassert (midiChannel >= 0 && midiChannel <= 16);
  22717. return ((unsigned int) n) < 128
  22718. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22719. }
  22720. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22721. {
  22722. return ((unsigned int) n) < 128
  22723. && (noteStates[n] & midiChannelMask) != 0;
  22724. }
  22725. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22726. {
  22727. jassert (midiChannel >= 0 && midiChannel <= 16);
  22728. jassert (((unsigned int) midiNoteNumber) < 128);
  22729. const ScopedLock sl (lock);
  22730. if (((unsigned int) midiNoteNumber) < 128)
  22731. {
  22732. const int timeNow = (int) Time::getMillisecondCounter();
  22733. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22734. eventsToAdd.clear (0, timeNow - 500);
  22735. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22736. }
  22737. }
  22738. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22739. {
  22740. if (((unsigned int) midiNoteNumber) < 128)
  22741. {
  22742. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22743. for (int i = listeners.size(); --i >= 0;)
  22744. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22745. }
  22746. }
  22747. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22748. {
  22749. const ScopedLock sl (lock);
  22750. if (isNoteOn (midiChannel, midiNoteNumber))
  22751. {
  22752. const int timeNow = (int) Time::getMillisecondCounter();
  22753. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22754. eventsToAdd.clear (0, timeNow - 500);
  22755. noteOffInternal (midiChannel, midiNoteNumber);
  22756. }
  22757. }
  22758. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22759. {
  22760. if (isNoteOn (midiChannel, midiNoteNumber))
  22761. {
  22762. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22763. for (int i = listeners.size(); --i >= 0;)
  22764. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22765. }
  22766. }
  22767. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22768. {
  22769. const ScopedLock sl (lock);
  22770. if (midiChannel <= 0)
  22771. {
  22772. for (int i = 1; i <= 16; ++i)
  22773. allNotesOff (i);
  22774. }
  22775. else
  22776. {
  22777. for (int i = 0; i < 128; ++i)
  22778. noteOff (midiChannel, i);
  22779. }
  22780. }
  22781. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22782. {
  22783. if (message.isNoteOn())
  22784. {
  22785. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22786. }
  22787. else if (message.isNoteOff())
  22788. {
  22789. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22790. }
  22791. else if (message.isAllNotesOff())
  22792. {
  22793. for (int i = 0; i < 128; ++i)
  22794. noteOffInternal (message.getChannel(), i);
  22795. }
  22796. }
  22797. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22798. const int startSample,
  22799. const int numSamples,
  22800. const bool injectIndirectEvents)
  22801. {
  22802. MidiBuffer::Iterator i (buffer);
  22803. MidiMessage message (0xf4, 0.0);
  22804. int time;
  22805. const ScopedLock sl (lock);
  22806. while (i.getNextEvent (message, time))
  22807. processNextMidiEvent (message);
  22808. if (injectIndirectEvents)
  22809. {
  22810. MidiBuffer::Iterator i2 (eventsToAdd);
  22811. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22812. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22813. while (i2.getNextEvent (message, time))
  22814. {
  22815. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22816. buffer.addEvent (message, startSample + pos);
  22817. }
  22818. }
  22819. eventsToAdd.clear();
  22820. }
  22821. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22822. {
  22823. const ScopedLock sl (lock);
  22824. listeners.addIfNotAlreadyThere (listener);
  22825. }
  22826. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22827. {
  22828. const ScopedLock sl (lock);
  22829. listeners.removeValue (listener);
  22830. }
  22831. END_JUCE_NAMESPACE
  22832. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22833. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22834. BEGIN_JUCE_NAMESPACE
  22835. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22836. {
  22837. numBytesUsed = 0;
  22838. int v = 0;
  22839. int i;
  22840. do
  22841. {
  22842. i = (int) *data++;
  22843. if (++numBytesUsed > 6)
  22844. break;
  22845. v = (v << 7) + (i & 0x7f);
  22846. } while (i & 0x80);
  22847. return v;
  22848. }
  22849. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22850. {
  22851. // this method only works for valid starting bytes of a short midi message
  22852. jassert (firstByte >= 0x80
  22853. && firstByte != 0xf0
  22854. && firstByte != 0xf7);
  22855. static const char messageLengths[] =
  22856. {
  22857. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22858. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22859. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22860. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22861. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22862. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22863. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22864. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22865. };
  22866. return messageLengths [firstByte & 0x7f];
  22867. }
  22868. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22869. : timeStamp (t),
  22870. size (dataSize)
  22871. {
  22872. jassert (dataSize > 0);
  22873. if (dataSize <= 4)
  22874. data = static_cast<uint8*> (preallocatedData.asBytes);
  22875. else
  22876. data = new uint8 [dataSize];
  22877. memcpy (data, d, dataSize);
  22878. // check that the length matches the data..
  22879. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22880. }
  22881. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22882. : timeStamp (t),
  22883. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22884. size (1)
  22885. {
  22886. data[0] = (uint8) byte1;
  22887. // check that the length matches the data..
  22888. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22889. }
  22890. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22891. : timeStamp (t),
  22892. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22893. size (2)
  22894. {
  22895. data[0] = (uint8) byte1;
  22896. data[1] = (uint8) byte2;
  22897. // check that the length matches the data..
  22898. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22899. }
  22900. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22901. : timeStamp (t),
  22902. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22903. size (3)
  22904. {
  22905. data[0] = (uint8) byte1;
  22906. data[1] = (uint8) byte2;
  22907. data[2] = (uint8) byte3;
  22908. // check that the length matches the data..
  22909. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22910. }
  22911. MidiMessage::MidiMessage (const MidiMessage& other)
  22912. : timeStamp (other.timeStamp),
  22913. size (other.size)
  22914. {
  22915. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22916. {
  22917. data = new uint8 [size];
  22918. memcpy (data, other.data, size);
  22919. }
  22920. else
  22921. {
  22922. data = static_cast<uint8*> (preallocatedData.asBytes);
  22923. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22924. }
  22925. }
  22926. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22927. : timeStamp (newTimeStamp),
  22928. size (other.size)
  22929. {
  22930. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22931. {
  22932. data = new uint8 [size];
  22933. memcpy (data, other.data, size);
  22934. }
  22935. else
  22936. {
  22937. data = static_cast<uint8*> (preallocatedData.asBytes);
  22938. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22939. }
  22940. }
  22941. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22942. : timeStamp (t),
  22943. data (static_cast<uint8*> (preallocatedData.asBytes))
  22944. {
  22945. const uint8* src = static_cast <const uint8*> (src_);
  22946. unsigned int byte = (unsigned int) *src;
  22947. if (byte < 0x80)
  22948. {
  22949. byte = (unsigned int) (uint8) lastStatusByte;
  22950. numBytesUsed = -1;
  22951. }
  22952. else
  22953. {
  22954. numBytesUsed = 0;
  22955. --sz;
  22956. ++src;
  22957. }
  22958. if (byte >= 0x80)
  22959. {
  22960. if (byte == 0xf0)
  22961. {
  22962. const uint8* d = src;
  22963. while (d < src + sz)
  22964. {
  22965. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22966. {
  22967. if (*d == 0xf7) // include an 0xf7 if we hit one
  22968. ++d;
  22969. break;
  22970. }
  22971. ++d;
  22972. }
  22973. size = 1 + (int) (d - src);
  22974. data = new uint8 [size];
  22975. *data = (uint8) byte;
  22976. memcpy (data + 1, src, size - 1);
  22977. }
  22978. else if (byte == 0xff)
  22979. {
  22980. int n;
  22981. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22982. size = jmin (sz + 1, n + 2 + bytesLeft);
  22983. data = new uint8 [size];
  22984. *data = (uint8) byte;
  22985. memcpy (data + 1, src, size - 1);
  22986. }
  22987. else
  22988. {
  22989. preallocatedData.asInt32 = 0;
  22990. size = getMessageLengthFromFirstByte ((uint8) byte);
  22991. data[0] = (uint8) byte;
  22992. if (size > 1)
  22993. {
  22994. data[1] = src[0];
  22995. if (size > 2)
  22996. data[2] = src[1];
  22997. }
  22998. }
  22999. numBytesUsed += size;
  23000. }
  23001. else
  23002. {
  23003. preallocatedData.asInt32 = 0;
  23004. size = 0;
  23005. }
  23006. }
  23007. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23008. {
  23009. if (this != &other)
  23010. {
  23011. timeStamp = other.timeStamp;
  23012. size = other.size;
  23013. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23014. delete[] data;
  23015. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23016. {
  23017. data = new uint8 [size];
  23018. memcpy (data, other.data, size);
  23019. }
  23020. else
  23021. {
  23022. data = static_cast<uint8*> (preallocatedData.asBytes);
  23023. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23024. }
  23025. }
  23026. return *this;
  23027. }
  23028. MidiMessage::~MidiMessage()
  23029. {
  23030. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23031. delete[] data;
  23032. }
  23033. int MidiMessage::getChannel() const throw()
  23034. {
  23035. if ((data[0] & 0xf0) != 0xf0)
  23036. return (data[0] & 0xf) + 1;
  23037. else
  23038. return 0;
  23039. }
  23040. bool MidiMessage::isForChannel (const int channel) const throw()
  23041. {
  23042. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23043. return ((data[0] & 0xf) == channel - 1)
  23044. && ((data[0] & 0xf0) != 0xf0);
  23045. }
  23046. void MidiMessage::setChannel (const int channel) throw()
  23047. {
  23048. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23049. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23050. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23051. | (uint8)(channel - 1));
  23052. }
  23053. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23054. {
  23055. return ((data[0] & 0xf0) == 0x90)
  23056. && (returnTrueForVelocity0 || data[2] != 0);
  23057. }
  23058. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23059. {
  23060. return ((data[0] & 0xf0) == 0x80)
  23061. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23062. }
  23063. bool MidiMessage::isNoteOnOrOff() const throw()
  23064. {
  23065. const int d = data[0] & 0xf0;
  23066. return (d == 0x90) || (d == 0x80);
  23067. }
  23068. int MidiMessage::getNoteNumber() const throw()
  23069. {
  23070. return data[1];
  23071. }
  23072. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23073. {
  23074. if (isNoteOnOrOff())
  23075. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23076. }
  23077. uint8 MidiMessage::getVelocity() const throw()
  23078. {
  23079. if (isNoteOnOrOff())
  23080. return data[2];
  23081. else
  23082. return 0;
  23083. }
  23084. float MidiMessage::getFloatVelocity() const throw()
  23085. {
  23086. return getVelocity() * (1.0f / 127.0f);
  23087. }
  23088. void MidiMessage::setVelocity (const float newVelocity) throw()
  23089. {
  23090. if (isNoteOnOrOff())
  23091. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23092. }
  23093. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23094. {
  23095. if (isNoteOnOrOff())
  23096. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23097. }
  23098. bool MidiMessage::isAftertouch() const throw()
  23099. {
  23100. return (data[0] & 0xf0) == 0xa0;
  23101. }
  23102. int MidiMessage::getAfterTouchValue() const throw()
  23103. {
  23104. return data[2];
  23105. }
  23106. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23107. const int noteNum,
  23108. const int aftertouchValue) throw()
  23109. {
  23110. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23111. jassert (((unsigned int) noteNum) <= 127);
  23112. jassert (((unsigned int) aftertouchValue) <= 127);
  23113. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23114. noteNum & 0x7f,
  23115. aftertouchValue & 0x7f);
  23116. }
  23117. bool MidiMessage::isChannelPressure() const throw()
  23118. {
  23119. return (data[0] & 0xf0) == 0xd0;
  23120. }
  23121. int MidiMessage::getChannelPressureValue() const throw()
  23122. {
  23123. jassert (isChannelPressure());
  23124. return data[1];
  23125. }
  23126. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23127. const int pressure) throw()
  23128. {
  23129. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23130. jassert (((unsigned int) pressure) <= 127);
  23131. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23132. pressure & 0x7f);
  23133. }
  23134. bool MidiMessage::isProgramChange() const throw()
  23135. {
  23136. return (data[0] & 0xf0) == 0xc0;
  23137. }
  23138. int MidiMessage::getProgramChangeNumber() const throw()
  23139. {
  23140. return data[1];
  23141. }
  23142. const MidiMessage MidiMessage::programChange (const int channel,
  23143. const int programNumber) throw()
  23144. {
  23145. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23146. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23147. programNumber & 0x7f);
  23148. }
  23149. bool MidiMessage::isPitchWheel() const throw()
  23150. {
  23151. return (data[0] & 0xf0) == 0xe0;
  23152. }
  23153. int MidiMessage::getPitchWheelValue() const throw()
  23154. {
  23155. return data[1] | (data[2] << 7);
  23156. }
  23157. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23158. const int position) throw()
  23159. {
  23160. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23161. jassert (((unsigned int) position) <= 0x3fff);
  23162. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23163. position & 127,
  23164. (position >> 7) & 127);
  23165. }
  23166. bool MidiMessage::isController() const throw()
  23167. {
  23168. return (data[0] & 0xf0) == 0xb0;
  23169. }
  23170. int MidiMessage::getControllerNumber() const throw()
  23171. {
  23172. jassert (isController());
  23173. return data[1];
  23174. }
  23175. int MidiMessage::getControllerValue() const throw()
  23176. {
  23177. jassert (isController());
  23178. return data[2];
  23179. }
  23180. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23181. const int controllerType,
  23182. const int value) throw()
  23183. {
  23184. // the channel must be between 1 and 16 inclusive
  23185. jassert (channel > 0 && channel <= 16);
  23186. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23187. controllerType & 127,
  23188. value & 127);
  23189. }
  23190. const MidiMessage MidiMessage::noteOn (const int channel,
  23191. const int noteNumber,
  23192. const float velocity) throw()
  23193. {
  23194. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23195. }
  23196. const MidiMessage MidiMessage::noteOn (const int channel,
  23197. const int noteNumber,
  23198. const uint8 velocity) throw()
  23199. {
  23200. jassert (channel > 0 && channel <= 16);
  23201. jassert (((unsigned int) noteNumber) <= 127);
  23202. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23203. noteNumber & 127,
  23204. jlimit (0, 127, roundToInt (velocity)));
  23205. }
  23206. const MidiMessage MidiMessage::noteOff (const int channel,
  23207. const int noteNumber) throw()
  23208. {
  23209. jassert (channel > 0 && channel <= 16);
  23210. jassert (((unsigned int) noteNumber) <= 127);
  23211. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23212. }
  23213. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23214. {
  23215. jassert (channel > 0 && channel <= 16);
  23216. return controllerEvent (channel, 123, 0);
  23217. }
  23218. bool MidiMessage::isAllNotesOff() const throw()
  23219. {
  23220. return (data[0] & 0xf0) == 0xb0
  23221. && data[1] == 123;
  23222. }
  23223. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23224. {
  23225. return controllerEvent (channel, 120, 0);
  23226. }
  23227. bool MidiMessage::isAllSoundOff() const throw()
  23228. {
  23229. return (data[0] & 0xf0) == 0xb0
  23230. && data[1] == 120;
  23231. }
  23232. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23233. {
  23234. return controllerEvent (channel, 121, 0);
  23235. }
  23236. const MidiMessage MidiMessage::masterVolume (const float volume)
  23237. {
  23238. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23239. uint8 buf[8];
  23240. buf[0] = 0xf0;
  23241. buf[1] = 0x7f;
  23242. buf[2] = 0x7f;
  23243. buf[3] = 0x04;
  23244. buf[4] = 0x01;
  23245. buf[5] = (uint8) (vol & 0x7f);
  23246. buf[6] = (uint8) (vol >> 7);
  23247. buf[7] = 0xf7;
  23248. return MidiMessage (buf, 8);
  23249. }
  23250. bool MidiMessage::isSysEx() const throw()
  23251. {
  23252. return *data == 0xf0;
  23253. }
  23254. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23255. {
  23256. MemoryBlock mm (dataSize + 2);
  23257. uint8* const m = static_cast <uint8*> (mm.getData());
  23258. m[0] = 0xf0;
  23259. memcpy (m + 1, sysexData, dataSize);
  23260. m[dataSize + 1] = 0xf7;
  23261. return MidiMessage (m, dataSize + 2);
  23262. }
  23263. const uint8* MidiMessage::getSysExData() const throw()
  23264. {
  23265. return (isSysEx()) ? getRawData() + 1 : 0;
  23266. }
  23267. int MidiMessage::getSysExDataSize() const throw()
  23268. {
  23269. return (isSysEx()) ? size - 2 : 0;
  23270. }
  23271. bool MidiMessage::isMetaEvent() const throw()
  23272. {
  23273. return *data == 0xff;
  23274. }
  23275. bool MidiMessage::isActiveSense() const throw()
  23276. {
  23277. return *data == 0xfe;
  23278. }
  23279. int MidiMessage::getMetaEventType() const throw()
  23280. {
  23281. if (*data != 0xff)
  23282. return -1;
  23283. else
  23284. return data[1];
  23285. }
  23286. int MidiMessage::getMetaEventLength() const throw()
  23287. {
  23288. if (*data == 0xff)
  23289. {
  23290. int n;
  23291. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23292. }
  23293. return 0;
  23294. }
  23295. const uint8* MidiMessage::getMetaEventData() const throw()
  23296. {
  23297. int n;
  23298. const uint8* d = data + 2;
  23299. readVariableLengthVal (d, n);
  23300. return d + n;
  23301. }
  23302. bool MidiMessage::isTrackMetaEvent() const throw()
  23303. {
  23304. return getMetaEventType() == 0;
  23305. }
  23306. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23307. {
  23308. return getMetaEventType() == 47;
  23309. }
  23310. bool MidiMessage::isTextMetaEvent() const throw()
  23311. {
  23312. const int t = getMetaEventType();
  23313. return t > 0 && t < 16;
  23314. }
  23315. const String MidiMessage::getTextFromTextMetaEvent() const
  23316. {
  23317. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23318. }
  23319. bool MidiMessage::isTrackNameEvent() const throw()
  23320. {
  23321. return (data[1] == 3)
  23322. && (*data == 0xff);
  23323. }
  23324. bool MidiMessage::isTempoMetaEvent() const throw()
  23325. {
  23326. return (data[1] == 81)
  23327. && (*data == 0xff);
  23328. }
  23329. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23330. {
  23331. return (data[1] == 0x20)
  23332. && (*data == 0xff)
  23333. && (data[2] == 1);
  23334. }
  23335. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23336. {
  23337. return data[3] + 1;
  23338. }
  23339. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23340. {
  23341. if (! isTempoMetaEvent())
  23342. return 0.0;
  23343. const uint8* const d = getMetaEventData();
  23344. return (((unsigned int) d[0] << 16)
  23345. | ((unsigned int) d[1] << 8)
  23346. | d[2])
  23347. / 1000000.0;
  23348. }
  23349. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23350. {
  23351. if (timeFormat > 0)
  23352. {
  23353. if (! isTempoMetaEvent())
  23354. return 0.5 / timeFormat;
  23355. return getTempoSecondsPerQuarterNote() / timeFormat;
  23356. }
  23357. else
  23358. {
  23359. const int frameCode = (-timeFormat) >> 8;
  23360. double framesPerSecond;
  23361. switch (frameCode)
  23362. {
  23363. case 24: framesPerSecond = 24.0; break;
  23364. case 25: framesPerSecond = 25.0; break;
  23365. case 29: framesPerSecond = 29.97; break;
  23366. case 30: framesPerSecond = 30.0; break;
  23367. default: framesPerSecond = 30.0; break;
  23368. }
  23369. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23370. }
  23371. }
  23372. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23373. {
  23374. uint8 d[8];
  23375. d[0] = 0xff;
  23376. d[1] = 81;
  23377. d[2] = 3;
  23378. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23379. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23380. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23381. return MidiMessage (d, 6, 0.0);
  23382. }
  23383. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23384. {
  23385. return (data[1] == 0x58)
  23386. && (*data == (uint8) 0xff);
  23387. }
  23388. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23389. {
  23390. if (isTimeSignatureMetaEvent())
  23391. {
  23392. const uint8* const d = getMetaEventData();
  23393. numerator = d[0];
  23394. denominator = 1 << d[1];
  23395. }
  23396. else
  23397. {
  23398. numerator = 4;
  23399. denominator = 4;
  23400. }
  23401. }
  23402. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23403. {
  23404. uint8 d[8];
  23405. d[0] = 0xff;
  23406. d[1] = 0x58;
  23407. d[2] = 0x04;
  23408. d[3] = (uint8) numerator;
  23409. int n = 1;
  23410. int powerOfTwo = 0;
  23411. while (n < denominator)
  23412. {
  23413. n <<= 1;
  23414. ++powerOfTwo;
  23415. }
  23416. d[4] = (uint8) powerOfTwo;
  23417. d[5] = 0x01;
  23418. d[6] = 96;
  23419. return MidiMessage (d, 7, 0.0);
  23420. }
  23421. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23422. {
  23423. uint8 d[8];
  23424. d[0] = 0xff;
  23425. d[1] = 0x20;
  23426. d[2] = 0x01;
  23427. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23428. return MidiMessage (d, 4, 0.0);
  23429. }
  23430. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23431. {
  23432. return getMetaEventType() == 89;
  23433. }
  23434. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23435. {
  23436. return (int) *getMetaEventData();
  23437. }
  23438. const MidiMessage MidiMessage::endOfTrack() throw()
  23439. {
  23440. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23441. }
  23442. bool MidiMessage::isSongPositionPointer() const throw()
  23443. {
  23444. return *data == 0xf2;
  23445. }
  23446. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23447. {
  23448. return data[1] | (data[2] << 7);
  23449. }
  23450. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23451. {
  23452. return MidiMessage (0xf2,
  23453. positionInMidiBeats & 127,
  23454. (positionInMidiBeats >> 7) & 127);
  23455. }
  23456. bool MidiMessage::isMidiStart() const throw()
  23457. {
  23458. return *data == 0xfa;
  23459. }
  23460. const MidiMessage MidiMessage::midiStart() throw()
  23461. {
  23462. return MidiMessage (0xfa);
  23463. }
  23464. bool MidiMessage::isMidiContinue() const throw()
  23465. {
  23466. return *data == 0xfb;
  23467. }
  23468. const MidiMessage MidiMessage::midiContinue() throw()
  23469. {
  23470. return MidiMessage (0xfb);
  23471. }
  23472. bool MidiMessage::isMidiStop() const throw()
  23473. {
  23474. return *data == 0xfc;
  23475. }
  23476. const MidiMessage MidiMessage::midiStop() throw()
  23477. {
  23478. return MidiMessage (0xfc);
  23479. }
  23480. bool MidiMessage::isMidiClock() const throw()
  23481. {
  23482. return *data == 0xf8;
  23483. }
  23484. const MidiMessage MidiMessage::midiClock() throw()
  23485. {
  23486. return MidiMessage (0xf8);
  23487. }
  23488. bool MidiMessage::isQuarterFrame() const throw()
  23489. {
  23490. return *data == 0xf1;
  23491. }
  23492. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23493. {
  23494. return ((int) data[1]) >> 4;
  23495. }
  23496. int MidiMessage::getQuarterFrameValue() const throw()
  23497. {
  23498. return ((int) data[1]) & 0x0f;
  23499. }
  23500. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23501. const int value) throw()
  23502. {
  23503. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23504. }
  23505. bool MidiMessage::isFullFrame() const throw()
  23506. {
  23507. return data[0] == 0xf0
  23508. && data[1] == 0x7f
  23509. && size >= 10
  23510. && data[3] == 0x01
  23511. && data[4] == 0x01;
  23512. }
  23513. void MidiMessage::getFullFrameParameters (int& hours,
  23514. int& minutes,
  23515. int& seconds,
  23516. int& frames,
  23517. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23518. {
  23519. jassert (isFullFrame());
  23520. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23521. hours = data[5] & 0x1f;
  23522. minutes = data[6];
  23523. seconds = data[7];
  23524. frames = data[8];
  23525. }
  23526. const MidiMessage MidiMessage::fullFrame (const int hours,
  23527. const int minutes,
  23528. const int seconds,
  23529. const int frames,
  23530. MidiMessage::SmpteTimecodeType timecodeType)
  23531. {
  23532. uint8 d[10];
  23533. d[0] = 0xf0;
  23534. d[1] = 0x7f;
  23535. d[2] = 0x7f;
  23536. d[3] = 0x01;
  23537. d[4] = 0x01;
  23538. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23539. d[6] = (uint8) minutes;
  23540. d[7] = (uint8) seconds;
  23541. d[8] = (uint8) frames;
  23542. d[9] = 0xf7;
  23543. return MidiMessage (d, 10, 0.0);
  23544. }
  23545. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23546. {
  23547. return data[0] == 0xf0
  23548. && data[1] == 0x7f
  23549. && data[3] == 0x06
  23550. && size > 5;
  23551. }
  23552. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23553. {
  23554. jassert (isMidiMachineControlMessage());
  23555. return (MidiMachineControlCommand) data[4];
  23556. }
  23557. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23558. {
  23559. uint8 d[6];
  23560. d[0] = 0xf0;
  23561. d[1] = 0x7f;
  23562. d[2] = 0x00;
  23563. d[3] = 0x06;
  23564. d[4] = (uint8) command;
  23565. d[5] = 0xf7;
  23566. return MidiMessage (d, 6, 0.0);
  23567. }
  23568. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23569. int& minutes,
  23570. int& seconds,
  23571. int& frames) const throw()
  23572. {
  23573. if (size >= 12
  23574. && data[0] == 0xf0
  23575. && data[1] == 0x7f
  23576. && data[3] == 0x06
  23577. && data[4] == 0x44
  23578. && data[5] == 0x06
  23579. && data[6] == 0x01)
  23580. {
  23581. hours = data[7] % 24; // (that some machines send out hours > 24)
  23582. minutes = data[8];
  23583. seconds = data[9];
  23584. frames = data[10];
  23585. return true;
  23586. }
  23587. return false;
  23588. }
  23589. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23590. int minutes,
  23591. int seconds,
  23592. int frames)
  23593. {
  23594. uint8 d[12];
  23595. d[0] = 0xf0;
  23596. d[1] = 0x7f;
  23597. d[2] = 0x00;
  23598. d[3] = 0x06;
  23599. d[4] = 0x44;
  23600. d[5] = 0x06;
  23601. d[6] = 0x01;
  23602. d[7] = (uint8) hours;
  23603. d[8] = (uint8) minutes;
  23604. d[9] = (uint8) seconds;
  23605. d[10] = (uint8) frames;
  23606. d[11] = 0xf7;
  23607. return MidiMessage (d, 12, 0.0);
  23608. }
  23609. const String MidiMessage::getMidiNoteName (int note,
  23610. bool useSharps,
  23611. bool includeOctaveNumber,
  23612. int octaveNumForMiddleC) throw()
  23613. {
  23614. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  23615. "F", "F#", "G", "G#", "A",
  23616. "A#", "B" };
  23617. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  23618. "F", "Gb", "G", "Ab", "A",
  23619. "Bb", "B" };
  23620. if (((unsigned int) note) < 128)
  23621. {
  23622. const String s ((useSharps) ? sharpNoteNames [note % 12]
  23623. : flatNoteNames [note % 12]);
  23624. if (includeOctaveNumber)
  23625. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  23626. else
  23627. return s;
  23628. }
  23629. return String::empty;
  23630. }
  23631. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  23632. {
  23633. noteNumber -= 12 * 6 + 9; // now 0 = A440
  23634. return 440.0 * pow (2.0, noteNumber / 12.0);
  23635. }
  23636. const String MidiMessage::getGMInstrumentName (int n) throw()
  23637. {
  23638. const char *names[] =
  23639. {
  23640. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23641. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23642. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23643. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23644. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23645. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23646. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23647. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23648. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23649. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23650. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23651. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23652. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23653. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23654. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23655. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23656. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23657. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23658. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23659. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23660. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23661. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23662. "Applause", "Gunshot"
  23663. };
  23664. return (((unsigned int) n) < 128) ? names[n]
  23665. : (const char*)0;
  23666. }
  23667. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  23668. {
  23669. const char* names[] =
  23670. {
  23671. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23672. "Bass", "Strings", "Ensemble", "Brass",
  23673. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23674. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23675. };
  23676. return (((unsigned int) n) <= 15) ? names[n]
  23677. : (const char*)0;
  23678. }
  23679. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  23680. {
  23681. const char* names[] =
  23682. {
  23683. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23684. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23685. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23686. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23687. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23688. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23689. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23690. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23691. "Mute Triangle", "Open Triangle"
  23692. };
  23693. return (n >= 35 && n <= 81) ? names [n - 35]
  23694. : (const char*)0;
  23695. }
  23696. const String MidiMessage::getControllerName (int n) throw()
  23697. {
  23698. const char* names[] =
  23699. {
  23700. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23701. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23702. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23703. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23704. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23705. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23706. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23707. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23708. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23709. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23710. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23711. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23712. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23713. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23714. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23715. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23716. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23717. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23718. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23720. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23721. "Poly Operation"
  23722. };
  23723. return (((unsigned int) n) < 128) ? names[n]
  23724. : (const char*)0;
  23725. }
  23726. END_JUCE_NAMESPACE
  23727. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23728. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23729. BEGIN_JUCE_NAMESPACE
  23730. MidiMessageCollector::MidiMessageCollector()
  23731. : lastCallbackTime (0),
  23732. sampleRate (44100.0001)
  23733. {
  23734. }
  23735. MidiMessageCollector::~MidiMessageCollector()
  23736. {
  23737. }
  23738. void MidiMessageCollector::reset (const double sampleRate_)
  23739. {
  23740. jassert (sampleRate_ > 0);
  23741. const ScopedLock sl (midiCallbackLock);
  23742. sampleRate = sampleRate_;
  23743. incomingMessages.clear();
  23744. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23745. }
  23746. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23747. {
  23748. // you need to call reset() to set the correct sample rate before using this object
  23749. jassert (sampleRate != 44100.0001);
  23750. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23751. // for details of what the number should be.
  23752. jassert (message.getTimeStamp() != 0);
  23753. const ScopedLock sl (midiCallbackLock);
  23754. const int sampleNumber
  23755. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23756. incomingMessages.addEvent (message, sampleNumber);
  23757. // if the messages don't get used for over a second, we'd better
  23758. // get rid of any old ones to avoid the queue getting too big
  23759. if (sampleNumber > sampleRate)
  23760. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23761. }
  23762. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23763. const int numSamples)
  23764. {
  23765. // you need to call reset() to set the correct sample rate before using this object
  23766. jassert (sampleRate != 44100.0001);
  23767. const double timeNow = Time::getMillisecondCounterHiRes();
  23768. const double msElapsed = timeNow - lastCallbackTime;
  23769. const ScopedLock sl (midiCallbackLock);
  23770. lastCallbackTime = timeNow;
  23771. if (! incomingMessages.isEmpty())
  23772. {
  23773. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23774. int startSample = 0;
  23775. int scale = 1 << 16;
  23776. const uint8* midiData;
  23777. int numBytes, samplePosition;
  23778. MidiBuffer::Iterator iter (incomingMessages);
  23779. if (numSourceSamples > numSamples)
  23780. {
  23781. // if our list of events is longer than the buffer we're being
  23782. // asked for, scale them down to squeeze them all in..
  23783. const int maxBlockLengthToUse = numSamples << 5;
  23784. if (numSourceSamples > maxBlockLengthToUse)
  23785. {
  23786. startSample = numSourceSamples - maxBlockLengthToUse;
  23787. numSourceSamples = maxBlockLengthToUse;
  23788. iter.setNextSamplePosition (startSample);
  23789. }
  23790. scale = (numSamples << 10) / numSourceSamples;
  23791. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23792. {
  23793. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23794. destBuffer.addEvent (midiData, numBytes,
  23795. jlimit (0, numSamples - 1, samplePosition));
  23796. }
  23797. }
  23798. else
  23799. {
  23800. // if our event list is shorter than the number we need, put them
  23801. // towards the end of the buffer
  23802. startSample = numSamples - numSourceSamples;
  23803. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23804. {
  23805. destBuffer.addEvent (midiData, numBytes,
  23806. jlimit (0, numSamples - 1, samplePosition + startSample));
  23807. }
  23808. }
  23809. incomingMessages.clear();
  23810. }
  23811. }
  23812. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23813. {
  23814. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23815. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23816. addMessageToQueue (m);
  23817. }
  23818. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23819. {
  23820. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23821. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23822. addMessageToQueue (m);
  23823. }
  23824. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23825. {
  23826. addMessageToQueue (message);
  23827. }
  23828. END_JUCE_NAMESPACE
  23829. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23830. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23831. BEGIN_JUCE_NAMESPACE
  23832. MidiMessageSequence::MidiMessageSequence()
  23833. {
  23834. }
  23835. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23836. {
  23837. list.ensureStorageAllocated (other.list.size());
  23838. for (int i = 0; i < other.list.size(); ++i)
  23839. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23840. }
  23841. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23842. {
  23843. MidiMessageSequence otherCopy (other);
  23844. swapWith (otherCopy);
  23845. return *this;
  23846. }
  23847. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23848. {
  23849. list.swapWithArray (other.list);
  23850. }
  23851. MidiMessageSequence::~MidiMessageSequence()
  23852. {
  23853. }
  23854. void MidiMessageSequence::clear()
  23855. {
  23856. list.clear();
  23857. }
  23858. int MidiMessageSequence::getNumEvents() const
  23859. {
  23860. return list.size();
  23861. }
  23862. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23863. {
  23864. return list [index];
  23865. }
  23866. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23867. {
  23868. const MidiEventHolder* const meh = list [index];
  23869. if (meh != 0 && meh->noteOffObject != 0)
  23870. return meh->noteOffObject->message.getTimeStamp();
  23871. else
  23872. return 0.0;
  23873. }
  23874. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23875. {
  23876. const MidiEventHolder* const meh = list [index];
  23877. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23878. }
  23879. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23880. {
  23881. return list.indexOf (event);
  23882. }
  23883. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23884. {
  23885. const int numEvents = list.size();
  23886. int i;
  23887. for (i = 0; i < numEvents; ++i)
  23888. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23889. break;
  23890. return i;
  23891. }
  23892. double MidiMessageSequence::getStartTime() const
  23893. {
  23894. if (list.size() > 0)
  23895. return list.getUnchecked(0)->message.getTimeStamp();
  23896. else
  23897. return 0;
  23898. }
  23899. double MidiMessageSequence::getEndTime() const
  23900. {
  23901. if (list.size() > 0)
  23902. return list.getLast()->message.getTimeStamp();
  23903. else
  23904. return 0;
  23905. }
  23906. double MidiMessageSequence::getEventTime (const int index) const
  23907. {
  23908. if (((unsigned int) index) < (unsigned int) list.size())
  23909. return list.getUnchecked (index)->message.getTimeStamp();
  23910. return 0.0;
  23911. }
  23912. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23913. double timeAdjustment)
  23914. {
  23915. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23916. timeAdjustment += newMessage.getTimeStamp();
  23917. newOne->message.setTimeStamp (timeAdjustment);
  23918. int i;
  23919. for (i = list.size(); --i >= 0;)
  23920. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23921. break;
  23922. list.insert (i + 1, newOne);
  23923. }
  23924. void MidiMessageSequence::deleteEvent (const int index,
  23925. const bool deleteMatchingNoteUp)
  23926. {
  23927. if (((unsigned int) index) < (unsigned int) list.size())
  23928. {
  23929. if (deleteMatchingNoteUp)
  23930. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23931. list.remove (index);
  23932. }
  23933. }
  23934. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23935. double timeAdjustment,
  23936. double firstAllowableTime,
  23937. double endOfAllowableDestTimes)
  23938. {
  23939. firstAllowableTime -= timeAdjustment;
  23940. endOfAllowableDestTimes -= timeAdjustment;
  23941. for (int i = 0; i < other.list.size(); ++i)
  23942. {
  23943. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23944. const double t = m.getTimeStamp();
  23945. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23946. {
  23947. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23948. newOne->message.setTimeStamp (timeAdjustment + t);
  23949. list.add (newOne);
  23950. }
  23951. }
  23952. sort();
  23953. }
  23954. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23955. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23956. {
  23957. const double diff = first->message.getTimeStamp()
  23958. - second->message.getTimeStamp();
  23959. return (diff > 0) - (diff < 0);
  23960. }
  23961. void MidiMessageSequence::sort()
  23962. {
  23963. list.sort (*this, true);
  23964. }
  23965. void MidiMessageSequence::updateMatchedPairs()
  23966. {
  23967. for (int i = 0; i < list.size(); ++i)
  23968. {
  23969. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23970. if (m1.isNoteOn())
  23971. {
  23972. list.getUnchecked(i)->noteOffObject = 0;
  23973. const int note = m1.getNoteNumber();
  23974. const int chan = m1.getChannel();
  23975. const int len = list.size();
  23976. for (int j = i + 1; j < len; ++j)
  23977. {
  23978. const MidiMessage& m = list.getUnchecked(j)->message;
  23979. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23980. {
  23981. if (m.isNoteOff())
  23982. {
  23983. list.getUnchecked(i)->noteOffObject = list[j];
  23984. break;
  23985. }
  23986. else if (m.isNoteOn())
  23987. {
  23988. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23989. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23990. list.getUnchecked(i)->noteOffObject = list[j];
  23991. break;
  23992. }
  23993. }
  23994. }
  23995. }
  23996. }
  23997. }
  23998. void MidiMessageSequence::addTimeToMessages (const double delta)
  23999. {
  24000. for (int i = list.size(); --i >= 0;)
  24001. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24002. + delta);
  24003. }
  24004. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24005. MidiMessageSequence& destSequence,
  24006. const bool alsoIncludeMetaEvents) const
  24007. {
  24008. for (int i = 0; i < list.size(); ++i)
  24009. {
  24010. const MidiMessage& mm = list.getUnchecked(i)->message;
  24011. if (mm.isForChannel (channelNumberToExtract)
  24012. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24013. {
  24014. destSequence.addEvent (mm);
  24015. }
  24016. }
  24017. }
  24018. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24019. {
  24020. for (int i = 0; i < list.size(); ++i)
  24021. {
  24022. const MidiMessage& mm = list.getUnchecked(i)->message;
  24023. if (mm.isSysEx())
  24024. destSequence.addEvent (mm);
  24025. }
  24026. }
  24027. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24028. {
  24029. for (int i = list.size(); --i >= 0;)
  24030. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24031. list.remove(i);
  24032. }
  24033. void MidiMessageSequence::deleteSysExMessages()
  24034. {
  24035. for (int i = list.size(); --i >= 0;)
  24036. if (list.getUnchecked(i)->message.isSysEx())
  24037. list.remove(i);
  24038. }
  24039. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24040. const double time,
  24041. OwnedArray<MidiMessage>& dest)
  24042. {
  24043. bool doneProg = false;
  24044. bool donePitchWheel = false;
  24045. Array <int> doneControllers;
  24046. doneControllers.ensureStorageAllocated (32);
  24047. for (int i = list.size(); --i >= 0;)
  24048. {
  24049. const MidiMessage& mm = list.getUnchecked(i)->message;
  24050. if (mm.isForChannel (channelNumber)
  24051. && mm.getTimeStamp() <= time)
  24052. {
  24053. if (mm.isProgramChange())
  24054. {
  24055. if (! doneProg)
  24056. {
  24057. dest.add (new MidiMessage (mm, 0.0));
  24058. doneProg = true;
  24059. }
  24060. }
  24061. else if (mm.isController())
  24062. {
  24063. if (! doneControllers.contains (mm.getControllerNumber()))
  24064. {
  24065. dest.add (new MidiMessage (mm, 0.0));
  24066. doneControllers.add (mm.getControllerNumber());
  24067. }
  24068. }
  24069. else if (mm.isPitchWheel())
  24070. {
  24071. if (! donePitchWheel)
  24072. {
  24073. dest.add (new MidiMessage (mm, 0.0));
  24074. donePitchWheel = true;
  24075. }
  24076. }
  24077. }
  24078. }
  24079. }
  24080. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24081. : message (message_),
  24082. noteOffObject (0)
  24083. {
  24084. }
  24085. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24086. {
  24087. }
  24088. END_JUCE_NAMESPACE
  24089. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24090. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24091. BEGIN_JUCE_NAMESPACE
  24092. AudioPluginFormat::AudioPluginFormat() throw()
  24093. {
  24094. }
  24095. AudioPluginFormat::~AudioPluginFormat()
  24096. {
  24097. }
  24098. END_JUCE_NAMESPACE
  24099. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24100. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24101. BEGIN_JUCE_NAMESPACE
  24102. AudioPluginFormatManager::AudioPluginFormatManager()
  24103. {
  24104. }
  24105. AudioPluginFormatManager::~AudioPluginFormatManager()
  24106. {
  24107. clearSingletonInstance();
  24108. }
  24109. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24110. void AudioPluginFormatManager::addDefaultFormats()
  24111. {
  24112. #if JUCE_DEBUG
  24113. // you should only call this method once!
  24114. for (int i = formats.size(); --i >= 0;)
  24115. {
  24116. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24117. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24118. #endif
  24119. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24120. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24121. #endif
  24122. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24123. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24124. #endif
  24125. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24126. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24127. #endif
  24128. }
  24129. #endif
  24130. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24131. formats.add (new AudioUnitPluginFormat());
  24132. #endif
  24133. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24134. formats.add (new VSTPluginFormat());
  24135. #endif
  24136. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24137. formats.add (new DirectXPluginFormat());
  24138. #endif
  24139. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24140. formats.add (new LADSPAPluginFormat());
  24141. #endif
  24142. }
  24143. int AudioPluginFormatManager::getNumFormats()
  24144. {
  24145. return formats.size();
  24146. }
  24147. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24148. {
  24149. return formats [index];
  24150. }
  24151. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24152. {
  24153. formats.add (format);
  24154. }
  24155. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24156. String& errorMessage) const
  24157. {
  24158. AudioPluginInstance* result = 0;
  24159. for (int i = 0; i < formats.size(); ++i)
  24160. {
  24161. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24162. if (result != 0)
  24163. break;
  24164. }
  24165. if (result == 0)
  24166. {
  24167. if (! doesPluginStillExist (description))
  24168. errorMessage = TRANS ("This plug-in file no longer exists");
  24169. else
  24170. errorMessage = TRANS ("This plug-in failed to load correctly");
  24171. }
  24172. return result;
  24173. }
  24174. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24175. {
  24176. for (int i = 0; i < formats.size(); ++i)
  24177. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24178. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24179. return false;
  24180. }
  24181. END_JUCE_NAMESPACE
  24182. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24183. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24184. #define JUCE_PLUGIN_HOST 1
  24185. BEGIN_JUCE_NAMESPACE
  24186. AudioPluginInstance::AudioPluginInstance()
  24187. {
  24188. }
  24189. AudioPluginInstance::~AudioPluginInstance()
  24190. {
  24191. }
  24192. END_JUCE_NAMESPACE
  24193. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24194. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24195. BEGIN_JUCE_NAMESPACE
  24196. KnownPluginList::KnownPluginList()
  24197. {
  24198. }
  24199. KnownPluginList::~KnownPluginList()
  24200. {
  24201. }
  24202. void KnownPluginList::clear()
  24203. {
  24204. if (types.size() > 0)
  24205. {
  24206. types.clear();
  24207. sendChangeMessage (this);
  24208. }
  24209. }
  24210. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  24211. {
  24212. for (int i = 0; i < types.size(); ++i)
  24213. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24214. return types.getUnchecked(i);
  24215. return 0;
  24216. }
  24217. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  24218. {
  24219. for (int i = 0; i < types.size(); ++i)
  24220. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24221. return types.getUnchecked(i);
  24222. return 0;
  24223. }
  24224. bool KnownPluginList::addType (const PluginDescription& type)
  24225. {
  24226. for (int i = types.size(); --i >= 0;)
  24227. {
  24228. if (types.getUnchecked(i)->isDuplicateOf (type))
  24229. {
  24230. // strange - found a duplicate plugin with different info..
  24231. jassert (types.getUnchecked(i)->name == type.name);
  24232. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24233. *types.getUnchecked(i) = type;
  24234. return false;
  24235. }
  24236. }
  24237. types.add (new PluginDescription (type));
  24238. sendChangeMessage (this);
  24239. return true;
  24240. }
  24241. void KnownPluginList::removeType (const int index)
  24242. {
  24243. types.remove (index);
  24244. sendChangeMessage (this);
  24245. }
  24246. static Time getFileModTime (const String& fileOrIdentifier) throw()
  24247. {
  24248. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24249. return File (fileOrIdentifier).getLastModificationTime();
  24250. return Time (0);
  24251. }
  24252. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24253. {
  24254. return t1 != t2 || t1 == Time (0);
  24255. }
  24256. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  24257. {
  24258. if (getTypeForFile (fileOrIdentifier) == 0)
  24259. return false;
  24260. for (int i = types.size(); --i >= 0;)
  24261. {
  24262. const PluginDescription* const d = types.getUnchecked(i);
  24263. if (d->fileOrIdentifier == fileOrIdentifier
  24264. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  24265. {
  24266. return false;
  24267. }
  24268. }
  24269. return true;
  24270. }
  24271. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24272. const bool dontRescanIfAlreadyInList,
  24273. OwnedArray <PluginDescription>& typesFound,
  24274. AudioPluginFormat& format)
  24275. {
  24276. bool addedOne = false;
  24277. if (dontRescanIfAlreadyInList
  24278. && getTypeForFile (fileOrIdentifier) != 0)
  24279. {
  24280. bool needsRescanning = false;
  24281. for (int i = types.size(); --i >= 0;)
  24282. {
  24283. const PluginDescription* const d = types.getUnchecked(i);
  24284. if (d->fileOrIdentifier == fileOrIdentifier)
  24285. {
  24286. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  24287. needsRescanning = true;
  24288. else
  24289. typesFound.add (new PluginDescription (*d));
  24290. }
  24291. }
  24292. if (! needsRescanning)
  24293. return false;
  24294. }
  24295. OwnedArray <PluginDescription> found;
  24296. format.findAllTypesForFile (found, fileOrIdentifier);
  24297. for (int i = 0; i < found.size(); ++i)
  24298. {
  24299. PluginDescription* const desc = found.getUnchecked(i);
  24300. jassert (desc != 0);
  24301. if (addType (*desc))
  24302. addedOne = true;
  24303. typesFound.add (new PluginDescription (*desc));
  24304. }
  24305. return addedOne;
  24306. }
  24307. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24308. OwnedArray <PluginDescription>& typesFound)
  24309. {
  24310. for (int i = 0; i < files.size(); ++i)
  24311. {
  24312. bool loaded = false;
  24313. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24314. {
  24315. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24316. if (scanAndAddFile (files[i], true, typesFound, *format))
  24317. loaded = true;
  24318. }
  24319. if (! loaded)
  24320. {
  24321. const File f (files[i]);
  24322. if (f.isDirectory())
  24323. {
  24324. StringArray s;
  24325. {
  24326. Array<File> subFiles;
  24327. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24328. for (int j = 0; j < subFiles.size(); ++j)
  24329. s.add (subFiles.getReference(j).getFullPathName());
  24330. }
  24331. scanAndAddDragAndDroppedFiles (s, typesFound);
  24332. }
  24333. }
  24334. }
  24335. }
  24336. class PluginSorter
  24337. {
  24338. public:
  24339. KnownPluginList::SortMethod method;
  24340. PluginSorter() throw() {}
  24341. int compareElements (const PluginDescription* const first,
  24342. const PluginDescription* const second) const throw()
  24343. {
  24344. int diff = 0;
  24345. if (method == KnownPluginList::sortByCategory)
  24346. diff = first->category.compareLexicographically (second->category);
  24347. else if (method == KnownPluginList::sortByManufacturer)
  24348. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24349. else if (method == KnownPluginList::sortByFileSystemLocation)
  24350. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24351. .upToLastOccurrenceOf ("/", false, false)
  24352. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24353. .upToLastOccurrenceOf ("/", false, false));
  24354. if (diff == 0)
  24355. diff = first->name.compareLexicographically (second->name);
  24356. return diff;
  24357. }
  24358. };
  24359. void KnownPluginList::sort (const SortMethod method)
  24360. {
  24361. if (method != defaultOrder)
  24362. {
  24363. PluginSorter sorter;
  24364. sorter.method = method;
  24365. types.sort (sorter, true);
  24366. sendChangeMessage (this);
  24367. }
  24368. }
  24369. XmlElement* KnownPluginList::createXml() const
  24370. {
  24371. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24372. for (int i = 0; i < types.size(); ++i)
  24373. e->addChildElement (types.getUnchecked(i)->createXml());
  24374. return e;
  24375. }
  24376. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24377. {
  24378. clear();
  24379. if (xml.hasTagName ("KNOWNPLUGINS"))
  24380. {
  24381. forEachXmlChildElement (xml, e)
  24382. {
  24383. PluginDescription info;
  24384. if (info.loadFromXml (*e))
  24385. addType (info);
  24386. }
  24387. }
  24388. }
  24389. const int menuIdBase = 0x324503f4;
  24390. // This is used to turn a bunch of paths into a nested menu structure.
  24391. struct PluginFilesystemTree
  24392. {
  24393. private:
  24394. String folder;
  24395. OwnedArray <PluginFilesystemTree> subFolders;
  24396. Array <PluginDescription*> plugins;
  24397. void addPlugin (PluginDescription* const pd, const String& path)
  24398. {
  24399. if (path.isEmpty())
  24400. {
  24401. plugins.add (pd);
  24402. }
  24403. else
  24404. {
  24405. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24406. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24407. for (int i = subFolders.size(); --i >= 0;)
  24408. {
  24409. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24410. {
  24411. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24412. return;
  24413. }
  24414. }
  24415. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24416. newFolder->folder = firstSubFolder;
  24417. subFolders.add (newFolder);
  24418. newFolder->addPlugin (pd, remainingPath);
  24419. }
  24420. }
  24421. // removes any deeply nested folders that don't contain any actual plugins
  24422. void optimise()
  24423. {
  24424. for (int i = subFolders.size(); --i >= 0;)
  24425. {
  24426. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24427. sub->optimise();
  24428. if (sub->plugins.size() == 0)
  24429. {
  24430. for (int j = 0; j < sub->subFolders.size(); ++j)
  24431. subFolders.add (sub->subFolders.getUnchecked(j));
  24432. sub->subFolders.clear (false);
  24433. subFolders.remove (i);
  24434. }
  24435. }
  24436. }
  24437. public:
  24438. void buildTree (const Array <PluginDescription*>& allPlugins)
  24439. {
  24440. for (int i = 0; i < allPlugins.size(); ++i)
  24441. {
  24442. String path (allPlugins.getUnchecked(i)
  24443. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24444. .upToLastOccurrenceOf ("/", false, false));
  24445. if (path.substring (1, 2) == ":")
  24446. path = path.substring (2);
  24447. addPlugin (allPlugins.getUnchecked(i), path);
  24448. }
  24449. optimise();
  24450. }
  24451. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24452. {
  24453. int i;
  24454. for (i = 0; i < subFolders.size(); ++i)
  24455. {
  24456. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24457. PopupMenu subMenu;
  24458. sub->addToMenu (subMenu, allPlugins);
  24459. #if JUCE_MAC
  24460. // avoid the special AU formatting nonsense on Mac..
  24461. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24462. #else
  24463. m.addSubMenu (sub->folder, subMenu);
  24464. #endif
  24465. }
  24466. for (i = 0; i < plugins.size(); ++i)
  24467. {
  24468. PluginDescription* const plugin = plugins.getUnchecked(i);
  24469. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24470. plugin->name, true, false);
  24471. }
  24472. }
  24473. };
  24474. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24475. {
  24476. Array <PluginDescription*> sorted;
  24477. {
  24478. PluginSorter sorter;
  24479. sorter.method = sortMethod;
  24480. for (int i = 0; i < types.size(); ++i)
  24481. sorted.addSorted (sorter, types.getUnchecked(i));
  24482. }
  24483. if (sortMethod == sortByCategory
  24484. || sortMethod == sortByManufacturer)
  24485. {
  24486. String lastSubMenuName;
  24487. PopupMenu sub;
  24488. for (int i = 0; i < sorted.size(); ++i)
  24489. {
  24490. const PluginDescription* const pd = sorted.getUnchecked(i);
  24491. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24492. : pd->manufacturerName);
  24493. if (! thisSubMenuName.containsNonWhitespaceChars())
  24494. thisSubMenuName = "Other";
  24495. if (thisSubMenuName != lastSubMenuName)
  24496. {
  24497. if (sub.getNumItems() > 0)
  24498. {
  24499. menu.addSubMenu (lastSubMenuName, sub);
  24500. sub.clear();
  24501. }
  24502. lastSubMenuName = thisSubMenuName;
  24503. }
  24504. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24505. }
  24506. if (sub.getNumItems() > 0)
  24507. menu.addSubMenu (lastSubMenuName, sub);
  24508. }
  24509. else if (sortMethod == sortByFileSystemLocation)
  24510. {
  24511. PluginFilesystemTree root;
  24512. root.buildTree (sorted);
  24513. root.addToMenu (menu, types);
  24514. }
  24515. else
  24516. {
  24517. for (int i = 0; i < sorted.size(); ++i)
  24518. {
  24519. const PluginDescription* const pd = sorted.getUnchecked(i);
  24520. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24521. }
  24522. }
  24523. }
  24524. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24525. {
  24526. const int i = menuResultCode - menuIdBase;
  24527. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24528. }
  24529. END_JUCE_NAMESPACE
  24530. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24531. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24532. BEGIN_JUCE_NAMESPACE
  24533. PluginDescription::PluginDescription()
  24534. : uid (0),
  24535. isInstrument (false),
  24536. numInputChannels (0),
  24537. numOutputChannels (0)
  24538. {
  24539. }
  24540. PluginDescription::~PluginDescription()
  24541. {
  24542. }
  24543. PluginDescription::PluginDescription (const PluginDescription& other)
  24544. : name (other.name),
  24545. pluginFormatName (other.pluginFormatName),
  24546. category (other.category),
  24547. manufacturerName (other.manufacturerName),
  24548. version (other.version),
  24549. fileOrIdentifier (other.fileOrIdentifier),
  24550. lastFileModTime (other.lastFileModTime),
  24551. uid (other.uid),
  24552. isInstrument (other.isInstrument),
  24553. numInputChannels (other.numInputChannels),
  24554. numOutputChannels (other.numOutputChannels)
  24555. {
  24556. }
  24557. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24558. {
  24559. name = other.name;
  24560. pluginFormatName = other.pluginFormatName;
  24561. category = other.category;
  24562. manufacturerName = other.manufacturerName;
  24563. version = other.version;
  24564. fileOrIdentifier = other.fileOrIdentifier;
  24565. uid = other.uid;
  24566. isInstrument = other.isInstrument;
  24567. lastFileModTime = other.lastFileModTime;
  24568. numInputChannels = other.numInputChannels;
  24569. numOutputChannels = other.numOutputChannels;
  24570. return *this;
  24571. }
  24572. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24573. {
  24574. return fileOrIdentifier == other.fileOrIdentifier
  24575. && uid == other.uid;
  24576. }
  24577. const String PluginDescription::createIdentifierString() const
  24578. {
  24579. return pluginFormatName
  24580. + "-" + name
  24581. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24582. + "-" + String::toHexString (uid);
  24583. }
  24584. XmlElement* PluginDescription::createXml() const
  24585. {
  24586. XmlElement* const e = new XmlElement ("PLUGIN");
  24587. e->setAttribute ("name", name);
  24588. e->setAttribute ("format", pluginFormatName);
  24589. e->setAttribute ("category", category);
  24590. e->setAttribute ("manufacturer", manufacturerName);
  24591. e->setAttribute ("version", version);
  24592. e->setAttribute ("file", fileOrIdentifier);
  24593. e->setAttribute ("uid", String::toHexString (uid));
  24594. e->setAttribute ("isInstrument", isInstrument);
  24595. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24596. e->setAttribute ("numInputs", numInputChannels);
  24597. e->setAttribute ("numOutputs", numOutputChannels);
  24598. return e;
  24599. }
  24600. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24601. {
  24602. if (xml.hasTagName ("PLUGIN"))
  24603. {
  24604. name = xml.getStringAttribute ("name");
  24605. pluginFormatName = xml.getStringAttribute ("format");
  24606. category = xml.getStringAttribute ("category");
  24607. manufacturerName = xml.getStringAttribute ("manufacturer");
  24608. version = xml.getStringAttribute ("version");
  24609. fileOrIdentifier = xml.getStringAttribute ("file");
  24610. uid = xml.getStringAttribute ("uid").getHexValue32();
  24611. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24612. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24613. numInputChannels = xml.getIntAttribute ("numInputs");
  24614. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24615. return true;
  24616. }
  24617. return false;
  24618. }
  24619. END_JUCE_NAMESPACE
  24620. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24621. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24622. BEGIN_JUCE_NAMESPACE
  24623. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24624. AudioPluginFormat& formatToLookFor,
  24625. FileSearchPath directoriesToSearch,
  24626. const bool recursive,
  24627. const File& deadMansPedalFile_)
  24628. : list (listToAddTo),
  24629. format (formatToLookFor),
  24630. deadMansPedalFile (deadMansPedalFile_),
  24631. nextIndex (0),
  24632. progress (0)
  24633. {
  24634. directoriesToSearch.removeRedundantPaths();
  24635. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24636. // If any plugins have crashed recently when being loaded, move them to the
  24637. // end of the list to give the others a chance to load correctly..
  24638. const StringArray crashedPlugins (getDeadMansPedalFile());
  24639. for (int i = 0; i < crashedPlugins.size(); ++i)
  24640. {
  24641. const String f = crashedPlugins[i];
  24642. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24643. if (f == filesOrIdentifiersToScan[j])
  24644. filesOrIdentifiersToScan.move (j, -1);
  24645. }
  24646. }
  24647. PluginDirectoryScanner::~PluginDirectoryScanner()
  24648. {
  24649. }
  24650. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24651. {
  24652. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24653. }
  24654. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24655. {
  24656. String file (filesOrIdentifiersToScan [nextIndex]);
  24657. if (file.isNotEmpty())
  24658. {
  24659. if (! list.isListingUpToDate (file))
  24660. {
  24661. OwnedArray <PluginDescription> typesFound;
  24662. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24663. StringArray crashedPlugins (getDeadMansPedalFile());
  24664. crashedPlugins.removeString (file);
  24665. crashedPlugins.add (file);
  24666. setDeadMansPedalFile (crashedPlugins);
  24667. list.scanAndAddFile (file,
  24668. dontRescanIfAlreadyInList,
  24669. typesFound,
  24670. format);
  24671. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24672. crashedPlugins.removeString (file);
  24673. setDeadMansPedalFile (crashedPlugins);
  24674. if (typesFound.size() == 0)
  24675. failedFiles.add (file);
  24676. }
  24677. ++nextIndex;
  24678. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  24679. }
  24680. return nextIndex < filesOrIdentifiersToScan.size();
  24681. }
  24682. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24683. {
  24684. StringArray lines;
  24685. if (deadMansPedalFile != File::nonexistent)
  24686. {
  24687. lines.addLines (deadMansPedalFile.loadFileAsString());
  24688. lines.removeEmptyStrings();
  24689. }
  24690. return lines;
  24691. }
  24692. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24693. {
  24694. if (deadMansPedalFile != File::nonexistent)
  24695. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24696. }
  24697. END_JUCE_NAMESPACE
  24698. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24699. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24700. BEGIN_JUCE_NAMESPACE
  24701. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24702. const File& deadMansPedalFile_,
  24703. PropertiesFile* const propertiesToUse_)
  24704. : list (listToEdit),
  24705. deadMansPedalFile (deadMansPedalFile_),
  24706. propertiesToUse (propertiesToUse_)
  24707. {
  24708. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  24709. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  24710. optionsButton->addButtonListener (this);
  24711. optionsButton->setTriggeredOnMouseDown (true);
  24712. setSize (400, 600);
  24713. list.addChangeListener (this);
  24714. changeListenerCallback (0);
  24715. }
  24716. PluginListComponent::~PluginListComponent()
  24717. {
  24718. list.removeChangeListener (this);
  24719. deleteAllChildren();
  24720. }
  24721. void PluginListComponent::resized()
  24722. {
  24723. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  24724. optionsButton->changeWidthToFitText (24);
  24725. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  24726. }
  24727. void PluginListComponent::changeListenerCallback (void*)
  24728. {
  24729. listBox->updateContent();
  24730. listBox->repaint();
  24731. }
  24732. int PluginListComponent::getNumRows()
  24733. {
  24734. return list.getNumTypes();
  24735. }
  24736. void PluginListComponent::paintListBoxItem (int row,
  24737. Graphics& g,
  24738. int width, int height,
  24739. bool rowIsSelected)
  24740. {
  24741. if (rowIsSelected)
  24742. g.fillAll (findColour (TextEditor::highlightColourId));
  24743. const PluginDescription* const pd = list.getType (row);
  24744. if (pd != 0)
  24745. {
  24746. GlyphArrangement ga;
  24747. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24748. g.setColour (Colours::black);
  24749. ga.draw (g);
  24750. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24751. String desc;
  24752. desc << pd->pluginFormatName
  24753. << (pd->isInstrument ? " instrument" : " effect")
  24754. << " - "
  24755. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24756. << " / "
  24757. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24758. if (pd->manufacturerName.isNotEmpty())
  24759. desc << " - " << pd->manufacturerName;
  24760. if (pd->version.isNotEmpty())
  24761. desc << " - " << pd->version;
  24762. if (pd->category.isNotEmpty())
  24763. desc << " - category: '" << pd->category << '\'';
  24764. g.setColour (Colours::grey);
  24765. ga.clear();
  24766. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24767. ga.draw (g);
  24768. }
  24769. }
  24770. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24771. {
  24772. list.removeType (lastRowSelected);
  24773. }
  24774. void PluginListComponent::buttonClicked (Button* b)
  24775. {
  24776. if (optionsButton == b)
  24777. {
  24778. PopupMenu menu;
  24779. menu.addItem (1, TRANS("Clear list"));
  24780. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24781. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24782. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24783. menu.addSeparator();
  24784. menu.addItem (2, TRANS("Sort alphabetically"));
  24785. menu.addItem (3, TRANS("Sort by category"));
  24786. menu.addItem (4, TRANS("Sort by manufacturer"));
  24787. menu.addSeparator();
  24788. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24789. {
  24790. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24791. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24792. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24793. }
  24794. const int r = menu.showAt (optionsButton);
  24795. if (r == 1)
  24796. {
  24797. list.clear();
  24798. }
  24799. else if (r == 2)
  24800. {
  24801. list.sort (KnownPluginList::sortAlphabetically);
  24802. }
  24803. else if (r == 3)
  24804. {
  24805. list.sort (KnownPluginList::sortByCategory);
  24806. }
  24807. else if (r == 4)
  24808. {
  24809. list.sort (KnownPluginList::sortByManufacturer);
  24810. }
  24811. else if (r == 5)
  24812. {
  24813. const SparseSet <int> selected (listBox->getSelectedRows());
  24814. for (int i = list.getNumTypes(); --i >= 0;)
  24815. if (selected.contains (i))
  24816. list.removeType (i);
  24817. }
  24818. else if (r == 6)
  24819. {
  24820. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24821. if (desc != 0)
  24822. {
  24823. if (File (desc->fileOrIdentifier).existsAsFile())
  24824. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24825. }
  24826. }
  24827. else if (r == 7)
  24828. {
  24829. for (int i = list.getNumTypes(); --i >= 0;)
  24830. {
  24831. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24832. {
  24833. list.removeType (i);
  24834. }
  24835. }
  24836. }
  24837. else if (r != 0)
  24838. {
  24839. typeToScan = r - 10;
  24840. startTimer (1);
  24841. }
  24842. }
  24843. }
  24844. void PluginListComponent::timerCallback()
  24845. {
  24846. stopTimer();
  24847. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24848. }
  24849. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24850. {
  24851. return true;
  24852. }
  24853. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24854. {
  24855. OwnedArray <PluginDescription> typesFound;
  24856. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24857. }
  24858. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24859. {
  24860. if (format == 0)
  24861. return;
  24862. FileSearchPath path (format->getDefaultLocationsToSearch());
  24863. if (propertiesToUse != 0)
  24864. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24865. {
  24866. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24867. FileSearchPathListComponent pathList;
  24868. pathList.setSize (500, 300);
  24869. pathList.setPath (path);
  24870. aw.addCustomComponent (&pathList);
  24871. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24872. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24873. if (aw.runModalLoop() == 0)
  24874. return;
  24875. path = pathList.getPath();
  24876. }
  24877. if (propertiesToUse != 0)
  24878. {
  24879. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24880. propertiesToUse->saveIfNeeded();
  24881. }
  24882. double progress = 0.0;
  24883. AlertWindow aw (TRANS("Scanning for plugins..."),
  24884. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24885. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24886. aw.addProgressBarComponent (progress);
  24887. aw.enterModalState();
  24888. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24889. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24890. for (;;)
  24891. {
  24892. aw.setMessage (TRANS("Testing:\n\n")
  24893. + scanner.getNextPluginFileThatWillBeScanned());
  24894. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24895. if (! scanner.scanNextFile (true))
  24896. break;
  24897. if (! aw.isCurrentlyModal())
  24898. break;
  24899. progress = scanner.getProgress();
  24900. }
  24901. if (scanner.getFailedFiles().size() > 0)
  24902. {
  24903. StringArray shortNames;
  24904. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24905. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24906. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24907. TRANS("Scan complete"),
  24908. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24909. + shortNames.joinIntoString (", "));
  24910. }
  24911. }
  24912. END_JUCE_NAMESPACE
  24913. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24914. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24915. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24916. #include <AudioUnit/AudioUnit.h>
  24917. #include <AudioUnit/AUCocoaUIView.h>
  24918. #include <CoreAudioKit/AUGenericView.h>
  24919. #if JUCE_SUPPORT_CARBON
  24920. #include <AudioToolbox/AudioUnitUtilities.h>
  24921. #include <AudioUnit/AudioUnitCarbonView.h>
  24922. #endif
  24923. BEGIN_JUCE_NAMESPACE
  24924. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24925. #endif
  24926. #if JUCE_MAC
  24927. // Change this to disable logging of various activities
  24928. #ifndef AU_LOGGING
  24929. #define AU_LOGGING 1
  24930. #endif
  24931. #if AU_LOGGING
  24932. #define log(a) Logger::writeToLog(a);
  24933. #else
  24934. #define log(a)
  24935. #endif
  24936. namespace AudioUnitFormatHelpers
  24937. {
  24938. static int insideCallback = 0;
  24939. static const String osTypeToString (OSType type)
  24940. {
  24941. char s[4];
  24942. s[0] = (char) (((uint32) type) >> 24);
  24943. s[1] = (char) (((uint32) type) >> 16);
  24944. s[2] = (char) (((uint32) type) >> 8);
  24945. s[3] = (char) ((uint32) type);
  24946. return String (s, 4);
  24947. }
  24948. static OSType stringToOSType (const String& s1)
  24949. {
  24950. const String s (s1 + " ");
  24951. return (((OSType) (unsigned char) s[0]) << 24)
  24952. | (((OSType) (unsigned char) s[1]) << 16)
  24953. | (((OSType) (unsigned char) s[2]) << 8)
  24954. | ((OSType) (unsigned char) s[3]);
  24955. }
  24956. static const char* auIdentifierPrefix = "AudioUnit:";
  24957. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24958. {
  24959. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24960. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24961. String s (auIdentifierPrefix);
  24962. if (desc.componentType == kAudioUnitType_MusicDevice)
  24963. s << "Synths/";
  24964. else if (desc.componentType == kAudioUnitType_MusicEffect
  24965. || desc.componentType == kAudioUnitType_Effect)
  24966. s << "Effects/";
  24967. else if (desc.componentType == kAudioUnitType_Generator)
  24968. s << "Generators/";
  24969. else if (desc.componentType == kAudioUnitType_Panner)
  24970. s << "Panners/";
  24971. s << osTypeToString (desc.componentType) << ","
  24972. << osTypeToString (desc.componentSubType) << ","
  24973. << osTypeToString (desc.componentManufacturer);
  24974. return s;
  24975. }
  24976. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24977. {
  24978. Handle componentNameHandle = NewHandle (sizeof (void*));
  24979. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24980. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24981. {
  24982. ComponentDescription desc;
  24983. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24984. {
  24985. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24986. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24987. if (nameString != 0 && nameString[0] != 0)
  24988. {
  24989. const String all ((const char*) nameString + 1, nameString[0]);
  24990. DBG ("name: "+ all);
  24991. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24992. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24993. }
  24994. if (infoString != 0 && infoString[0] != 0)
  24995. {
  24996. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24997. }
  24998. if (name.isEmpty())
  24999. name = "<Unknown>";
  25000. }
  25001. DisposeHandle (componentNameHandle);
  25002. DisposeHandle (componentInfoHandle);
  25003. }
  25004. }
  25005. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25006. String& name, String& version, String& manufacturer)
  25007. {
  25008. zerostruct (desc);
  25009. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25010. {
  25011. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25012. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25013. StringArray tokens;
  25014. tokens.addTokens (s, ",", String::empty);
  25015. tokens.trim();
  25016. tokens.removeEmptyStrings();
  25017. if (tokens.size() == 3)
  25018. {
  25019. desc.componentType = stringToOSType (tokens[0]);
  25020. desc.componentSubType = stringToOSType (tokens[1]);
  25021. desc.componentManufacturer = stringToOSType (tokens[2]);
  25022. ComponentRecord* comp = FindNextComponent (0, &desc);
  25023. if (comp != 0)
  25024. {
  25025. getAUDetails (comp, name, manufacturer);
  25026. return true;
  25027. }
  25028. }
  25029. }
  25030. return false;
  25031. }
  25032. }
  25033. class AudioUnitPluginWindowCarbon;
  25034. class AudioUnitPluginWindowCocoa;
  25035. class AudioUnitPluginInstance : public AudioPluginInstance
  25036. {
  25037. public:
  25038. ~AudioUnitPluginInstance();
  25039. // AudioPluginInstance methods:
  25040. void fillInPluginDescription (PluginDescription& desc) const
  25041. {
  25042. desc.name = pluginName;
  25043. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25044. desc.uid = ((int) componentDesc.componentType)
  25045. ^ ((int) componentDesc.componentSubType)
  25046. ^ ((int) componentDesc.componentManufacturer);
  25047. desc.lastFileModTime = 0;
  25048. desc.pluginFormatName = "AudioUnit";
  25049. desc.category = getCategory();
  25050. desc.manufacturerName = manufacturer;
  25051. desc.version = version;
  25052. desc.numInputChannels = getNumInputChannels();
  25053. desc.numOutputChannels = getNumOutputChannels();
  25054. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25055. }
  25056. const String getName() const { return pluginName; }
  25057. bool acceptsMidi() const { return wantsMidiMessages; }
  25058. bool producesMidi() const { return false; }
  25059. // AudioProcessor methods:
  25060. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25061. void releaseResources();
  25062. void processBlock (AudioSampleBuffer& buffer,
  25063. MidiBuffer& midiMessages);
  25064. AudioProcessorEditor* createEditor();
  25065. const String getInputChannelName (int index) const;
  25066. bool isInputChannelStereoPair (int index) const;
  25067. const String getOutputChannelName (int index) const;
  25068. bool isOutputChannelStereoPair (int index) const;
  25069. int getNumParameters();
  25070. float getParameter (int index);
  25071. void setParameter (int index, float newValue);
  25072. const String getParameterName (int index);
  25073. const String getParameterText (int index);
  25074. bool isParameterAutomatable (int index) const;
  25075. int getNumPrograms();
  25076. int getCurrentProgram();
  25077. void setCurrentProgram (int index);
  25078. const String getProgramName (int index);
  25079. void changeProgramName (int index, const String& newName);
  25080. void getStateInformation (MemoryBlock& destData);
  25081. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25082. void setStateInformation (const void* data, int sizeInBytes);
  25083. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25084. juce_UseDebuggingNewOperator
  25085. private:
  25086. friend class AudioUnitPluginWindowCarbon;
  25087. friend class AudioUnitPluginWindowCocoa;
  25088. friend class AudioUnitPluginFormat;
  25089. ComponentDescription componentDesc;
  25090. String pluginName, manufacturer, version;
  25091. String fileOrIdentifier;
  25092. CriticalSection lock;
  25093. bool initialised, wantsMidiMessages, wasPlaying;
  25094. HeapBlock <AudioBufferList> outputBufferList;
  25095. AudioTimeStamp timeStamp;
  25096. AudioSampleBuffer* currentBuffer;
  25097. AudioUnit audioUnit;
  25098. Array <int> parameterIds;
  25099. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25100. void initialise();
  25101. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25102. const AudioTimeStamp* inTimeStamp,
  25103. UInt32 inBusNumber,
  25104. UInt32 inNumberFrames,
  25105. AudioBufferList* ioData) const;
  25106. static OSStatus renderGetInputCallback (void* inRefCon,
  25107. AudioUnitRenderActionFlags* ioActionFlags,
  25108. const AudioTimeStamp* inTimeStamp,
  25109. UInt32 inBusNumber,
  25110. UInt32 inNumberFrames,
  25111. AudioBufferList* ioData)
  25112. {
  25113. return ((AudioUnitPluginInstance*) inRefCon)
  25114. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25115. }
  25116. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25117. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25118. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25119. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25120. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25121. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25122. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25123. {
  25124. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25125. }
  25126. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25127. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25128. Float64* outCurrentMeasureDownBeat)
  25129. {
  25130. return ((AudioUnitPluginInstance*) inHostUserData)
  25131. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25132. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25133. }
  25134. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25135. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25136. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25137. {
  25138. return ((AudioUnitPluginInstance*) inHostUserData)
  25139. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25140. outCurrentSampleInTimeLine, outIsCycling,
  25141. outCycleStartBeat, outCycleEndBeat);
  25142. }
  25143. void getNumChannels (int& numIns, int& numOuts)
  25144. {
  25145. numIns = 0;
  25146. numOuts = 0;
  25147. AUChannelInfo supportedChannels [128];
  25148. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25149. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25150. 0, supportedChannels, &supportedChannelsSize) == noErr
  25151. && supportedChannelsSize > 0)
  25152. {
  25153. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25154. {
  25155. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  25156. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  25157. }
  25158. }
  25159. else
  25160. {
  25161. // (this really means the plugin will take any number of ins/outs as long
  25162. // as they are the same)
  25163. numIns = numOuts = 2;
  25164. }
  25165. }
  25166. const String getCategory() const;
  25167. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25168. };
  25169. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25170. : fileOrIdentifier (fileOrIdentifier),
  25171. initialised (false),
  25172. wantsMidiMessages (false),
  25173. audioUnit (0),
  25174. currentBuffer (0)
  25175. {
  25176. using namespace AudioUnitFormatHelpers;
  25177. try
  25178. {
  25179. ++insideCallback;
  25180. log ("Opening AU: " + fileOrIdentifier);
  25181. if (getComponentDescFromFile (fileOrIdentifier))
  25182. {
  25183. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25184. if (comp != 0)
  25185. {
  25186. audioUnit = (AudioUnit) OpenComponent (comp);
  25187. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25188. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25189. }
  25190. }
  25191. --insideCallback;
  25192. }
  25193. catch (...)
  25194. {
  25195. --insideCallback;
  25196. }
  25197. }
  25198. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25199. {
  25200. const ScopedLock sl (lock);
  25201. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25202. if (audioUnit != 0)
  25203. {
  25204. AudioUnitUninitialize (audioUnit);
  25205. CloseComponent (audioUnit);
  25206. audioUnit = 0;
  25207. }
  25208. }
  25209. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25210. {
  25211. zerostruct (componentDesc);
  25212. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25213. return true;
  25214. const File file (fileOrIdentifier);
  25215. if (! file.hasFileExtension (".component"))
  25216. return false;
  25217. const char* const utf8 = fileOrIdentifier.toUTF8();
  25218. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25219. strlen (utf8), file.isDirectory());
  25220. if (url != 0)
  25221. {
  25222. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25223. CFRelease (url);
  25224. if (bundleRef != 0)
  25225. {
  25226. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25227. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25228. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25229. if (pluginName.isEmpty())
  25230. pluginName = file.getFileNameWithoutExtension();
  25231. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25232. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25233. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25234. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25235. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25236. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25237. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25238. UseResFile (resFileId);
  25239. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25240. {
  25241. Handle h = Get1IndResource ('thng', i);
  25242. if (h != 0)
  25243. {
  25244. HLock (h);
  25245. const uint32* const types = (const uint32*) *h;
  25246. if (types[0] == kAudioUnitType_MusicDevice
  25247. || types[0] == kAudioUnitType_MusicEffect
  25248. || types[0] == kAudioUnitType_Effect
  25249. || types[0] == kAudioUnitType_Generator
  25250. || types[0] == kAudioUnitType_Panner)
  25251. {
  25252. componentDesc.componentType = types[0];
  25253. componentDesc.componentSubType = types[1];
  25254. componentDesc.componentManufacturer = types[2];
  25255. break;
  25256. }
  25257. HUnlock (h);
  25258. ReleaseResource (h);
  25259. }
  25260. }
  25261. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25262. CFRelease (bundleRef);
  25263. }
  25264. }
  25265. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25266. }
  25267. void AudioUnitPluginInstance::initialise()
  25268. {
  25269. if (initialised || audioUnit == 0)
  25270. return;
  25271. log ("Initialising AU: " + pluginName);
  25272. parameterIds.clear();
  25273. {
  25274. UInt32 paramListSize = 0;
  25275. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25276. 0, 0, &paramListSize);
  25277. if (paramListSize > 0)
  25278. {
  25279. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25280. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25281. 0, &parameterIds.getReference(0), &paramListSize);
  25282. }
  25283. }
  25284. {
  25285. AURenderCallbackStruct info;
  25286. zerostruct (info);
  25287. info.inputProcRefCon = this;
  25288. info.inputProc = renderGetInputCallback;
  25289. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25290. 0, &info, sizeof (info));
  25291. }
  25292. {
  25293. HostCallbackInfo info;
  25294. zerostruct (info);
  25295. info.hostUserData = this;
  25296. info.beatAndTempoProc = getBeatAndTempoCallback;
  25297. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25298. info.transportStateProc = getTransportStateCallback;
  25299. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25300. 0, &info, sizeof (info));
  25301. }
  25302. int numIns, numOuts;
  25303. getNumChannels (numIns, numOuts);
  25304. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25305. initialised = AudioUnitInitialize (audioUnit) == noErr;
  25306. setLatencySamples (0);
  25307. }
  25308. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25309. int samplesPerBlockExpected)
  25310. {
  25311. if (audioUnit != 0)
  25312. {
  25313. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25314. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25315. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25316. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25317. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25318. {
  25319. if (initialised)
  25320. {
  25321. AudioUnitUninitialize (audioUnit);
  25322. initialised = false;
  25323. }
  25324. Float64 sr = sampleRate_;
  25325. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25326. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25327. }
  25328. }
  25329. initialise();
  25330. if (initialised)
  25331. {
  25332. int numIns, numOuts;
  25333. getNumChannels (numIns, numOuts);
  25334. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25335. Float64 latencySecs = 0.0;
  25336. UInt32 latencySize = sizeof (latencySecs);
  25337. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25338. 0, &latencySecs, &latencySize);
  25339. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25340. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25341. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25342. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25343. AudioStreamBasicDescription stream;
  25344. zerostruct (stream);
  25345. stream.mSampleRate = sampleRate_;
  25346. stream.mFormatID = kAudioFormatLinearPCM;
  25347. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25348. stream.mFramesPerPacket = 1;
  25349. stream.mBytesPerPacket = 4;
  25350. stream.mBytesPerFrame = 4;
  25351. stream.mBitsPerChannel = 32;
  25352. stream.mChannelsPerFrame = numIns;
  25353. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25354. 0, &stream, sizeof (stream));
  25355. stream.mChannelsPerFrame = numOuts;
  25356. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25357. 0, &stream, sizeof (stream));
  25358. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25359. outputBufferList->mNumberBuffers = numOuts;
  25360. for (int i = numOuts; --i >= 0;)
  25361. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25362. zerostruct (timeStamp);
  25363. timeStamp.mSampleTime = 0;
  25364. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25365. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25366. currentBuffer = 0;
  25367. wasPlaying = false;
  25368. }
  25369. }
  25370. void AudioUnitPluginInstance::releaseResources()
  25371. {
  25372. if (initialised)
  25373. {
  25374. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25375. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25376. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25377. outputBufferList.free();
  25378. currentBuffer = 0;
  25379. }
  25380. }
  25381. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25382. const AudioTimeStamp* inTimeStamp,
  25383. UInt32 inBusNumber,
  25384. UInt32 inNumberFrames,
  25385. AudioBufferList* ioData) const
  25386. {
  25387. if (inBusNumber == 0
  25388. && currentBuffer != 0)
  25389. {
  25390. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25391. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25392. {
  25393. if (i < currentBuffer->getNumChannels())
  25394. {
  25395. memcpy (ioData->mBuffers[i].mData,
  25396. currentBuffer->getSampleData (i, 0),
  25397. sizeof (float) * inNumberFrames);
  25398. }
  25399. else
  25400. {
  25401. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25402. }
  25403. }
  25404. }
  25405. return noErr;
  25406. }
  25407. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25408. MidiBuffer& midiMessages)
  25409. {
  25410. const int numSamples = buffer.getNumSamples();
  25411. if (initialised)
  25412. {
  25413. AudioUnitRenderActionFlags flags = 0;
  25414. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25415. for (int i = getNumOutputChannels(); --i >= 0;)
  25416. {
  25417. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25418. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25419. }
  25420. currentBuffer = &buffer;
  25421. if (wantsMidiMessages)
  25422. {
  25423. const uint8* midiEventData;
  25424. int midiEventSize, midiEventPosition;
  25425. MidiBuffer::Iterator i (midiMessages);
  25426. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25427. {
  25428. if (midiEventSize <= 3)
  25429. MusicDeviceMIDIEvent (audioUnit,
  25430. midiEventData[0], midiEventData[1], midiEventData[2],
  25431. midiEventPosition);
  25432. else
  25433. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25434. }
  25435. midiMessages.clear();
  25436. }
  25437. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25438. 0, numSamples, outputBufferList);
  25439. timeStamp.mSampleTime += numSamples;
  25440. }
  25441. else
  25442. {
  25443. // Not initialised, so just bypass..
  25444. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25445. buffer.clear (i, 0, buffer.getNumSamples());
  25446. }
  25447. }
  25448. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25449. {
  25450. AudioPlayHead* const ph = getPlayHead();
  25451. AudioPlayHead::CurrentPositionInfo result;
  25452. if (ph != 0 && ph->getCurrentPosition (result))
  25453. {
  25454. if (outCurrentBeat != 0)
  25455. *outCurrentBeat = result.ppqPosition;
  25456. if (outCurrentTempo != 0)
  25457. *outCurrentTempo = result.bpm;
  25458. }
  25459. else
  25460. {
  25461. if (outCurrentBeat != 0)
  25462. *outCurrentBeat = 0;
  25463. if (outCurrentTempo != 0)
  25464. *outCurrentTempo = 120.0;
  25465. }
  25466. return noErr;
  25467. }
  25468. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25469. Float32* outTimeSig_Numerator,
  25470. UInt32* outTimeSig_Denominator,
  25471. Float64* outCurrentMeasureDownBeat) const
  25472. {
  25473. AudioPlayHead* const ph = getPlayHead();
  25474. AudioPlayHead::CurrentPositionInfo result;
  25475. if (ph != 0 && ph->getCurrentPosition (result))
  25476. {
  25477. if (outTimeSig_Numerator != 0)
  25478. *outTimeSig_Numerator = result.timeSigNumerator;
  25479. if (outTimeSig_Denominator != 0)
  25480. *outTimeSig_Denominator = result.timeSigDenominator;
  25481. if (outDeltaSampleOffsetToNextBeat != 0)
  25482. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25483. if (outCurrentMeasureDownBeat != 0)
  25484. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25485. }
  25486. else
  25487. {
  25488. if (outDeltaSampleOffsetToNextBeat != 0)
  25489. *outDeltaSampleOffsetToNextBeat = 0;
  25490. if (outTimeSig_Numerator != 0)
  25491. *outTimeSig_Numerator = 4;
  25492. if (outTimeSig_Denominator != 0)
  25493. *outTimeSig_Denominator = 4;
  25494. if (outCurrentMeasureDownBeat != 0)
  25495. *outCurrentMeasureDownBeat = 0;
  25496. }
  25497. return noErr;
  25498. }
  25499. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25500. Boolean* outTransportStateChanged,
  25501. Float64* outCurrentSampleInTimeLine,
  25502. Boolean* outIsCycling,
  25503. Float64* outCycleStartBeat,
  25504. Float64* outCycleEndBeat)
  25505. {
  25506. AudioPlayHead* const ph = getPlayHead();
  25507. AudioPlayHead::CurrentPositionInfo result;
  25508. if (ph != 0 && ph->getCurrentPosition (result))
  25509. {
  25510. if (outIsPlaying != 0)
  25511. *outIsPlaying = result.isPlaying;
  25512. if (outTransportStateChanged != 0)
  25513. {
  25514. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25515. wasPlaying = result.isPlaying;
  25516. }
  25517. if (outCurrentSampleInTimeLine != 0)
  25518. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25519. if (outIsCycling != 0)
  25520. *outIsCycling = false;
  25521. if (outCycleStartBeat != 0)
  25522. *outCycleStartBeat = 0;
  25523. if (outCycleEndBeat != 0)
  25524. *outCycleEndBeat = 0;
  25525. }
  25526. else
  25527. {
  25528. if (outIsPlaying != 0)
  25529. *outIsPlaying = false;
  25530. if (outTransportStateChanged != 0)
  25531. *outTransportStateChanged = false;
  25532. if (outCurrentSampleInTimeLine != 0)
  25533. *outCurrentSampleInTimeLine = 0;
  25534. if (outIsCycling != 0)
  25535. *outIsCycling = false;
  25536. if (outCycleStartBeat != 0)
  25537. *outCycleStartBeat = 0;
  25538. if (outCycleEndBeat != 0)
  25539. *outCycleEndBeat = 0;
  25540. }
  25541. return noErr;
  25542. }
  25543. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  25544. {
  25545. public:
  25546. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25547. : AudioProcessorEditor (&plugin_),
  25548. plugin (plugin_)
  25549. {
  25550. addAndMakeVisible (&wrapper);
  25551. setOpaque (true);
  25552. setVisible (true);
  25553. setSize (100, 100);
  25554. createView (createGenericViewIfNeeded);
  25555. }
  25556. ~AudioUnitPluginWindowCocoa()
  25557. {
  25558. const bool wasValid = isValid();
  25559. wrapper.setView (0);
  25560. if (wasValid)
  25561. plugin.editorBeingDeleted (this);
  25562. }
  25563. bool isValid() const { return wrapper.getView() != 0; }
  25564. void paint (Graphics& g)
  25565. {
  25566. g.fillAll (Colours::white);
  25567. }
  25568. void resized()
  25569. {
  25570. wrapper.setSize (getWidth(), getHeight());
  25571. }
  25572. private:
  25573. AudioUnitPluginInstance& plugin;
  25574. NSViewComponent wrapper;
  25575. bool createView (const bool createGenericViewIfNeeded)
  25576. {
  25577. NSView* pluginView = 0;
  25578. UInt32 dataSize = 0;
  25579. Boolean isWritable = false;
  25580. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25581. 0, &dataSize, &isWritable) == noErr
  25582. && dataSize != 0
  25583. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25584. 0, &dataSize, &isWritable) == noErr)
  25585. {
  25586. HeapBlock <AudioUnitCocoaViewInfo> info;
  25587. info.calloc (dataSize, 1);
  25588. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25589. 0, info, &dataSize) == noErr)
  25590. {
  25591. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25592. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25593. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25594. Class viewClass = [viewBundle classNamed: viewClassName];
  25595. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25596. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25597. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25598. {
  25599. id factory = [[[viewClass alloc] init] autorelease];
  25600. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25601. withSize: NSMakeSize (getWidth(), getHeight())];
  25602. }
  25603. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25604. {
  25605. CFRelease (info->mCocoaAUViewClass[i]);
  25606. CFRelease (info->mCocoaAUViewBundleLocation);
  25607. }
  25608. }
  25609. }
  25610. if (createGenericViewIfNeeded && (pluginView == 0))
  25611. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25612. wrapper.setView (pluginView);
  25613. if (pluginView != 0)
  25614. setSize ([pluginView frame].size.width,
  25615. [pluginView frame].size.height);
  25616. return pluginView != 0;
  25617. }
  25618. };
  25619. #if JUCE_SUPPORT_CARBON
  25620. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25621. {
  25622. public:
  25623. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25624. : AudioProcessorEditor (&plugin_),
  25625. plugin (plugin_),
  25626. viewComponent (0)
  25627. {
  25628. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25629. setOpaque (true);
  25630. setVisible (true);
  25631. setSize (400, 300);
  25632. ComponentDescription viewList [16];
  25633. UInt32 viewListSize = sizeof (viewList);
  25634. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25635. 0, &viewList, &viewListSize);
  25636. componentRecord = FindNextComponent (0, &viewList[0]);
  25637. }
  25638. ~AudioUnitPluginWindowCarbon()
  25639. {
  25640. innerWrapper = 0;
  25641. if (isValid())
  25642. plugin.editorBeingDeleted (this);
  25643. }
  25644. bool isValid() const throw() { return componentRecord != 0; }
  25645. void paint (Graphics& g)
  25646. {
  25647. g.fillAll (Colours::black);
  25648. }
  25649. void resized()
  25650. {
  25651. innerWrapper->setSize (getWidth(), getHeight());
  25652. }
  25653. bool keyStateChanged (bool)
  25654. {
  25655. return false;
  25656. }
  25657. bool keyPressed (const KeyPress&)
  25658. {
  25659. return false;
  25660. }
  25661. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25662. AudioUnitCarbonView getViewComponent()
  25663. {
  25664. if (viewComponent == 0 && componentRecord != 0)
  25665. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25666. return viewComponent;
  25667. }
  25668. void closeViewComponent()
  25669. {
  25670. if (viewComponent != 0)
  25671. {
  25672. log ("Closing AU GUI: " + plugin.getName());
  25673. CloseComponent (viewComponent);
  25674. viewComponent = 0;
  25675. }
  25676. }
  25677. juce_UseDebuggingNewOperator
  25678. private:
  25679. AudioUnitPluginInstance& plugin;
  25680. ComponentRecord* componentRecord;
  25681. AudioUnitCarbonView viewComponent;
  25682. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25683. {
  25684. public:
  25685. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25686. : owner (owner_)
  25687. {
  25688. }
  25689. ~InnerWrapperComponent()
  25690. {
  25691. deleteWindow();
  25692. }
  25693. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25694. {
  25695. log ("Opening AU GUI: " + owner->plugin.getName());
  25696. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25697. if (viewComponent == 0)
  25698. return 0;
  25699. Float32Point pos = { 0, 0 };
  25700. Float32Point size = { 250, 200 };
  25701. HIViewRef pluginView = 0;
  25702. AudioUnitCarbonViewCreate (viewComponent,
  25703. owner->getAudioUnit(),
  25704. windowRef,
  25705. rootView,
  25706. &pos,
  25707. &size,
  25708. (ControlRef*) &pluginView);
  25709. return pluginView;
  25710. }
  25711. void removeView (HIViewRef)
  25712. {
  25713. owner->closeViewComponent();
  25714. }
  25715. private:
  25716. AudioUnitPluginWindowCarbon* const owner;
  25717. };
  25718. friend class InnerWrapperComponent;
  25719. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25720. };
  25721. #endif
  25722. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25723. {
  25724. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25725. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25726. w = 0;
  25727. #if JUCE_SUPPORT_CARBON
  25728. if (w == 0)
  25729. {
  25730. w = new AudioUnitPluginWindowCarbon (*this);
  25731. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25732. w = 0;
  25733. }
  25734. #endif
  25735. if (w == 0)
  25736. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25737. return w.release();
  25738. }
  25739. const String AudioUnitPluginInstance::getCategory() const
  25740. {
  25741. const char* result = 0;
  25742. switch (componentDesc.componentType)
  25743. {
  25744. case kAudioUnitType_Effect:
  25745. case kAudioUnitType_MusicEffect:
  25746. result = "Effect";
  25747. break;
  25748. case kAudioUnitType_MusicDevice:
  25749. result = "Synth";
  25750. break;
  25751. case kAudioUnitType_Generator:
  25752. result = "Generator";
  25753. break;
  25754. case kAudioUnitType_Panner:
  25755. result = "Panner";
  25756. break;
  25757. default:
  25758. break;
  25759. }
  25760. return result;
  25761. }
  25762. int AudioUnitPluginInstance::getNumParameters()
  25763. {
  25764. return parameterIds.size();
  25765. }
  25766. float AudioUnitPluginInstance::getParameter (int index)
  25767. {
  25768. const ScopedLock sl (lock);
  25769. Float32 value = 0.0f;
  25770. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25771. {
  25772. AudioUnitGetParameter (audioUnit,
  25773. (UInt32) parameterIds.getUnchecked (index),
  25774. kAudioUnitScope_Global, 0,
  25775. &value);
  25776. }
  25777. return value;
  25778. }
  25779. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25780. {
  25781. const ScopedLock sl (lock);
  25782. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25783. {
  25784. AudioUnitSetParameter (audioUnit,
  25785. (UInt32) parameterIds.getUnchecked (index),
  25786. kAudioUnitScope_Global, 0,
  25787. newValue, 0);
  25788. }
  25789. }
  25790. const String AudioUnitPluginInstance::getParameterName (int index)
  25791. {
  25792. AudioUnitParameterInfo info;
  25793. zerostruct (info);
  25794. UInt32 sz = sizeof (info);
  25795. String name;
  25796. if (AudioUnitGetProperty (audioUnit,
  25797. kAudioUnitProperty_ParameterInfo,
  25798. kAudioUnitScope_Global,
  25799. parameterIds [index], &info, &sz) == noErr)
  25800. {
  25801. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25802. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25803. else
  25804. name = String (info.name, sizeof (info.name));
  25805. }
  25806. return name;
  25807. }
  25808. const String AudioUnitPluginInstance::getParameterText (int index)
  25809. {
  25810. return String (getParameter (index));
  25811. }
  25812. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25813. {
  25814. AudioUnitParameterInfo info;
  25815. UInt32 sz = sizeof (info);
  25816. if (AudioUnitGetProperty (audioUnit,
  25817. kAudioUnitProperty_ParameterInfo,
  25818. kAudioUnitScope_Global,
  25819. parameterIds [index], &info, &sz) == noErr)
  25820. {
  25821. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25822. }
  25823. return true;
  25824. }
  25825. int AudioUnitPluginInstance::getNumPrograms()
  25826. {
  25827. CFArrayRef presets;
  25828. UInt32 sz = sizeof (CFArrayRef);
  25829. int num = 0;
  25830. if (AudioUnitGetProperty (audioUnit,
  25831. kAudioUnitProperty_FactoryPresets,
  25832. kAudioUnitScope_Global,
  25833. 0, &presets, &sz) == noErr)
  25834. {
  25835. num = (int) CFArrayGetCount (presets);
  25836. CFRelease (presets);
  25837. }
  25838. return num;
  25839. }
  25840. int AudioUnitPluginInstance::getCurrentProgram()
  25841. {
  25842. AUPreset current;
  25843. current.presetNumber = 0;
  25844. UInt32 sz = sizeof (AUPreset);
  25845. AudioUnitGetProperty (audioUnit,
  25846. kAudioUnitProperty_FactoryPresets,
  25847. kAudioUnitScope_Global,
  25848. 0, &current, &sz);
  25849. return current.presetNumber;
  25850. }
  25851. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25852. {
  25853. AUPreset current;
  25854. current.presetNumber = newIndex;
  25855. current.presetName = 0;
  25856. AudioUnitSetProperty (audioUnit,
  25857. kAudioUnitProperty_FactoryPresets,
  25858. kAudioUnitScope_Global,
  25859. 0, &current, sizeof (AUPreset));
  25860. }
  25861. const String AudioUnitPluginInstance::getProgramName (int index)
  25862. {
  25863. String s;
  25864. CFArrayRef presets;
  25865. UInt32 sz = sizeof (CFArrayRef);
  25866. if (AudioUnitGetProperty (audioUnit,
  25867. kAudioUnitProperty_FactoryPresets,
  25868. kAudioUnitScope_Global,
  25869. 0, &presets, &sz) == noErr)
  25870. {
  25871. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25872. {
  25873. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25874. if (p != 0 && p->presetNumber == index)
  25875. {
  25876. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25877. break;
  25878. }
  25879. }
  25880. CFRelease (presets);
  25881. }
  25882. return s;
  25883. }
  25884. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25885. {
  25886. jassertfalse; // xxx not implemented!
  25887. }
  25888. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  25889. {
  25890. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25891. return "Input " + String (index + 1);
  25892. return String::empty;
  25893. }
  25894. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25895. {
  25896. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25897. return false;
  25898. return true;
  25899. }
  25900. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  25901. {
  25902. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25903. return "Output " + String (index + 1);
  25904. return String::empty;
  25905. }
  25906. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25907. {
  25908. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25909. return false;
  25910. return true;
  25911. }
  25912. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25913. {
  25914. getCurrentProgramStateInformation (destData);
  25915. }
  25916. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25917. {
  25918. CFPropertyListRef propertyList = 0;
  25919. UInt32 sz = sizeof (CFPropertyListRef);
  25920. if (AudioUnitGetProperty (audioUnit,
  25921. kAudioUnitProperty_ClassInfo,
  25922. kAudioUnitScope_Global,
  25923. 0, &propertyList, &sz) == noErr)
  25924. {
  25925. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25926. CFWriteStreamOpen (stream);
  25927. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25928. CFWriteStreamClose (stream);
  25929. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25930. destData.setSize (bytesWritten);
  25931. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25932. CFRelease (data);
  25933. CFRelease (stream);
  25934. CFRelease (propertyList);
  25935. }
  25936. }
  25937. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25938. {
  25939. setCurrentProgramStateInformation (data, sizeInBytes);
  25940. }
  25941. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25942. {
  25943. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25944. (const UInt8*) data,
  25945. sizeInBytes,
  25946. kCFAllocatorNull);
  25947. CFReadStreamOpen (stream);
  25948. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25949. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25950. stream,
  25951. 0,
  25952. kCFPropertyListImmutable,
  25953. &format,
  25954. 0);
  25955. CFRelease (stream);
  25956. if (propertyList != 0)
  25957. AudioUnitSetProperty (audioUnit,
  25958. kAudioUnitProperty_ClassInfo,
  25959. kAudioUnitScope_Global,
  25960. 0, &propertyList, sizeof (propertyList));
  25961. }
  25962. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25963. {
  25964. }
  25965. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25966. {
  25967. }
  25968. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25969. const String& fileOrIdentifier)
  25970. {
  25971. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25972. return;
  25973. PluginDescription desc;
  25974. desc.fileOrIdentifier = fileOrIdentifier;
  25975. desc.uid = 0;
  25976. try
  25977. {
  25978. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25979. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25980. if (auInstance != 0)
  25981. {
  25982. auInstance->fillInPluginDescription (desc);
  25983. results.add (new PluginDescription (desc));
  25984. }
  25985. }
  25986. catch (...)
  25987. {
  25988. // crashed while loading...
  25989. }
  25990. }
  25991. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25992. {
  25993. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25994. {
  25995. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25996. if (result->audioUnit != 0)
  25997. {
  25998. result->initialise();
  25999. return result.release();
  26000. }
  26001. }
  26002. return 0;
  26003. }
  26004. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26005. const bool /*recursive*/)
  26006. {
  26007. StringArray result;
  26008. ComponentRecord* comp = 0;
  26009. ComponentDescription desc;
  26010. zerostruct (desc);
  26011. for (;;)
  26012. {
  26013. zerostruct (desc);
  26014. comp = FindNextComponent (comp, &desc);
  26015. if (comp == 0)
  26016. break;
  26017. GetComponentInfo (comp, &desc, 0, 0, 0);
  26018. if (desc.componentType == kAudioUnitType_MusicDevice
  26019. || desc.componentType == kAudioUnitType_MusicEffect
  26020. || desc.componentType == kAudioUnitType_Effect
  26021. || desc.componentType == kAudioUnitType_Generator
  26022. || desc.componentType == kAudioUnitType_Panner)
  26023. {
  26024. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26025. DBG (s);
  26026. result.add (s);
  26027. }
  26028. }
  26029. return result;
  26030. }
  26031. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26032. {
  26033. ComponentDescription desc;
  26034. String name, version, manufacturer;
  26035. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26036. return FindNextComponent (0, &desc) != 0;
  26037. const File f (fileOrIdentifier);
  26038. return f.hasFileExtension (".component")
  26039. && f.isDirectory();
  26040. }
  26041. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26042. {
  26043. ComponentDescription desc;
  26044. String name, version, manufacturer;
  26045. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26046. if (name.isEmpty())
  26047. name = fileOrIdentifier;
  26048. return name;
  26049. }
  26050. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26051. {
  26052. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26053. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26054. else
  26055. return File (desc.fileOrIdentifier).exists();
  26056. }
  26057. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26058. {
  26059. return FileSearchPath ("/(Default AudioUnit locations)");
  26060. }
  26061. #endif
  26062. END_JUCE_NAMESPACE
  26063. #undef log
  26064. #endif
  26065. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26066. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26067. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26068. #define JUCE_MAC_VST_INCLUDED 1
  26069. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26070. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26071. #if JUCE_WINDOWS
  26072. #undef _WIN32_WINNT
  26073. #define _WIN32_WINNT 0x500
  26074. #undef STRICT
  26075. #define STRICT
  26076. #include <windows.h>
  26077. #include <float.h>
  26078. #pragma warning (disable : 4312 4355)
  26079. #elif JUCE_LINUX
  26080. #include <float.h>
  26081. #include <sys/time.h>
  26082. #include <X11/Xlib.h>
  26083. #include <X11/Xutil.h>
  26084. #include <X11/Xatom.h>
  26085. #undef Font
  26086. #undef KeyPress
  26087. #undef Drawable
  26088. #undef Time
  26089. #else
  26090. #include <Cocoa/Cocoa.h>
  26091. #include <Carbon/Carbon.h>
  26092. #endif
  26093. #if ! (JUCE_MAC && JUCE_64BIT)
  26094. BEGIN_JUCE_NAMESPACE
  26095. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26096. #endif
  26097. #undef PRAGMA_ALIGN_SUPPORTED
  26098. #define VST_FORCE_DEPRECATED 0
  26099. #if JUCE_MSVC
  26100. #pragma warning (push)
  26101. #pragma warning (disable: 4996)
  26102. #endif
  26103. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26104. your include path if you want to add VST support.
  26105. If you're not interested in VSTs, you can disable them by changing the
  26106. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26107. */
  26108. #include "pluginterfaces/vst2.x/aeffectx.h"
  26109. #if JUCE_MSVC
  26110. #pragma warning (pop)
  26111. #endif
  26112. #if JUCE_LINUX
  26113. #define Font JUCE_NAMESPACE::Font
  26114. #define KeyPress JUCE_NAMESPACE::KeyPress
  26115. #define Drawable JUCE_NAMESPACE::Drawable
  26116. #define Time JUCE_NAMESPACE::Time
  26117. #endif
  26118. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26119. #ifdef __aeffect__
  26120. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26121. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26122. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26123. events to the list.
  26124. This is used by both the VST hosting code and the plugin wrapper.
  26125. */
  26126. class VSTMidiEventList
  26127. {
  26128. public:
  26129. VSTMidiEventList()
  26130. : numEventsUsed (0), numEventsAllocated (0)
  26131. {
  26132. }
  26133. ~VSTMidiEventList()
  26134. {
  26135. freeEvents();
  26136. }
  26137. void clear()
  26138. {
  26139. numEventsUsed = 0;
  26140. if (events != 0)
  26141. events->numEvents = 0;
  26142. }
  26143. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26144. {
  26145. ensureSize (numEventsUsed + 1);
  26146. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26147. events->numEvents = ++numEventsUsed;
  26148. if (numBytes <= 4)
  26149. {
  26150. if (e->type == kVstSysExType)
  26151. {
  26152. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26153. e->type = kVstMidiType;
  26154. e->byteSize = sizeof (VstMidiEvent);
  26155. e->noteLength = 0;
  26156. e->noteOffset = 0;
  26157. e->detune = 0;
  26158. e->noteOffVelocity = 0;
  26159. }
  26160. e->deltaFrames = frameOffset;
  26161. memcpy (e->midiData, midiData, numBytes);
  26162. }
  26163. else
  26164. {
  26165. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26166. if (se->type == kVstSysExType)
  26167. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26168. else
  26169. se->sysexDump = (char*) juce_malloc (numBytes);
  26170. memcpy (se->sysexDump, midiData, numBytes);
  26171. se->type = kVstSysExType;
  26172. se->byteSize = sizeof (VstMidiSysexEvent);
  26173. se->deltaFrames = frameOffset;
  26174. se->flags = 0;
  26175. se->dumpBytes = numBytes;
  26176. se->resvd1 = 0;
  26177. se->resvd2 = 0;
  26178. }
  26179. }
  26180. // Handy method to pull the events out of an event buffer supplied by the host
  26181. // or plugin.
  26182. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26183. {
  26184. for (int i = 0; i < events->numEvents; ++i)
  26185. {
  26186. const VstEvent* const e = events->events[i];
  26187. if (e != 0)
  26188. {
  26189. if (e->type == kVstMidiType)
  26190. {
  26191. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26192. 4, e->deltaFrames);
  26193. }
  26194. else if (e->type == kVstSysExType)
  26195. {
  26196. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26197. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26198. e->deltaFrames);
  26199. }
  26200. }
  26201. }
  26202. }
  26203. void ensureSize (int numEventsNeeded)
  26204. {
  26205. if (numEventsNeeded > numEventsAllocated)
  26206. {
  26207. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26208. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26209. if (events == 0)
  26210. events.calloc (size, 1);
  26211. else
  26212. events.realloc (size, 1);
  26213. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26214. {
  26215. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26216. (int) sizeof (VstMidiSysexEvent)));
  26217. e->type = kVstMidiType;
  26218. e->byteSize = sizeof (VstMidiEvent);
  26219. events->events[i] = (VstEvent*) e;
  26220. }
  26221. numEventsAllocated = numEventsNeeded;
  26222. }
  26223. }
  26224. void freeEvents()
  26225. {
  26226. if (events != 0)
  26227. {
  26228. for (int i = numEventsAllocated; --i >= 0;)
  26229. {
  26230. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26231. if (e->type == kVstSysExType)
  26232. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26233. juce_free (e);
  26234. }
  26235. events.free();
  26236. numEventsUsed = 0;
  26237. numEventsAllocated = 0;
  26238. }
  26239. }
  26240. HeapBlock <VstEvents> events;
  26241. private:
  26242. int numEventsUsed, numEventsAllocated;
  26243. };
  26244. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26245. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26246. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26247. #if ! JUCE_WINDOWS
  26248. static void _fpreset() {}
  26249. static void _clearfp() {}
  26250. #endif
  26251. extern void juce_callAnyTimersSynchronously();
  26252. const int fxbVersionNum = 1;
  26253. struct fxProgram
  26254. {
  26255. long chunkMagic; // 'CcnK'
  26256. long byteSize; // of this chunk, excl. magic + byteSize
  26257. long fxMagic; // 'FxCk'
  26258. long version;
  26259. long fxID; // fx unique id
  26260. long fxVersion;
  26261. long numParams;
  26262. char prgName[28];
  26263. float params[1]; // variable no. of parameters
  26264. };
  26265. struct fxSet
  26266. {
  26267. long chunkMagic; // 'CcnK'
  26268. long byteSize; // of this chunk, excl. magic + byteSize
  26269. long fxMagic; // 'FxBk'
  26270. long version;
  26271. long fxID; // fx unique id
  26272. long fxVersion;
  26273. long numPrograms;
  26274. char future[128];
  26275. fxProgram programs[1]; // variable no. of programs
  26276. };
  26277. struct fxChunkSet
  26278. {
  26279. long chunkMagic; // 'CcnK'
  26280. long byteSize; // of this chunk, excl. magic + byteSize
  26281. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26282. long version;
  26283. long fxID; // fx unique id
  26284. long fxVersion;
  26285. long numPrograms;
  26286. char future[128];
  26287. long chunkSize;
  26288. char chunk[8]; // variable
  26289. };
  26290. struct fxProgramSet
  26291. {
  26292. long chunkMagic; // 'CcnK'
  26293. long byteSize; // of this chunk, excl. magic + byteSize
  26294. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26295. long version;
  26296. long fxID; // fx unique id
  26297. long fxVersion;
  26298. long numPrograms;
  26299. char name[28];
  26300. long chunkSize;
  26301. char chunk[8]; // variable
  26302. };
  26303. static long vst_swap (const long x) throw()
  26304. {
  26305. #ifdef JUCE_LITTLE_ENDIAN
  26306. return (long) ByteOrder::swap ((uint32) x);
  26307. #else
  26308. return x;
  26309. #endif
  26310. }
  26311. static float vst_swapFloat (const float x) throw()
  26312. {
  26313. #ifdef JUCE_LITTLE_ENDIAN
  26314. union { uint32 asInt; float asFloat; } n;
  26315. n.asFloat = x;
  26316. n.asInt = ByteOrder::swap (n.asInt);
  26317. return n.asFloat;
  26318. #else
  26319. return x;
  26320. #endif
  26321. }
  26322. typedef AEffect* (*MainCall) (audioMasterCallback);
  26323. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26324. static int shellUIDToCreate = 0;
  26325. static int insideVSTCallback = 0;
  26326. class VSTPluginWindow;
  26327. // Change this to disable logging of various VST activities
  26328. #ifndef VST_LOGGING
  26329. #define VST_LOGGING 1
  26330. #endif
  26331. #if VST_LOGGING
  26332. #define log(a) Logger::writeToLog(a);
  26333. #else
  26334. #define log(a)
  26335. #endif
  26336. #if JUCE_MAC && JUCE_PPC
  26337. static void* NewCFMFromMachO (void* const machofp) throw()
  26338. {
  26339. void* result = juce_malloc (8);
  26340. ((void**) result)[0] = machofp;
  26341. ((void**) result)[1] = result;
  26342. return result;
  26343. }
  26344. #endif
  26345. #if JUCE_LINUX
  26346. extern Display* display;
  26347. extern XContext windowHandleXContext;
  26348. typedef void (*EventProcPtr) (XEvent* ev);
  26349. static bool xErrorTriggered;
  26350. static int temporaryErrorHandler (Display*, XErrorEvent*)
  26351. {
  26352. xErrorTriggered = true;
  26353. return 0;
  26354. }
  26355. static int getPropertyFromXWindow (Window handle, Atom atom)
  26356. {
  26357. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26358. xErrorTriggered = false;
  26359. int userSize;
  26360. unsigned long bytes, userCount;
  26361. unsigned char* data;
  26362. Atom userType;
  26363. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26364. &userType, &userSize, &userCount, &bytes, &data);
  26365. XSetErrorHandler (oldErrorHandler);
  26366. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  26367. : 0;
  26368. }
  26369. static Window getChildWindow (Window windowToCheck)
  26370. {
  26371. Window rootWindow, parentWindow;
  26372. Window* childWindows;
  26373. unsigned int numChildren;
  26374. XQueryTree (display,
  26375. windowToCheck,
  26376. &rootWindow,
  26377. &parentWindow,
  26378. &childWindows,
  26379. &numChildren);
  26380. if (numChildren > 0)
  26381. return childWindows [0];
  26382. return 0;
  26383. }
  26384. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26385. {
  26386. if (e.mods.isLeftButtonDown())
  26387. {
  26388. ev.xbutton.button = Button1;
  26389. ev.xbutton.state |= Button1Mask;
  26390. }
  26391. else if (e.mods.isRightButtonDown())
  26392. {
  26393. ev.xbutton.button = Button3;
  26394. ev.xbutton.state |= Button3Mask;
  26395. }
  26396. else if (e.mods.isMiddleButtonDown())
  26397. {
  26398. ev.xbutton.button = Button2;
  26399. ev.xbutton.state |= Button2Mask;
  26400. }
  26401. }
  26402. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26403. {
  26404. if (e.mods.isLeftButtonDown())
  26405. ev.xmotion.state |= Button1Mask;
  26406. else if (e.mods.isRightButtonDown())
  26407. ev.xmotion.state |= Button3Mask;
  26408. else if (e.mods.isMiddleButtonDown())
  26409. ev.xmotion.state |= Button2Mask;
  26410. }
  26411. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26412. {
  26413. if (e.mods.isLeftButtonDown())
  26414. ev.xcrossing.state |= Button1Mask;
  26415. else if (e.mods.isRightButtonDown())
  26416. ev.xcrossing.state |= Button3Mask;
  26417. else if (e.mods.isMiddleButtonDown())
  26418. ev.xcrossing.state |= Button2Mask;
  26419. }
  26420. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26421. {
  26422. if (increment < 0)
  26423. {
  26424. ev.xbutton.button = Button5;
  26425. ev.xbutton.state |= Button5Mask;
  26426. }
  26427. else if (increment > 0)
  26428. {
  26429. ev.xbutton.button = Button4;
  26430. ev.xbutton.state |= Button4Mask;
  26431. }
  26432. }
  26433. #endif
  26434. class ModuleHandle : public ReferenceCountedObject
  26435. {
  26436. public:
  26437. File file;
  26438. MainCall moduleMain;
  26439. String pluginName;
  26440. static Array <ModuleHandle*>& getActiveModules()
  26441. {
  26442. static Array <ModuleHandle*> activeModules;
  26443. return activeModules;
  26444. }
  26445. static ModuleHandle* findOrCreateModule (const File& file)
  26446. {
  26447. for (int i = getActiveModules().size(); --i >= 0;)
  26448. {
  26449. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26450. if (module->file == file)
  26451. return module;
  26452. }
  26453. _fpreset(); // (doesn't do any harm)
  26454. ++insideVSTCallback;
  26455. shellUIDToCreate = 0;
  26456. log ("Attempting to load VST: " + file.getFullPathName());
  26457. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26458. if (! m->open())
  26459. m = 0;
  26460. --insideVSTCallback;
  26461. _fpreset(); // (doesn't do any harm)
  26462. return m.release();
  26463. }
  26464. ModuleHandle (const File& file_)
  26465. : file (file_),
  26466. moduleMain (0),
  26467. #if JUCE_WINDOWS || JUCE_LINUX
  26468. hModule (0)
  26469. #elif JUCE_MAC
  26470. fragId (0),
  26471. resHandle (0),
  26472. bundleRef (0),
  26473. resFileId (0)
  26474. #endif
  26475. {
  26476. getActiveModules().add (this);
  26477. #if JUCE_WINDOWS || JUCE_LINUX
  26478. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26479. #elif JUCE_MAC
  26480. FSRef ref;
  26481. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26482. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26483. #endif
  26484. }
  26485. ~ModuleHandle()
  26486. {
  26487. getActiveModules().removeValue (this);
  26488. close();
  26489. }
  26490. juce_UseDebuggingNewOperator
  26491. #if JUCE_WINDOWS || JUCE_LINUX
  26492. void* hModule;
  26493. String fullParentDirectoryPathName;
  26494. bool open()
  26495. {
  26496. #if JUCE_WINDOWS
  26497. static bool timePeriodSet = false;
  26498. if (! timePeriodSet)
  26499. {
  26500. timePeriodSet = true;
  26501. timeBeginPeriod (2);
  26502. }
  26503. #endif
  26504. pluginName = file.getFileNameWithoutExtension();
  26505. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26506. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26507. if (moduleMain == 0)
  26508. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26509. return moduleMain != 0;
  26510. }
  26511. void close()
  26512. {
  26513. _fpreset(); // (doesn't do any harm)
  26514. PlatformUtilities::freeDynamicLibrary (hModule);
  26515. }
  26516. void closeEffect (AEffect* eff)
  26517. {
  26518. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26519. }
  26520. #else
  26521. CFragConnectionID fragId;
  26522. Handle resHandle;
  26523. CFBundleRef bundleRef;
  26524. FSSpec parentDirFSSpec;
  26525. short resFileId;
  26526. bool open()
  26527. {
  26528. bool ok = false;
  26529. const String filename (file.getFullPathName());
  26530. if (file.hasFileExtension (".vst"))
  26531. {
  26532. const char* const utf8 = filename.toUTF8();
  26533. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26534. strlen (utf8), file.isDirectory());
  26535. if (url != 0)
  26536. {
  26537. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26538. CFRelease (url);
  26539. if (bundleRef != 0)
  26540. {
  26541. if (CFBundleLoadExecutable (bundleRef))
  26542. {
  26543. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26544. if (moduleMain == 0)
  26545. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26546. if (moduleMain != 0)
  26547. {
  26548. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26549. if (name != 0)
  26550. {
  26551. if (CFGetTypeID (name) == CFStringGetTypeID())
  26552. {
  26553. char buffer[1024];
  26554. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26555. pluginName = buffer;
  26556. }
  26557. }
  26558. if (pluginName.isEmpty())
  26559. pluginName = file.getFileNameWithoutExtension();
  26560. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26561. ok = true;
  26562. }
  26563. }
  26564. if (! ok)
  26565. {
  26566. CFBundleUnloadExecutable (bundleRef);
  26567. CFRelease (bundleRef);
  26568. bundleRef = 0;
  26569. }
  26570. }
  26571. }
  26572. }
  26573. #if JUCE_PPC
  26574. else
  26575. {
  26576. FSRef fn;
  26577. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26578. {
  26579. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26580. if (resFileId != -1)
  26581. {
  26582. const int numEffs = Count1Resources ('aEff');
  26583. for (int i = 0; i < numEffs; ++i)
  26584. {
  26585. resHandle = Get1IndResource ('aEff', i + 1);
  26586. if (resHandle != 0)
  26587. {
  26588. OSType type;
  26589. Str255 name;
  26590. SInt16 id;
  26591. GetResInfo (resHandle, &id, &type, name);
  26592. pluginName = String ((const char*) name + 1, name[0]);
  26593. DetachResource (resHandle);
  26594. HLock (resHandle);
  26595. Ptr ptr;
  26596. Str255 errorText;
  26597. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26598. name, kPrivateCFragCopy,
  26599. &fragId, &ptr, errorText);
  26600. if (err == noErr)
  26601. {
  26602. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26603. ok = true;
  26604. }
  26605. else
  26606. {
  26607. HUnlock (resHandle);
  26608. }
  26609. break;
  26610. }
  26611. }
  26612. if (! ok)
  26613. CloseResFile (resFileId);
  26614. }
  26615. }
  26616. }
  26617. #endif
  26618. return ok;
  26619. }
  26620. void close()
  26621. {
  26622. #if JUCE_PPC
  26623. if (fragId != 0)
  26624. {
  26625. if (moduleMain != 0)
  26626. disposeMachOFromCFM ((void*) moduleMain);
  26627. CloseConnection (&fragId);
  26628. HUnlock (resHandle);
  26629. if (resFileId != 0)
  26630. CloseResFile (resFileId);
  26631. }
  26632. else
  26633. #endif
  26634. if (bundleRef != 0)
  26635. {
  26636. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26637. if (CFGetRetainCount (bundleRef) == 1)
  26638. CFBundleUnloadExecutable (bundleRef);
  26639. if (CFGetRetainCount (bundleRef) > 0)
  26640. CFRelease (bundleRef);
  26641. }
  26642. }
  26643. void closeEffect (AEffect* eff)
  26644. {
  26645. #if JUCE_PPC
  26646. if (fragId != 0)
  26647. {
  26648. Array<void*> thingsToDelete;
  26649. thingsToDelete.add ((void*) eff->dispatcher);
  26650. thingsToDelete.add ((void*) eff->process);
  26651. thingsToDelete.add ((void*) eff->setParameter);
  26652. thingsToDelete.add ((void*) eff->getParameter);
  26653. thingsToDelete.add ((void*) eff->processReplacing);
  26654. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26655. for (int i = thingsToDelete.size(); --i >= 0;)
  26656. disposeMachOFromCFM (thingsToDelete[i]);
  26657. }
  26658. else
  26659. #endif
  26660. {
  26661. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26662. }
  26663. }
  26664. #if JUCE_PPC
  26665. static void* newMachOFromCFM (void* cfmfp)
  26666. {
  26667. if (cfmfp == 0)
  26668. return 0;
  26669. UInt32* const mfp = new UInt32[6];
  26670. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26671. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26672. mfp[2] = 0x800c0000;
  26673. mfp[3] = 0x804c0004;
  26674. mfp[4] = 0x7c0903a6;
  26675. mfp[5] = 0x4e800420;
  26676. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26677. return mfp;
  26678. }
  26679. static void disposeMachOFromCFM (void* ptr)
  26680. {
  26681. delete[] static_cast <UInt32*> (ptr);
  26682. }
  26683. void coerceAEffectFunctionCalls (AEffect* eff)
  26684. {
  26685. if (fragId != 0)
  26686. {
  26687. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26688. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26689. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26690. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26691. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26692. }
  26693. }
  26694. #endif
  26695. #endif
  26696. };
  26697. /**
  26698. An instance of a plugin, created by a VSTPluginFormat.
  26699. */
  26700. class VSTPluginInstance : public AudioPluginInstance,
  26701. private Timer,
  26702. private AsyncUpdater
  26703. {
  26704. public:
  26705. ~VSTPluginInstance();
  26706. // AudioPluginInstance methods:
  26707. void fillInPluginDescription (PluginDescription& desc) const
  26708. {
  26709. desc.name = name;
  26710. desc.fileOrIdentifier = module->file.getFullPathName();
  26711. desc.uid = getUID();
  26712. desc.lastFileModTime = module->file.getLastModificationTime();
  26713. desc.pluginFormatName = "VST";
  26714. desc.category = getCategory();
  26715. {
  26716. char buffer [kVstMaxVendorStrLen + 8];
  26717. zerostruct (buffer);
  26718. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26719. desc.manufacturerName = buffer;
  26720. }
  26721. desc.version = getVersion();
  26722. desc.numInputChannels = getNumInputChannels();
  26723. desc.numOutputChannels = getNumOutputChannels();
  26724. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26725. }
  26726. const String getName() const { return name; }
  26727. int getUID() const throw();
  26728. bool acceptsMidi() const { return wantsMidiMessages; }
  26729. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26730. // AudioProcessor methods:
  26731. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26732. void releaseResources();
  26733. void processBlock (AudioSampleBuffer& buffer,
  26734. MidiBuffer& midiMessages);
  26735. AudioProcessorEditor* createEditor();
  26736. const String getInputChannelName (int index) const;
  26737. bool isInputChannelStereoPair (int index) const;
  26738. const String getOutputChannelName (int index) const;
  26739. bool isOutputChannelStereoPair (int index) const;
  26740. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26741. float getParameter (int index);
  26742. void setParameter (int index, float newValue);
  26743. const String getParameterName (int index);
  26744. const String getParameterText (int index);
  26745. bool isParameterAutomatable (int index) const;
  26746. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26747. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26748. void setCurrentProgram (int index);
  26749. const String getProgramName (int index);
  26750. void changeProgramName (int index, const String& newName);
  26751. void getStateInformation (MemoryBlock& destData);
  26752. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26753. void setStateInformation (const void* data, int sizeInBytes);
  26754. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26755. void timerCallback();
  26756. void handleAsyncUpdate();
  26757. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26758. juce_UseDebuggingNewOperator
  26759. private:
  26760. friend class VSTPluginWindow;
  26761. friend class VSTPluginFormat;
  26762. AEffect* effect;
  26763. String name;
  26764. CriticalSection lock;
  26765. bool wantsMidiMessages, initialised, isPowerOn;
  26766. mutable StringArray programNames;
  26767. AudioSampleBuffer tempBuffer;
  26768. CriticalSection midiInLock;
  26769. MidiBuffer incomingMidi;
  26770. VSTMidiEventList midiEventsToSend;
  26771. VstTimeInfo vstHostTime;
  26772. HeapBlock <float*> channels;
  26773. ReferenceCountedObjectPtr <ModuleHandle> module;
  26774. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26775. bool restoreProgramSettings (const fxProgram* const prog);
  26776. const String getCurrentProgramName();
  26777. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26778. void updateStoredProgramNames();
  26779. void initialise();
  26780. void handleMidiFromPlugin (const VstEvents* const events);
  26781. void createTempParameterStore (MemoryBlock& dest);
  26782. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26783. const String getParameterLabel (int index) const;
  26784. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26785. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26786. void setChunkData (const char* data, int size, bool isPreset);
  26787. bool loadFromFXBFile (const void* data, int numBytes);
  26788. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26789. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26790. const String getVersion() const throw();
  26791. const String getCategory() const throw();
  26792. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26793. void setPower (const bool on);
  26794. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26795. };
  26796. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26797. : effect (0),
  26798. wantsMidiMessages (false),
  26799. initialised (false),
  26800. isPowerOn (false),
  26801. tempBuffer (1, 1),
  26802. module (module_)
  26803. {
  26804. try
  26805. {
  26806. _fpreset();
  26807. ++insideVSTCallback;
  26808. name = module->pluginName;
  26809. log ("Creating VST instance: " + name);
  26810. #if JUCE_MAC
  26811. if (module->resFileId != 0)
  26812. UseResFile (module->resFileId);
  26813. #if JUCE_PPC
  26814. if (module->fragId != 0)
  26815. {
  26816. static void* audioMasterCoerced = 0;
  26817. if (audioMasterCoerced == 0)
  26818. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26819. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26820. }
  26821. else
  26822. #endif
  26823. #endif
  26824. {
  26825. effect = module->moduleMain (&audioMaster);
  26826. }
  26827. --insideVSTCallback;
  26828. if (effect != 0 && effect->magic == kEffectMagic)
  26829. {
  26830. #if JUCE_PPC
  26831. module->coerceAEffectFunctionCalls (effect);
  26832. #endif
  26833. jassert (effect->resvd2 == 0);
  26834. jassert (effect->object != 0);
  26835. _fpreset(); // some dodgy plugs fuck around with this
  26836. }
  26837. else
  26838. {
  26839. effect = 0;
  26840. }
  26841. }
  26842. catch (...)
  26843. {
  26844. --insideVSTCallback;
  26845. }
  26846. }
  26847. VSTPluginInstance::~VSTPluginInstance()
  26848. {
  26849. {
  26850. const ScopedLock sl (lock);
  26851. jassert (insideVSTCallback == 0);
  26852. if (effect != 0 && effect->magic == kEffectMagic)
  26853. {
  26854. try
  26855. {
  26856. #if JUCE_MAC
  26857. if (module->resFileId != 0)
  26858. UseResFile (module->resFileId);
  26859. #endif
  26860. // Must delete any editors before deleting the plugin instance!
  26861. jassert (getActiveEditor() == 0);
  26862. _fpreset(); // some dodgy plugs fuck around with this
  26863. module->closeEffect (effect);
  26864. }
  26865. catch (...)
  26866. {}
  26867. }
  26868. module = 0;
  26869. effect = 0;
  26870. }
  26871. }
  26872. void VSTPluginInstance::initialise()
  26873. {
  26874. if (initialised || effect == 0)
  26875. return;
  26876. log ("Initialising VST: " + module->pluginName);
  26877. initialised = true;
  26878. dispatch (effIdentify, 0, 0, 0, 0);
  26879. // this code would ask the plugin for its name, but so few plugins
  26880. // actually bother implementing this correctly, that it's better to
  26881. // just ignore it and use the file name instead.
  26882. /* {
  26883. char buffer [256];
  26884. zerostruct (buffer);
  26885. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26886. name = String (buffer).trim();
  26887. if (name.isEmpty())
  26888. name = module->pluginName;
  26889. }
  26890. */
  26891. if (getSampleRate() > 0)
  26892. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26893. if (getBlockSize() > 0)
  26894. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26895. dispatch (effOpen, 0, 0, 0, 0);
  26896. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26897. getSampleRate(), getBlockSize());
  26898. if (getNumPrograms() > 1)
  26899. setCurrentProgram (0);
  26900. else
  26901. dispatch (effSetProgram, 0, 0, 0, 0);
  26902. int i;
  26903. for (i = effect->numInputs; --i >= 0;)
  26904. dispatch (effConnectInput, i, 1, 0, 0);
  26905. for (i = effect->numOutputs; --i >= 0;)
  26906. dispatch (effConnectOutput, i, 1, 0, 0);
  26907. updateStoredProgramNames();
  26908. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26909. setLatencySamples (effect->initialDelay);
  26910. }
  26911. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26912. int samplesPerBlockExpected)
  26913. {
  26914. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26915. sampleRate_, samplesPerBlockExpected);
  26916. setLatencySamples (effect->initialDelay);
  26917. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26918. vstHostTime.tempo = 120.0;
  26919. vstHostTime.timeSigNumerator = 4;
  26920. vstHostTime.timeSigDenominator = 4;
  26921. vstHostTime.sampleRate = sampleRate_;
  26922. vstHostTime.samplePos = 0;
  26923. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26924. initialise();
  26925. if (initialised)
  26926. {
  26927. wantsMidiMessages = wantsMidiMessages
  26928. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26929. if (wantsMidiMessages)
  26930. midiEventsToSend.ensureSize (256);
  26931. else
  26932. midiEventsToSend.freeEvents();
  26933. incomingMidi.clear();
  26934. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26935. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26936. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26937. if (! isPowerOn)
  26938. setPower (true);
  26939. // dodgy hack to force some plugins to initialise the sample rate..
  26940. if ((! hasEditor()) && getNumParameters() > 0)
  26941. {
  26942. const float old = getParameter (0);
  26943. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26944. setParameter (0, old);
  26945. }
  26946. dispatch (effStartProcess, 0, 0, 0, 0);
  26947. }
  26948. }
  26949. void VSTPluginInstance::releaseResources()
  26950. {
  26951. if (initialised)
  26952. {
  26953. dispatch (effStopProcess, 0, 0, 0, 0);
  26954. setPower (false);
  26955. }
  26956. tempBuffer.setSize (1, 1);
  26957. incomingMidi.clear();
  26958. midiEventsToSend.freeEvents();
  26959. channels.free();
  26960. }
  26961. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26962. MidiBuffer& midiMessages)
  26963. {
  26964. const int numSamples = buffer.getNumSamples();
  26965. if (initialised)
  26966. {
  26967. AudioPlayHead* playHead = getPlayHead();
  26968. if (playHead != 0)
  26969. {
  26970. AudioPlayHead::CurrentPositionInfo position;
  26971. playHead->getCurrentPosition (position);
  26972. vstHostTime.tempo = position.bpm;
  26973. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26974. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26975. vstHostTime.ppqPos = position.ppqPosition;
  26976. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26977. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26978. if (position.isPlaying)
  26979. vstHostTime.flags |= kVstTransportPlaying;
  26980. else
  26981. vstHostTime.flags &= ~kVstTransportPlaying;
  26982. }
  26983. #if JUCE_WINDOWS
  26984. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26985. #elif JUCE_LINUX
  26986. timeval micro;
  26987. gettimeofday (&micro, 0);
  26988. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26989. #elif JUCE_MAC
  26990. UnsignedWide micro;
  26991. Microseconds (&micro);
  26992. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26993. #endif
  26994. if (wantsMidiMessages)
  26995. {
  26996. midiEventsToSend.clear();
  26997. midiEventsToSend.ensureSize (1);
  26998. MidiBuffer::Iterator iter (midiMessages);
  26999. const uint8* midiData;
  27000. int numBytesOfMidiData, samplePosition;
  27001. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27002. {
  27003. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27004. jlimit (0, numSamples - 1, samplePosition));
  27005. }
  27006. try
  27007. {
  27008. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27009. }
  27010. catch (...)
  27011. {}
  27012. }
  27013. int i;
  27014. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  27015. for (i = 0; i < maxChans; ++i)
  27016. channels[i] = buffer.getSampleData (i);
  27017. channels [maxChans] = 0;
  27018. _clearfp();
  27019. if ((effect->flags & effFlagsCanReplacing) != 0)
  27020. {
  27021. try
  27022. {
  27023. effect->processReplacing (effect, channels, channels, numSamples);
  27024. }
  27025. catch (...)
  27026. {}
  27027. }
  27028. else
  27029. {
  27030. tempBuffer.setSize (effect->numOutputs, numSamples);
  27031. tempBuffer.clear();
  27032. float* outs [64];
  27033. for (i = effect->numOutputs; --i >= 0;)
  27034. outs[i] = tempBuffer.getSampleData (i);
  27035. outs [effect->numOutputs] = 0;
  27036. try
  27037. {
  27038. effect->process (effect, channels, outs, numSamples);
  27039. }
  27040. catch (...)
  27041. {}
  27042. for (i = effect->numOutputs; --i >= 0;)
  27043. buffer.copyFrom (i, 0, outs[i], numSamples);
  27044. }
  27045. }
  27046. else
  27047. {
  27048. // Not initialised, so just bypass..
  27049. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27050. buffer.clear (i, 0, buffer.getNumSamples());
  27051. }
  27052. {
  27053. // copy any incoming midi..
  27054. const ScopedLock sl (midiInLock);
  27055. midiMessages.swapWith (incomingMidi);
  27056. incomingMidi.clear();
  27057. }
  27058. }
  27059. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27060. {
  27061. if (events != 0)
  27062. {
  27063. const ScopedLock sl (midiInLock);
  27064. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27065. }
  27066. }
  27067. static Array <VSTPluginWindow*> activeVSTWindows;
  27068. class VSTPluginWindow : public AudioProcessorEditor,
  27069. #if ! JUCE_MAC
  27070. public ComponentMovementWatcher,
  27071. #endif
  27072. public Timer
  27073. {
  27074. public:
  27075. VSTPluginWindow (VSTPluginInstance& plugin_)
  27076. : AudioProcessorEditor (&plugin_),
  27077. #if ! JUCE_MAC
  27078. ComponentMovementWatcher (this),
  27079. #endif
  27080. plugin (plugin_),
  27081. isOpen (false),
  27082. wasShowing (false),
  27083. pluginRefusesToResize (false),
  27084. pluginWantsKeys (false),
  27085. alreadyInside (false),
  27086. recursiveResize (false)
  27087. {
  27088. #if JUCE_WINDOWS
  27089. sizeCheckCount = 0;
  27090. pluginHWND = 0;
  27091. #elif JUCE_LINUX
  27092. pluginWindow = None;
  27093. pluginProc = None;
  27094. #else
  27095. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27096. #endif
  27097. activeVSTWindows.add (this);
  27098. setSize (1, 1);
  27099. setOpaque (true);
  27100. setVisible (true);
  27101. }
  27102. ~VSTPluginWindow()
  27103. {
  27104. #if JUCE_MAC
  27105. innerWrapper = 0;
  27106. #else
  27107. closePluginWindow();
  27108. #endif
  27109. activeVSTWindows.removeValue (this);
  27110. plugin.editorBeingDeleted (this);
  27111. }
  27112. #if ! JUCE_MAC
  27113. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27114. {
  27115. if (recursiveResize)
  27116. return;
  27117. Component* const topComp = getTopLevelComponent();
  27118. if (topComp->getPeer() != 0)
  27119. {
  27120. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27121. recursiveResize = true;
  27122. #if JUCE_WINDOWS
  27123. if (pluginHWND != 0)
  27124. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27125. #elif JUCE_LINUX
  27126. if (pluginWindow != 0)
  27127. {
  27128. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27129. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27130. XMapRaised (display, pluginWindow);
  27131. }
  27132. #endif
  27133. recursiveResize = false;
  27134. }
  27135. }
  27136. void componentVisibilityChanged (Component&)
  27137. {
  27138. const bool isShowingNow = isShowing();
  27139. if (wasShowing != isShowingNow)
  27140. {
  27141. wasShowing = isShowingNow;
  27142. if (isShowingNow)
  27143. openPluginWindow();
  27144. else
  27145. closePluginWindow();
  27146. }
  27147. componentMovedOrResized (true, true);
  27148. }
  27149. void componentPeerChanged()
  27150. {
  27151. closePluginWindow();
  27152. openPluginWindow();
  27153. }
  27154. #endif
  27155. bool keyStateChanged (bool)
  27156. {
  27157. return pluginWantsKeys;
  27158. }
  27159. bool keyPressed (const KeyPress&)
  27160. {
  27161. return pluginWantsKeys;
  27162. }
  27163. #if JUCE_MAC
  27164. void paint (Graphics& g)
  27165. {
  27166. g.fillAll (Colours::black);
  27167. }
  27168. #else
  27169. void paint (Graphics& g)
  27170. {
  27171. if (isOpen)
  27172. {
  27173. ComponentPeer* const peer = getPeer();
  27174. if (peer != 0)
  27175. {
  27176. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27177. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27178. #if JUCE_LINUX
  27179. if (pluginWindow != 0)
  27180. {
  27181. const Rectangle<int> clip (g.getClipBounds());
  27182. XEvent ev;
  27183. zerostruct (ev);
  27184. ev.xexpose.type = Expose;
  27185. ev.xexpose.display = display;
  27186. ev.xexpose.window = pluginWindow;
  27187. ev.xexpose.x = clip.getX();
  27188. ev.xexpose.y = clip.getY();
  27189. ev.xexpose.width = clip.getWidth();
  27190. ev.xexpose.height = clip.getHeight();
  27191. sendEventToChild (&ev);
  27192. }
  27193. #endif
  27194. }
  27195. }
  27196. else
  27197. {
  27198. g.fillAll (Colours::black);
  27199. }
  27200. }
  27201. #endif
  27202. void timerCallback()
  27203. {
  27204. #if JUCE_WINDOWS
  27205. if (--sizeCheckCount <= 0)
  27206. {
  27207. sizeCheckCount = 10;
  27208. checkPluginWindowSize();
  27209. }
  27210. #endif
  27211. try
  27212. {
  27213. static bool reentrant = false;
  27214. if (! reentrant)
  27215. {
  27216. reentrant = true;
  27217. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27218. reentrant = false;
  27219. }
  27220. }
  27221. catch (...)
  27222. {}
  27223. }
  27224. void mouseDown (const MouseEvent& e)
  27225. {
  27226. #if JUCE_LINUX
  27227. if (pluginWindow == 0)
  27228. return;
  27229. toFront (true);
  27230. XEvent ev;
  27231. zerostruct (ev);
  27232. ev.xbutton.display = display;
  27233. ev.xbutton.type = ButtonPress;
  27234. ev.xbutton.window = pluginWindow;
  27235. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27236. ev.xbutton.time = CurrentTime;
  27237. ev.xbutton.x = e.x;
  27238. ev.xbutton.y = e.y;
  27239. ev.xbutton.x_root = e.getScreenX();
  27240. ev.xbutton.y_root = e.getScreenY();
  27241. translateJuceToXButtonModifiers (e, ev);
  27242. sendEventToChild (&ev);
  27243. #elif JUCE_WINDOWS
  27244. (void) e;
  27245. toFront (true);
  27246. #endif
  27247. }
  27248. void broughtToFront()
  27249. {
  27250. activeVSTWindows.removeValue (this);
  27251. activeVSTWindows.add (this);
  27252. #if JUCE_MAC
  27253. dispatch (effEditTop, 0, 0, 0, 0);
  27254. #endif
  27255. }
  27256. juce_UseDebuggingNewOperator
  27257. private:
  27258. VSTPluginInstance& plugin;
  27259. bool isOpen, wasShowing, recursiveResize;
  27260. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27261. #if JUCE_WINDOWS
  27262. HWND pluginHWND;
  27263. void* originalWndProc;
  27264. int sizeCheckCount;
  27265. #elif JUCE_LINUX
  27266. Window pluginWindow;
  27267. EventProcPtr pluginProc;
  27268. #endif
  27269. #if JUCE_MAC
  27270. void openPluginWindow (WindowRef parentWindow)
  27271. {
  27272. if (isOpen || parentWindow == 0)
  27273. return;
  27274. isOpen = true;
  27275. ERect* rect = 0;
  27276. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27277. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27278. // do this before and after like in the steinberg example
  27279. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27280. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27281. // Install keyboard hooks
  27282. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27283. // double-check it's not too tiny
  27284. int w = 250, h = 150;
  27285. if (rect != 0)
  27286. {
  27287. w = rect->right - rect->left;
  27288. h = rect->bottom - rect->top;
  27289. if (w == 0 || h == 0)
  27290. {
  27291. w = 250;
  27292. h = 150;
  27293. }
  27294. }
  27295. w = jmax (w, 32);
  27296. h = jmax (h, 32);
  27297. setSize (w, h);
  27298. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27299. repaint();
  27300. }
  27301. #else
  27302. void openPluginWindow()
  27303. {
  27304. if (isOpen || getWindowHandle() == 0)
  27305. return;
  27306. log ("Opening VST UI: " + plugin.name);
  27307. isOpen = true;
  27308. ERect* rect = 0;
  27309. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27310. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27311. // do this before and after like in the steinberg example
  27312. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27313. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27314. // Install keyboard hooks
  27315. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27316. #if JUCE_WINDOWS
  27317. originalWndProc = 0;
  27318. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27319. if (pluginHWND == 0)
  27320. {
  27321. isOpen = false;
  27322. setSize (300, 150);
  27323. return;
  27324. }
  27325. #pragma warning (push)
  27326. #pragma warning (disable: 4244)
  27327. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  27328. if (! pluginWantsKeys)
  27329. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27330. #pragma warning (pop)
  27331. int w, h;
  27332. RECT r;
  27333. GetWindowRect (pluginHWND, &r);
  27334. w = r.right - r.left;
  27335. h = r.bottom - r.top;
  27336. if (rect != 0)
  27337. {
  27338. const int rw = rect->right - rect->left;
  27339. const int rh = rect->bottom - rect->top;
  27340. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27341. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27342. {
  27343. // very dodgy logic to decide which size is right.
  27344. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27345. {
  27346. SetWindowPos (pluginHWND, 0,
  27347. 0, 0, rw, rh,
  27348. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27349. GetWindowRect (pluginHWND, &r);
  27350. w = r.right - r.left;
  27351. h = r.bottom - r.top;
  27352. pluginRefusesToResize = (w != rw) || (h != rh);
  27353. w = rw;
  27354. h = rh;
  27355. }
  27356. }
  27357. }
  27358. #elif JUCE_LINUX
  27359. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27360. if (pluginWindow != 0)
  27361. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27362. XInternAtom (display, "_XEventProc", False));
  27363. int w = 250, h = 150;
  27364. if (rect != 0)
  27365. {
  27366. w = rect->right - rect->left;
  27367. h = rect->bottom - rect->top;
  27368. if (w == 0 || h == 0)
  27369. {
  27370. w = 250;
  27371. h = 150;
  27372. }
  27373. }
  27374. if (pluginWindow != 0)
  27375. XMapRaised (display, pluginWindow);
  27376. #endif
  27377. // double-check it's not too tiny
  27378. w = jmax (w, 32);
  27379. h = jmax (h, 32);
  27380. setSize (w, h);
  27381. #if JUCE_WINDOWS
  27382. checkPluginWindowSize();
  27383. #endif
  27384. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27385. repaint();
  27386. }
  27387. #endif
  27388. #if ! JUCE_MAC
  27389. void closePluginWindow()
  27390. {
  27391. if (isOpen)
  27392. {
  27393. log ("Closing VST UI: " + plugin.getName());
  27394. isOpen = false;
  27395. dispatch (effEditClose, 0, 0, 0, 0);
  27396. #if JUCE_WINDOWS
  27397. #pragma warning (push)
  27398. #pragma warning (disable: 4244)
  27399. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27400. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27401. #pragma warning (pop)
  27402. stopTimer();
  27403. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27404. DestroyWindow (pluginHWND);
  27405. pluginHWND = 0;
  27406. #elif JUCE_LINUX
  27407. stopTimer();
  27408. pluginWindow = 0;
  27409. pluginProc = 0;
  27410. #endif
  27411. }
  27412. }
  27413. #endif
  27414. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27415. {
  27416. return plugin.dispatch (opcode, index, value, ptr, opt);
  27417. }
  27418. #if JUCE_WINDOWS
  27419. void checkPluginWindowSize() throw()
  27420. {
  27421. RECT r;
  27422. GetWindowRect (pluginHWND, &r);
  27423. const int w = r.right - r.left;
  27424. const int h = r.bottom - r.top;
  27425. if (isShowing() && w > 0 && h > 0
  27426. && (w != getWidth() || h != getHeight())
  27427. && ! pluginRefusesToResize)
  27428. {
  27429. setSize (w, h);
  27430. sizeCheckCount = 0;
  27431. }
  27432. }
  27433. // hooks to get keyboard events from VST windows..
  27434. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27435. {
  27436. for (int i = activeVSTWindows.size(); --i >= 0;)
  27437. {
  27438. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  27439. if (w->pluginHWND == hW)
  27440. {
  27441. if (message == WM_CHAR
  27442. || message == WM_KEYDOWN
  27443. || message == WM_SYSKEYDOWN
  27444. || message == WM_KEYUP
  27445. || message == WM_SYSKEYUP
  27446. || message == WM_APPCOMMAND)
  27447. {
  27448. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27449. message, wParam, lParam);
  27450. }
  27451. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27452. (HWND) w->pluginHWND,
  27453. message,
  27454. wParam,
  27455. lParam);
  27456. }
  27457. }
  27458. return DefWindowProc (hW, message, wParam, lParam);
  27459. }
  27460. #endif
  27461. #if JUCE_LINUX
  27462. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27463. void sendEventToChild (XEvent* event)
  27464. {
  27465. if (pluginProc != 0)
  27466. {
  27467. // if the plugin publishes an event procedure, pass the event directly..
  27468. pluginProc (event);
  27469. }
  27470. else if (pluginWindow != 0)
  27471. {
  27472. // if the plugin has a window, then send the event to the window so that
  27473. // its message thread will pick it up..
  27474. XSendEvent (display, pluginWindow, False, 0L, event);
  27475. XFlush (display);
  27476. }
  27477. }
  27478. void mouseEnter (const MouseEvent& e)
  27479. {
  27480. if (pluginWindow != 0)
  27481. {
  27482. XEvent ev;
  27483. zerostruct (ev);
  27484. ev.xcrossing.display = display;
  27485. ev.xcrossing.type = EnterNotify;
  27486. ev.xcrossing.window = pluginWindow;
  27487. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27488. ev.xcrossing.time = CurrentTime;
  27489. ev.xcrossing.x = e.x;
  27490. ev.xcrossing.y = e.y;
  27491. ev.xcrossing.x_root = e.getScreenX();
  27492. ev.xcrossing.y_root = e.getScreenY();
  27493. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27494. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27495. translateJuceToXCrossingModifiers (e, ev);
  27496. sendEventToChild (&ev);
  27497. }
  27498. }
  27499. void mouseExit (const MouseEvent& e)
  27500. {
  27501. if (pluginWindow != 0)
  27502. {
  27503. XEvent ev;
  27504. zerostruct (ev);
  27505. ev.xcrossing.display = display;
  27506. ev.xcrossing.type = LeaveNotify;
  27507. ev.xcrossing.window = pluginWindow;
  27508. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27509. ev.xcrossing.time = CurrentTime;
  27510. ev.xcrossing.x = e.x;
  27511. ev.xcrossing.y = e.y;
  27512. ev.xcrossing.x_root = e.getScreenX();
  27513. ev.xcrossing.y_root = e.getScreenY();
  27514. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27515. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27516. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27517. translateJuceToXCrossingModifiers (e, ev);
  27518. sendEventToChild (&ev);
  27519. }
  27520. }
  27521. void mouseMove (const MouseEvent& e)
  27522. {
  27523. if (pluginWindow != 0)
  27524. {
  27525. XEvent ev;
  27526. zerostruct (ev);
  27527. ev.xmotion.display = display;
  27528. ev.xmotion.type = MotionNotify;
  27529. ev.xmotion.window = pluginWindow;
  27530. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27531. ev.xmotion.time = CurrentTime;
  27532. ev.xmotion.is_hint = NotifyNormal;
  27533. ev.xmotion.x = e.x;
  27534. ev.xmotion.y = e.y;
  27535. ev.xmotion.x_root = e.getScreenX();
  27536. ev.xmotion.y_root = e.getScreenY();
  27537. sendEventToChild (&ev);
  27538. }
  27539. }
  27540. void mouseDrag (const MouseEvent& e)
  27541. {
  27542. if (pluginWindow != 0)
  27543. {
  27544. XEvent ev;
  27545. zerostruct (ev);
  27546. ev.xmotion.display = display;
  27547. ev.xmotion.type = MotionNotify;
  27548. ev.xmotion.window = pluginWindow;
  27549. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27550. ev.xmotion.time = CurrentTime;
  27551. ev.xmotion.x = e.x ;
  27552. ev.xmotion.y = e.y;
  27553. ev.xmotion.x_root = e.getScreenX();
  27554. ev.xmotion.y_root = e.getScreenY();
  27555. ev.xmotion.is_hint = NotifyNormal;
  27556. translateJuceToXMotionModifiers (e, ev);
  27557. sendEventToChild (&ev);
  27558. }
  27559. }
  27560. void mouseUp (const MouseEvent& e)
  27561. {
  27562. if (pluginWindow != 0)
  27563. {
  27564. XEvent ev;
  27565. zerostruct (ev);
  27566. ev.xbutton.display = display;
  27567. ev.xbutton.type = ButtonRelease;
  27568. ev.xbutton.window = pluginWindow;
  27569. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27570. ev.xbutton.time = CurrentTime;
  27571. ev.xbutton.x = e.x;
  27572. ev.xbutton.y = e.y;
  27573. ev.xbutton.x_root = e.getScreenX();
  27574. ev.xbutton.y_root = e.getScreenY();
  27575. translateJuceToXButtonModifiers (e, ev);
  27576. sendEventToChild (&ev);
  27577. }
  27578. }
  27579. void mouseWheelMove (const MouseEvent& e,
  27580. float incrementX,
  27581. float incrementY)
  27582. {
  27583. if (pluginWindow != 0)
  27584. {
  27585. XEvent ev;
  27586. zerostruct (ev);
  27587. ev.xbutton.display = display;
  27588. ev.xbutton.type = ButtonPress;
  27589. ev.xbutton.window = pluginWindow;
  27590. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27591. ev.xbutton.time = CurrentTime;
  27592. ev.xbutton.x = e.x;
  27593. ev.xbutton.y = e.y;
  27594. ev.xbutton.x_root = e.getScreenX();
  27595. ev.xbutton.y_root = e.getScreenY();
  27596. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27597. sendEventToChild (&ev);
  27598. // TODO - put a usleep here ?
  27599. ev.xbutton.type = ButtonRelease;
  27600. sendEventToChild (&ev);
  27601. }
  27602. }
  27603. #endif
  27604. #if JUCE_MAC
  27605. #if ! JUCE_SUPPORT_CARBON
  27606. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27607. #endif
  27608. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27609. {
  27610. public:
  27611. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27612. : owner (owner_),
  27613. alreadyInside (false)
  27614. {
  27615. }
  27616. ~InnerWrapperComponent()
  27617. {
  27618. deleteWindow();
  27619. }
  27620. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27621. {
  27622. owner->openPluginWindow (windowRef);
  27623. return 0;
  27624. }
  27625. void removeView (HIViewRef)
  27626. {
  27627. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27628. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27629. }
  27630. bool getEmbeddedViewSize (int& w, int& h)
  27631. {
  27632. ERect* rect = 0;
  27633. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27634. w = rect->right - rect->left;
  27635. h = rect->bottom - rect->top;
  27636. return true;
  27637. }
  27638. void mouseDown (int x, int y)
  27639. {
  27640. if (! alreadyInside)
  27641. {
  27642. alreadyInside = true;
  27643. getTopLevelComponent()->toFront (true);
  27644. owner->dispatch (effEditMouse, x, y, 0, 0);
  27645. alreadyInside = false;
  27646. }
  27647. else
  27648. {
  27649. PostEvent (::mouseDown, 0);
  27650. }
  27651. }
  27652. void paint()
  27653. {
  27654. ComponentPeer* const peer = getPeer();
  27655. if (peer != 0)
  27656. {
  27657. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27658. ERect r;
  27659. r.left = pos.getX();
  27660. r.right = r.left + getWidth();
  27661. r.top = pos.getY();
  27662. r.bottom = r.top + getHeight();
  27663. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27664. }
  27665. }
  27666. private:
  27667. VSTPluginWindow* const owner;
  27668. bool alreadyInside;
  27669. };
  27670. friend class InnerWrapperComponent;
  27671. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27672. void resized()
  27673. {
  27674. innerWrapper->setSize (getWidth(), getHeight());
  27675. }
  27676. #endif
  27677. };
  27678. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27679. {
  27680. if (hasEditor())
  27681. return new VSTPluginWindow (*this);
  27682. return 0;
  27683. }
  27684. void VSTPluginInstance::handleAsyncUpdate()
  27685. {
  27686. // indicates that something about the plugin has changed..
  27687. updateHostDisplay();
  27688. }
  27689. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27690. {
  27691. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27692. {
  27693. changeProgramName (getCurrentProgram(), prog->prgName);
  27694. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27695. setParameter (i, vst_swapFloat (prog->params[i]));
  27696. return true;
  27697. }
  27698. return false;
  27699. }
  27700. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27701. const int dataSize)
  27702. {
  27703. if (dataSize < 28)
  27704. return false;
  27705. const fxSet* const set = (const fxSet*) data;
  27706. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27707. || vst_swap (set->version) > fxbVersionNum)
  27708. return false;
  27709. if (vst_swap (set->fxMagic) == 'FxBk')
  27710. {
  27711. // bank of programs
  27712. if (vst_swap (set->numPrograms) >= 0)
  27713. {
  27714. const int oldProg = getCurrentProgram();
  27715. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27716. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27717. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27718. {
  27719. if (i != oldProg)
  27720. {
  27721. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27722. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27723. return false;
  27724. if (vst_swap (set->numPrograms) > 0)
  27725. setCurrentProgram (i);
  27726. if (! restoreProgramSettings (prog))
  27727. return false;
  27728. }
  27729. }
  27730. if (vst_swap (set->numPrograms) > 0)
  27731. setCurrentProgram (oldProg);
  27732. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27733. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27734. return false;
  27735. if (! restoreProgramSettings (prog))
  27736. return false;
  27737. }
  27738. }
  27739. else if (vst_swap (set->fxMagic) == 'FxCk')
  27740. {
  27741. // single program
  27742. const fxProgram* const prog = (const fxProgram*) data;
  27743. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27744. return false;
  27745. changeProgramName (getCurrentProgram(), prog->prgName);
  27746. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27747. setParameter (i, vst_swapFloat (prog->params[i]));
  27748. }
  27749. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27750. {
  27751. // non-preset chunk
  27752. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27753. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27754. return false;
  27755. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27756. }
  27757. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27758. {
  27759. // preset chunk
  27760. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27761. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27762. return false;
  27763. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27764. changeProgramName (getCurrentProgram(), cset->name);
  27765. }
  27766. else
  27767. {
  27768. return false;
  27769. }
  27770. return true;
  27771. }
  27772. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  27773. {
  27774. const int numParams = getNumParameters();
  27775. prog->chunkMagic = vst_swap ('CcnK');
  27776. prog->byteSize = 0;
  27777. prog->fxMagic = vst_swap ('FxCk');
  27778. prog->version = vst_swap (fxbVersionNum);
  27779. prog->fxID = vst_swap (getUID());
  27780. prog->fxVersion = vst_swap (getVersionNumber());
  27781. prog->numParams = vst_swap (numParams);
  27782. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27783. for (int i = 0; i < numParams; ++i)
  27784. prog->params[i] = vst_swapFloat (getParameter (i));
  27785. }
  27786. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27787. {
  27788. const int numPrograms = getNumPrograms();
  27789. const int numParams = getNumParameters();
  27790. if (usesChunks())
  27791. {
  27792. if (isFXB)
  27793. {
  27794. MemoryBlock chunk;
  27795. getChunkData (chunk, false, maxSizeMB);
  27796. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27797. dest.setSize (totalLen, true);
  27798. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27799. set->chunkMagic = vst_swap ('CcnK');
  27800. set->byteSize = 0;
  27801. set->fxMagic = vst_swap ('FBCh');
  27802. set->version = vst_swap (fxbVersionNum);
  27803. set->fxID = vst_swap (getUID());
  27804. set->fxVersion = vst_swap (getVersionNumber());
  27805. set->numPrograms = vst_swap (numPrograms);
  27806. set->chunkSize = vst_swap ((long) chunk.getSize());
  27807. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27808. }
  27809. else
  27810. {
  27811. MemoryBlock chunk;
  27812. getChunkData (chunk, true, maxSizeMB);
  27813. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27814. dest.setSize (totalLen, true);
  27815. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27816. set->chunkMagic = vst_swap ('CcnK');
  27817. set->byteSize = 0;
  27818. set->fxMagic = vst_swap ('FPCh');
  27819. set->version = vst_swap (fxbVersionNum);
  27820. set->fxID = vst_swap (getUID());
  27821. set->fxVersion = vst_swap (getVersionNumber());
  27822. set->numPrograms = vst_swap (numPrograms);
  27823. set->chunkSize = vst_swap ((long) chunk.getSize());
  27824. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27825. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27826. }
  27827. }
  27828. else
  27829. {
  27830. if (isFXB)
  27831. {
  27832. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27833. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27834. dest.setSize (len, true);
  27835. fxSet* const set = (fxSet*) dest.getData();
  27836. set->chunkMagic = vst_swap ('CcnK');
  27837. set->byteSize = 0;
  27838. set->fxMagic = vst_swap ('FxBk');
  27839. set->version = vst_swap (fxbVersionNum);
  27840. set->fxID = vst_swap (getUID());
  27841. set->fxVersion = vst_swap (getVersionNumber());
  27842. set->numPrograms = vst_swap (numPrograms);
  27843. const int oldProgram = getCurrentProgram();
  27844. MemoryBlock oldSettings;
  27845. createTempParameterStore (oldSettings);
  27846. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27847. for (int i = 0; i < numPrograms; ++i)
  27848. {
  27849. if (i != oldProgram)
  27850. {
  27851. setCurrentProgram (i);
  27852. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27853. }
  27854. }
  27855. setCurrentProgram (oldProgram);
  27856. restoreFromTempParameterStore (oldSettings);
  27857. }
  27858. else
  27859. {
  27860. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27861. dest.setSize (totalLen, true);
  27862. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27863. }
  27864. }
  27865. return true;
  27866. }
  27867. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27868. {
  27869. if (usesChunks())
  27870. {
  27871. void* data = 0;
  27872. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27873. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27874. {
  27875. mb.setSize (bytes);
  27876. mb.copyFrom (data, 0, bytes);
  27877. }
  27878. }
  27879. }
  27880. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27881. {
  27882. if (size > 0 && usesChunks())
  27883. {
  27884. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27885. if (! isPreset)
  27886. updateStoredProgramNames();
  27887. }
  27888. }
  27889. void VSTPluginInstance::timerCallback()
  27890. {
  27891. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27892. stopTimer();
  27893. }
  27894. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27895. {
  27896. const ScopedLock sl (lock);
  27897. ++insideVSTCallback;
  27898. int result = 0;
  27899. try
  27900. {
  27901. if (effect != 0)
  27902. {
  27903. #if JUCE_MAC
  27904. if (module->resFileId != 0)
  27905. UseResFile (module->resFileId);
  27906. CGrafPtr oldPort;
  27907. if (getActiveEditor() != 0)
  27908. {
  27909. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27910. GetPort (&oldPort);
  27911. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27912. SetOrigin (-pos.getX(), -pos.getY());
  27913. }
  27914. #endif
  27915. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27916. #if JUCE_MAC
  27917. if (getActiveEditor() != 0)
  27918. SetPort (oldPort);
  27919. module->resFileId = CurResFile();
  27920. #endif
  27921. --insideVSTCallback;
  27922. return result;
  27923. }
  27924. }
  27925. catch (...)
  27926. {
  27927. }
  27928. --insideVSTCallback;
  27929. return result;
  27930. }
  27931. // handles non plugin-specific callbacks..
  27932. static const int defaultVSTSampleRateValue = 16384;
  27933. static const int defaultVSTBlockSizeValue = 512;
  27934. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27935. {
  27936. (void) index;
  27937. (void) value;
  27938. (void) opt;
  27939. switch (opcode)
  27940. {
  27941. case audioMasterCanDo:
  27942. {
  27943. static const char* canDos[] = { "supplyIdle",
  27944. "sendVstEvents",
  27945. "sendVstMidiEvent",
  27946. "sendVstTimeInfo",
  27947. "receiveVstEvents",
  27948. "receiveVstMidiEvent",
  27949. "supportShell",
  27950. "shellCategory" };
  27951. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27952. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27953. return 1;
  27954. return 0;
  27955. }
  27956. case audioMasterVersion:
  27957. return 0x2400;
  27958. case audioMasterCurrentId:
  27959. return shellUIDToCreate;
  27960. case audioMasterGetNumAutomatableParameters:
  27961. return 0;
  27962. case audioMasterGetAutomationState:
  27963. return 1;
  27964. case audioMasterGetVendorVersion:
  27965. return 0x0101;
  27966. case audioMasterGetVendorString:
  27967. case audioMasterGetProductString:
  27968. {
  27969. String hostName ("Juce VST Host");
  27970. if (JUCEApplication::getInstance() != 0)
  27971. hostName = JUCEApplication::getInstance()->getApplicationName();
  27972. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27973. }
  27974. break;
  27975. case audioMasterGetSampleRate:
  27976. return (VstIntPtr) defaultVSTSampleRateValue;
  27977. case audioMasterGetBlockSize:
  27978. return (VstIntPtr) defaultVSTBlockSizeValue;
  27979. case audioMasterSetOutputSampleRate:
  27980. return 0;
  27981. default:
  27982. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27983. break;
  27984. }
  27985. return 0;
  27986. }
  27987. // handles callbacks for a specific plugin
  27988. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27989. {
  27990. switch (opcode)
  27991. {
  27992. case audioMasterAutomate:
  27993. sendParamChangeMessageToListeners (index, opt);
  27994. break;
  27995. case audioMasterProcessEvents:
  27996. handleMidiFromPlugin ((const VstEvents*) ptr);
  27997. break;
  27998. case audioMasterGetTime:
  27999. #if JUCE_MSVC
  28000. #pragma warning (push)
  28001. #pragma warning (disable: 4311)
  28002. #endif
  28003. return (VstIntPtr) &vstHostTime;
  28004. #if JUCE_MSVC
  28005. #pragma warning (pop)
  28006. #endif
  28007. break;
  28008. case audioMasterIdle:
  28009. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28010. {
  28011. ++insideVSTCallback;
  28012. #if JUCE_MAC
  28013. if (getActiveEditor() != 0)
  28014. dispatch (effEditIdle, 0, 0, 0, 0);
  28015. #endif
  28016. juce_callAnyTimersSynchronously();
  28017. handleUpdateNowIfNeeded();
  28018. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28019. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28020. --insideVSTCallback;
  28021. }
  28022. break;
  28023. case audioMasterUpdateDisplay:
  28024. triggerAsyncUpdate();
  28025. break;
  28026. case audioMasterTempoAt:
  28027. // returns (10000 * bpm)
  28028. break;
  28029. case audioMasterNeedIdle:
  28030. startTimer (50);
  28031. break;
  28032. case audioMasterSizeWindow:
  28033. if (getActiveEditor() != 0)
  28034. getActiveEditor()->setSize (index, value);
  28035. return 1;
  28036. case audioMasterGetSampleRate:
  28037. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28038. case audioMasterGetBlockSize:
  28039. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28040. case audioMasterWantMidi:
  28041. wantsMidiMessages = true;
  28042. break;
  28043. case audioMasterGetDirectory:
  28044. #if JUCE_MAC
  28045. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28046. #else
  28047. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28048. #endif
  28049. case audioMasterGetAutomationState:
  28050. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28051. break;
  28052. // none of these are handled (yet)..
  28053. case audioMasterBeginEdit:
  28054. case audioMasterEndEdit:
  28055. case audioMasterSetTime:
  28056. case audioMasterPinConnected:
  28057. case audioMasterGetParameterQuantization:
  28058. case audioMasterIOChanged:
  28059. case audioMasterGetInputLatency:
  28060. case audioMasterGetOutputLatency:
  28061. case audioMasterGetPreviousPlug:
  28062. case audioMasterGetNextPlug:
  28063. case audioMasterWillReplaceOrAccumulate:
  28064. case audioMasterGetCurrentProcessLevel:
  28065. case audioMasterOfflineStart:
  28066. case audioMasterOfflineRead:
  28067. case audioMasterOfflineWrite:
  28068. case audioMasterOfflineGetCurrentPass:
  28069. case audioMasterOfflineGetCurrentMetaPass:
  28070. case audioMasterVendorSpecific:
  28071. case audioMasterSetIcon:
  28072. case audioMasterGetLanguage:
  28073. case audioMasterOpenWindow:
  28074. case audioMasterCloseWindow:
  28075. break;
  28076. default:
  28077. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28078. }
  28079. return 0;
  28080. }
  28081. // entry point for all callbacks from the plugin
  28082. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28083. {
  28084. try
  28085. {
  28086. if (effect != 0 && effect->resvd2 != 0)
  28087. {
  28088. return ((VSTPluginInstance*)(effect->resvd2))
  28089. ->handleCallback (opcode, index, value, ptr, opt);
  28090. }
  28091. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28092. }
  28093. catch (...)
  28094. {
  28095. return 0;
  28096. }
  28097. }
  28098. const String VSTPluginInstance::getVersion() const throw()
  28099. {
  28100. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28101. String s;
  28102. if (v == 0 || v == -1)
  28103. v = getVersionNumber();
  28104. if (v != 0)
  28105. {
  28106. int versionBits[4];
  28107. int n = 0;
  28108. while (v != 0)
  28109. {
  28110. versionBits [n++] = (v & 0xff);
  28111. v >>= 8;
  28112. }
  28113. s << 'V';
  28114. while (n > 0)
  28115. {
  28116. s << versionBits [--n];
  28117. if (n > 0)
  28118. s << '.';
  28119. }
  28120. }
  28121. return s;
  28122. }
  28123. int VSTPluginInstance::getUID() const throw()
  28124. {
  28125. int uid = effect != 0 ? effect->uniqueID : 0;
  28126. if (uid == 0)
  28127. uid = module->file.hashCode();
  28128. return uid;
  28129. }
  28130. const String VSTPluginInstance::getCategory() const throw()
  28131. {
  28132. const char* result = 0;
  28133. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28134. {
  28135. case kPlugCategEffect:
  28136. result = "Effect";
  28137. break;
  28138. case kPlugCategSynth:
  28139. result = "Synth";
  28140. break;
  28141. case kPlugCategAnalysis:
  28142. result = "Anaylsis";
  28143. break;
  28144. case kPlugCategMastering:
  28145. result = "Mastering";
  28146. break;
  28147. case kPlugCategSpacializer:
  28148. result = "Spacial";
  28149. break;
  28150. case kPlugCategRoomFx:
  28151. result = "Reverb";
  28152. break;
  28153. case kPlugSurroundFx:
  28154. result = "Surround";
  28155. break;
  28156. case kPlugCategRestoration:
  28157. result = "Restoration";
  28158. break;
  28159. case kPlugCategGenerator:
  28160. result = "Tone generation";
  28161. break;
  28162. default:
  28163. break;
  28164. }
  28165. return result;
  28166. }
  28167. float VSTPluginInstance::getParameter (int index)
  28168. {
  28169. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28170. {
  28171. try
  28172. {
  28173. const ScopedLock sl (lock);
  28174. return effect->getParameter (effect, index);
  28175. }
  28176. catch (...)
  28177. {
  28178. }
  28179. }
  28180. return 0.0f;
  28181. }
  28182. void VSTPluginInstance::setParameter (int index, float newValue)
  28183. {
  28184. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28185. {
  28186. try
  28187. {
  28188. const ScopedLock sl (lock);
  28189. if (effect->getParameter (effect, index) != newValue)
  28190. effect->setParameter (effect, index, newValue);
  28191. }
  28192. catch (...)
  28193. {
  28194. }
  28195. }
  28196. }
  28197. const String VSTPluginInstance::getParameterName (int index)
  28198. {
  28199. if (effect != 0)
  28200. {
  28201. jassert (index >= 0 && index < effect->numParams);
  28202. char nm [256];
  28203. zerostruct (nm);
  28204. dispatch (effGetParamName, index, 0, nm, 0);
  28205. return String (nm).trim();
  28206. }
  28207. return String::empty;
  28208. }
  28209. const String VSTPluginInstance::getParameterLabel (int index) const
  28210. {
  28211. if (effect != 0)
  28212. {
  28213. jassert (index >= 0 && index < effect->numParams);
  28214. char nm [256];
  28215. zerostruct (nm);
  28216. dispatch (effGetParamLabel, index, 0, nm, 0);
  28217. return String (nm).trim();
  28218. }
  28219. return String::empty;
  28220. }
  28221. const String VSTPluginInstance::getParameterText (int index)
  28222. {
  28223. if (effect != 0)
  28224. {
  28225. jassert (index >= 0 && index < effect->numParams);
  28226. char nm [256];
  28227. zerostruct (nm);
  28228. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28229. return String (nm).trim();
  28230. }
  28231. return String::empty;
  28232. }
  28233. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28234. {
  28235. if (effect != 0)
  28236. {
  28237. jassert (index >= 0 && index < effect->numParams);
  28238. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28239. }
  28240. return false;
  28241. }
  28242. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28243. {
  28244. dest.setSize (64 + 4 * getNumParameters());
  28245. dest.fillWith (0);
  28246. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28247. float* const p = (float*) (((char*) dest.getData()) + 64);
  28248. for (int i = 0; i < getNumParameters(); ++i)
  28249. p[i] = getParameter(i);
  28250. }
  28251. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28252. {
  28253. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28254. float* p = (float*) (((char*) m.getData()) + 64);
  28255. for (int i = 0; i < getNumParameters(); ++i)
  28256. setParameter (i, p[i]);
  28257. }
  28258. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28259. {
  28260. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28261. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28262. }
  28263. const String VSTPluginInstance::getProgramName (int index)
  28264. {
  28265. if (index == getCurrentProgram())
  28266. {
  28267. return getCurrentProgramName();
  28268. }
  28269. else if (effect != 0)
  28270. {
  28271. char nm [256];
  28272. zerostruct (nm);
  28273. if (dispatch (effGetProgramNameIndexed,
  28274. jlimit (0, getNumPrograms(), index),
  28275. -1, nm, 0) != 0)
  28276. {
  28277. return String (nm).trim();
  28278. }
  28279. }
  28280. return programNames [index];
  28281. }
  28282. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28283. {
  28284. if (index == getCurrentProgram())
  28285. {
  28286. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28287. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28288. }
  28289. else
  28290. {
  28291. jassertfalse; // xxx not implemented!
  28292. }
  28293. }
  28294. void VSTPluginInstance::updateStoredProgramNames()
  28295. {
  28296. if (effect != 0 && getNumPrograms() > 0)
  28297. {
  28298. char nm [256];
  28299. zerostruct (nm);
  28300. // only do this if the plugin can't use indexed names..
  28301. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28302. {
  28303. const int oldProgram = getCurrentProgram();
  28304. MemoryBlock oldSettings;
  28305. createTempParameterStore (oldSettings);
  28306. for (int i = 0; i < getNumPrograms(); ++i)
  28307. {
  28308. setCurrentProgram (i);
  28309. getCurrentProgramName(); // (this updates the list)
  28310. }
  28311. setCurrentProgram (oldProgram);
  28312. restoreFromTempParameterStore (oldSettings);
  28313. }
  28314. }
  28315. }
  28316. const String VSTPluginInstance::getCurrentProgramName()
  28317. {
  28318. if (effect != 0)
  28319. {
  28320. char nm [256];
  28321. zerostruct (nm);
  28322. dispatch (effGetProgramName, 0, 0, nm, 0);
  28323. const int index = getCurrentProgram();
  28324. if (programNames[index].isEmpty())
  28325. {
  28326. while (programNames.size() < index)
  28327. programNames.add (String::empty);
  28328. programNames.set (index, String (nm).trim());
  28329. }
  28330. return String (nm).trim();
  28331. }
  28332. return String::empty;
  28333. }
  28334. const String VSTPluginInstance::getInputChannelName (int index) const
  28335. {
  28336. if (index >= 0 && index < getNumInputChannels())
  28337. {
  28338. VstPinProperties pinProps;
  28339. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28340. return String (pinProps.label, sizeof (pinProps.label));
  28341. }
  28342. return String::empty;
  28343. }
  28344. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28345. {
  28346. if (index < 0 || index >= getNumInputChannels())
  28347. return false;
  28348. VstPinProperties pinProps;
  28349. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28350. return (pinProps.flags & kVstPinIsStereo) != 0;
  28351. return true;
  28352. }
  28353. const String VSTPluginInstance::getOutputChannelName (int index) const
  28354. {
  28355. if (index >= 0 && index < getNumOutputChannels())
  28356. {
  28357. VstPinProperties pinProps;
  28358. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28359. return String (pinProps.label, sizeof (pinProps.label));
  28360. }
  28361. return String::empty;
  28362. }
  28363. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28364. {
  28365. if (index < 0 || index >= getNumOutputChannels())
  28366. return false;
  28367. VstPinProperties pinProps;
  28368. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28369. return (pinProps.flags & kVstPinIsStereo) != 0;
  28370. return true;
  28371. }
  28372. void VSTPluginInstance::setPower (const bool on)
  28373. {
  28374. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28375. isPowerOn = on;
  28376. }
  28377. const int defaultMaxSizeMB = 64;
  28378. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28379. {
  28380. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28381. }
  28382. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28383. {
  28384. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28385. }
  28386. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28387. {
  28388. loadFromFXBFile (data, sizeInBytes);
  28389. }
  28390. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28391. {
  28392. loadFromFXBFile (data, sizeInBytes);
  28393. }
  28394. VSTPluginFormat::VSTPluginFormat()
  28395. {
  28396. }
  28397. VSTPluginFormat::~VSTPluginFormat()
  28398. {
  28399. }
  28400. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28401. const String& fileOrIdentifier)
  28402. {
  28403. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28404. return;
  28405. PluginDescription desc;
  28406. desc.fileOrIdentifier = fileOrIdentifier;
  28407. desc.uid = 0;
  28408. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28409. if (instance == 0)
  28410. return;
  28411. try
  28412. {
  28413. #if JUCE_MAC
  28414. if (instance->module->resFileId != 0)
  28415. UseResFile (instance->module->resFileId);
  28416. #endif
  28417. instance->fillInPluginDescription (desc);
  28418. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28419. if (category != kPlugCategShell)
  28420. {
  28421. // Normal plugin...
  28422. results.add (new PluginDescription (desc));
  28423. ++insideVSTCallback;
  28424. instance->dispatch (effOpen, 0, 0, 0, 0);
  28425. --insideVSTCallback;
  28426. }
  28427. else
  28428. {
  28429. // It's a shell plugin, so iterate all the subtypes...
  28430. char shellEffectName [64];
  28431. for (;;)
  28432. {
  28433. zerostruct (shellEffectName);
  28434. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28435. if (uid == 0)
  28436. {
  28437. break;
  28438. }
  28439. else
  28440. {
  28441. desc.uid = uid;
  28442. desc.name = shellEffectName;
  28443. bool alreadyThere = false;
  28444. for (int i = results.size(); --i >= 0;)
  28445. {
  28446. PluginDescription* const d = results.getUnchecked(i);
  28447. if (d->isDuplicateOf (desc))
  28448. {
  28449. alreadyThere = true;
  28450. break;
  28451. }
  28452. }
  28453. if (! alreadyThere)
  28454. results.add (new PluginDescription (desc));
  28455. }
  28456. }
  28457. }
  28458. }
  28459. catch (...)
  28460. {
  28461. // crashed while loading...
  28462. }
  28463. }
  28464. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28465. {
  28466. ScopedPointer <VSTPluginInstance> result;
  28467. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28468. {
  28469. File file (desc.fileOrIdentifier);
  28470. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28471. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28472. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28473. if (module != 0)
  28474. {
  28475. shellUIDToCreate = desc.uid;
  28476. result = new VSTPluginInstance (module);
  28477. if (result->effect != 0)
  28478. {
  28479. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28480. result->initialise();
  28481. }
  28482. else
  28483. {
  28484. result = 0;
  28485. }
  28486. }
  28487. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28488. }
  28489. return result.release();
  28490. }
  28491. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28492. {
  28493. const File f (fileOrIdentifier);
  28494. #if JUCE_MAC
  28495. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28496. return true;
  28497. #if JUCE_PPC
  28498. FSRef fileRef;
  28499. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28500. {
  28501. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28502. if (resFileId != -1)
  28503. {
  28504. const int numEffects = Count1Resources ('aEff');
  28505. CloseResFile (resFileId);
  28506. if (numEffects > 0)
  28507. return true;
  28508. }
  28509. }
  28510. #endif
  28511. return false;
  28512. #elif JUCE_WINDOWS
  28513. return f.existsAsFile()
  28514. && f.hasFileExtension (".dll");
  28515. #elif JUCE_LINUX
  28516. return f.existsAsFile()
  28517. && f.hasFileExtension (".so");
  28518. #endif
  28519. }
  28520. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28521. {
  28522. return fileOrIdentifier;
  28523. }
  28524. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28525. {
  28526. return File (desc.fileOrIdentifier).exists();
  28527. }
  28528. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28529. {
  28530. StringArray results;
  28531. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28532. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28533. return results;
  28534. }
  28535. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28536. {
  28537. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28538. // .component or .vst directories.
  28539. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28540. while (iter.next())
  28541. {
  28542. const File f (iter.getFile());
  28543. bool isPlugin = false;
  28544. if (fileMightContainThisPluginType (f.getFullPathName()))
  28545. {
  28546. isPlugin = true;
  28547. results.add (f.getFullPathName());
  28548. }
  28549. if (recursive && (! isPlugin) && f.isDirectory())
  28550. recursiveFileSearch (results, f, true);
  28551. }
  28552. }
  28553. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28554. {
  28555. #if JUCE_MAC
  28556. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28557. #elif JUCE_WINDOWS
  28558. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28559. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28560. #elif JUCE_LINUX
  28561. return FileSearchPath ("/usr/lib/vst");
  28562. #endif
  28563. }
  28564. END_JUCE_NAMESPACE
  28565. #endif
  28566. #undef log
  28567. #endif
  28568. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28569. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28570. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28571. BEGIN_JUCE_NAMESPACE
  28572. AudioProcessor::AudioProcessor()
  28573. : playHead (0),
  28574. activeEditor (0),
  28575. sampleRate (0),
  28576. blockSize (0),
  28577. numInputChannels (0),
  28578. numOutputChannels (0),
  28579. latencySamples (0),
  28580. suspended (false),
  28581. nonRealtime (false)
  28582. {
  28583. }
  28584. AudioProcessor::~AudioProcessor()
  28585. {
  28586. // ooh, nasty - the editor should have been deleted before the filter
  28587. // that it refers to is deleted..
  28588. jassert (activeEditor == 0);
  28589. #if JUCE_DEBUG
  28590. // This will fail if you've called beginParameterChangeGesture() for one
  28591. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28592. jassert (changingParams.countNumberOfSetBits() == 0);
  28593. #endif
  28594. }
  28595. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28596. {
  28597. playHead = newPlayHead;
  28598. }
  28599. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28600. {
  28601. const ScopedLock sl (listenerLock);
  28602. listeners.addIfNotAlreadyThere (newListener);
  28603. }
  28604. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28605. {
  28606. const ScopedLock sl (listenerLock);
  28607. listeners.removeValue (listenerToRemove);
  28608. }
  28609. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28610. const int numOuts,
  28611. const double sampleRate_,
  28612. const int blockSize_) throw()
  28613. {
  28614. numInputChannels = numIns;
  28615. numOutputChannels = numOuts;
  28616. sampleRate = sampleRate_;
  28617. blockSize = blockSize_;
  28618. }
  28619. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28620. {
  28621. nonRealtime = nonRealtime_;
  28622. }
  28623. void AudioProcessor::setLatencySamples (const int newLatency)
  28624. {
  28625. if (latencySamples != newLatency)
  28626. {
  28627. latencySamples = newLatency;
  28628. updateHostDisplay();
  28629. }
  28630. }
  28631. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28632. const float newValue)
  28633. {
  28634. setParameter (parameterIndex, newValue);
  28635. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28636. }
  28637. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28638. {
  28639. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28640. for (int i = listeners.size(); --i >= 0;)
  28641. {
  28642. AudioProcessorListener* l;
  28643. {
  28644. const ScopedLock sl (listenerLock);
  28645. l = listeners [i];
  28646. }
  28647. if (l != 0)
  28648. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28649. }
  28650. }
  28651. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28652. {
  28653. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28654. #if JUCE_DEBUG
  28655. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28656. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28657. jassert (! changingParams [parameterIndex]);
  28658. changingParams.setBit (parameterIndex);
  28659. #endif
  28660. for (int i = listeners.size(); --i >= 0;)
  28661. {
  28662. AudioProcessorListener* l;
  28663. {
  28664. const ScopedLock sl (listenerLock);
  28665. l = listeners [i];
  28666. }
  28667. if (l != 0)
  28668. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28669. }
  28670. }
  28671. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28672. {
  28673. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28674. #if JUCE_DEBUG
  28675. // This means you've called endParameterChangeGesture without having previously called
  28676. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28677. // calls matched correctly.
  28678. jassert (changingParams [parameterIndex]);
  28679. changingParams.clearBit (parameterIndex);
  28680. #endif
  28681. for (int i = listeners.size(); --i >= 0;)
  28682. {
  28683. AudioProcessorListener* l;
  28684. {
  28685. const ScopedLock sl (listenerLock);
  28686. l = listeners [i];
  28687. }
  28688. if (l != 0)
  28689. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28690. }
  28691. }
  28692. void AudioProcessor::updateHostDisplay()
  28693. {
  28694. for (int i = listeners.size(); --i >= 0;)
  28695. {
  28696. AudioProcessorListener* l;
  28697. {
  28698. const ScopedLock sl (listenerLock);
  28699. l = listeners [i];
  28700. }
  28701. if (l != 0)
  28702. l->audioProcessorChanged (this);
  28703. }
  28704. }
  28705. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28706. {
  28707. return true;
  28708. }
  28709. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28710. {
  28711. return false;
  28712. }
  28713. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28714. {
  28715. const ScopedLock sl (callbackLock);
  28716. suspended = shouldBeSuspended;
  28717. }
  28718. void AudioProcessor::reset()
  28719. {
  28720. }
  28721. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28722. {
  28723. const ScopedLock sl (callbackLock);
  28724. jassert (activeEditor == editor);
  28725. if (activeEditor == editor)
  28726. activeEditor = 0;
  28727. }
  28728. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28729. {
  28730. if (activeEditor != 0)
  28731. return activeEditor;
  28732. AudioProcessorEditor* const ed = createEditor();
  28733. if (ed != 0)
  28734. {
  28735. // you must give your editor comp a size before returning it..
  28736. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28737. const ScopedLock sl (callbackLock);
  28738. activeEditor = ed;
  28739. }
  28740. return ed;
  28741. }
  28742. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28743. {
  28744. getStateInformation (destData);
  28745. }
  28746. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28747. {
  28748. setStateInformation (data, sizeInBytes);
  28749. }
  28750. // magic number to identify memory blocks that we've stored as XML
  28751. const uint32 magicXmlNumber = 0x21324356;
  28752. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28753. JUCE_NAMESPACE::MemoryBlock& destData)
  28754. {
  28755. const String xmlString (xml.createDocument (String::empty, true, false));
  28756. const int stringLength = xmlString.getNumBytesAsUTF8();
  28757. destData.setSize (stringLength + 10);
  28758. char* const d = (char*) destData.getData();
  28759. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28760. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28761. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28762. }
  28763. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28764. const int sizeInBytes)
  28765. {
  28766. if (sizeInBytes > 8
  28767. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28768. {
  28769. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  28770. if (stringLength > 0)
  28771. {
  28772. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  28773. jmin ((sizeInBytes - 8), stringLength)));
  28774. return doc.getDocumentElement();
  28775. }
  28776. }
  28777. return 0;
  28778. }
  28779. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28780. {
  28781. }
  28782. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28783. {
  28784. }
  28785. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28786. {
  28787. return timeInSeconds == other.timeInSeconds
  28788. && ppqPosition == other.ppqPosition
  28789. && editOriginTime == other.editOriginTime
  28790. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28791. && frameRate == other.frameRate
  28792. && isPlaying == other.isPlaying
  28793. && isRecording == other.isRecording
  28794. && bpm == other.bpm
  28795. && timeSigNumerator == other.timeSigNumerator
  28796. && timeSigDenominator == other.timeSigDenominator;
  28797. }
  28798. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28799. {
  28800. return ! operator== (other);
  28801. }
  28802. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28803. {
  28804. zerostruct (*this);
  28805. timeSigNumerator = 4;
  28806. timeSigDenominator = 4;
  28807. bpm = 120;
  28808. }
  28809. END_JUCE_NAMESPACE
  28810. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28811. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28812. BEGIN_JUCE_NAMESPACE
  28813. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28814. : owner (owner_)
  28815. {
  28816. // the filter must be valid..
  28817. jassert (owner != 0);
  28818. }
  28819. AudioProcessorEditor::~AudioProcessorEditor()
  28820. {
  28821. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28822. // filter for some reason..
  28823. jassert (owner->getActiveEditor() != this);
  28824. }
  28825. END_JUCE_NAMESPACE
  28826. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28827. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28828. BEGIN_JUCE_NAMESPACE
  28829. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28830. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28831. : id (id_),
  28832. processor (processor_),
  28833. isPrepared (false)
  28834. {
  28835. jassert (processor_ != 0);
  28836. }
  28837. AudioProcessorGraph::Node::~Node()
  28838. {
  28839. }
  28840. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28841. AudioProcessorGraph* const graph)
  28842. {
  28843. if (! isPrepared)
  28844. {
  28845. isPrepared = true;
  28846. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28847. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28848. if (ioProc != 0)
  28849. ioProc->setParentGraph (graph);
  28850. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28851. processor->getNumOutputChannels(),
  28852. sampleRate, blockSize);
  28853. processor->prepareToPlay (sampleRate, blockSize);
  28854. }
  28855. }
  28856. void AudioProcessorGraph::Node::unprepare()
  28857. {
  28858. if (isPrepared)
  28859. {
  28860. isPrepared = false;
  28861. processor->releaseResources();
  28862. }
  28863. }
  28864. AudioProcessorGraph::AudioProcessorGraph()
  28865. : lastNodeId (0),
  28866. renderingBuffers (1, 1),
  28867. currentAudioOutputBuffer (1, 1)
  28868. {
  28869. }
  28870. AudioProcessorGraph::~AudioProcessorGraph()
  28871. {
  28872. clearRenderingSequence();
  28873. clear();
  28874. }
  28875. const String AudioProcessorGraph::getName() const
  28876. {
  28877. return "Audio Graph";
  28878. }
  28879. void AudioProcessorGraph::clear()
  28880. {
  28881. nodes.clear();
  28882. connections.clear();
  28883. triggerAsyncUpdate();
  28884. }
  28885. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28886. {
  28887. for (int i = nodes.size(); --i >= 0;)
  28888. if (nodes.getUnchecked(i)->id == nodeId)
  28889. return nodes.getUnchecked(i);
  28890. return 0;
  28891. }
  28892. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28893. uint32 nodeId)
  28894. {
  28895. if (newProcessor == 0)
  28896. {
  28897. jassertfalse;
  28898. return 0;
  28899. }
  28900. if (nodeId == 0)
  28901. {
  28902. nodeId = ++lastNodeId;
  28903. }
  28904. else
  28905. {
  28906. // you can't add a node with an id that already exists in the graph..
  28907. jassert (getNodeForId (nodeId) == 0);
  28908. removeNode (nodeId);
  28909. }
  28910. lastNodeId = nodeId;
  28911. Node* const n = new Node (nodeId, newProcessor);
  28912. nodes.add (n);
  28913. triggerAsyncUpdate();
  28914. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28915. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  28916. if (ioProc != 0)
  28917. ioProc->setParentGraph (this);
  28918. return n;
  28919. }
  28920. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28921. {
  28922. disconnectNode (nodeId);
  28923. for (int i = nodes.size(); --i >= 0;)
  28924. {
  28925. if (nodes.getUnchecked(i)->id == nodeId)
  28926. {
  28927. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28928. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  28929. if (ioProc != 0)
  28930. ioProc->setParentGraph (0);
  28931. nodes.remove (i);
  28932. triggerAsyncUpdate();
  28933. return true;
  28934. }
  28935. }
  28936. return false;
  28937. }
  28938. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28939. const int sourceChannelIndex,
  28940. const uint32 destNodeId,
  28941. const int destChannelIndex) const
  28942. {
  28943. for (int i = connections.size(); --i >= 0;)
  28944. {
  28945. const Connection* const c = connections.getUnchecked(i);
  28946. if (c->sourceNodeId == sourceNodeId
  28947. && c->destNodeId == destNodeId
  28948. && c->sourceChannelIndex == sourceChannelIndex
  28949. && c->destChannelIndex == destChannelIndex)
  28950. {
  28951. return c;
  28952. }
  28953. }
  28954. return 0;
  28955. }
  28956. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28957. const uint32 possibleDestNodeId) const
  28958. {
  28959. for (int i = connections.size(); --i >= 0;)
  28960. {
  28961. const Connection* const c = connections.getUnchecked(i);
  28962. if (c->sourceNodeId == possibleSourceNodeId
  28963. && c->destNodeId == possibleDestNodeId)
  28964. {
  28965. return true;
  28966. }
  28967. }
  28968. return false;
  28969. }
  28970. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28971. const int sourceChannelIndex,
  28972. const uint32 destNodeId,
  28973. const int destChannelIndex) const
  28974. {
  28975. if (sourceChannelIndex < 0
  28976. || destChannelIndex < 0
  28977. || sourceNodeId == destNodeId
  28978. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28979. return false;
  28980. const Node* const source = getNodeForId (sourceNodeId);
  28981. if (source == 0
  28982. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28983. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28984. return false;
  28985. const Node* const dest = getNodeForId (destNodeId);
  28986. if (dest == 0
  28987. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28988. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28989. return false;
  28990. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28991. destNodeId, destChannelIndex) == 0;
  28992. }
  28993. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28994. const int sourceChannelIndex,
  28995. const uint32 destNodeId,
  28996. const int destChannelIndex)
  28997. {
  28998. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28999. return false;
  29000. Connection* const c = new Connection();
  29001. c->sourceNodeId = sourceNodeId;
  29002. c->sourceChannelIndex = sourceChannelIndex;
  29003. c->destNodeId = destNodeId;
  29004. c->destChannelIndex = destChannelIndex;
  29005. connections.add (c);
  29006. triggerAsyncUpdate();
  29007. return true;
  29008. }
  29009. void AudioProcessorGraph::removeConnection (const int index)
  29010. {
  29011. connections.remove (index);
  29012. triggerAsyncUpdate();
  29013. }
  29014. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29015. const uint32 destNodeId, const int destChannelIndex)
  29016. {
  29017. bool doneAnything = false;
  29018. for (int i = connections.size(); --i >= 0;)
  29019. {
  29020. const Connection* const c = connections.getUnchecked(i);
  29021. if (c->sourceNodeId == sourceNodeId
  29022. && c->destNodeId == destNodeId
  29023. && c->sourceChannelIndex == sourceChannelIndex
  29024. && c->destChannelIndex == destChannelIndex)
  29025. {
  29026. removeConnection (i);
  29027. doneAnything = true;
  29028. triggerAsyncUpdate();
  29029. }
  29030. }
  29031. return doneAnything;
  29032. }
  29033. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29034. {
  29035. bool doneAnything = false;
  29036. for (int i = connections.size(); --i >= 0;)
  29037. {
  29038. const Connection* const c = connections.getUnchecked(i);
  29039. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29040. {
  29041. removeConnection (i);
  29042. doneAnything = true;
  29043. triggerAsyncUpdate();
  29044. }
  29045. }
  29046. return doneAnything;
  29047. }
  29048. bool AudioProcessorGraph::removeIllegalConnections()
  29049. {
  29050. bool doneAnything = false;
  29051. for (int i = connections.size(); --i >= 0;)
  29052. {
  29053. const Connection* const c = connections.getUnchecked(i);
  29054. const Node* const source = getNodeForId (c->sourceNodeId);
  29055. const Node* const dest = getNodeForId (c->destNodeId);
  29056. if (source == 0 || dest == 0
  29057. || (c->sourceChannelIndex != midiChannelIndex
  29058. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29059. || (c->sourceChannelIndex == midiChannelIndex
  29060. && ! source->processor->producesMidi())
  29061. || (c->destChannelIndex != midiChannelIndex
  29062. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29063. || (c->destChannelIndex == midiChannelIndex
  29064. && ! dest->processor->acceptsMidi()))
  29065. {
  29066. removeConnection (i);
  29067. doneAnything = true;
  29068. triggerAsyncUpdate();
  29069. }
  29070. }
  29071. return doneAnything;
  29072. }
  29073. namespace GraphRenderingOps
  29074. {
  29075. class AudioGraphRenderingOp
  29076. {
  29077. public:
  29078. AudioGraphRenderingOp() {}
  29079. virtual ~AudioGraphRenderingOp() {}
  29080. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29081. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29082. const int numSamples) = 0;
  29083. juce_UseDebuggingNewOperator
  29084. };
  29085. class ClearChannelOp : public AudioGraphRenderingOp
  29086. {
  29087. public:
  29088. ClearChannelOp (const int channelNum_)
  29089. : channelNum (channelNum_)
  29090. {}
  29091. ~ClearChannelOp() {}
  29092. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29093. {
  29094. sharedBufferChans.clear (channelNum, 0, numSamples);
  29095. }
  29096. private:
  29097. const int channelNum;
  29098. ClearChannelOp (const ClearChannelOp&);
  29099. ClearChannelOp& operator= (const ClearChannelOp&);
  29100. };
  29101. class CopyChannelOp : public AudioGraphRenderingOp
  29102. {
  29103. public:
  29104. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29105. : srcChannelNum (srcChannelNum_),
  29106. dstChannelNum (dstChannelNum_)
  29107. {}
  29108. ~CopyChannelOp() {}
  29109. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29110. {
  29111. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29112. }
  29113. private:
  29114. const int srcChannelNum, dstChannelNum;
  29115. CopyChannelOp (const CopyChannelOp&);
  29116. CopyChannelOp& operator= (const CopyChannelOp&);
  29117. };
  29118. class AddChannelOp : public AudioGraphRenderingOp
  29119. {
  29120. public:
  29121. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29122. : srcChannelNum (srcChannelNum_),
  29123. dstChannelNum (dstChannelNum_)
  29124. {}
  29125. ~AddChannelOp() {}
  29126. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29127. {
  29128. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29129. }
  29130. private:
  29131. const int srcChannelNum, dstChannelNum;
  29132. AddChannelOp (const AddChannelOp&);
  29133. AddChannelOp& operator= (const AddChannelOp&);
  29134. };
  29135. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29136. {
  29137. public:
  29138. ClearMidiBufferOp (const int bufferNum_)
  29139. : bufferNum (bufferNum_)
  29140. {}
  29141. ~ClearMidiBufferOp() {}
  29142. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29143. {
  29144. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29145. }
  29146. private:
  29147. const int bufferNum;
  29148. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29149. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29150. };
  29151. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29152. {
  29153. public:
  29154. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29155. : srcBufferNum (srcBufferNum_),
  29156. dstBufferNum (dstBufferNum_)
  29157. {}
  29158. ~CopyMidiBufferOp() {}
  29159. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29160. {
  29161. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29162. }
  29163. private:
  29164. const int srcBufferNum, dstBufferNum;
  29165. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29166. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29167. };
  29168. class AddMidiBufferOp : public AudioGraphRenderingOp
  29169. {
  29170. public:
  29171. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29172. : srcBufferNum (srcBufferNum_),
  29173. dstBufferNum (dstBufferNum_)
  29174. {}
  29175. ~AddMidiBufferOp() {}
  29176. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29177. {
  29178. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29179. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29180. }
  29181. private:
  29182. const int srcBufferNum, dstBufferNum;
  29183. AddMidiBufferOp (const AddMidiBufferOp&);
  29184. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29185. };
  29186. class ProcessBufferOp : public AudioGraphRenderingOp
  29187. {
  29188. public:
  29189. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29190. const Array <int>& audioChannelsToUse_,
  29191. const int totalChans_,
  29192. const int midiBufferToUse_)
  29193. : node (node_),
  29194. processor (node_->processor),
  29195. audioChannelsToUse (audioChannelsToUse_),
  29196. totalChans (jmax (1, totalChans_)),
  29197. midiBufferToUse (midiBufferToUse_)
  29198. {
  29199. channels.calloc (totalChans);
  29200. while (audioChannelsToUse.size() < totalChans)
  29201. audioChannelsToUse.add (0);
  29202. }
  29203. ~ProcessBufferOp()
  29204. {
  29205. }
  29206. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29207. {
  29208. for (int i = totalChans; --i >= 0;)
  29209. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29210. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29211. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29212. }
  29213. const AudioProcessorGraph::Node::Ptr node;
  29214. AudioProcessor* const processor;
  29215. private:
  29216. Array <int> audioChannelsToUse;
  29217. HeapBlock <float*> channels;
  29218. int totalChans;
  29219. int midiBufferToUse;
  29220. ProcessBufferOp (const ProcessBufferOp&);
  29221. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29222. };
  29223. /** Used to calculate the correct sequence of rendering ops needed, based on
  29224. the best re-use of shared buffers at each stage.
  29225. */
  29226. class RenderingOpSequenceCalculator
  29227. {
  29228. public:
  29229. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29230. const Array<void*>& orderedNodes_,
  29231. Array<void*>& renderingOps)
  29232. : graph (graph_),
  29233. orderedNodes (orderedNodes_)
  29234. {
  29235. nodeIds.add (-2); // first buffer is read-only zeros
  29236. channels.add (0);
  29237. midiNodeIds.add (-2);
  29238. for (int i = 0; i < orderedNodes.size(); ++i)
  29239. {
  29240. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29241. renderingOps, i);
  29242. markAnyUnusedBuffersAsFree (i);
  29243. }
  29244. }
  29245. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29246. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29247. juce_UseDebuggingNewOperator
  29248. private:
  29249. AudioProcessorGraph& graph;
  29250. const Array<void*>& orderedNodes;
  29251. Array <int> nodeIds, channels, midiNodeIds;
  29252. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29253. Array<void*>& renderingOps,
  29254. const int ourRenderingIndex)
  29255. {
  29256. const int numIns = node->processor->getNumInputChannels();
  29257. const int numOuts = node->processor->getNumOutputChannels();
  29258. const int totalChans = jmax (numIns, numOuts);
  29259. Array <int> audioChannelsToUse;
  29260. int midiBufferToUse = -1;
  29261. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29262. {
  29263. // get a list of all the inputs to this node
  29264. Array <int> sourceNodes, sourceOutputChans;
  29265. for (int i = graph.getNumConnections(); --i >= 0;)
  29266. {
  29267. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29268. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29269. {
  29270. sourceNodes.add (c->sourceNodeId);
  29271. sourceOutputChans.add (c->sourceChannelIndex);
  29272. }
  29273. }
  29274. int bufIndex = -1;
  29275. if (sourceNodes.size() == 0)
  29276. {
  29277. // unconnected input channel
  29278. if (inputChan >= numOuts)
  29279. {
  29280. bufIndex = getReadOnlyEmptyBuffer();
  29281. jassert (bufIndex >= 0);
  29282. }
  29283. else
  29284. {
  29285. bufIndex = getFreeBuffer (false);
  29286. renderingOps.add (new ClearChannelOp (bufIndex));
  29287. }
  29288. }
  29289. else if (sourceNodes.size() == 1)
  29290. {
  29291. // channel with a straightforward single input..
  29292. const int srcNode = sourceNodes.getUnchecked(0);
  29293. const int srcChan = sourceOutputChans.getUnchecked(0);
  29294. bufIndex = getBufferContaining (srcNode, srcChan);
  29295. if (bufIndex < 0)
  29296. {
  29297. // if not found, this is probably a feedback loop
  29298. bufIndex = getReadOnlyEmptyBuffer();
  29299. jassert (bufIndex >= 0);
  29300. }
  29301. if (inputChan < numOuts
  29302. && isBufferNeededLater (ourRenderingIndex,
  29303. inputChan,
  29304. srcNode, srcChan))
  29305. {
  29306. // can't mess up this channel because it's needed later by another node, so we
  29307. // need to use a copy of it..
  29308. const int newFreeBuffer = getFreeBuffer (false);
  29309. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29310. bufIndex = newFreeBuffer;
  29311. }
  29312. }
  29313. else
  29314. {
  29315. // channel with a mix of several inputs..
  29316. // try to find a re-usable channel from our inputs..
  29317. int reusableInputIndex = -1;
  29318. for (int i = 0; i < sourceNodes.size(); ++i)
  29319. {
  29320. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29321. sourceOutputChans.getUnchecked(i));
  29322. if (sourceBufIndex >= 0
  29323. && ! isBufferNeededLater (ourRenderingIndex,
  29324. inputChan,
  29325. sourceNodes.getUnchecked(i),
  29326. sourceOutputChans.getUnchecked(i)))
  29327. {
  29328. // we've found one of our input chans that can be re-used..
  29329. reusableInputIndex = i;
  29330. bufIndex = sourceBufIndex;
  29331. break;
  29332. }
  29333. }
  29334. if (reusableInputIndex < 0)
  29335. {
  29336. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29337. bufIndex = getFreeBuffer (false);
  29338. jassert (bufIndex != 0);
  29339. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29340. sourceOutputChans.getUnchecked (0));
  29341. if (srcIndex < 0)
  29342. {
  29343. // if not found, this is probably a feedback loop
  29344. renderingOps.add (new ClearChannelOp (bufIndex));
  29345. }
  29346. else
  29347. {
  29348. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29349. }
  29350. reusableInputIndex = 0;
  29351. }
  29352. for (int j = 0; j < sourceNodes.size(); ++j)
  29353. {
  29354. if (j != reusableInputIndex)
  29355. {
  29356. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29357. sourceOutputChans.getUnchecked(j));
  29358. if (srcIndex >= 0)
  29359. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29360. }
  29361. }
  29362. }
  29363. jassert (bufIndex >= 0);
  29364. audioChannelsToUse.add (bufIndex);
  29365. if (inputChan < numOuts)
  29366. markBufferAsContaining (bufIndex, node->id, inputChan);
  29367. }
  29368. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29369. {
  29370. const int bufIndex = getFreeBuffer (false);
  29371. jassert (bufIndex != 0);
  29372. audioChannelsToUse.add (bufIndex);
  29373. markBufferAsContaining (bufIndex, node->id, outputChan);
  29374. }
  29375. // Now the same thing for midi..
  29376. Array <int> midiSourceNodes;
  29377. for (int i = graph.getNumConnections(); --i >= 0;)
  29378. {
  29379. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29380. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29381. midiSourceNodes.add (c->sourceNodeId);
  29382. }
  29383. if (midiSourceNodes.size() == 0)
  29384. {
  29385. // No midi inputs..
  29386. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29387. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  29388. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29389. }
  29390. else if (midiSourceNodes.size() == 1)
  29391. {
  29392. // One midi input..
  29393. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29394. AudioProcessorGraph::midiChannelIndex);
  29395. if (midiBufferToUse >= 0)
  29396. {
  29397. if (isBufferNeededLater (ourRenderingIndex,
  29398. AudioProcessorGraph::midiChannelIndex,
  29399. midiSourceNodes.getUnchecked(0),
  29400. AudioProcessorGraph::midiChannelIndex))
  29401. {
  29402. // can't mess up this channel because it's needed later by another node, so we
  29403. // need to use a copy of it..
  29404. const int newFreeBuffer = getFreeBuffer (true);
  29405. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29406. midiBufferToUse = newFreeBuffer;
  29407. }
  29408. }
  29409. else
  29410. {
  29411. // probably a feedback loop, so just use an empty one..
  29412. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29413. }
  29414. }
  29415. else
  29416. {
  29417. // More than one midi input being mixed..
  29418. int reusableInputIndex = -1;
  29419. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29420. {
  29421. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29422. AudioProcessorGraph::midiChannelIndex);
  29423. if (sourceBufIndex >= 0
  29424. && ! isBufferNeededLater (ourRenderingIndex,
  29425. AudioProcessorGraph::midiChannelIndex,
  29426. midiSourceNodes.getUnchecked(i),
  29427. AudioProcessorGraph::midiChannelIndex))
  29428. {
  29429. // we've found one of our input buffers that can be re-used..
  29430. reusableInputIndex = i;
  29431. midiBufferToUse = sourceBufIndex;
  29432. break;
  29433. }
  29434. }
  29435. if (reusableInputIndex < 0)
  29436. {
  29437. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29438. midiBufferToUse = getFreeBuffer (true);
  29439. jassert (midiBufferToUse >= 0);
  29440. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29441. AudioProcessorGraph::midiChannelIndex);
  29442. if (srcIndex >= 0)
  29443. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29444. else
  29445. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29446. reusableInputIndex = 0;
  29447. }
  29448. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29449. {
  29450. if (j != reusableInputIndex)
  29451. {
  29452. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29453. AudioProcessorGraph::midiChannelIndex);
  29454. if (srcIndex >= 0)
  29455. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29456. }
  29457. }
  29458. }
  29459. if (node->processor->producesMidi())
  29460. markBufferAsContaining (midiBufferToUse, node->id,
  29461. AudioProcessorGraph::midiChannelIndex);
  29462. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29463. totalChans, midiBufferToUse));
  29464. }
  29465. int getFreeBuffer (const bool forMidi)
  29466. {
  29467. if (forMidi)
  29468. {
  29469. for (int i = 1; i < midiNodeIds.size(); ++i)
  29470. if (midiNodeIds.getUnchecked(i) < 0)
  29471. return i;
  29472. midiNodeIds.add (-1);
  29473. return midiNodeIds.size() - 1;
  29474. }
  29475. else
  29476. {
  29477. for (int i = 1; i < nodeIds.size(); ++i)
  29478. if (nodeIds.getUnchecked(i) < 0)
  29479. return i;
  29480. nodeIds.add (-1);
  29481. channels.add (0);
  29482. return nodeIds.size() - 1;
  29483. }
  29484. }
  29485. int getReadOnlyEmptyBuffer() const
  29486. {
  29487. return 0;
  29488. }
  29489. int getBufferContaining (const int nodeId, const int outputChannel) const
  29490. {
  29491. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29492. {
  29493. for (int i = midiNodeIds.size(); --i >= 0;)
  29494. if (midiNodeIds.getUnchecked(i) == nodeId)
  29495. return i;
  29496. }
  29497. else
  29498. {
  29499. for (int i = nodeIds.size(); --i >= 0;)
  29500. if (nodeIds.getUnchecked(i) == nodeId
  29501. && channels.getUnchecked(i) == outputChannel)
  29502. return i;
  29503. }
  29504. return -1;
  29505. }
  29506. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29507. {
  29508. int i;
  29509. for (i = 0; i < nodeIds.size(); ++i)
  29510. {
  29511. if (nodeIds.getUnchecked(i) >= 0
  29512. && ! isBufferNeededLater (stepIndex, -1,
  29513. nodeIds.getUnchecked(i),
  29514. channels.getUnchecked(i)))
  29515. {
  29516. nodeIds.set (i, -1);
  29517. }
  29518. }
  29519. for (i = 0; i < midiNodeIds.size(); ++i)
  29520. {
  29521. if (midiNodeIds.getUnchecked(i) >= 0
  29522. && ! isBufferNeededLater (stepIndex, -1,
  29523. midiNodeIds.getUnchecked(i),
  29524. AudioProcessorGraph::midiChannelIndex))
  29525. {
  29526. midiNodeIds.set (i, -1);
  29527. }
  29528. }
  29529. }
  29530. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29531. int inputChannelOfIndexToIgnore,
  29532. const int nodeId,
  29533. const int outputChanIndex) const
  29534. {
  29535. while (stepIndexToSearchFrom < orderedNodes.size())
  29536. {
  29537. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29538. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29539. {
  29540. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29541. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29542. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29543. return true;
  29544. }
  29545. else
  29546. {
  29547. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  29548. if (i != inputChannelOfIndexToIgnore
  29549. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29550. node->id, i) != 0)
  29551. return true;
  29552. }
  29553. inputChannelOfIndexToIgnore = -1;
  29554. ++stepIndexToSearchFrom;
  29555. }
  29556. return false;
  29557. }
  29558. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29559. {
  29560. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29561. {
  29562. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29563. midiNodeIds.set (bufferNum, nodeId);
  29564. }
  29565. else
  29566. {
  29567. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29568. nodeIds.set (bufferNum, nodeId);
  29569. channels.set (bufferNum, outputIndex);
  29570. }
  29571. }
  29572. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29573. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29574. };
  29575. }
  29576. void AudioProcessorGraph::clearRenderingSequence()
  29577. {
  29578. const ScopedLock sl (renderLock);
  29579. for (int i = renderingOps.size(); --i >= 0;)
  29580. {
  29581. GraphRenderingOps::AudioGraphRenderingOp* const r
  29582. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29583. renderingOps.remove (i);
  29584. delete r;
  29585. }
  29586. }
  29587. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29588. const uint32 possibleDestinationId,
  29589. const int recursionCheck) const
  29590. {
  29591. if (recursionCheck > 0)
  29592. {
  29593. for (int i = connections.size(); --i >= 0;)
  29594. {
  29595. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29596. if (c->destNodeId == possibleDestinationId
  29597. && (c->sourceNodeId == possibleInputId
  29598. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29599. return true;
  29600. }
  29601. }
  29602. return false;
  29603. }
  29604. void AudioProcessorGraph::buildRenderingSequence()
  29605. {
  29606. Array<void*> newRenderingOps;
  29607. int numRenderingBuffersNeeded = 2;
  29608. int numMidiBuffersNeeded = 1;
  29609. {
  29610. MessageManagerLock mml;
  29611. Array<void*> orderedNodes;
  29612. int i;
  29613. for (i = 0; i < nodes.size(); ++i)
  29614. {
  29615. Node* const node = nodes.getUnchecked(i);
  29616. node->prepare (getSampleRate(), getBlockSize(), this);
  29617. int j = 0;
  29618. for (; j < orderedNodes.size(); ++j)
  29619. if (isAnInputTo (node->id,
  29620. ((Node*) orderedNodes.getUnchecked (j))->id,
  29621. nodes.size() + 1))
  29622. break;
  29623. orderedNodes.insert (j, node);
  29624. }
  29625. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29626. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29627. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29628. }
  29629. Array<void*> oldRenderingOps (renderingOps);
  29630. {
  29631. // swap over to the new rendering sequence..
  29632. const ScopedLock sl (renderLock);
  29633. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29634. renderingBuffers.clear();
  29635. for (int i = midiBuffers.size(); --i >= 0;)
  29636. midiBuffers.getUnchecked(i)->clear();
  29637. while (midiBuffers.size() < numMidiBuffersNeeded)
  29638. midiBuffers.add (new MidiBuffer());
  29639. renderingOps = newRenderingOps;
  29640. }
  29641. for (int i = oldRenderingOps.size(); --i >= 0;)
  29642. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29643. }
  29644. void AudioProcessorGraph::handleAsyncUpdate()
  29645. {
  29646. buildRenderingSequence();
  29647. }
  29648. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29649. {
  29650. currentAudioInputBuffer = 0;
  29651. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29652. currentMidiInputBuffer = 0;
  29653. currentMidiOutputBuffer.clear();
  29654. clearRenderingSequence();
  29655. buildRenderingSequence();
  29656. }
  29657. void AudioProcessorGraph::releaseResources()
  29658. {
  29659. for (int i = 0; i < nodes.size(); ++i)
  29660. nodes.getUnchecked(i)->unprepare();
  29661. renderingBuffers.setSize (1, 1);
  29662. midiBuffers.clear();
  29663. currentAudioInputBuffer = 0;
  29664. currentAudioOutputBuffer.setSize (1, 1);
  29665. currentMidiInputBuffer = 0;
  29666. currentMidiOutputBuffer.clear();
  29667. }
  29668. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29669. {
  29670. const int numSamples = buffer.getNumSamples();
  29671. const ScopedLock sl (renderLock);
  29672. currentAudioInputBuffer = &buffer;
  29673. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29674. currentAudioOutputBuffer.clear();
  29675. currentMidiInputBuffer = &midiMessages;
  29676. currentMidiOutputBuffer.clear();
  29677. int i;
  29678. for (i = 0; i < renderingOps.size(); ++i)
  29679. {
  29680. GraphRenderingOps::AudioGraphRenderingOp* const op
  29681. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29682. op->perform (renderingBuffers, midiBuffers, numSamples);
  29683. }
  29684. for (i = 0; i < buffer.getNumChannels(); ++i)
  29685. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29686. midiMessages.clear();
  29687. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29688. }
  29689. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29690. {
  29691. return "Input " + String (channelIndex + 1);
  29692. }
  29693. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29694. {
  29695. return "Output " + String (channelIndex + 1);
  29696. }
  29697. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29698. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29699. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29700. bool AudioProcessorGraph::producesMidi() const { return true; }
  29701. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29702. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29703. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29704. : type (type_),
  29705. graph (0)
  29706. {
  29707. }
  29708. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29709. {
  29710. }
  29711. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29712. {
  29713. switch (type)
  29714. {
  29715. case audioOutputNode: return "Audio Output";
  29716. case audioInputNode: return "Audio Input";
  29717. case midiOutputNode: return "Midi Output";
  29718. case midiInputNode: return "Midi Input";
  29719. default: break;
  29720. }
  29721. return String::empty;
  29722. }
  29723. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29724. {
  29725. d.name = getName();
  29726. d.uid = d.name.hashCode();
  29727. d.category = "I/O devices";
  29728. d.pluginFormatName = "Internal";
  29729. d.manufacturerName = "Raw Material Software";
  29730. d.version = "1.0";
  29731. d.isInstrument = false;
  29732. d.numInputChannels = getNumInputChannels();
  29733. if (type == audioOutputNode && graph != 0)
  29734. d.numInputChannels = graph->getNumInputChannels();
  29735. d.numOutputChannels = getNumOutputChannels();
  29736. if (type == audioInputNode && graph != 0)
  29737. d.numOutputChannels = graph->getNumOutputChannels();
  29738. }
  29739. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29740. {
  29741. jassert (graph != 0);
  29742. }
  29743. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29744. {
  29745. }
  29746. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29747. MidiBuffer& midiMessages)
  29748. {
  29749. jassert (graph != 0);
  29750. switch (type)
  29751. {
  29752. case audioOutputNode:
  29753. {
  29754. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29755. buffer.getNumChannels()); --i >= 0;)
  29756. {
  29757. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29758. }
  29759. break;
  29760. }
  29761. case audioInputNode:
  29762. {
  29763. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29764. buffer.getNumChannels()); --i >= 0;)
  29765. {
  29766. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29767. }
  29768. break;
  29769. }
  29770. case midiOutputNode:
  29771. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29772. break;
  29773. case midiInputNode:
  29774. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29775. break;
  29776. default:
  29777. break;
  29778. }
  29779. }
  29780. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29781. {
  29782. return type == midiOutputNode;
  29783. }
  29784. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29785. {
  29786. return type == midiInputNode;
  29787. }
  29788. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29789. {
  29790. switch (type)
  29791. {
  29792. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29793. case midiOutputNode: return "Midi Output";
  29794. default: break;
  29795. }
  29796. return String::empty;
  29797. }
  29798. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29799. {
  29800. switch (type)
  29801. {
  29802. case audioInputNode: return "Input " + String (channelIndex + 1);
  29803. case midiInputNode: return "Midi Input";
  29804. default: break;
  29805. }
  29806. return String::empty;
  29807. }
  29808. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29809. {
  29810. return type == audioInputNode || type == audioOutputNode;
  29811. }
  29812. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29813. {
  29814. return isInputChannelStereoPair (index);
  29815. }
  29816. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29817. {
  29818. return type == audioInputNode || type == midiInputNode;
  29819. }
  29820. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29821. {
  29822. return type == audioOutputNode || type == midiOutputNode;
  29823. }
  29824. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29825. {
  29826. return 0;
  29827. }
  29828. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29829. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29830. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29831. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29832. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29833. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29834. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29835. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29836. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29837. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29838. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29839. {
  29840. }
  29841. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29842. {
  29843. }
  29844. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29845. {
  29846. graph = newGraph;
  29847. if (graph != 0)
  29848. {
  29849. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29850. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29851. getSampleRate(),
  29852. getBlockSize());
  29853. updateHostDisplay();
  29854. }
  29855. }
  29856. END_JUCE_NAMESPACE
  29857. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29858. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29859. BEGIN_JUCE_NAMESPACE
  29860. AudioProcessorPlayer::AudioProcessorPlayer()
  29861. : processor (0),
  29862. sampleRate (0),
  29863. blockSize (0),
  29864. isPrepared (false),
  29865. numInputChans (0),
  29866. numOutputChans (0),
  29867. tempBuffer (1, 1)
  29868. {
  29869. }
  29870. AudioProcessorPlayer::~AudioProcessorPlayer()
  29871. {
  29872. setProcessor (0);
  29873. }
  29874. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29875. {
  29876. if (processor != processorToPlay)
  29877. {
  29878. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29879. {
  29880. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29881. sampleRate, blockSize);
  29882. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29883. }
  29884. AudioProcessor* oldOne;
  29885. {
  29886. const ScopedLock sl (lock);
  29887. oldOne = isPrepared ? processor : 0;
  29888. processor = processorToPlay;
  29889. isPrepared = true;
  29890. }
  29891. if (oldOne != 0)
  29892. oldOne->releaseResources();
  29893. }
  29894. }
  29895. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29896. const int numInputChannels,
  29897. float** const outputChannelData,
  29898. const int numOutputChannels,
  29899. const int numSamples)
  29900. {
  29901. // these should have been prepared by audioDeviceAboutToStart()...
  29902. jassert (sampleRate > 0 && blockSize > 0);
  29903. incomingMidi.clear();
  29904. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29905. int i, totalNumChans = 0;
  29906. if (numInputChannels > numOutputChannels)
  29907. {
  29908. // if there aren't enough output channels for the number of
  29909. // inputs, we need to create some temporary extra ones (can't
  29910. // use the input data in case it gets written to)
  29911. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29912. false, false, true);
  29913. for (i = 0; i < numOutputChannels; ++i)
  29914. {
  29915. channels[totalNumChans] = outputChannelData[i];
  29916. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29917. ++totalNumChans;
  29918. }
  29919. for (i = numOutputChannels; i < numInputChannels; ++i)
  29920. {
  29921. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29922. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29923. ++totalNumChans;
  29924. }
  29925. }
  29926. else
  29927. {
  29928. for (i = 0; i < numInputChannels; ++i)
  29929. {
  29930. channels[totalNumChans] = outputChannelData[i];
  29931. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29932. ++totalNumChans;
  29933. }
  29934. for (i = numInputChannels; i < numOutputChannels; ++i)
  29935. {
  29936. channels[totalNumChans] = outputChannelData[i];
  29937. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29938. ++totalNumChans;
  29939. }
  29940. }
  29941. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29942. const ScopedLock sl (lock);
  29943. if (processor != 0)
  29944. {
  29945. const ScopedLock sl (processor->getCallbackLock());
  29946. if (processor->isSuspended())
  29947. {
  29948. for (i = 0; i < numOutputChannels; ++i)
  29949. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29950. }
  29951. else
  29952. {
  29953. processor->processBlock (buffer, incomingMidi);
  29954. }
  29955. }
  29956. }
  29957. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29958. {
  29959. const ScopedLock sl (lock);
  29960. sampleRate = device->getCurrentSampleRate();
  29961. blockSize = device->getCurrentBufferSizeSamples();
  29962. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29963. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29964. messageCollector.reset (sampleRate);
  29965. zeromem (channels, sizeof (channels));
  29966. if (processor != 0)
  29967. {
  29968. if (isPrepared)
  29969. processor->releaseResources();
  29970. AudioProcessor* const oldProcessor = processor;
  29971. setProcessor (0);
  29972. setProcessor (oldProcessor);
  29973. }
  29974. }
  29975. void AudioProcessorPlayer::audioDeviceStopped()
  29976. {
  29977. const ScopedLock sl (lock);
  29978. if (processor != 0 && isPrepared)
  29979. processor->releaseResources();
  29980. sampleRate = 0.0;
  29981. blockSize = 0;
  29982. isPrepared = false;
  29983. tempBuffer.setSize (1, 1);
  29984. }
  29985. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29986. {
  29987. messageCollector.addMessageToQueue (message);
  29988. }
  29989. END_JUCE_NAMESPACE
  29990. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29991. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29992. BEGIN_JUCE_NAMESPACE
  29993. class ProcessorParameterPropertyComp : public PropertyComponent,
  29994. public AudioProcessorListener,
  29995. public AsyncUpdater
  29996. {
  29997. public:
  29998. ProcessorParameterPropertyComp (const String& name,
  29999. AudioProcessor* const owner_,
  30000. const int index_)
  30001. : PropertyComponent (name),
  30002. owner (owner_),
  30003. index (index_)
  30004. {
  30005. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  30006. owner_->addListener (this);
  30007. }
  30008. ~ProcessorParameterPropertyComp()
  30009. {
  30010. owner->removeListener (this);
  30011. deleteAllChildren();
  30012. }
  30013. void refresh()
  30014. {
  30015. slider->setValue (owner->getParameter (index), false);
  30016. }
  30017. void audioProcessorChanged (AudioProcessor*) {}
  30018. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30019. {
  30020. if (parameterIndex == index)
  30021. triggerAsyncUpdate();
  30022. }
  30023. void handleAsyncUpdate()
  30024. {
  30025. refresh();
  30026. }
  30027. juce_UseDebuggingNewOperator
  30028. private:
  30029. AudioProcessor* const owner;
  30030. const int index;
  30031. Slider* slider;
  30032. class ParamSlider : public Slider
  30033. {
  30034. public:
  30035. ParamSlider (AudioProcessor* const owner_, const int index_)
  30036. : Slider (String::empty),
  30037. owner (owner_),
  30038. index (index_)
  30039. {
  30040. setRange (0.0, 1.0, 0.0);
  30041. setSliderStyle (Slider::LinearBar);
  30042. setTextBoxIsEditable (false);
  30043. setScrollWheelEnabled (false);
  30044. }
  30045. ~ParamSlider()
  30046. {
  30047. }
  30048. void valueChanged()
  30049. {
  30050. const float newVal = (float) getValue();
  30051. if (owner->getParameter (index) != newVal)
  30052. owner->setParameter (index, newVal);
  30053. }
  30054. const String getTextFromValue (double /*value*/)
  30055. {
  30056. return owner->getParameterText (index);
  30057. }
  30058. juce_UseDebuggingNewOperator
  30059. private:
  30060. AudioProcessor* const owner;
  30061. const int index;
  30062. ParamSlider (const ParamSlider&);
  30063. ParamSlider& operator= (const ParamSlider&);
  30064. };
  30065. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30066. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30067. };
  30068. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30069. : AudioProcessorEditor (owner_)
  30070. {
  30071. setOpaque (true);
  30072. addAndMakeVisible (panel = new PropertyPanel());
  30073. Array <PropertyComponent*> params;
  30074. const int numParams = owner_->getNumParameters();
  30075. int totalHeight = 0;
  30076. for (int i = 0; i < numParams; ++i)
  30077. {
  30078. String name (owner_->getParameterName (i));
  30079. if (name.trim().isEmpty())
  30080. name = "Unnamed";
  30081. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  30082. params.add (pc);
  30083. totalHeight += pc->getPreferredHeight();
  30084. }
  30085. panel->addProperties (params);
  30086. setSize (400, jlimit (25, 400, totalHeight));
  30087. }
  30088. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30089. {
  30090. deleteAllChildren();
  30091. }
  30092. void GenericAudioProcessorEditor::paint (Graphics& g)
  30093. {
  30094. g.fillAll (Colours::white);
  30095. }
  30096. void GenericAudioProcessorEditor::resized()
  30097. {
  30098. panel->setSize (getWidth(), getHeight());
  30099. }
  30100. END_JUCE_NAMESPACE
  30101. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30102. /*** Start of inlined file: juce_Sampler.cpp ***/
  30103. BEGIN_JUCE_NAMESPACE
  30104. SamplerSound::SamplerSound (const String& name_,
  30105. AudioFormatReader& source,
  30106. const BigInteger& midiNotes_,
  30107. const int midiNoteForNormalPitch,
  30108. const double attackTimeSecs,
  30109. const double releaseTimeSecs,
  30110. const double maxSampleLengthSeconds)
  30111. : name (name_),
  30112. midiNotes (midiNotes_),
  30113. midiRootNote (midiNoteForNormalPitch)
  30114. {
  30115. sourceSampleRate = source.sampleRate;
  30116. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30117. {
  30118. length = 0;
  30119. attackSamples = 0;
  30120. releaseSamples = 0;
  30121. }
  30122. else
  30123. {
  30124. length = jmin ((int) source.lengthInSamples,
  30125. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30126. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30127. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30128. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30129. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30130. }
  30131. }
  30132. SamplerSound::~SamplerSound()
  30133. {
  30134. }
  30135. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30136. {
  30137. return midiNotes [midiNoteNumber];
  30138. }
  30139. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30140. {
  30141. return true;
  30142. }
  30143. SamplerVoice::SamplerVoice()
  30144. : pitchRatio (0.0),
  30145. sourceSamplePosition (0.0),
  30146. lgain (0.0f),
  30147. rgain (0.0f),
  30148. isInAttack (false),
  30149. isInRelease (false)
  30150. {
  30151. }
  30152. SamplerVoice::~SamplerVoice()
  30153. {
  30154. }
  30155. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30156. {
  30157. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30158. }
  30159. void SamplerVoice::startNote (const int midiNoteNumber,
  30160. const float velocity,
  30161. SynthesiserSound* s,
  30162. const int /*currentPitchWheelPosition*/)
  30163. {
  30164. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30165. jassert (sound != 0); // this object can only play SamplerSounds!
  30166. if (sound != 0)
  30167. {
  30168. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30169. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30170. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30171. sourceSamplePosition = 0.0;
  30172. lgain = velocity;
  30173. rgain = velocity;
  30174. isInAttack = (sound->attackSamples > 0);
  30175. isInRelease = false;
  30176. if (isInAttack)
  30177. {
  30178. attackReleaseLevel = 0.0f;
  30179. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30180. }
  30181. else
  30182. {
  30183. attackReleaseLevel = 1.0f;
  30184. attackDelta = 0.0f;
  30185. }
  30186. if (sound->releaseSamples > 0)
  30187. {
  30188. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30189. }
  30190. else
  30191. {
  30192. releaseDelta = 0.0f;
  30193. }
  30194. }
  30195. }
  30196. void SamplerVoice::stopNote (const bool allowTailOff)
  30197. {
  30198. if (allowTailOff)
  30199. {
  30200. isInAttack = false;
  30201. isInRelease = true;
  30202. }
  30203. else
  30204. {
  30205. clearCurrentNote();
  30206. }
  30207. }
  30208. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30209. {
  30210. }
  30211. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30212. const int /*newValue*/)
  30213. {
  30214. }
  30215. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30216. {
  30217. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30218. if (playingSound != 0)
  30219. {
  30220. const float* const inL = playingSound->data->getSampleData (0, 0);
  30221. const float* const inR = playingSound->data->getNumChannels() > 1
  30222. ? playingSound->data->getSampleData (1, 0) : 0;
  30223. float* outL = outputBuffer.getSampleData (0, startSample);
  30224. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30225. while (--numSamples >= 0)
  30226. {
  30227. const int pos = (int) sourceSamplePosition;
  30228. const float alpha = (float) (sourceSamplePosition - pos);
  30229. const float invAlpha = 1.0f - alpha;
  30230. // just using a very simple linear interpolation here..
  30231. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30232. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30233. : l;
  30234. l *= lgain;
  30235. r *= rgain;
  30236. if (isInAttack)
  30237. {
  30238. l *= attackReleaseLevel;
  30239. r *= attackReleaseLevel;
  30240. attackReleaseLevel += attackDelta;
  30241. if (attackReleaseLevel >= 1.0f)
  30242. {
  30243. attackReleaseLevel = 1.0f;
  30244. isInAttack = false;
  30245. }
  30246. }
  30247. else if (isInRelease)
  30248. {
  30249. l *= attackReleaseLevel;
  30250. r *= attackReleaseLevel;
  30251. attackReleaseLevel += releaseDelta;
  30252. if (attackReleaseLevel <= 0.0f)
  30253. {
  30254. stopNote (false);
  30255. break;
  30256. }
  30257. }
  30258. if (outR != 0)
  30259. {
  30260. *outL++ += l;
  30261. *outR++ += r;
  30262. }
  30263. else
  30264. {
  30265. *outL++ += (l + r) * 0.5f;
  30266. }
  30267. sourceSamplePosition += pitchRatio;
  30268. if (sourceSamplePosition > playingSound->length)
  30269. {
  30270. stopNote (false);
  30271. break;
  30272. }
  30273. }
  30274. }
  30275. }
  30276. END_JUCE_NAMESPACE
  30277. /*** End of inlined file: juce_Sampler.cpp ***/
  30278. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30279. BEGIN_JUCE_NAMESPACE
  30280. SynthesiserSound::SynthesiserSound()
  30281. {
  30282. }
  30283. SynthesiserSound::~SynthesiserSound()
  30284. {
  30285. }
  30286. SynthesiserVoice::SynthesiserVoice()
  30287. : currentSampleRate (44100.0),
  30288. currentlyPlayingNote (-1),
  30289. noteOnTime (0),
  30290. currentlyPlayingSound (0)
  30291. {
  30292. }
  30293. SynthesiserVoice::~SynthesiserVoice()
  30294. {
  30295. }
  30296. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30297. {
  30298. return currentlyPlayingSound != 0
  30299. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30300. }
  30301. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30302. {
  30303. currentSampleRate = newRate;
  30304. }
  30305. void SynthesiserVoice::clearCurrentNote()
  30306. {
  30307. currentlyPlayingNote = -1;
  30308. currentlyPlayingSound = 0;
  30309. }
  30310. Synthesiser::Synthesiser()
  30311. : sampleRate (0),
  30312. lastNoteOnCounter (0),
  30313. shouldStealNotes (true)
  30314. {
  30315. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30316. lastPitchWheelValues[i] = 0x2000;
  30317. }
  30318. Synthesiser::~Synthesiser()
  30319. {
  30320. }
  30321. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30322. {
  30323. const ScopedLock sl (lock);
  30324. return voices [index];
  30325. }
  30326. void Synthesiser::clearVoices()
  30327. {
  30328. const ScopedLock sl (lock);
  30329. voices.clear();
  30330. }
  30331. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30332. {
  30333. const ScopedLock sl (lock);
  30334. voices.add (newVoice);
  30335. }
  30336. void Synthesiser::removeVoice (const int index)
  30337. {
  30338. const ScopedLock sl (lock);
  30339. voices.remove (index);
  30340. }
  30341. void Synthesiser::clearSounds()
  30342. {
  30343. const ScopedLock sl (lock);
  30344. sounds.clear();
  30345. }
  30346. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30347. {
  30348. const ScopedLock sl (lock);
  30349. sounds.add (newSound);
  30350. }
  30351. void Synthesiser::removeSound (const int index)
  30352. {
  30353. const ScopedLock sl (lock);
  30354. sounds.remove (index);
  30355. }
  30356. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30357. {
  30358. shouldStealNotes = shouldStealNotes_;
  30359. }
  30360. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30361. {
  30362. if (sampleRate != newRate)
  30363. {
  30364. const ScopedLock sl (lock);
  30365. allNotesOff (0, false);
  30366. sampleRate = newRate;
  30367. for (int i = voices.size(); --i >= 0;)
  30368. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30369. }
  30370. }
  30371. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30372. const MidiBuffer& midiData,
  30373. int startSample,
  30374. int numSamples)
  30375. {
  30376. // must set the sample rate before using this!
  30377. jassert (sampleRate != 0);
  30378. const ScopedLock sl (lock);
  30379. MidiBuffer::Iterator midiIterator (midiData);
  30380. midiIterator.setNextSamplePosition (startSample);
  30381. MidiMessage m (0xf4, 0.0);
  30382. while (numSamples > 0)
  30383. {
  30384. int midiEventPos;
  30385. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30386. && midiEventPos < startSample + numSamples;
  30387. const int numThisTime = useEvent ? midiEventPos - startSample
  30388. : numSamples;
  30389. if (numThisTime > 0)
  30390. {
  30391. for (int i = voices.size(); --i >= 0;)
  30392. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30393. }
  30394. if (useEvent)
  30395. {
  30396. if (m.isNoteOn())
  30397. {
  30398. const int channel = m.getChannel();
  30399. noteOn (channel,
  30400. m.getNoteNumber(),
  30401. m.getFloatVelocity());
  30402. }
  30403. else if (m.isNoteOff())
  30404. {
  30405. noteOff (m.getChannel(),
  30406. m.getNoteNumber(),
  30407. true);
  30408. }
  30409. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30410. {
  30411. allNotesOff (m.getChannel(), true);
  30412. }
  30413. else if (m.isPitchWheel())
  30414. {
  30415. const int channel = m.getChannel();
  30416. const int wheelPos = m.getPitchWheelValue();
  30417. lastPitchWheelValues [channel - 1] = wheelPos;
  30418. handlePitchWheel (channel, wheelPos);
  30419. }
  30420. else if (m.isController())
  30421. {
  30422. handleController (m.getChannel(),
  30423. m.getControllerNumber(),
  30424. m.getControllerValue());
  30425. }
  30426. }
  30427. startSample += numThisTime;
  30428. numSamples -= numThisTime;
  30429. }
  30430. }
  30431. void Synthesiser::noteOn (const int midiChannel,
  30432. const int midiNoteNumber,
  30433. const float velocity)
  30434. {
  30435. const ScopedLock sl (lock);
  30436. for (int i = sounds.size(); --i >= 0;)
  30437. {
  30438. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30439. if (sound->appliesToNote (midiNoteNumber)
  30440. && sound->appliesToChannel (midiChannel))
  30441. {
  30442. startVoice (findFreeVoice (sound, shouldStealNotes),
  30443. sound, midiChannel, midiNoteNumber, velocity);
  30444. }
  30445. }
  30446. }
  30447. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30448. SynthesiserSound* const sound,
  30449. const int midiChannel,
  30450. const int midiNoteNumber,
  30451. const float velocity)
  30452. {
  30453. if (voice != 0 && sound != 0)
  30454. {
  30455. if (voice->currentlyPlayingSound != 0)
  30456. voice->stopNote (false);
  30457. voice->startNote (midiNoteNumber,
  30458. velocity,
  30459. sound,
  30460. lastPitchWheelValues [midiChannel - 1]);
  30461. voice->currentlyPlayingNote = midiNoteNumber;
  30462. voice->noteOnTime = ++lastNoteOnCounter;
  30463. voice->currentlyPlayingSound = sound;
  30464. }
  30465. }
  30466. void Synthesiser::noteOff (const int midiChannel,
  30467. const int midiNoteNumber,
  30468. const bool allowTailOff)
  30469. {
  30470. const ScopedLock sl (lock);
  30471. for (int i = voices.size(); --i >= 0;)
  30472. {
  30473. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30474. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30475. {
  30476. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30477. if (sound != 0
  30478. && sound->appliesToNote (midiNoteNumber)
  30479. && sound->appliesToChannel (midiChannel))
  30480. {
  30481. voice->stopNote (allowTailOff);
  30482. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30483. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30484. }
  30485. }
  30486. }
  30487. }
  30488. void Synthesiser::allNotesOff (const int midiChannel,
  30489. const bool allowTailOff)
  30490. {
  30491. const ScopedLock sl (lock);
  30492. for (int i = voices.size(); --i >= 0;)
  30493. {
  30494. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30495. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30496. voice->stopNote (allowTailOff);
  30497. }
  30498. }
  30499. void Synthesiser::handlePitchWheel (const int midiChannel,
  30500. const int wheelValue)
  30501. {
  30502. const ScopedLock sl (lock);
  30503. for (int i = voices.size(); --i >= 0;)
  30504. {
  30505. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30506. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30507. {
  30508. voice->pitchWheelMoved (wheelValue);
  30509. }
  30510. }
  30511. }
  30512. void Synthesiser::handleController (const int midiChannel,
  30513. const int controllerNumber,
  30514. const int controllerValue)
  30515. {
  30516. const ScopedLock sl (lock);
  30517. for (int i = voices.size(); --i >= 0;)
  30518. {
  30519. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30520. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30521. voice->controllerMoved (controllerNumber, controllerValue);
  30522. }
  30523. }
  30524. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30525. const bool stealIfNoneAvailable) const
  30526. {
  30527. const ScopedLock sl (lock);
  30528. for (int i = voices.size(); --i >= 0;)
  30529. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30530. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30531. return voices.getUnchecked (i);
  30532. if (stealIfNoneAvailable)
  30533. {
  30534. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30535. SynthesiserVoice* oldest = 0;
  30536. for (int i = voices.size(); --i >= 0;)
  30537. {
  30538. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30539. if (voice->canPlaySound (soundToPlay)
  30540. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30541. oldest = voice;
  30542. }
  30543. jassert (oldest != 0);
  30544. return oldest;
  30545. }
  30546. return 0;
  30547. }
  30548. END_JUCE_NAMESPACE
  30549. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30550. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30551. BEGIN_JUCE_NAMESPACE
  30552. ActionBroadcaster::ActionBroadcaster() throw()
  30553. {
  30554. // are you trying to create this object before or after juce has been intialised??
  30555. jassert (MessageManager::instance != 0);
  30556. }
  30557. ActionBroadcaster::~ActionBroadcaster()
  30558. {
  30559. // all event-based objects must be deleted BEFORE juce is shut down!
  30560. jassert (MessageManager::instance != 0);
  30561. }
  30562. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30563. {
  30564. actionListenerList.addActionListener (listener);
  30565. }
  30566. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30567. {
  30568. jassert (actionListenerList.isValidMessageListener());
  30569. if (actionListenerList.isValidMessageListener())
  30570. actionListenerList.removeActionListener (listener);
  30571. }
  30572. void ActionBroadcaster::removeAllActionListeners()
  30573. {
  30574. actionListenerList.removeAllActionListeners();
  30575. }
  30576. void ActionBroadcaster::sendActionMessage (const String& message) const
  30577. {
  30578. actionListenerList.sendActionMessage (message);
  30579. }
  30580. END_JUCE_NAMESPACE
  30581. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30582. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30583. BEGIN_JUCE_NAMESPACE
  30584. // special message of our own with a string in it
  30585. class ActionMessage : public Message
  30586. {
  30587. public:
  30588. const String message;
  30589. ActionMessage (const String& messageText,
  30590. void* const listener_) throw()
  30591. : message (messageText)
  30592. {
  30593. pointerParameter = listener_;
  30594. }
  30595. ~ActionMessage() throw()
  30596. {
  30597. }
  30598. private:
  30599. ActionMessage (const ActionMessage&);
  30600. ActionMessage& operator= (const ActionMessage&);
  30601. };
  30602. ActionListenerList::ActionListenerList() throw()
  30603. {
  30604. }
  30605. ActionListenerList::~ActionListenerList() throw()
  30606. {
  30607. }
  30608. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  30609. {
  30610. const ScopedLock sl (actionListenerLock_);
  30611. jassert (listener != 0);
  30612. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30613. if (listener != 0)
  30614. actionListeners_.add (listener);
  30615. }
  30616. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  30617. {
  30618. const ScopedLock sl (actionListenerLock_);
  30619. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30620. actionListeners_.removeValue (listener);
  30621. }
  30622. void ActionListenerList::removeAllActionListeners() throw()
  30623. {
  30624. const ScopedLock sl (actionListenerLock_);
  30625. actionListeners_.clear();
  30626. }
  30627. void ActionListenerList::sendActionMessage (const String& message) const
  30628. {
  30629. const ScopedLock sl (actionListenerLock_);
  30630. for (int i = actionListeners_.size(); --i >= 0;)
  30631. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30632. }
  30633. void ActionListenerList::handleMessage (const Message& message)
  30634. {
  30635. const ActionMessage& am = (const ActionMessage&) message;
  30636. if (actionListeners_.contains (am.pointerParameter))
  30637. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30638. }
  30639. END_JUCE_NAMESPACE
  30640. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30641. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30642. BEGIN_JUCE_NAMESPACE
  30643. AsyncUpdater::AsyncUpdater() throw()
  30644. : asyncMessagePending (false)
  30645. {
  30646. internalAsyncHandler.owner = this;
  30647. }
  30648. AsyncUpdater::~AsyncUpdater()
  30649. {
  30650. }
  30651. void AsyncUpdater::triggerAsyncUpdate() throw()
  30652. {
  30653. if (! asyncMessagePending)
  30654. {
  30655. asyncMessagePending = true;
  30656. internalAsyncHandler.postMessage (new Message());
  30657. }
  30658. }
  30659. void AsyncUpdater::cancelPendingUpdate() throw()
  30660. {
  30661. asyncMessagePending = false;
  30662. }
  30663. void AsyncUpdater::handleUpdateNowIfNeeded()
  30664. {
  30665. if (asyncMessagePending)
  30666. {
  30667. asyncMessagePending = false;
  30668. handleAsyncUpdate();
  30669. }
  30670. }
  30671. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30672. {
  30673. owner->handleUpdateNowIfNeeded();
  30674. }
  30675. END_JUCE_NAMESPACE
  30676. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30677. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30678. BEGIN_JUCE_NAMESPACE
  30679. ChangeBroadcaster::ChangeBroadcaster() throw()
  30680. {
  30681. // are you trying to create this object before or after juce has been intialised??
  30682. jassert (MessageManager::instance != 0);
  30683. }
  30684. ChangeBroadcaster::~ChangeBroadcaster()
  30685. {
  30686. // all event-based objects must be deleted BEFORE juce is shut down!
  30687. jassert (MessageManager::instance != 0);
  30688. }
  30689. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  30690. {
  30691. changeListenerList.addChangeListener (listener);
  30692. }
  30693. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  30694. {
  30695. jassert (changeListenerList.isValidMessageListener());
  30696. if (changeListenerList.isValidMessageListener())
  30697. changeListenerList.removeChangeListener (listener);
  30698. }
  30699. void ChangeBroadcaster::removeAllChangeListeners() throw()
  30700. {
  30701. changeListenerList.removeAllChangeListeners();
  30702. }
  30703. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  30704. {
  30705. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30706. }
  30707. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30708. {
  30709. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30710. }
  30711. void ChangeBroadcaster::dispatchPendingMessages()
  30712. {
  30713. changeListenerList.dispatchPendingMessages();
  30714. }
  30715. END_JUCE_NAMESPACE
  30716. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30717. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30718. BEGIN_JUCE_NAMESPACE
  30719. ChangeListenerList::ChangeListenerList() throw()
  30720. : lastChangedObject (0),
  30721. messagePending (false)
  30722. {
  30723. }
  30724. ChangeListenerList::~ChangeListenerList() throw()
  30725. {
  30726. }
  30727. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  30728. {
  30729. const ScopedLock sl (lock);
  30730. jassert (listener != 0);
  30731. if (listener != 0)
  30732. listeners.add (listener);
  30733. }
  30734. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  30735. {
  30736. const ScopedLock sl (lock);
  30737. listeners.removeValue (listener);
  30738. }
  30739. void ChangeListenerList::removeAllChangeListeners() throw()
  30740. {
  30741. const ScopedLock sl (lock);
  30742. listeners.clear();
  30743. }
  30744. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  30745. {
  30746. const ScopedLock sl (lock);
  30747. if ((! messagePending) && (listeners.size() > 0))
  30748. {
  30749. lastChangedObject = objectThatHasChanged;
  30750. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30751. messagePending = true;
  30752. }
  30753. }
  30754. void ChangeListenerList::handleMessage (const Message& message)
  30755. {
  30756. sendSynchronousChangeMessage (message.pointerParameter);
  30757. }
  30758. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30759. {
  30760. const ScopedLock sl (lock);
  30761. messagePending = false;
  30762. for (int i = listeners.size(); --i >= 0;)
  30763. {
  30764. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30765. {
  30766. const ScopedUnlock tempUnlocker (lock);
  30767. l->changeListenerCallback (objectThatHasChanged);
  30768. }
  30769. i = jmin (i, listeners.size());
  30770. }
  30771. }
  30772. void ChangeListenerList::dispatchPendingMessages()
  30773. {
  30774. if (messagePending)
  30775. sendSynchronousChangeMessage (lastChangedObject);
  30776. }
  30777. END_JUCE_NAMESPACE
  30778. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30779. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30780. BEGIN_JUCE_NAMESPACE
  30781. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30782. const uint32 magicMessageHeaderNumber)
  30783. : Thread ("Juce IPC connection"),
  30784. callbackConnectionState (false),
  30785. useMessageThread (callbacksOnMessageThread),
  30786. magicMessageHeader (magicMessageHeaderNumber),
  30787. pipeReceiveMessageTimeout (-1)
  30788. {
  30789. }
  30790. InterprocessConnection::~InterprocessConnection()
  30791. {
  30792. callbackConnectionState = false;
  30793. disconnect();
  30794. }
  30795. bool InterprocessConnection::connectToSocket (const String& hostName,
  30796. const int portNumber,
  30797. const int timeOutMillisecs)
  30798. {
  30799. disconnect();
  30800. const ScopedLock sl (pipeAndSocketLock);
  30801. socket = new StreamingSocket();
  30802. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30803. {
  30804. connectionMadeInt();
  30805. startThread();
  30806. return true;
  30807. }
  30808. else
  30809. {
  30810. socket = 0;
  30811. return false;
  30812. }
  30813. }
  30814. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30815. const int pipeReceiveMessageTimeoutMs)
  30816. {
  30817. disconnect();
  30818. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30819. if (newPipe->openExisting (pipeName))
  30820. {
  30821. const ScopedLock sl (pipeAndSocketLock);
  30822. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30823. initialiseWithPipe (newPipe.release());
  30824. return true;
  30825. }
  30826. return false;
  30827. }
  30828. bool InterprocessConnection::createPipe (const String& pipeName,
  30829. const int pipeReceiveMessageTimeoutMs)
  30830. {
  30831. disconnect();
  30832. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30833. if (newPipe->createNewPipe (pipeName))
  30834. {
  30835. const ScopedLock sl (pipeAndSocketLock);
  30836. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30837. initialiseWithPipe (newPipe.release());
  30838. return true;
  30839. }
  30840. return false;
  30841. }
  30842. void InterprocessConnection::disconnect()
  30843. {
  30844. if (socket != 0)
  30845. socket->close();
  30846. if (pipe != 0)
  30847. {
  30848. pipe->cancelPendingReads();
  30849. pipe->close();
  30850. }
  30851. stopThread (4000);
  30852. {
  30853. const ScopedLock sl (pipeAndSocketLock);
  30854. socket = 0;
  30855. pipe = 0;
  30856. }
  30857. connectionLostInt();
  30858. }
  30859. bool InterprocessConnection::isConnected() const
  30860. {
  30861. const ScopedLock sl (pipeAndSocketLock);
  30862. return ((socket != 0 && socket->isConnected())
  30863. || (pipe != 0 && pipe->isOpen()))
  30864. && isThreadRunning();
  30865. }
  30866. const String InterprocessConnection::getConnectedHostName() const
  30867. {
  30868. if (pipe != 0)
  30869. {
  30870. return "localhost";
  30871. }
  30872. else if (socket != 0)
  30873. {
  30874. if (! socket->isLocal())
  30875. return socket->getHostName();
  30876. return "localhost";
  30877. }
  30878. return String::empty;
  30879. }
  30880. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30881. {
  30882. uint32 messageHeader[2];
  30883. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30884. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30885. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30886. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30887. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30888. size_t bytesWritten = 0;
  30889. const ScopedLock sl (pipeAndSocketLock);
  30890. if (socket != 0)
  30891. {
  30892. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30893. }
  30894. else if (pipe != 0)
  30895. {
  30896. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30897. }
  30898. if (bytesWritten < 0)
  30899. {
  30900. // error..
  30901. return false;
  30902. }
  30903. return (bytesWritten == messageData.getSize());
  30904. }
  30905. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30906. {
  30907. jassert (socket == 0);
  30908. socket = socket_;
  30909. connectionMadeInt();
  30910. startThread();
  30911. }
  30912. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30913. {
  30914. jassert (pipe == 0);
  30915. pipe = pipe_;
  30916. connectionMadeInt();
  30917. startThread();
  30918. }
  30919. const int messageMagicNumber = 0xb734128b;
  30920. void InterprocessConnection::handleMessage (const Message& message)
  30921. {
  30922. if (message.intParameter1 == messageMagicNumber)
  30923. {
  30924. switch (message.intParameter2)
  30925. {
  30926. case 0:
  30927. {
  30928. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30929. messageReceived (*data);
  30930. break;
  30931. }
  30932. case 1:
  30933. connectionMade();
  30934. break;
  30935. case 2:
  30936. connectionLost();
  30937. break;
  30938. }
  30939. }
  30940. }
  30941. void InterprocessConnection::connectionMadeInt()
  30942. {
  30943. if (! callbackConnectionState)
  30944. {
  30945. callbackConnectionState = true;
  30946. if (useMessageThread)
  30947. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30948. else
  30949. connectionMade();
  30950. }
  30951. }
  30952. void InterprocessConnection::connectionLostInt()
  30953. {
  30954. if (callbackConnectionState)
  30955. {
  30956. callbackConnectionState = false;
  30957. if (useMessageThread)
  30958. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30959. else
  30960. connectionLost();
  30961. }
  30962. }
  30963. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30964. {
  30965. jassert (callbackConnectionState);
  30966. if (useMessageThread)
  30967. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30968. else
  30969. messageReceived (data);
  30970. }
  30971. bool InterprocessConnection::readNextMessageInt()
  30972. {
  30973. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30974. uint32 messageHeader[2];
  30975. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30976. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30977. if (bytes == sizeof (messageHeader)
  30978. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30979. {
  30980. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30981. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30982. {
  30983. MemoryBlock messageData (bytesInMessage, true);
  30984. int bytesRead = 0;
  30985. while (bytesInMessage > 0)
  30986. {
  30987. if (threadShouldExit())
  30988. return false;
  30989. const int numThisTime = jmin (bytesInMessage, 65536);
  30990. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30991. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30992. if (bytesIn <= 0)
  30993. break;
  30994. bytesRead += bytesIn;
  30995. bytesInMessage -= bytesIn;
  30996. }
  30997. if (bytesRead >= 0)
  30998. deliverDataInt (messageData);
  30999. }
  31000. }
  31001. else if (bytes < 0)
  31002. {
  31003. {
  31004. const ScopedLock sl (pipeAndSocketLock);
  31005. socket = 0;
  31006. }
  31007. connectionLostInt();
  31008. return false;
  31009. }
  31010. return true;
  31011. }
  31012. void InterprocessConnection::run()
  31013. {
  31014. while (! threadShouldExit())
  31015. {
  31016. if (socket != 0)
  31017. {
  31018. const int ready = socket->waitUntilReady (true, 0);
  31019. if (ready < 0)
  31020. {
  31021. {
  31022. const ScopedLock sl (pipeAndSocketLock);
  31023. socket = 0;
  31024. }
  31025. connectionLostInt();
  31026. break;
  31027. }
  31028. else if (ready > 0)
  31029. {
  31030. if (! readNextMessageInt())
  31031. break;
  31032. }
  31033. else
  31034. {
  31035. Thread::sleep (2);
  31036. }
  31037. }
  31038. else if (pipe != 0)
  31039. {
  31040. if (! pipe->isOpen())
  31041. {
  31042. {
  31043. const ScopedLock sl (pipeAndSocketLock);
  31044. pipe = 0;
  31045. }
  31046. connectionLostInt();
  31047. break;
  31048. }
  31049. else
  31050. {
  31051. if (! readNextMessageInt())
  31052. break;
  31053. }
  31054. }
  31055. else
  31056. {
  31057. break;
  31058. }
  31059. }
  31060. }
  31061. END_JUCE_NAMESPACE
  31062. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31063. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31064. BEGIN_JUCE_NAMESPACE
  31065. InterprocessConnectionServer::InterprocessConnectionServer()
  31066. : Thread ("Juce IPC server")
  31067. {
  31068. }
  31069. InterprocessConnectionServer::~InterprocessConnectionServer()
  31070. {
  31071. stop();
  31072. }
  31073. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31074. {
  31075. stop();
  31076. socket = new StreamingSocket();
  31077. if (socket->createListener (portNumber))
  31078. {
  31079. startThread();
  31080. return true;
  31081. }
  31082. socket = 0;
  31083. return false;
  31084. }
  31085. void InterprocessConnectionServer::stop()
  31086. {
  31087. signalThreadShouldExit();
  31088. if (socket != 0)
  31089. socket->close();
  31090. stopThread (4000);
  31091. socket = 0;
  31092. }
  31093. void InterprocessConnectionServer::run()
  31094. {
  31095. while ((! threadShouldExit()) && socket != 0)
  31096. {
  31097. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31098. if (clientSocket != 0)
  31099. {
  31100. InterprocessConnection* newConnection = createConnectionObject();
  31101. if (newConnection != 0)
  31102. newConnection->initialiseWithSocket (clientSocket.release());
  31103. }
  31104. }
  31105. }
  31106. END_JUCE_NAMESPACE
  31107. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31108. /*** Start of inlined file: juce_Message.cpp ***/
  31109. BEGIN_JUCE_NAMESPACE
  31110. Message::Message() throw()
  31111. : intParameter1 (0),
  31112. intParameter2 (0),
  31113. intParameter3 (0),
  31114. pointerParameter (0)
  31115. {
  31116. }
  31117. Message::Message (const int intParameter1_,
  31118. const int intParameter2_,
  31119. const int intParameter3_,
  31120. void* const pointerParameter_) throw()
  31121. : intParameter1 (intParameter1_),
  31122. intParameter2 (intParameter2_),
  31123. intParameter3 (intParameter3_),
  31124. pointerParameter (pointerParameter_)
  31125. {
  31126. }
  31127. Message::~Message() throw()
  31128. {
  31129. }
  31130. END_JUCE_NAMESPACE
  31131. /*** End of inlined file: juce_Message.cpp ***/
  31132. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31133. BEGIN_JUCE_NAMESPACE
  31134. MessageListener::MessageListener() throw()
  31135. {
  31136. // are you trying to create a messagelistener before or after juce has been intialised??
  31137. jassert (MessageManager::instance != 0);
  31138. if (MessageManager::instance != 0)
  31139. MessageManager::instance->messageListeners.add (this);
  31140. }
  31141. MessageListener::~MessageListener()
  31142. {
  31143. if (MessageManager::instance != 0)
  31144. MessageManager::instance->messageListeners.removeValue (this);
  31145. }
  31146. void MessageListener::postMessage (Message* const message) const throw()
  31147. {
  31148. message->messageRecipient = const_cast <MessageListener*> (this);
  31149. if (MessageManager::instance == 0)
  31150. MessageManager::getInstance();
  31151. MessageManager::instance->postMessageToQueue (message);
  31152. }
  31153. bool MessageListener::isValidMessageListener() const throw()
  31154. {
  31155. return (MessageManager::instance != 0)
  31156. && MessageManager::instance->messageListeners.contains (this);
  31157. }
  31158. END_JUCE_NAMESPACE
  31159. /*** End of inlined file: juce_MessageListener.cpp ***/
  31160. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31161. BEGIN_JUCE_NAMESPACE
  31162. // platform-specific functions..
  31163. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31164. bool juce_postMessageToSystemQueue (Message* message);
  31165. MessageManager* MessageManager::instance = 0;
  31166. static const int quitMessageId = 0xfffff321;
  31167. MessageManager::MessageManager() throw()
  31168. : quitMessagePosted (false),
  31169. quitMessageReceived (false),
  31170. threadWithLock (0)
  31171. {
  31172. messageThreadId = Thread::getCurrentThreadId();
  31173. }
  31174. MessageManager::~MessageManager() throw()
  31175. {
  31176. broadcastListeners = 0;
  31177. doPlatformSpecificShutdown();
  31178. // If you hit this assertion, then you've probably leaked a Component or some other
  31179. // kind of MessageListener object...
  31180. jassert (messageListeners.size() == 0);
  31181. jassert (instance == this);
  31182. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31183. }
  31184. MessageManager* MessageManager::getInstance() throw()
  31185. {
  31186. if (instance == 0)
  31187. {
  31188. instance = new MessageManager();
  31189. doPlatformSpecificInitialisation();
  31190. }
  31191. return instance;
  31192. }
  31193. void MessageManager::postMessageToQueue (Message* const message)
  31194. {
  31195. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31196. delete message;
  31197. }
  31198. CallbackMessage::CallbackMessage() throw() {}
  31199. CallbackMessage::~CallbackMessage() throw() {}
  31200. void CallbackMessage::post()
  31201. {
  31202. if (MessageManager::instance != 0)
  31203. MessageManager::instance->postCallbackMessage (this);
  31204. }
  31205. void MessageManager::postCallbackMessage (Message* const message)
  31206. {
  31207. message->messageRecipient = 0;
  31208. postMessageToQueue (message);
  31209. }
  31210. // not for public use..
  31211. void MessageManager::deliverMessage (Message* const message)
  31212. {
  31213. const ScopedPointer <Message> messageDeleter (message);
  31214. MessageListener* const recipient = message->messageRecipient;
  31215. JUCE_TRY
  31216. {
  31217. if (messageListeners.contains (recipient))
  31218. {
  31219. recipient->handleMessage (*message);
  31220. }
  31221. else if (recipient == 0)
  31222. {
  31223. if (message->intParameter1 == quitMessageId)
  31224. {
  31225. quitMessageReceived = true;
  31226. }
  31227. else
  31228. {
  31229. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31230. if (cm != 0)
  31231. cm->messageCallback();
  31232. }
  31233. }
  31234. }
  31235. JUCE_CATCH_EXCEPTION
  31236. }
  31237. #if ! (JUCE_MAC || JUCE_IOS)
  31238. void MessageManager::runDispatchLoop()
  31239. {
  31240. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31241. runDispatchLoopUntil (-1);
  31242. }
  31243. void MessageManager::stopDispatchLoop()
  31244. {
  31245. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31246. m->messageRecipient = 0;
  31247. postMessageToQueue (m);
  31248. quitMessagePosted = true;
  31249. }
  31250. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31251. {
  31252. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31253. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31254. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31255. && ! quitMessageReceived)
  31256. {
  31257. JUCE_TRY
  31258. {
  31259. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31260. {
  31261. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31262. if (msToWait > 0)
  31263. Thread::sleep (jmin (5, msToWait));
  31264. }
  31265. }
  31266. JUCE_CATCH_EXCEPTION
  31267. }
  31268. return ! quitMessageReceived;
  31269. }
  31270. #endif
  31271. void MessageManager::deliverBroadcastMessage (const String& value)
  31272. {
  31273. if (broadcastListeners != 0)
  31274. broadcastListeners->sendActionMessage (value);
  31275. }
  31276. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31277. {
  31278. if (broadcastListeners == 0)
  31279. broadcastListeners = new ActionListenerList();
  31280. broadcastListeners->addActionListener (listener);
  31281. }
  31282. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31283. {
  31284. if (broadcastListeners != 0)
  31285. broadcastListeners->removeActionListener (listener);
  31286. }
  31287. bool MessageManager::isThisTheMessageThread() const throw()
  31288. {
  31289. return Thread::getCurrentThreadId() == messageThreadId;
  31290. }
  31291. void MessageManager::setCurrentThreadAsMessageThread()
  31292. {
  31293. if (messageThreadId != Thread::getCurrentThreadId())
  31294. {
  31295. messageThreadId = Thread::getCurrentThreadId();
  31296. // This is needed on windows to make sure the message window is created by this thread
  31297. doPlatformSpecificShutdown();
  31298. doPlatformSpecificInitialisation();
  31299. }
  31300. }
  31301. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31302. {
  31303. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31304. return thisThread == messageThreadId || thisThread == threadWithLock;
  31305. }
  31306. /* The only safe way to lock the message thread while another thread does
  31307. some work is by posting a special message, whose purpose is to tie up the event
  31308. loop until the other thread has finished its business.
  31309. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31310. get locked before making an event callback, because if the same OS lock gets indirectly
  31311. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31312. in Cocoa).
  31313. */
  31314. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31315. {
  31316. public:
  31317. SharedEvents() {}
  31318. ~SharedEvents() {}
  31319. /* This class just holds a couple of events to communicate between the BlockingMessage
  31320. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31321. this shared data must be kept in a separate, ref-counted container. */
  31322. WaitableEvent lockedEvent, releaseEvent;
  31323. private:
  31324. SharedEvents (const SharedEvents&);
  31325. SharedEvents& operator= (const SharedEvents&);
  31326. };
  31327. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31328. {
  31329. public:
  31330. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31331. ~BlockingMessage() throw() {}
  31332. void messageCallback()
  31333. {
  31334. events->lockedEvent.signal();
  31335. events->releaseEvent.wait();
  31336. }
  31337. juce_UseDebuggingNewOperator
  31338. private:
  31339. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31340. BlockingMessage (const BlockingMessage&);
  31341. BlockingMessage& operator= (const BlockingMessage&);
  31342. };
  31343. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31344. : sharedEvents (0),
  31345. locked (false)
  31346. {
  31347. init (threadToCheck, 0);
  31348. }
  31349. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31350. : sharedEvents (0),
  31351. locked (false)
  31352. {
  31353. init (0, jobToCheckForExitSignal);
  31354. }
  31355. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31356. {
  31357. if (MessageManager::instance != 0)
  31358. {
  31359. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31360. {
  31361. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31362. }
  31363. else
  31364. {
  31365. if (threadToCheck == 0 && job == 0)
  31366. {
  31367. MessageManager::instance->lockingLock.enter();
  31368. }
  31369. else
  31370. {
  31371. while (! MessageManager::instance->lockingLock.tryEnter())
  31372. {
  31373. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31374. || (job != 0 && job->shouldExit()))
  31375. return;
  31376. Thread::sleep (1);
  31377. }
  31378. }
  31379. sharedEvents = new SharedEvents();
  31380. sharedEvents->incReferenceCount();
  31381. (new BlockingMessage (sharedEvents))->post();
  31382. while (! sharedEvents->lockedEvent.wait (50))
  31383. {
  31384. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31385. || (job != 0 && job->shouldExit()))
  31386. {
  31387. sharedEvents->releaseEvent.signal();
  31388. sharedEvents->decReferenceCount();
  31389. sharedEvents = 0;
  31390. MessageManager::instance->lockingLock.exit();
  31391. return;
  31392. }
  31393. }
  31394. jassert (MessageManager::instance->threadWithLock == 0);
  31395. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31396. locked = true;
  31397. }
  31398. }
  31399. }
  31400. MessageManagerLock::~MessageManagerLock() throw()
  31401. {
  31402. if (sharedEvents != 0)
  31403. {
  31404. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31405. sharedEvents->releaseEvent.signal();
  31406. sharedEvents->decReferenceCount();
  31407. if (MessageManager::instance != 0)
  31408. {
  31409. MessageManager::instance->threadWithLock = 0;
  31410. MessageManager::instance->lockingLock.exit();
  31411. }
  31412. }
  31413. }
  31414. END_JUCE_NAMESPACE
  31415. /*** End of inlined file: juce_MessageManager.cpp ***/
  31416. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31417. BEGIN_JUCE_NAMESPACE
  31418. class MultiTimer::MultiTimerCallback : public Timer
  31419. {
  31420. public:
  31421. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31422. : timerId (timerId_),
  31423. owner (owner_)
  31424. {
  31425. }
  31426. ~MultiTimerCallback()
  31427. {
  31428. }
  31429. void timerCallback()
  31430. {
  31431. owner.timerCallback (timerId);
  31432. }
  31433. const int timerId;
  31434. private:
  31435. MultiTimer& owner;
  31436. };
  31437. MultiTimer::MultiTimer() throw()
  31438. {
  31439. }
  31440. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31441. {
  31442. }
  31443. MultiTimer::~MultiTimer()
  31444. {
  31445. const ScopedLock sl (timerListLock);
  31446. timers.clear();
  31447. }
  31448. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31449. {
  31450. const ScopedLock sl (timerListLock);
  31451. for (int i = timers.size(); --i >= 0;)
  31452. {
  31453. MultiTimerCallback* const t = timers.getUnchecked(i);
  31454. if (t->timerId == timerId)
  31455. {
  31456. t->startTimer (intervalInMilliseconds);
  31457. return;
  31458. }
  31459. }
  31460. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31461. timers.add (newTimer);
  31462. newTimer->startTimer (intervalInMilliseconds);
  31463. }
  31464. void MultiTimer::stopTimer (const int timerId) throw()
  31465. {
  31466. const ScopedLock sl (timerListLock);
  31467. for (int i = timers.size(); --i >= 0;)
  31468. {
  31469. MultiTimerCallback* const t = timers.getUnchecked(i);
  31470. if (t->timerId == timerId)
  31471. t->stopTimer();
  31472. }
  31473. }
  31474. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31475. {
  31476. const ScopedLock sl (timerListLock);
  31477. for (int i = timers.size(); --i >= 0;)
  31478. {
  31479. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31480. if (t->timerId == timerId)
  31481. return t->isTimerRunning();
  31482. }
  31483. return false;
  31484. }
  31485. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31486. {
  31487. const ScopedLock sl (timerListLock);
  31488. for (int i = timers.size(); --i >= 0;)
  31489. {
  31490. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31491. if (t->timerId == timerId)
  31492. return t->getTimerInterval();
  31493. }
  31494. return 0;
  31495. }
  31496. END_JUCE_NAMESPACE
  31497. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31498. /*** Start of inlined file: juce_Timer.cpp ***/
  31499. BEGIN_JUCE_NAMESPACE
  31500. class InternalTimerThread : private Thread,
  31501. private MessageListener,
  31502. private DeletedAtShutdown,
  31503. private AsyncUpdater
  31504. {
  31505. public:
  31506. InternalTimerThread()
  31507. : Thread ("Juce Timer"),
  31508. firstTimer (0),
  31509. callbackNeeded (0)
  31510. {
  31511. triggerAsyncUpdate();
  31512. }
  31513. ~InternalTimerThread() throw()
  31514. {
  31515. stopThread (4000);
  31516. jassert (instance == this || instance == 0);
  31517. if (instance == this)
  31518. instance = 0;
  31519. }
  31520. void run()
  31521. {
  31522. uint32 lastTime = Time::getMillisecondCounter();
  31523. while (! threadShouldExit())
  31524. {
  31525. const uint32 now = Time::getMillisecondCounter();
  31526. if (now <= lastTime)
  31527. {
  31528. wait (2);
  31529. continue;
  31530. }
  31531. const int elapsed = now - lastTime;
  31532. lastTime = now;
  31533. int timeUntilFirstTimer = 1000;
  31534. {
  31535. const ScopedLock sl (lock);
  31536. decrementAllCounters (elapsed);
  31537. if (firstTimer != 0)
  31538. timeUntilFirstTimer = firstTimer->countdownMs;
  31539. }
  31540. if (timeUntilFirstTimer <= 0)
  31541. {
  31542. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31543. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31544. but if it fails it means the message-thread changed the value from under us so at least
  31545. some processing is happenening and we can just loop around and try again
  31546. */
  31547. if (callbackNeeded.compareAndSetBool (1, 0))
  31548. {
  31549. postMessage (new Message());
  31550. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31551. when the app has a modal loop), so this is how long to wait before assuming the
  31552. message has been lost and trying again.
  31553. */
  31554. const uint32 messageDeliveryTimeout = now + 2000;
  31555. while (callbackNeeded.get() != 0)
  31556. {
  31557. wait (4);
  31558. if (threadShouldExit())
  31559. return;
  31560. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31561. break;
  31562. }
  31563. }
  31564. }
  31565. else
  31566. {
  31567. // don't wait for too long because running this loop also helps keep the
  31568. // Time::getApproximateMillisecondTimer value stay up-to-date
  31569. wait (jlimit (1, 50, timeUntilFirstTimer));
  31570. }
  31571. }
  31572. }
  31573. void callTimers()
  31574. {
  31575. const ScopedLock sl (lock);
  31576. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31577. {
  31578. Timer* const t = firstTimer;
  31579. t->countdownMs = t->periodMs;
  31580. removeTimer (t);
  31581. addTimer (t);
  31582. const ScopedUnlock ul (lock);
  31583. JUCE_TRY
  31584. {
  31585. t->timerCallback();
  31586. }
  31587. JUCE_CATCH_EXCEPTION
  31588. }
  31589. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31590. before the boolean is set. This set should never fail since if it was false in the first place,
  31591. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31592. get a message then the value is true and the other thread can only set it to true again and
  31593. we will get another callback to set it to false.
  31594. */
  31595. callbackNeeded.set (0);
  31596. }
  31597. void handleMessage (const Message&)
  31598. {
  31599. callTimers();
  31600. }
  31601. void callTimersSynchronously()
  31602. {
  31603. if (! isThreadRunning())
  31604. {
  31605. // (This is relied on by some plugins in cases where the MM has
  31606. // had to restart and the async callback never started)
  31607. cancelPendingUpdate();
  31608. triggerAsyncUpdate();
  31609. }
  31610. callTimers();
  31611. }
  31612. static void callAnyTimersSynchronously()
  31613. {
  31614. if (InternalTimerThread::instance != 0)
  31615. InternalTimerThread::instance->callTimersSynchronously();
  31616. }
  31617. static inline void add (Timer* const tim) throw()
  31618. {
  31619. if (instance == 0)
  31620. instance = new InternalTimerThread();
  31621. const ScopedLock sl (instance->lock);
  31622. instance->addTimer (tim);
  31623. }
  31624. static inline void remove (Timer* const tim) throw()
  31625. {
  31626. if (instance != 0)
  31627. {
  31628. const ScopedLock sl (instance->lock);
  31629. instance->removeTimer (tim);
  31630. }
  31631. }
  31632. static inline void resetCounter (Timer* const tim,
  31633. const int newCounter) throw()
  31634. {
  31635. if (instance != 0)
  31636. {
  31637. tim->countdownMs = newCounter;
  31638. tim->periodMs = newCounter;
  31639. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31640. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31641. {
  31642. const ScopedLock sl (instance->lock);
  31643. instance->removeTimer (tim);
  31644. instance->addTimer (tim);
  31645. }
  31646. }
  31647. }
  31648. private:
  31649. friend class Timer;
  31650. static InternalTimerThread* instance;
  31651. static CriticalSection lock;
  31652. Timer* volatile firstTimer;
  31653. Atomic <int> callbackNeeded;
  31654. void addTimer (Timer* const t) throw()
  31655. {
  31656. #if JUCE_DEBUG
  31657. Timer* tt = firstTimer;
  31658. while (tt != 0)
  31659. {
  31660. // trying to add a timer that's already here - shouldn't get to this point,
  31661. // so if you get this assertion, let me know!
  31662. jassert (tt != t);
  31663. tt = tt->next;
  31664. }
  31665. jassert (t->previous == 0 && t->next == 0);
  31666. #endif
  31667. Timer* i = firstTimer;
  31668. if (i == 0 || i->countdownMs > t->countdownMs)
  31669. {
  31670. t->next = firstTimer;
  31671. firstTimer = t;
  31672. }
  31673. else
  31674. {
  31675. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31676. i = i->next;
  31677. jassert (i != 0);
  31678. t->next = i->next;
  31679. t->previous = i;
  31680. i->next = t;
  31681. }
  31682. if (t->next != 0)
  31683. t->next->previous = t;
  31684. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31685. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31686. notify();
  31687. }
  31688. void removeTimer (Timer* const t) throw()
  31689. {
  31690. #if JUCE_DEBUG
  31691. Timer* tt = firstTimer;
  31692. bool found = false;
  31693. while (tt != 0)
  31694. {
  31695. if (tt == t)
  31696. {
  31697. found = true;
  31698. break;
  31699. }
  31700. tt = tt->next;
  31701. }
  31702. // trying to remove a timer that's not here - shouldn't get to this point,
  31703. // so if you get this assertion, let me know!
  31704. jassert (found);
  31705. #endif
  31706. if (t->previous != 0)
  31707. {
  31708. jassert (firstTimer != t);
  31709. t->previous->next = t->next;
  31710. }
  31711. else
  31712. {
  31713. jassert (firstTimer == t);
  31714. firstTimer = t->next;
  31715. }
  31716. if (t->next != 0)
  31717. t->next->previous = t->previous;
  31718. t->next = 0;
  31719. t->previous = 0;
  31720. }
  31721. void decrementAllCounters (const int numMillisecs) const
  31722. {
  31723. Timer* t = firstTimer;
  31724. while (t != 0)
  31725. {
  31726. t->countdownMs -= numMillisecs;
  31727. t = t->next;
  31728. }
  31729. }
  31730. void handleAsyncUpdate()
  31731. {
  31732. startThread (7);
  31733. }
  31734. InternalTimerThread (const InternalTimerThread&);
  31735. InternalTimerThread& operator= (const InternalTimerThread&);
  31736. };
  31737. InternalTimerThread* InternalTimerThread::instance = 0;
  31738. CriticalSection InternalTimerThread::lock;
  31739. void juce_callAnyTimersSynchronously()
  31740. {
  31741. InternalTimerThread::callAnyTimersSynchronously();
  31742. }
  31743. #if JUCE_DEBUG
  31744. static SortedSet <Timer*> activeTimers;
  31745. #endif
  31746. Timer::Timer() throw()
  31747. : countdownMs (0),
  31748. periodMs (0),
  31749. previous (0),
  31750. next (0)
  31751. {
  31752. #if JUCE_DEBUG
  31753. activeTimers.add (this);
  31754. #endif
  31755. }
  31756. Timer::Timer (const Timer&) throw()
  31757. : countdownMs (0),
  31758. periodMs (0),
  31759. previous (0),
  31760. next (0)
  31761. {
  31762. #if JUCE_DEBUG
  31763. activeTimers.add (this);
  31764. #endif
  31765. }
  31766. Timer::~Timer()
  31767. {
  31768. stopTimer();
  31769. #if JUCE_DEBUG
  31770. activeTimers.removeValue (this);
  31771. #endif
  31772. }
  31773. void Timer::startTimer (const int interval) throw()
  31774. {
  31775. const ScopedLock sl (InternalTimerThread::lock);
  31776. #if JUCE_DEBUG
  31777. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31778. jassert (activeTimers.contains (this));
  31779. #endif
  31780. if (periodMs == 0)
  31781. {
  31782. countdownMs = interval;
  31783. periodMs = jmax (1, interval);
  31784. InternalTimerThread::add (this);
  31785. }
  31786. else
  31787. {
  31788. InternalTimerThread::resetCounter (this, interval);
  31789. }
  31790. }
  31791. void Timer::stopTimer() throw()
  31792. {
  31793. const ScopedLock sl (InternalTimerThread::lock);
  31794. #if JUCE_DEBUG
  31795. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31796. jassert (activeTimers.contains (this));
  31797. #endif
  31798. if (periodMs > 0)
  31799. {
  31800. InternalTimerThread::remove (this);
  31801. periodMs = 0;
  31802. }
  31803. }
  31804. END_JUCE_NAMESPACE
  31805. /*** End of inlined file: juce_Timer.cpp ***/
  31806. #endif
  31807. #if JUCE_BUILD_GUI
  31808. /*** Start of inlined file: juce_Component.cpp ***/
  31809. BEGIN_JUCE_NAMESPACE
  31810. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31811. enum ComponentMessageNumbers
  31812. {
  31813. customCommandMessage = 0x7fff0001,
  31814. exitModalStateMessage = 0x7fff0002
  31815. };
  31816. static uint32 nextComponentUID = 0;
  31817. Component* Component::currentlyFocusedComponent = 0;
  31818. Component::Component()
  31819. : parentComponent_ (0),
  31820. componentUID (++nextComponentUID),
  31821. numDeepMouseListeners (0),
  31822. lookAndFeel_ (0),
  31823. effect_ (0),
  31824. bufferedImage_ (0),
  31825. mouseListeners_ (0),
  31826. keyListeners_ (0),
  31827. componentFlags_ (0)
  31828. {
  31829. }
  31830. Component::Component (const String& name)
  31831. : componentName_ (name),
  31832. parentComponent_ (0),
  31833. componentUID (++nextComponentUID),
  31834. numDeepMouseListeners (0),
  31835. lookAndFeel_ (0),
  31836. effect_ (0),
  31837. bufferedImage_ (0),
  31838. mouseListeners_ (0),
  31839. keyListeners_ (0),
  31840. componentFlags_ (0)
  31841. {
  31842. }
  31843. Component::~Component()
  31844. {
  31845. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31846. if (parentComponent_ != 0)
  31847. {
  31848. parentComponent_->removeChildComponent (this);
  31849. }
  31850. else if ((currentlyFocusedComponent == this)
  31851. || isParentOf (currentlyFocusedComponent))
  31852. {
  31853. giveAwayFocus();
  31854. }
  31855. if (flags.hasHeavyweightPeerFlag)
  31856. removeFromDesktop();
  31857. for (int i = childComponentList_.size(); --i >= 0;)
  31858. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31859. delete mouseListeners_;
  31860. delete keyListeners_;
  31861. }
  31862. void Component::setName (const String& name)
  31863. {
  31864. // if component methods are being called from threads other than the message
  31865. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31866. checkMessageManagerIsLocked
  31867. if (componentName_ != name)
  31868. {
  31869. componentName_ = name;
  31870. if (flags.hasHeavyweightPeerFlag)
  31871. {
  31872. ComponentPeer* const peer = getPeer();
  31873. jassert (peer != 0);
  31874. if (peer != 0)
  31875. peer->setTitle (name);
  31876. }
  31877. BailOutChecker checker (this);
  31878. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31879. }
  31880. }
  31881. void Component::setVisible (bool shouldBeVisible)
  31882. {
  31883. if (flags.visibleFlag != shouldBeVisible)
  31884. {
  31885. // if component methods are being called from threads other than the message
  31886. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31887. checkMessageManagerIsLocked
  31888. SafePointer<Component> safePointer (this);
  31889. flags.visibleFlag = shouldBeVisible;
  31890. internalRepaint (0, 0, getWidth(), getHeight());
  31891. sendFakeMouseMove();
  31892. if (! shouldBeVisible)
  31893. {
  31894. if (currentlyFocusedComponent == this
  31895. || isParentOf (currentlyFocusedComponent))
  31896. {
  31897. if (parentComponent_ != 0)
  31898. parentComponent_->grabKeyboardFocus();
  31899. else
  31900. giveAwayFocus();
  31901. }
  31902. }
  31903. if (safePointer != 0)
  31904. {
  31905. sendVisibilityChangeMessage();
  31906. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31907. {
  31908. ComponentPeer* const peer = getPeer();
  31909. jassert (peer != 0);
  31910. if (peer != 0)
  31911. {
  31912. peer->setVisible (shouldBeVisible);
  31913. internalHierarchyChanged();
  31914. }
  31915. }
  31916. }
  31917. }
  31918. }
  31919. void Component::visibilityChanged()
  31920. {
  31921. }
  31922. void Component::sendVisibilityChangeMessage()
  31923. {
  31924. BailOutChecker checker (this);
  31925. visibilityChanged();
  31926. if (! checker.shouldBailOut())
  31927. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31928. }
  31929. bool Component::isShowing() const
  31930. {
  31931. if (flags.visibleFlag)
  31932. {
  31933. if (parentComponent_ != 0)
  31934. {
  31935. return parentComponent_->isShowing();
  31936. }
  31937. else
  31938. {
  31939. const ComponentPeer* const peer = getPeer();
  31940. return peer != 0 && ! peer->isMinimised();
  31941. }
  31942. }
  31943. return false;
  31944. }
  31945. class FadeOutProxyComponent : public Component,
  31946. public Timer
  31947. {
  31948. public:
  31949. FadeOutProxyComponent (Component* comp,
  31950. const int fadeLengthMs,
  31951. const int deltaXToMove,
  31952. const int deltaYToMove,
  31953. const float scaleFactorAtEnd)
  31954. : lastTime (0),
  31955. alpha (1.0f),
  31956. scale (1.0f)
  31957. {
  31958. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31959. setBounds (comp->getBounds());
  31960. comp->getParentComponent()->addAndMakeVisible (this);
  31961. toBehind (comp);
  31962. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31963. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31964. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31965. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31966. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31967. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31968. setInterceptsMouseClicks (false, false);
  31969. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31970. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31971. }
  31972. ~FadeOutProxyComponent()
  31973. {
  31974. }
  31975. void paint (Graphics& g)
  31976. {
  31977. g.setOpacity (alpha);
  31978. g.drawImage (image,
  31979. 0, 0, getWidth(), getHeight(),
  31980. 0, 0, image.getWidth(), image.getHeight());
  31981. }
  31982. void timerCallback()
  31983. {
  31984. const uint32 now = Time::getMillisecondCounter();
  31985. if (lastTime == 0)
  31986. lastTime = now;
  31987. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31988. lastTime = now;
  31989. alpha += alphaChangePerMs * msPassed;
  31990. if (alpha > 0)
  31991. {
  31992. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31993. {
  31994. centreX += xChangePerMs * msPassed;
  31995. centreY += yChangePerMs * msPassed;
  31996. scale += scaleChangePerMs * msPassed;
  31997. const int w = roundToInt (image.getWidth() * scale);
  31998. const int h = roundToInt (image.getHeight() * scale);
  31999. setBounds (roundToInt (centreX) - w / 2,
  32000. roundToInt (centreY) - h / 2,
  32001. w, h);
  32002. }
  32003. repaint();
  32004. }
  32005. else
  32006. {
  32007. delete this;
  32008. }
  32009. }
  32010. juce_UseDebuggingNewOperator
  32011. private:
  32012. Image image;
  32013. uint32 lastTime;
  32014. float alpha, alphaChangePerMs;
  32015. float centreX, xChangePerMs;
  32016. float centreY, yChangePerMs;
  32017. float scale, scaleChangePerMs;
  32018. FadeOutProxyComponent (const FadeOutProxyComponent&);
  32019. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  32020. };
  32021. void Component::fadeOutComponent (const int millisecondsToFade,
  32022. const int deltaXToMove,
  32023. const int deltaYToMove,
  32024. const float scaleFactorAtEnd)
  32025. {
  32026. //xxx won't work for comps without parents
  32027. if (isShowing() && millisecondsToFade > 0)
  32028. new FadeOutProxyComponent (this, millisecondsToFade,
  32029. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  32030. setVisible (false);
  32031. }
  32032. bool Component::isValidComponent() const
  32033. {
  32034. return (this != 0) && isValidMessageListener();
  32035. }
  32036. void* Component::getWindowHandle() const
  32037. {
  32038. const ComponentPeer* const peer = getPeer();
  32039. if (peer != 0)
  32040. return peer->getNativeHandle();
  32041. return 0;
  32042. }
  32043. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32044. {
  32045. // if component methods are being called from threads other than the message
  32046. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32047. checkMessageManagerIsLocked
  32048. if (isOpaque())
  32049. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32050. else
  32051. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32052. int currentStyleFlags = 0;
  32053. // don't use getPeer(), so that we only get the peer that's specifically
  32054. // for this comp, and not for one of its parents.
  32055. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32056. if (peer != 0)
  32057. currentStyleFlags = peer->getStyleFlags();
  32058. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32059. {
  32060. SafePointer<Component> safePointer (this);
  32061. #if JUCE_LINUX
  32062. // it's wise to give the component a non-zero size before
  32063. // putting it on the desktop, as X windows get confused by this, and
  32064. // a (1, 1) minimum size is enforced here.
  32065. setSize (jmax (1, getWidth()),
  32066. jmax (1, getHeight()));
  32067. #endif
  32068. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32069. bool wasFullscreen = false;
  32070. bool wasMinimised = false;
  32071. ComponentBoundsConstrainer* currentConstainer = 0;
  32072. Rectangle<int> oldNonFullScreenBounds;
  32073. if (peer != 0)
  32074. {
  32075. wasFullscreen = peer->isFullScreen();
  32076. wasMinimised = peer->isMinimised();
  32077. currentConstainer = peer->getConstrainer();
  32078. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32079. removeFromDesktop();
  32080. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32081. }
  32082. if (parentComponent_ != 0)
  32083. parentComponent_->removeChildComponent (this);
  32084. if (safePointer != 0)
  32085. {
  32086. flags.hasHeavyweightPeerFlag = true;
  32087. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32088. Desktop::getInstance().addDesktopComponent (this);
  32089. bounds_.setPosition (topLeft);
  32090. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32091. peer->setVisible (isVisible());
  32092. if (wasFullscreen)
  32093. {
  32094. peer->setFullScreen (true);
  32095. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32096. }
  32097. if (wasMinimised)
  32098. peer->setMinimised (true);
  32099. if (isAlwaysOnTop())
  32100. peer->setAlwaysOnTop (true);
  32101. peer->setConstrainer (currentConstainer);
  32102. repaint();
  32103. }
  32104. internalHierarchyChanged();
  32105. }
  32106. }
  32107. void Component::removeFromDesktop()
  32108. {
  32109. // if component methods are being called from threads other than the message
  32110. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32111. checkMessageManagerIsLocked
  32112. if (flags.hasHeavyweightPeerFlag)
  32113. {
  32114. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32115. flags.hasHeavyweightPeerFlag = false;
  32116. jassert (peer != 0);
  32117. delete peer;
  32118. Desktop::getInstance().removeDesktopComponent (this);
  32119. }
  32120. }
  32121. bool Component::isOnDesktop() const throw()
  32122. {
  32123. return flags.hasHeavyweightPeerFlag;
  32124. }
  32125. void Component::userTriedToCloseWindow()
  32126. {
  32127. /* This means that the user's trying to get rid of your window with the 'close window' system
  32128. menu option (on windows) or possibly the task manager - you should really handle this
  32129. and delete or hide your component in an appropriate way.
  32130. If you want to ignore the event and don't want to trigger this assertion, just override
  32131. this method and do nothing.
  32132. */
  32133. jassertfalse;
  32134. }
  32135. void Component::minimisationStateChanged (bool)
  32136. {
  32137. }
  32138. void Component::setOpaque (const bool shouldBeOpaque)
  32139. {
  32140. if (shouldBeOpaque != flags.opaqueFlag)
  32141. {
  32142. flags.opaqueFlag = shouldBeOpaque;
  32143. if (flags.hasHeavyweightPeerFlag)
  32144. {
  32145. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32146. if (peer != 0)
  32147. {
  32148. // to make it recreate the heavyweight window
  32149. addToDesktop (peer->getStyleFlags());
  32150. }
  32151. }
  32152. repaint();
  32153. }
  32154. }
  32155. bool Component::isOpaque() const throw()
  32156. {
  32157. return flags.opaqueFlag;
  32158. }
  32159. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32160. {
  32161. if (shouldBeBuffered != flags.bufferToImageFlag)
  32162. {
  32163. bufferedImage_ = Image::null;
  32164. flags.bufferToImageFlag = shouldBeBuffered;
  32165. }
  32166. }
  32167. void Component::toFront (const bool setAsForeground)
  32168. {
  32169. // if component methods are being called from threads other than the message
  32170. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32171. checkMessageManagerIsLocked
  32172. if (flags.hasHeavyweightPeerFlag)
  32173. {
  32174. ComponentPeer* const peer = getPeer();
  32175. if (peer != 0)
  32176. {
  32177. peer->toFront (setAsForeground);
  32178. if (setAsForeground && ! hasKeyboardFocus (true))
  32179. grabKeyboardFocus();
  32180. }
  32181. }
  32182. else if (parentComponent_ != 0)
  32183. {
  32184. Array<Component*>& childList = parentComponent_->childComponentList_;
  32185. if (childList.getLast() != this)
  32186. {
  32187. const int index = childList.indexOf (this);
  32188. if (index >= 0)
  32189. {
  32190. int insertIndex = -1;
  32191. if (! flags.alwaysOnTopFlag)
  32192. {
  32193. insertIndex = childList.size() - 1;
  32194. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32195. --insertIndex;
  32196. }
  32197. if (index != insertIndex)
  32198. {
  32199. childList.move (index, insertIndex);
  32200. sendFakeMouseMove();
  32201. repaintParent();
  32202. }
  32203. }
  32204. }
  32205. if (setAsForeground)
  32206. {
  32207. internalBroughtToFront();
  32208. grabKeyboardFocus();
  32209. }
  32210. }
  32211. }
  32212. void Component::toBehind (Component* const other)
  32213. {
  32214. if (other != 0 && other != this)
  32215. {
  32216. // the two components must belong to the same parent..
  32217. jassert (parentComponent_ == other->parentComponent_);
  32218. if (parentComponent_ != 0)
  32219. {
  32220. Array<Component*>& childList = parentComponent_->childComponentList_;
  32221. const int index = childList.indexOf (this);
  32222. if (index >= 0 && childList [index + 1] != other)
  32223. {
  32224. int otherIndex = childList.indexOf (other);
  32225. if (otherIndex >= 0)
  32226. {
  32227. if (index < otherIndex)
  32228. --otherIndex;
  32229. childList.move (index, otherIndex);
  32230. sendFakeMouseMove();
  32231. repaintParent();
  32232. }
  32233. }
  32234. }
  32235. else if (isOnDesktop())
  32236. {
  32237. jassert (other->isOnDesktop());
  32238. if (other->isOnDesktop())
  32239. {
  32240. ComponentPeer* const us = getPeer();
  32241. ComponentPeer* const them = other->getPeer();
  32242. jassert (us != 0 && them != 0);
  32243. if (us != 0 && them != 0)
  32244. us->toBehind (them);
  32245. }
  32246. }
  32247. }
  32248. }
  32249. void Component::toBack()
  32250. {
  32251. Array<Component*>& childList = parentComponent_->childComponentList_;
  32252. if (isOnDesktop())
  32253. {
  32254. jassertfalse; //xxx need to add this to native window
  32255. }
  32256. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32257. {
  32258. const int index = childList.indexOf (this);
  32259. if (index > 0)
  32260. {
  32261. int insertIndex = 0;
  32262. if (flags.alwaysOnTopFlag)
  32263. {
  32264. while (insertIndex < childList.size()
  32265. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32266. {
  32267. ++insertIndex;
  32268. }
  32269. }
  32270. if (index != insertIndex)
  32271. {
  32272. childList.move (index, insertIndex);
  32273. sendFakeMouseMove();
  32274. repaintParent();
  32275. }
  32276. }
  32277. }
  32278. }
  32279. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32280. {
  32281. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32282. {
  32283. flags.alwaysOnTopFlag = shouldStayOnTop;
  32284. if (isOnDesktop())
  32285. {
  32286. ComponentPeer* const peer = getPeer();
  32287. jassert (peer != 0);
  32288. if (peer != 0)
  32289. {
  32290. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32291. {
  32292. // some kinds of peer can't change their always-on-top status, so
  32293. // for these, we'll need to create a new window
  32294. const int oldFlags = peer->getStyleFlags();
  32295. removeFromDesktop();
  32296. addToDesktop (oldFlags);
  32297. }
  32298. }
  32299. }
  32300. if (shouldStayOnTop)
  32301. toFront (false);
  32302. internalHierarchyChanged();
  32303. }
  32304. }
  32305. bool Component::isAlwaysOnTop() const throw()
  32306. {
  32307. return flags.alwaysOnTopFlag;
  32308. }
  32309. int Component::proportionOfWidth (const float proportion) const throw()
  32310. {
  32311. return roundToInt (proportion * bounds_.getWidth());
  32312. }
  32313. int Component::proportionOfHeight (const float proportion) const throw()
  32314. {
  32315. return roundToInt (proportion * bounds_.getHeight());
  32316. }
  32317. int Component::getParentWidth() const throw()
  32318. {
  32319. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32320. : getParentMonitorArea().getWidth();
  32321. }
  32322. int Component::getParentHeight() const throw()
  32323. {
  32324. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32325. : getParentMonitorArea().getHeight();
  32326. }
  32327. int Component::getScreenX() const
  32328. {
  32329. return getScreenPosition().getX();
  32330. }
  32331. int Component::getScreenY() const
  32332. {
  32333. return getScreenPosition().getY();
  32334. }
  32335. const Point<int> Component::getScreenPosition() const
  32336. {
  32337. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32338. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32339. : getPosition());
  32340. }
  32341. const Rectangle<int> Component::getScreenBounds() const
  32342. {
  32343. return bounds_.withPosition (getScreenPosition());
  32344. }
  32345. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32346. {
  32347. const Component* c = this;
  32348. Point<int> p (relativePosition);
  32349. do
  32350. {
  32351. if (c->flags.hasHeavyweightPeerFlag)
  32352. return c->getPeer()->relativePositionToGlobal (p);
  32353. p += c->getPosition();
  32354. c = c->parentComponent_;
  32355. }
  32356. while (c != 0);
  32357. return p;
  32358. }
  32359. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32360. {
  32361. if (flags.hasHeavyweightPeerFlag)
  32362. {
  32363. return getPeer()->globalPositionToRelative (screenPosition);
  32364. }
  32365. else
  32366. {
  32367. if (parentComponent_ != 0)
  32368. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32369. return screenPosition - getPosition();
  32370. }
  32371. }
  32372. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32373. {
  32374. Point<int> p (positionRelativeToThis);
  32375. if (targetComponent != 0)
  32376. {
  32377. const Component* c = this;
  32378. do
  32379. {
  32380. if (c == targetComponent)
  32381. return p;
  32382. if (c->flags.hasHeavyweightPeerFlag)
  32383. {
  32384. p = c->getPeer()->relativePositionToGlobal (p);
  32385. break;
  32386. }
  32387. p += c->getPosition();
  32388. c = c->parentComponent_;
  32389. }
  32390. while (c != 0);
  32391. p = targetComponent->globalPositionToRelative (p);
  32392. }
  32393. return p;
  32394. }
  32395. void Component::setBounds (const int x, const int y, int w, int h)
  32396. {
  32397. // if component methods are being called from threads other than the message
  32398. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32399. checkMessageManagerIsLocked
  32400. if (w < 0) w = 0;
  32401. if (h < 0) h = 0;
  32402. const bool wasResized = (getWidth() != w || getHeight() != h);
  32403. const bool wasMoved = (getX() != x || getY() != y);
  32404. #if JUCE_DEBUG
  32405. // It's a very bad idea to try to resize a window during its paint() method!
  32406. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32407. #endif
  32408. if (wasMoved || wasResized)
  32409. {
  32410. if (flags.visibleFlag)
  32411. {
  32412. // send a fake mouse move to trigger enter/exit messages if needed..
  32413. sendFakeMouseMove();
  32414. if (! flags.hasHeavyweightPeerFlag)
  32415. repaintParent();
  32416. }
  32417. bounds_.setBounds (x, y, w, h);
  32418. if (wasResized)
  32419. repaint();
  32420. else if (! flags.hasHeavyweightPeerFlag)
  32421. repaintParent();
  32422. if (flags.hasHeavyweightPeerFlag)
  32423. {
  32424. ComponentPeer* const peer = getPeer();
  32425. if (peer != 0)
  32426. {
  32427. if (wasMoved && wasResized)
  32428. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32429. else if (wasMoved)
  32430. peer->setPosition (getX(), getY());
  32431. else if (wasResized)
  32432. peer->setSize (getWidth(), getHeight());
  32433. }
  32434. }
  32435. sendMovedResizedMessages (wasMoved, wasResized);
  32436. }
  32437. }
  32438. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32439. {
  32440. JUCE_TRY
  32441. {
  32442. if (wasMoved)
  32443. moved();
  32444. if (wasResized)
  32445. {
  32446. resized();
  32447. for (int i = childComponentList_.size(); --i >= 0;)
  32448. {
  32449. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32450. i = jmin (i, childComponentList_.size());
  32451. }
  32452. }
  32453. BailOutChecker checker (this);
  32454. if (parentComponent_ != 0)
  32455. parentComponent_->childBoundsChanged (this);
  32456. if (! checker.shouldBailOut())
  32457. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32458. *this, wasMoved, wasResized);
  32459. }
  32460. JUCE_CATCH_EXCEPTION
  32461. }
  32462. void Component::setSize (const int w, const int h)
  32463. {
  32464. setBounds (getX(), getY(), w, h);
  32465. }
  32466. void Component::setTopLeftPosition (const int x, const int y)
  32467. {
  32468. setBounds (x, y, getWidth(), getHeight());
  32469. }
  32470. void Component::setTopRightPosition (const int x, const int y)
  32471. {
  32472. setTopLeftPosition (x - getWidth(), y);
  32473. }
  32474. void Component::setBounds (const Rectangle<int>& r)
  32475. {
  32476. setBounds (r.getX(),
  32477. r.getY(),
  32478. r.getWidth(),
  32479. r.getHeight());
  32480. }
  32481. void Component::setBoundsRelative (const float x, const float y,
  32482. const float w, const float h)
  32483. {
  32484. const int pw = getParentWidth();
  32485. const int ph = getParentHeight();
  32486. setBounds (roundToInt (x * pw),
  32487. roundToInt (y * ph),
  32488. roundToInt (w * pw),
  32489. roundToInt (h * ph));
  32490. }
  32491. void Component::setCentrePosition (const int x, const int y)
  32492. {
  32493. setTopLeftPosition (x - getWidth() / 2,
  32494. y - getHeight() / 2);
  32495. }
  32496. void Component::setCentreRelative (const float x, const float y)
  32497. {
  32498. setCentrePosition (roundToInt (getParentWidth() * x),
  32499. roundToInt (getParentHeight() * y));
  32500. }
  32501. void Component::centreWithSize (const int width, const int height)
  32502. {
  32503. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32504. setBounds (parentArea.getCentreX() - width / 2,
  32505. parentArea.getCentreY() - height / 2,
  32506. width, height);
  32507. }
  32508. void Component::setBoundsInset (const BorderSize& borders)
  32509. {
  32510. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32511. }
  32512. void Component::setBoundsToFit (int x, int y, int width, int height,
  32513. const Justification& justification,
  32514. const bool onlyReduceInSize)
  32515. {
  32516. // it's no good calling this method unless both the component and
  32517. // target rectangle have a finite size.
  32518. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32519. if (getWidth() > 0 && getHeight() > 0
  32520. && width > 0 && height > 0)
  32521. {
  32522. int newW, newH;
  32523. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32524. {
  32525. newW = getWidth();
  32526. newH = getHeight();
  32527. }
  32528. else
  32529. {
  32530. const double imageRatio = getHeight() / (double) getWidth();
  32531. const double targetRatio = height / (double) width;
  32532. if (imageRatio <= targetRatio)
  32533. {
  32534. newW = width;
  32535. newH = jmin (height, roundToInt (newW * imageRatio));
  32536. }
  32537. else
  32538. {
  32539. newH = height;
  32540. newW = jmin (width, roundToInt (newH / imageRatio));
  32541. }
  32542. }
  32543. if (newW > 0 && newH > 0)
  32544. {
  32545. int newX, newY;
  32546. justification.applyToRectangle (newX, newY, newW, newH,
  32547. x, y, width, height);
  32548. setBounds (newX, newY, newW, newH);
  32549. }
  32550. }
  32551. }
  32552. bool Component::hitTest (int x, int y)
  32553. {
  32554. if (! flags.ignoresMouseClicksFlag)
  32555. return true;
  32556. if (flags.allowChildMouseClicksFlag)
  32557. {
  32558. for (int i = getNumChildComponents(); --i >= 0;)
  32559. {
  32560. Component* const c = getChildComponent (i);
  32561. if (c->isVisible()
  32562. && c->bounds_.contains (x, y)
  32563. && c->hitTest (x - c->getX(),
  32564. y - c->getY()))
  32565. {
  32566. return true;
  32567. }
  32568. }
  32569. }
  32570. return false;
  32571. }
  32572. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32573. const bool allowClicksOnChildComponents) throw()
  32574. {
  32575. flags.ignoresMouseClicksFlag = ! allowClicks;
  32576. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32577. }
  32578. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32579. bool& allowsClicksOnChildComponents) const throw()
  32580. {
  32581. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32582. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32583. }
  32584. bool Component::contains (const int x, const int y)
  32585. {
  32586. if (((unsigned int) x) < (unsigned int) getWidth()
  32587. && ((unsigned int) y) < (unsigned int) getHeight()
  32588. && hitTest (x, y))
  32589. {
  32590. if (parentComponent_ != 0)
  32591. {
  32592. return parentComponent_->contains (x + getX(),
  32593. y + getY());
  32594. }
  32595. else if (flags.hasHeavyweightPeerFlag)
  32596. {
  32597. const ComponentPeer* const peer = getPeer();
  32598. if (peer != 0)
  32599. return peer->contains (Point<int> (x, y), true);
  32600. }
  32601. }
  32602. return false;
  32603. }
  32604. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32605. {
  32606. if (! contains (x, y))
  32607. return false;
  32608. Component* p = this;
  32609. while (p->parentComponent_ != 0)
  32610. {
  32611. x += p->getX();
  32612. y += p->getY();
  32613. p = p->parentComponent_;
  32614. }
  32615. const Component* const c = p->getComponentAt (x, y);
  32616. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32617. }
  32618. Component* Component::getComponentAt (const Point<int>& position)
  32619. {
  32620. return getComponentAt (position.getX(), position.getY());
  32621. }
  32622. Component* Component::getComponentAt (const int x, const int y)
  32623. {
  32624. if (flags.visibleFlag
  32625. && ((unsigned int) x) < (unsigned int) getWidth()
  32626. && ((unsigned int) y) < (unsigned int) getHeight()
  32627. && hitTest (x, y))
  32628. {
  32629. for (int i = childComponentList_.size(); --i >= 0;)
  32630. {
  32631. Component* const child = childComponentList_.getUnchecked(i);
  32632. Component* const c = child->getComponentAt (x - child->getX(),
  32633. y - child->getY());
  32634. if (c != 0)
  32635. return c;
  32636. }
  32637. return this;
  32638. }
  32639. return 0;
  32640. }
  32641. void Component::addChildComponent (Component* const child, int zOrder)
  32642. {
  32643. // if component methods are being called from threads other than the message
  32644. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32645. checkMessageManagerIsLocked
  32646. if (child != 0 && child->parentComponent_ != this)
  32647. {
  32648. if (child->parentComponent_ != 0)
  32649. child->parentComponent_->removeChildComponent (child);
  32650. else
  32651. child->removeFromDesktop();
  32652. child->parentComponent_ = this;
  32653. if (child->isVisible())
  32654. child->repaintParent();
  32655. if (! child->isAlwaysOnTop())
  32656. {
  32657. if (zOrder < 0 || zOrder > childComponentList_.size())
  32658. zOrder = childComponentList_.size();
  32659. while (zOrder > 0)
  32660. {
  32661. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32662. break;
  32663. --zOrder;
  32664. }
  32665. }
  32666. childComponentList_.insert (zOrder, child);
  32667. child->internalHierarchyChanged();
  32668. internalChildrenChanged();
  32669. }
  32670. }
  32671. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32672. {
  32673. if (child != 0)
  32674. {
  32675. child->setVisible (true);
  32676. addChildComponent (child, zOrder);
  32677. }
  32678. }
  32679. void Component::removeChildComponent (Component* const child)
  32680. {
  32681. removeChildComponent (childComponentList_.indexOf (child));
  32682. }
  32683. Component* Component::removeChildComponent (const int index)
  32684. {
  32685. // if component methods are being called from threads other than the message
  32686. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32687. checkMessageManagerIsLocked
  32688. Component* const child = childComponentList_ [index];
  32689. if (child != 0)
  32690. {
  32691. sendFakeMouseMove();
  32692. child->repaintParent();
  32693. childComponentList_.remove (index);
  32694. child->parentComponent_ = 0;
  32695. JUCE_TRY
  32696. {
  32697. if ((currentlyFocusedComponent == child)
  32698. || child->isParentOf (currentlyFocusedComponent))
  32699. {
  32700. // get rid first to force the grabKeyboardFocus to change to us.
  32701. giveAwayFocus();
  32702. grabKeyboardFocus();
  32703. }
  32704. }
  32705. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32706. catch (const std::exception& e)
  32707. {
  32708. currentlyFocusedComponent = 0;
  32709. Desktop::getInstance().triggerFocusCallback();
  32710. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32711. }
  32712. catch (...)
  32713. {
  32714. currentlyFocusedComponent = 0;
  32715. Desktop::getInstance().triggerFocusCallback();
  32716. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32717. }
  32718. #endif
  32719. child->internalHierarchyChanged();
  32720. internalChildrenChanged();
  32721. }
  32722. return child;
  32723. }
  32724. void Component::removeAllChildren()
  32725. {
  32726. while (childComponentList_.size() > 0)
  32727. removeChildComponent (childComponentList_.size() - 1);
  32728. }
  32729. void Component::deleteAllChildren()
  32730. {
  32731. while (childComponentList_.size() > 0)
  32732. delete (removeChildComponent (childComponentList_.size() - 1));
  32733. }
  32734. int Component::getNumChildComponents() const throw()
  32735. {
  32736. return childComponentList_.size();
  32737. }
  32738. Component* Component::getChildComponent (const int index) const throw()
  32739. {
  32740. return childComponentList_ [index];
  32741. }
  32742. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32743. {
  32744. return childComponentList_.indexOf (const_cast <Component*> (child));
  32745. }
  32746. Component* Component::getTopLevelComponent() const throw()
  32747. {
  32748. const Component* comp = this;
  32749. while (comp->parentComponent_ != 0)
  32750. comp = comp->parentComponent_;
  32751. return const_cast <Component*> (comp);
  32752. }
  32753. bool Component::isParentOf (const Component* possibleChild) const throw()
  32754. {
  32755. if (! possibleChild->isValidComponent())
  32756. {
  32757. jassert (possibleChild == 0);
  32758. return false;
  32759. }
  32760. while (possibleChild != 0)
  32761. {
  32762. possibleChild = possibleChild->parentComponent_;
  32763. if (possibleChild == this)
  32764. return true;
  32765. }
  32766. return false;
  32767. }
  32768. void Component::parentHierarchyChanged()
  32769. {
  32770. }
  32771. void Component::childrenChanged()
  32772. {
  32773. }
  32774. void Component::internalChildrenChanged()
  32775. {
  32776. if (componentListeners.isEmpty())
  32777. {
  32778. childrenChanged();
  32779. }
  32780. else
  32781. {
  32782. BailOutChecker checker (this);
  32783. childrenChanged();
  32784. if (! checker.shouldBailOut())
  32785. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32786. }
  32787. }
  32788. void Component::internalHierarchyChanged()
  32789. {
  32790. BailOutChecker checker (this);
  32791. parentHierarchyChanged();
  32792. if (checker.shouldBailOut())
  32793. return;
  32794. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32795. if (checker.shouldBailOut())
  32796. return;
  32797. for (int i = childComponentList_.size(); --i >= 0;)
  32798. {
  32799. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32800. if (checker.shouldBailOut())
  32801. {
  32802. // you really shouldn't delete the parent component during a callback telling you
  32803. // that it's changed..
  32804. jassertfalse;
  32805. return;
  32806. }
  32807. i = jmin (i, childComponentList_.size());
  32808. }
  32809. }
  32810. void* Component::runModalLoopCallback (void* userData)
  32811. {
  32812. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32813. }
  32814. int Component::runModalLoop()
  32815. {
  32816. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32817. {
  32818. // use a callback so this can be called from non-gui threads
  32819. return (int) (pointer_sized_int) MessageManager::getInstance()
  32820. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32821. }
  32822. if (! isCurrentlyModal())
  32823. enterModalState (true);
  32824. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32825. }
  32826. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32827. {
  32828. // if component methods are being called from threads other than the message
  32829. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32830. checkMessageManagerIsLocked
  32831. // Check for an attempt to make a component modal when it already is!
  32832. // This can cause nasty problems..
  32833. jassert (! flags.currentlyModalFlag);
  32834. if (! isCurrentlyModal())
  32835. {
  32836. ModalComponentManager::getInstance()->startModal (this, callback);
  32837. flags.currentlyModalFlag = true;
  32838. setVisible (true);
  32839. if (takeKeyboardFocus_)
  32840. grabKeyboardFocus();
  32841. }
  32842. }
  32843. void Component::exitModalState (const int returnValue)
  32844. {
  32845. if (isCurrentlyModal())
  32846. {
  32847. if (MessageManager::getInstance()->isThisTheMessageThread())
  32848. {
  32849. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32850. flags.currentlyModalFlag = false;
  32851. bringModalComponentToFront();
  32852. }
  32853. else
  32854. {
  32855. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32856. }
  32857. }
  32858. }
  32859. bool Component::isCurrentlyModal() const throw()
  32860. {
  32861. return flags.currentlyModalFlag
  32862. && getCurrentlyModalComponent() == this;
  32863. }
  32864. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32865. {
  32866. Component* const mc = getCurrentlyModalComponent();
  32867. return mc != 0
  32868. && mc != this
  32869. && (! mc->isParentOf (this))
  32870. && ! mc->canModalEventBeSentToComponent (this);
  32871. }
  32872. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32873. {
  32874. return ModalComponentManager::getInstance()->getNumModalComponents();
  32875. }
  32876. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32877. {
  32878. return ModalComponentManager::getInstance()->getModalComponent (index);
  32879. }
  32880. void Component::bringModalComponentToFront()
  32881. {
  32882. ComponentPeer* lastOne = 0;
  32883. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32884. {
  32885. Component* const c = getCurrentlyModalComponent (i);
  32886. if (c == 0)
  32887. break;
  32888. ComponentPeer* peer = c->getPeer();
  32889. if (peer != 0 && peer != lastOne)
  32890. {
  32891. if (lastOne == 0)
  32892. {
  32893. peer->toFront (true);
  32894. peer->grabFocus();
  32895. }
  32896. else
  32897. peer->toBehind (lastOne);
  32898. lastOne = peer;
  32899. }
  32900. }
  32901. }
  32902. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32903. {
  32904. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32905. }
  32906. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32907. {
  32908. return flags.bringToFrontOnClickFlag;
  32909. }
  32910. void Component::setMouseCursor (const MouseCursor& cursor)
  32911. {
  32912. if (cursor_ != cursor)
  32913. {
  32914. cursor_ = cursor;
  32915. if (flags.visibleFlag)
  32916. updateMouseCursor();
  32917. }
  32918. }
  32919. const MouseCursor Component::getMouseCursor()
  32920. {
  32921. return cursor_;
  32922. }
  32923. void Component::updateMouseCursor() const
  32924. {
  32925. sendFakeMouseMove();
  32926. }
  32927. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32928. {
  32929. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32930. }
  32931. void Component::repaintParent()
  32932. {
  32933. if (flags.visibleFlag)
  32934. internalRepaint (0, 0, getWidth(), getHeight());
  32935. }
  32936. void Component::repaint()
  32937. {
  32938. repaint (0, 0, getWidth(), getHeight());
  32939. }
  32940. void Component::repaint (const int x, const int y,
  32941. const int w, const int h)
  32942. {
  32943. bufferedImage_ = Image::null;
  32944. if (flags.visibleFlag)
  32945. internalRepaint (x, y, w, h);
  32946. }
  32947. void Component::repaint (const Rectangle<int>& area)
  32948. {
  32949. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32950. }
  32951. void Component::internalRepaint (int x, int y, int w, int h)
  32952. {
  32953. // if component methods are being called from threads other than the message
  32954. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32955. checkMessageManagerIsLocked
  32956. if (x < 0)
  32957. {
  32958. w += x;
  32959. x = 0;
  32960. }
  32961. if (x + w > getWidth())
  32962. w = getWidth() - x;
  32963. if (w > 0)
  32964. {
  32965. if (y < 0)
  32966. {
  32967. h += y;
  32968. y = 0;
  32969. }
  32970. if (y + h > getHeight())
  32971. h = getHeight() - y;
  32972. if (h > 0)
  32973. {
  32974. if (parentComponent_ != 0)
  32975. {
  32976. x += getX();
  32977. y += getY();
  32978. if (parentComponent_->flags.visibleFlag)
  32979. parentComponent_->internalRepaint (x, y, w, h);
  32980. }
  32981. else if (flags.hasHeavyweightPeerFlag)
  32982. {
  32983. ComponentPeer* const peer = getPeer();
  32984. if (peer != 0)
  32985. peer->repaint (Rectangle<int> (x, y, w, h));
  32986. }
  32987. }
  32988. }
  32989. }
  32990. void Component::renderComponent (Graphics& g)
  32991. {
  32992. const Rectangle<int> clipBounds (g.getClipBounds());
  32993. g.saveState();
  32994. clipObscuredRegions (g, clipBounds, 0, 0);
  32995. if (! g.isClipEmpty())
  32996. {
  32997. if (flags.bufferToImageFlag)
  32998. {
  32999. if (bufferedImage_.isNull())
  33000. {
  33001. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33002. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33003. Graphics imG (bufferedImage_);
  33004. paint (imG);
  33005. }
  33006. g.setColour (Colours::black);
  33007. g.drawImageAt (bufferedImage_, 0, 0);
  33008. }
  33009. else
  33010. {
  33011. paint (g);
  33012. }
  33013. }
  33014. g.restoreState();
  33015. for (int i = 0; i < childComponentList_.size(); ++i)
  33016. {
  33017. Component* const child = childComponentList_.getUnchecked (i);
  33018. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33019. {
  33020. g.saveState();
  33021. if (g.reduceClipRegion (child->getX(), child->getY(),
  33022. child->getWidth(), child->getHeight()))
  33023. {
  33024. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33025. {
  33026. const Component* const sibling = childComponentList_.getUnchecked (j);
  33027. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33028. g.excludeClipRegion (sibling->getBounds());
  33029. }
  33030. if (! g.isClipEmpty())
  33031. {
  33032. g.setOrigin (child->getX(), child->getY());
  33033. child->paintEntireComponent (g);
  33034. }
  33035. }
  33036. g.restoreState();
  33037. }
  33038. }
  33039. g.saveState();
  33040. paintOverChildren (g);
  33041. g.restoreState();
  33042. }
  33043. void Component::paintEntireComponent (Graphics& g)
  33044. {
  33045. jassert (! g.isClipEmpty());
  33046. #if JUCE_DEBUG
  33047. flags.isInsidePaintCall = true;
  33048. #endif
  33049. if (effect_ != 0)
  33050. {
  33051. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33052. getWidth(), getHeight(),
  33053. ! flags.opaqueFlag, Image::NativeImage);
  33054. {
  33055. Graphics g2 (effectImage);
  33056. renderComponent (g2);
  33057. }
  33058. effect_->applyEffect (effectImage, g);
  33059. }
  33060. else
  33061. {
  33062. renderComponent (g);
  33063. }
  33064. #if JUCE_DEBUG
  33065. flags.isInsidePaintCall = false;
  33066. #endif
  33067. }
  33068. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33069. const bool clipImageToComponentBounds)
  33070. {
  33071. Rectangle<int> r (areaToGrab);
  33072. if (clipImageToComponentBounds)
  33073. r = r.getIntersection (getLocalBounds());
  33074. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33075. jmax (1, r.getWidth()),
  33076. jmax (1, r.getHeight()),
  33077. true);
  33078. Graphics imageContext (componentImage);
  33079. imageContext.setOrigin (-r.getX(), -r.getY());
  33080. paintEntireComponent (imageContext);
  33081. return componentImage;
  33082. }
  33083. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33084. {
  33085. if (effect_ != effect)
  33086. {
  33087. effect_ = effect;
  33088. repaint();
  33089. }
  33090. }
  33091. LookAndFeel& Component::getLookAndFeel() const throw()
  33092. {
  33093. const Component* c = this;
  33094. do
  33095. {
  33096. if (c->lookAndFeel_ != 0)
  33097. return *(c->lookAndFeel_);
  33098. c = c->parentComponent_;
  33099. }
  33100. while (c != 0);
  33101. return LookAndFeel::getDefaultLookAndFeel();
  33102. }
  33103. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33104. {
  33105. if (lookAndFeel_ != newLookAndFeel)
  33106. {
  33107. lookAndFeel_ = newLookAndFeel;
  33108. sendLookAndFeelChange();
  33109. }
  33110. }
  33111. void Component::lookAndFeelChanged()
  33112. {
  33113. }
  33114. void Component::sendLookAndFeelChange()
  33115. {
  33116. repaint();
  33117. lookAndFeelChanged();
  33118. // (it's not a great idea to do anything that would delete this component
  33119. // during the lookAndFeelChanged() callback)
  33120. jassert (isValidComponent());
  33121. SafePointer<Component> safePointer (this);
  33122. for (int i = childComponentList_.size(); --i >= 0;)
  33123. {
  33124. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33125. if (safePointer == 0)
  33126. return;
  33127. i = jmin (i, childComponentList_.size());
  33128. }
  33129. }
  33130. static const Identifier getColourPropertyId (const int colourId)
  33131. {
  33132. String s;
  33133. s.preallocateStorage (18);
  33134. s << "jcclr_" << String::toHexString (colourId);
  33135. return s;
  33136. }
  33137. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33138. {
  33139. var* v = properties.getItem (getColourPropertyId (colourId));
  33140. if (v != 0)
  33141. return Colour ((int) *v);
  33142. if (inheritFromParent && parentComponent_ != 0)
  33143. return parentComponent_->findColour (colourId, true);
  33144. return getLookAndFeel().findColour (colourId);
  33145. }
  33146. bool Component::isColourSpecified (const int colourId) const
  33147. {
  33148. return properties.contains (getColourPropertyId (colourId));
  33149. }
  33150. void Component::removeColour (const int colourId)
  33151. {
  33152. if (properties.remove (getColourPropertyId (colourId)))
  33153. colourChanged();
  33154. }
  33155. void Component::setColour (const int colourId, const Colour& colour)
  33156. {
  33157. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  33158. colourChanged();
  33159. }
  33160. void Component::copyAllExplicitColoursTo (Component& target) const
  33161. {
  33162. bool changed = false;
  33163. for (int i = properties.size(); --i >= 0;)
  33164. {
  33165. const Identifier name (properties.getName(i));
  33166. if (name.toString().startsWith ("jcclr_"))
  33167. if (target.properties.set (name, properties [name]))
  33168. changed = true;
  33169. }
  33170. if (changed)
  33171. target.colourChanged();
  33172. }
  33173. void Component::colourChanged()
  33174. {
  33175. }
  33176. const Rectangle<int> Component::getLocalBounds() const throw()
  33177. {
  33178. return Rectangle<int> (getWidth(), getHeight());
  33179. }
  33180. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33181. {
  33182. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33183. : Desktop::getInstance().getMainMonitorArea();
  33184. }
  33185. const Rectangle<int> Component::getUnclippedArea() const
  33186. {
  33187. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33188. Component* p = parentComponent_;
  33189. int px = getX();
  33190. int py = getY();
  33191. while (p != 0)
  33192. {
  33193. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33194. return Rectangle<int>();
  33195. px += p->getX();
  33196. py += p->getY();
  33197. p = p->parentComponent_;
  33198. }
  33199. return Rectangle<int> (x, y, w, h);
  33200. }
  33201. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33202. const int deltaX, const int deltaY) const
  33203. {
  33204. for (int i = childComponentList_.size(); --i >= 0;)
  33205. {
  33206. const Component* const c = childComponentList_.getUnchecked(i);
  33207. if (c->isVisible())
  33208. {
  33209. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33210. if (! newClip.isEmpty())
  33211. {
  33212. if (c->isOpaque())
  33213. {
  33214. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33215. }
  33216. else
  33217. {
  33218. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33219. c->getX() + deltaX,
  33220. c->getY() + deltaY);
  33221. }
  33222. }
  33223. }
  33224. }
  33225. }
  33226. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33227. {
  33228. result.clear();
  33229. const Rectangle<int> unclipped (getUnclippedArea());
  33230. if (! unclipped.isEmpty())
  33231. {
  33232. result.add (unclipped);
  33233. if (includeSiblings)
  33234. {
  33235. const Component* const c = getTopLevelComponent();
  33236. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33237. c->getLocalBounds(), this);
  33238. }
  33239. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33240. result.consolidate();
  33241. }
  33242. }
  33243. void Component::subtractObscuredRegions (RectangleList& result,
  33244. const Point<int>& delta,
  33245. const Rectangle<int>& clipRect,
  33246. const Component* const compToAvoid) const
  33247. {
  33248. for (int i = childComponentList_.size(); --i >= 0;)
  33249. {
  33250. const Component* const c = childComponentList_.getUnchecked(i);
  33251. if (c != compToAvoid && c->isVisible())
  33252. {
  33253. if (c->isOpaque())
  33254. {
  33255. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33256. childBounds.translate (delta.getX(), delta.getY());
  33257. result.subtract (childBounds);
  33258. }
  33259. else
  33260. {
  33261. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33262. newClip.translate (-c->getX(), -c->getY());
  33263. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33264. newClip, compToAvoid);
  33265. }
  33266. }
  33267. }
  33268. }
  33269. void Component::mouseEnter (const MouseEvent&)
  33270. {
  33271. // base class does nothing
  33272. }
  33273. void Component::mouseExit (const MouseEvent&)
  33274. {
  33275. // base class does nothing
  33276. }
  33277. void Component::mouseDown (const MouseEvent&)
  33278. {
  33279. // base class does nothing
  33280. }
  33281. void Component::mouseUp (const MouseEvent&)
  33282. {
  33283. // base class does nothing
  33284. }
  33285. void Component::mouseDrag (const MouseEvent&)
  33286. {
  33287. // base class does nothing
  33288. }
  33289. void Component::mouseMove (const MouseEvent&)
  33290. {
  33291. // base class does nothing
  33292. }
  33293. void Component::mouseDoubleClick (const MouseEvent&)
  33294. {
  33295. // base class does nothing
  33296. }
  33297. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33298. {
  33299. // the base class just passes this event up to its parent..
  33300. if (parentComponent_ != 0)
  33301. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33302. wheelIncrementX, wheelIncrementY);
  33303. }
  33304. void Component::resized()
  33305. {
  33306. // base class does nothing
  33307. }
  33308. void Component::moved()
  33309. {
  33310. // base class does nothing
  33311. }
  33312. void Component::childBoundsChanged (Component*)
  33313. {
  33314. // base class does nothing
  33315. }
  33316. void Component::parentSizeChanged()
  33317. {
  33318. // base class does nothing
  33319. }
  33320. void Component::addComponentListener (ComponentListener* const newListener)
  33321. {
  33322. jassert (isValidComponent());
  33323. componentListeners.add (newListener);
  33324. }
  33325. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33326. {
  33327. jassert (isValidComponent());
  33328. componentListeners.remove (listenerToRemove);
  33329. }
  33330. void Component::inputAttemptWhenModal()
  33331. {
  33332. bringModalComponentToFront();
  33333. getLookAndFeel().playAlertSound();
  33334. }
  33335. bool Component::canModalEventBeSentToComponent (const Component*)
  33336. {
  33337. return false;
  33338. }
  33339. void Component::internalModalInputAttempt()
  33340. {
  33341. Component* const current = getCurrentlyModalComponent();
  33342. if (current != 0)
  33343. current->inputAttemptWhenModal();
  33344. }
  33345. void Component::paint (Graphics&)
  33346. {
  33347. // all painting is done in the subclasses
  33348. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33349. }
  33350. void Component::paintOverChildren (Graphics&)
  33351. {
  33352. // all painting is done in the subclasses
  33353. }
  33354. void Component::handleMessage (const Message& message)
  33355. {
  33356. if (message.intParameter1 == exitModalStateMessage)
  33357. {
  33358. exitModalState (message.intParameter2);
  33359. }
  33360. else if (message.intParameter1 == customCommandMessage)
  33361. {
  33362. handleCommandMessage (message.intParameter2);
  33363. }
  33364. }
  33365. void Component::postCommandMessage (const int commandId)
  33366. {
  33367. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33368. }
  33369. void Component::handleCommandMessage (int)
  33370. {
  33371. // used by subclasses
  33372. }
  33373. void Component::addMouseListener (MouseListener* const newListener,
  33374. const bool wantsEventsForAllNestedChildComponents)
  33375. {
  33376. // if component methods are being called from threads other than the message
  33377. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33378. checkMessageManagerIsLocked
  33379. if (mouseListeners_ == 0)
  33380. mouseListeners_ = new Array<MouseListener*>();
  33381. if (! mouseListeners_->contains (newListener))
  33382. {
  33383. if (wantsEventsForAllNestedChildComponents)
  33384. {
  33385. mouseListeners_->insert (0, newListener);
  33386. ++numDeepMouseListeners;
  33387. }
  33388. else
  33389. {
  33390. mouseListeners_->add (newListener);
  33391. }
  33392. }
  33393. }
  33394. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33395. {
  33396. // if component methods are being called from threads other than the message
  33397. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33398. checkMessageManagerIsLocked
  33399. if (mouseListeners_ != 0)
  33400. {
  33401. const int index = mouseListeners_->indexOf (listenerToRemove);
  33402. if (index >= 0)
  33403. {
  33404. if (index < numDeepMouseListeners)
  33405. --numDeepMouseListeners;
  33406. mouseListeners_->remove (index);
  33407. }
  33408. }
  33409. }
  33410. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33411. {
  33412. if (isCurrentlyBlockedByAnotherModalComponent())
  33413. {
  33414. // if something else is modal, always just show a normal mouse cursor
  33415. source.showMouseCursor (MouseCursor::NormalCursor);
  33416. return;
  33417. }
  33418. if (! flags.mouseInsideFlag)
  33419. {
  33420. flags.mouseInsideFlag = true;
  33421. flags.mouseOverFlag = true;
  33422. flags.draggingFlag = false;
  33423. BailOutChecker checker (this);
  33424. if (flags.repaintOnMouseActivityFlag)
  33425. repaint();
  33426. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33427. this, this, time, relativePos,
  33428. time, 0, false);
  33429. mouseEnter (me);
  33430. if (checker.shouldBailOut())
  33431. return;
  33432. Desktop::getInstance().resetTimer();
  33433. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33434. if (checker.shouldBailOut())
  33435. return;
  33436. if (mouseListeners_ != 0)
  33437. {
  33438. for (int i = mouseListeners_->size(); --i >= 0;)
  33439. {
  33440. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33441. if (checker.shouldBailOut())
  33442. return;
  33443. i = jmin (i, mouseListeners_->size());
  33444. }
  33445. }
  33446. Component* p = parentComponent_;
  33447. while (p != 0)
  33448. {
  33449. if (p->numDeepMouseListeners > 0)
  33450. {
  33451. BailOutChecker checker2 (this, p);
  33452. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33453. {
  33454. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33455. if (checker2.shouldBailOut())
  33456. return;
  33457. i = jmin (i, p->numDeepMouseListeners);
  33458. }
  33459. }
  33460. p = p->parentComponent_;
  33461. }
  33462. }
  33463. }
  33464. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33465. {
  33466. BailOutChecker checker (this);
  33467. if (flags.draggingFlag)
  33468. {
  33469. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33470. if (checker.shouldBailOut())
  33471. return;
  33472. }
  33473. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33474. {
  33475. flags.mouseInsideFlag = false;
  33476. flags.mouseOverFlag = false;
  33477. flags.draggingFlag = false;
  33478. if (flags.repaintOnMouseActivityFlag)
  33479. repaint();
  33480. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33481. this, this, time, relativePos,
  33482. time, 0, false);
  33483. mouseExit (me);
  33484. if (checker.shouldBailOut())
  33485. return;
  33486. Desktop::getInstance().resetTimer();
  33487. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33488. if (checker.shouldBailOut())
  33489. return;
  33490. if (mouseListeners_ != 0)
  33491. {
  33492. for (int i = mouseListeners_->size(); --i >= 0;)
  33493. {
  33494. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33495. if (checker.shouldBailOut())
  33496. return;
  33497. i = jmin (i, mouseListeners_->size());
  33498. }
  33499. }
  33500. Component* p = parentComponent_;
  33501. while (p != 0)
  33502. {
  33503. if (p->numDeepMouseListeners > 0)
  33504. {
  33505. BailOutChecker checker2 (this, p);
  33506. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33507. {
  33508. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33509. if (checker2.shouldBailOut())
  33510. return;
  33511. i = jmin (i, p->numDeepMouseListeners);
  33512. }
  33513. }
  33514. p = p->parentComponent_;
  33515. }
  33516. }
  33517. }
  33518. class InternalDragRepeater : public Timer
  33519. {
  33520. public:
  33521. InternalDragRepeater()
  33522. {}
  33523. ~InternalDragRepeater()
  33524. {
  33525. clearSingletonInstance();
  33526. }
  33527. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33528. void timerCallback()
  33529. {
  33530. Desktop& desktop = Desktop::getInstance();
  33531. int numMiceDown = 0;
  33532. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33533. {
  33534. MouseInputSource* const source = desktop.getMouseSource(i);
  33535. if (source->isDragging())
  33536. {
  33537. source->triggerFakeMove();
  33538. ++numMiceDown;
  33539. }
  33540. }
  33541. if (numMiceDown == 0)
  33542. deleteInstance();
  33543. }
  33544. juce_UseDebuggingNewOperator
  33545. private:
  33546. InternalDragRepeater (const InternalDragRepeater&);
  33547. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33548. };
  33549. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33550. void Component::beginDragAutoRepeat (const int interval)
  33551. {
  33552. if (interval > 0)
  33553. {
  33554. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33555. InternalDragRepeater::getInstance()->startTimer (interval);
  33556. }
  33557. else
  33558. {
  33559. InternalDragRepeater::deleteInstance();
  33560. }
  33561. }
  33562. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33563. {
  33564. Desktop& desktop = Desktop::getInstance();
  33565. BailOutChecker checker (this);
  33566. if (isCurrentlyBlockedByAnotherModalComponent())
  33567. {
  33568. internalModalInputAttempt();
  33569. if (checker.shouldBailOut())
  33570. return;
  33571. // If processing the input attempt has exited the modal loop, we'll allow the event
  33572. // to be delivered..
  33573. if (isCurrentlyBlockedByAnotherModalComponent())
  33574. {
  33575. // allow blocked mouse-events to go to global listeners..
  33576. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33577. this, this, time, relativePos, time,
  33578. source.getNumberOfMultipleClicks(), false);
  33579. desktop.resetTimer();
  33580. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33581. return;
  33582. }
  33583. }
  33584. {
  33585. Component* c = this;
  33586. while (c != 0)
  33587. {
  33588. if (c->isBroughtToFrontOnMouseClick())
  33589. {
  33590. c->toFront (true);
  33591. if (checker.shouldBailOut())
  33592. return;
  33593. }
  33594. c = c->parentComponent_;
  33595. }
  33596. }
  33597. if (! flags.dontFocusOnMouseClickFlag)
  33598. {
  33599. grabFocusInternal (focusChangedByMouseClick);
  33600. if (checker.shouldBailOut())
  33601. return;
  33602. }
  33603. flags.draggingFlag = true;
  33604. flags.mouseOverFlag = true;
  33605. if (flags.repaintOnMouseActivityFlag)
  33606. repaint();
  33607. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33608. this, this, time, relativePos, time,
  33609. source.getNumberOfMultipleClicks(), false);
  33610. mouseDown (me);
  33611. if (checker.shouldBailOut())
  33612. return;
  33613. desktop.resetTimer();
  33614. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33615. if (checker.shouldBailOut())
  33616. return;
  33617. if (mouseListeners_ != 0)
  33618. {
  33619. for (int i = mouseListeners_->size(); --i >= 0;)
  33620. {
  33621. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  33622. if (checker.shouldBailOut())
  33623. return;
  33624. i = jmin (i, mouseListeners_->size());
  33625. }
  33626. }
  33627. Component* p = parentComponent_;
  33628. while (p != 0)
  33629. {
  33630. if (p->numDeepMouseListeners > 0)
  33631. {
  33632. BailOutChecker checker2 (this, p);
  33633. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33634. {
  33635. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  33636. if (checker2.shouldBailOut())
  33637. return;
  33638. i = jmin (i, p->numDeepMouseListeners);
  33639. }
  33640. }
  33641. p = p->parentComponent_;
  33642. }
  33643. }
  33644. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33645. {
  33646. if (flags.draggingFlag)
  33647. {
  33648. Desktop& desktop = Desktop::getInstance();
  33649. flags.draggingFlag = false;
  33650. BailOutChecker checker (this);
  33651. if (flags.repaintOnMouseActivityFlag)
  33652. repaint();
  33653. const MouseEvent me (source, relativePos,
  33654. oldModifiers, this, this, time,
  33655. globalPositionToRelative (source.getLastMouseDownPosition()),
  33656. source.getLastMouseDownTime(),
  33657. source.getNumberOfMultipleClicks(),
  33658. source.hasMouseMovedSignificantlySincePressed());
  33659. mouseUp (me);
  33660. if (checker.shouldBailOut())
  33661. return;
  33662. desktop.resetTimer();
  33663. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33664. if (checker.shouldBailOut())
  33665. return;
  33666. if (mouseListeners_ != 0)
  33667. {
  33668. for (int i = mouseListeners_->size(); --i >= 0;)
  33669. {
  33670. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  33671. if (checker.shouldBailOut())
  33672. return;
  33673. i = jmin (i, mouseListeners_->size());
  33674. }
  33675. }
  33676. {
  33677. Component* p = parentComponent_;
  33678. while (p != 0)
  33679. {
  33680. if (p->numDeepMouseListeners > 0)
  33681. {
  33682. BailOutChecker checker2 (this, p);
  33683. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33684. {
  33685. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  33686. if (checker2.shouldBailOut())
  33687. return;
  33688. i = jmin (i, p->numDeepMouseListeners);
  33689. }
  33690. }
  33691. p = p->parentComponent_;
  33692. }
  33693. }
  33694. // check for double-click
  33695. if (me.getNumberOfClicks() >= 2)
  33696. {
  33697. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33698. mouseDoubleClick (me);
  33699. if (checker.shouldBailOut())
  33700. return;
  33701. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33702. if (checker.shouldBailOut())
  33703. return;
  33704. for (int i = numListeners; --i >= 0;)
  33705. {
  33706. if (checker.shouldBailOut())
  33707. return;
  33708. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33709. if (ml != 0)
  33710. ml->mouseDoubleClick (me);
  33711. }
  33712. if (checker.shouldBailOut())
  33713. return;
  33714. Component* p = parentComponent_;
  33715. while (p != 0)
  33716. {
  33717. if (p->numDeepMouseListeners > 0)
  33718. {
  33719. BailOutChecker checker2 (this, p);
  33720. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33721. {
  33722. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33723. if (checker2.shouldBailOut())
  33724. return;
  33725. i = jmin (i, p->numDeepMouseListeners);
  33726. }
  33727. }
  33728. p = p->parentComponent_;
  33729. }
  33730. }
  33731. }
  33732. }
  33733. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33734. {
  33735. if (flags.draggingFlag)
  33736. {
  33737. Desktop& desktop = Desktop::getInstance();
  33738. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33739. BailOutChecker checker (this);
  33740. const MouseEvent me (source, relativePos,
  33741. source.getCurrentModifiers(), this, this, time,
  33742. globalPositionToRelative (source.getLastMouseDownPosition()),
  33743. source.getLastMouseDownTime(),
  33744. source.getNumberOfMultipleClicks(),
  33745. source.hasMouseMovedSignificantlySincePressed());
  33746. mouseDrag (me);
  33747. if (checker.shouldBailOut())
  33748. return;
  33749. desktop.resetTimer();
  33750. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33751. if (checker.shouldBailOut())
  33752. return;
  33753. if (mouseListeners_ != 0)
  33754. {
  33755. for (int i = mouseListeners_->size(); --i >= 0;)
  33756. {
  33757. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33758. if (checker.shouldBailOut())
  33759. return;
  33760. i = jmin (i, mouseListeners_->size());
  33761. }
  33762. }
  33763. Component* p = parentComponent_;
  33764. while (p != 0)
  33765. {
  33766. if (p->numDeepMouseListeners > 0)
  33767. {
  33768. BailOutChecker checker2 (this, p);
  33769. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33770. {
  33771. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33772. if (checker2.shouldBailOut())
  33773. return;
  33774. i = jmin (i, p->numDeepMouseListeners);
  33775. }
  33776. }
  33777. p = p->parentComponent_;
  33778. }
  33779. }
  33780. }
  33781. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33782. {
  33783. Desktop& desktop = Desktop::getInstance();
  33784. BailOutChecker checker (this);
  33785. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33786. this, this, time, relativePos,
  33787. time, 0, false);
  33788. if (isCurrentlyBlockedByAnotherModalComponent())
  33789. {
  33790. // allow blocked mouse-events to go to global listeners..
  33791. desktop.sendMouseMove();
  33792. }
  33793. else
  33794. {
  33795. flags.mouseOverFlag = true;
  33796. mouseMove (me);
  33797. if (checker.shouldBailOut())
  33798. return;
  33799. desktop.resetTimer();
  33800. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33801. if (checker.shouldBailOut())
  33802. return;
  33803. if (mouseListeners_ != 0)
  33804. {
  33805. for (int i = mouseListeners_->size(); --i >= 0;)
  33806. {
  33807. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33808. if (checker.shouldBailOut())
  33809. return;
  33810. i = jmin (i, mouseListeners_->size());
  33811. }
  33812. }
  33813. Component* p = parentComponent_;
  33814. while (p != 0)
  33815. {
  33816. if (p->numDeepMouseListeners > 0)
  33817. {
  33818. BailOutChecker checker2 (this, p);
  33819. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33820. {
  33821. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33822. if (checker2.shouldBailOut())
  33823. return;
  33824. i = jmin (i, p->numDeepMouseListeners);
  33825. }
  33826. }
  33827. p = p->parentComponent_;
  33828. }
  33829. }
  33830. }
  33831. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33832. const Time& time, const float amountX, const float amountY)
  33833. {
  33834. Desktop& desktop = Desktop::getInstance();
  33835. BailOutChecker checker (this);
  33836. const float wheelIncrementX = amountX / 256.0f;
  33837. const float wheelIncrementY = amountY / 256.0f;
  33838. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33839. this, this, time, relativePos, time, 0, false);
  33840. if (isCurrentlyBlockedByAnotherModalComponent())
  33841. {
  33842. // allow blocked mouse-events to go to global listeners..
  33843. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33844. }
  33845. else
  33846. {
  33847. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33848. if (checker.shouldBailOut())
  33849. return;
  33850. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33851. if (checker.shouldBailOut())
  33852. return;
  33853. if (mouseListeners_ != 0)
  33854. {
  33855. for (int i = mouseListeners_->size(); --i >= 0;)
  33856. {
  33857. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33858. if (checker.shouldBailOut())
  33859. return;
  33860. i = jmin (i, mouseListeners_->size());
  33861. }
  33862. }
  33863. Component* p = parentComponent_;
  33864. while (p != 0)
  33865. {
  33866. if (p->numDeepMouseListeners > 0)
  33867. {
  33868. BailOutChecker checker2 (this, p);
  33869. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33870. {
  33871. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33872. if (checker2.shouldBailOut())
  33873. return;
  33874. i = jmin (i, p->numDeepMouseListeners);
  33875. }
  33876. }
  33877. p = p->parentComponent_;
  33878. }
  33879. }
  33880. }
  33881. void Component::sendFakeMouseMove() const
  33882. {
  33883. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33884. }
  33885. void Component::broughtToFront()
  33886. {
  33887. }
  33888. void Component::internalBroughtToFront()
  33889. {
  33890. if (! isValidComponent())
  33891. return;
  33892. if (flags.hasHeavyweightPeerFlag)
  33893. Desktop::getInstance().componentBroughtToFront (this);
  33894. BailOutChecker checker (this);
  33895. broughtToFront();
  33896. if (checker.shouldBailOut())
  33897. return;
  33898. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33899. if (checker.shouldBailOut())
  33900. return;
  33901. // When brought to the front and there's a modal component blocking this one,
  33902. // we need to bring the modal one to the front instead..
  33903. Component* const cm = getCurrentlyModalComponent();
  33904. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33905. bringModalComponentToFront();
  33906. }
  33907. void Component::focusGained (FocusChangeType)
  33908. {
  33909. // base class does nothing
  33910. }
  33911. void Component::internalFocusGain (const FocusChangeType cause)
  33912. {
  33913. SafePointer<Component> safePointer (this);
  33914. focusGained (cause);
  33915. if (safePointer != 0)
  33916. internalChildFocusChange (cause);
  33917. }
  33918. void Component::focusLost (FocusChangeType)
  33919. {
  33920. // base class does nothing
  33921. }
  33922. void Component::internalFocusLoss (const FocusChangeType cause)
  33923. {
  33924. SafePointer<Component> safePointer (this);
  33925. focusLost (focusChangedDirectly);
  33926. if (safePointer != 0)
  33927. internalChildFocusChange (cause);
  33928. }
  33929. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33930. {
  33931. // base class does nothing
  33932. }
  33933. void Component::internalChildFocusChange (FocusChangeType cause)
  33934. {
  33935. const bool childIsNowFocused = hasKeyboardFocus (true);
  33936. if (flags.childCompFocusedFlag != childIsNowFocused)
  33937. {
  33938. flags.childCompFocusedFlag = childIsNowFocused;
  33939. SafePointer<Component> safePointer (this);
  33940. focusOfChildComponentChanged (cause);
  33941. if (safePointer == 0)
  33942. return;
  33943. }
  33944. if (parentComponent_ != 0)
  33945. parentComponent_->internalChildFocusChange (cause);
  33946. }
  33947. bool Component::isEnabled() const throw()
  33948. {
  33949. return (! flags.isDisabledFlag)
  33950. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33951. }
  33952. void Component::setEnabled (const bool shouldBeEnabled)
  33953. {
  33954. if (flags.isDisabledFlag == shouldBeEnabled)
  33955. {
  33956. flags.isDisabledFlag = ! shouldBeEnabled;
  33957. // if any parent components are disabled, setting our flag won't make a difference,
  33958. // so no need to send a change message
  33959. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33960. sendEnablementChangeMessage();
  33961. }
  33962. }
  33963. void Component::sendEnablementChangeMessage()
  33964. {
  33965. SafePointer<Component> safePointer (this);
  33966. enablementChanged();
  33967. if (safePointer == 0)
  33968. return;
  33969. for (int i = getNumChildComponents(); --i >= 0;)
  33970. {
  33971. Component* const c = getChildComponent (i);
  33972. if (c != 0)
  33973. {
  33974. c->sendEnablementChangeMessage();
  33975. if (safePointer == 0)
  33976. return;
  33977. }
  33978. }
  33979. }
  33980. void Component::enablementChanged()
  33981. {
  33982. }
  33983. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33984. {
  33985. flags.wantsFocusFlag = wantsFocus;
  33986. }
  33987. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33988. {
  33989. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33990. }
  33991. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33992. {
  33993. return ! flags.dontFocusOnMouseClickFlag;
  33994. }
  33995. bool Component::getWantsKeyboardFocus() const throw()
  33996. {
  33997. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33998. }
  33999. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34000. {
  34001. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34002. }
  34003. bool Component::isFocusContainer() const throw()
  34004. {
  34005. return flags.isFocusContainerFlag;
  34006. }
  34007. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34008. int Component::getExplicitFocusOrder() const
  34009. {
  34010. return properties [juce_explicitFocusOrderId];
  34011. }
  34012. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34013. {
  34014. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34015. }
  34016. KeyboardFocusTraverser* Component::createFocusTraverser()
  34017. {
  34018. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34019. return new KeyboardFocusTraverser();
  34020. return parentComponent_->createFocusTraverser();
  34021. }
  34022. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34023. {
  34024. // give the focus to this component
  34025. if (currentlyFocusedComponent != this)
  34026. {
  34027. JUCE_TRY
  34028. {
  34029. // get the focus onto our desktop window
  34030. ComponentPeer* const peer = getPeer();
  34031. if (peer != 0)
  34032. {
  34033. SafePointer<Component> safePointer (this);
  34034. peer->grabFocus();
  34035. if (peer->isFocused() && currentlyFocusedComponent != this)
  34036. {
  34037. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34038. currentlyFocusedComponent = this;
  34039. Desktop::getInstance().triggerFocusCallback();
  34040. // call this after setting currentlyFocusedComponent so that the one that's
  34041. // losing it has a chance to see where focus is going
  34042. if (componentLosingFocus != 0)
  34043. componentLosingFocus->internalFocusLoss (cause);
  34044. if (currentlyFocusedComponent == this)
  34045. {
  34046. focusGained (cause);
  34047. if (safePointer != 0)
  34048. internalChildFocusChange (cause);
  34049. }
  34050. }
  34051. }
  34052. }
  34053. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34054. catch (const std::exception& e)
  34055. {
  34056. currentlyFocusedComponent = 0;
  34057. Desktop::getInstance().triggerFocusCallback();
  34058. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34059. }
  34060. catch (...)
  34061. {
  34062. currentlyFocusedComponent = 0;
  34063. Desktop::getInstance().triggerFocusCallback();
  34064. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34065. }
  34066. #endif
  34067. }
  34068. }
  34069. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34070. {
  34071. if (isShowing())
  34072. {
  34073. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34074. {
  34075. takeKeyboardFocus (cause);
  34076. }
  34077. else
  34078. {
  34079. if (isParentOf (currentlyFocusedComponent)
  34080. && currentlyFocusedComponent->isShowing())
  34081. {
  34082. // do nothing if the focused component is actually a child of ours..
  34083. }
  34084. else
  34085. {
  34086. // find the default child component..
  34087. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34088. if (traverser != 0)
  34089. {
  34090. Component* const defaultComp = traverser->getDefaultComponent (this);
  34091. traverser = 0;
  34092. if (defaultComp != 0)
  34093. {
  34094. defaultComp->grabFocusInternal (cause, false);
  34095. return;
  34096. }
  34097. }
  34098. if (canTryParent && parentComponent_ != 0)
  34099. {
  34100. // if no children want it and we're allowed to try our parent comp,
  34101. // then pass up to parent, which will try our siblings.
  34102. parentComponent_->grabFocusInternal (cause, true);
  34103. }
  34104. }
  34105. }
  34106. }
  34107. }
  34108. void Component::grabKeyboardFocus()
  34109. {
  34110. // if component methods are being called from threads other than the message
  34111. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34112. checkMessageManagerIsLocked
  34113. grabFocusInternal (focusChangedDirectly);
  34114. }
  34115. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34116. {
  34117. // if component methods are being called from threads other than the message
  34118. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34119. checkMessageManagerIsLocked
  34120. if (parentComponent_ != 0)
  34121. {
  34122. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34123. if (traverser != 0)
  34124. {
  34125. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34126. : traverser->getPreviousComponent (this);
  34127. traverser = 0;
  34128. if (nextComp != 0)
  34129. {
  34130. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34131. {
  34132. SafePointer<Component> nextCompPointer (nextComp);
  34133. internalModalInputAttempt();
  34134. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34135. return;
  34136. }
  34137. nextComp->grabFocusInternal (focusChangedByTabKey);
  34138. return;
  34139. }
  34140. }
  34141. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34142. }
  34143. }
  34144. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34145. {
  34146. return (currentlyFocusedComponent == this)
  34147. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34148. }
  34149. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34150. {
  34151. return currentlyFocusedComponent;
  34152. }
  34153. void Component::giveAwayFocus()
  34154. {
  34155. // use a copy so we can clear the value before the call
  34156. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34157. currentlyFocusedComponent = 0;
  34158. Desktop::getInstance().triggerFocusCallback();
  34159. if (componentLosingFocus != 0)
  34160. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34161. }
  34162. bool Component::isMouseOver() const throw()
  34163. {
  34164. return flags.mouseOverFlag;
  34165. }
  34166. bool Component::isMouseButtonDown() const throw()
  34167. {
  34168. return flags.draggingFlag;
  34169. }
  34170. bool Component::isMouseOverOrDragging() const throw()
  34171. {
  34172. return flags.mouseOverFlag || flags.draggingFlag;
  34173. }
  34174. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34175. {
  34176. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34177. }
  34178. const Point<int> Component::getMouseXYRelative() const
  34179. {
  34180. return globalPositionToRelative (Desktop::getMousePosition());
  34181. }
  34182. const Rectangle<int> Component::getParentMonitorArea() const
  34183. {
  34184. return Desktop::getInstance()
  34185. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34186. }
  34187. void Component::addKeyListener (KeyListener* const newListener)
  34188. {
  34189. if (keyListeners_ == 0)
  34190. keyListeners_ = new Array <KeyListener*>();
  34191. keyListeners_->addIfNotAlreadyThere (newListener);
  34192. }
  34193. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34194. {
  34195. if (keyListeners_ != 0)
  34196. keyListeners_->removeValue (listenerToRemove);
  34197. }
  34198. bool Component::keyPressed (const KeyPress&)
  34199. {
  34200. return false;
  34201. }
  34202. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34203. {
  34204. return false;
  34205. }
  34206. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34207. {
  34208. if (parentComponent_ != 0)
  34209. parentComponent_->modifierKeysChanged (modifiers);
  34210. }
  34211. void Component::internalModifierKeysChanged()
  34212. {
  34213. sendFakeMouseMove();
  34214. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34215. }
  34216. ComponentPeer* Component::getPeer() const
  34217. {
  34218. if (flags.hasHeavyweightPeerFlag)
  34219. return ComponentPeer::getPeerFor (this);
  34220. else if (parentComponent_ != 0)
  34221. return parentComponent_->getPeer();
  34222. else
  34223. return 0;
  34224. }
  34225. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34226. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34227. {
  34228. jassert (component1 != 0);
  34229. }
  34230. bool Component::BailOutChecker::shouldBailOut() const throw()
  34231. {
  34232. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34233. }
  34234. END_JUCE_NAMESPACE
  34235. /*** End of inlined file: juce_Component.cpp ***/
  34236. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34237. BEGIN_JUCE_NAMESPACE
  34238. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34239. void ComponentListener::componentBroughtToFront (Component&) {}
  34240. void ComponentListener::componentVisibilityChanged (Component&) {}
  34241. void ComponentListener::componentChildrenChanged (Component&) {}
  34242. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34243. void ComponentListener::componentNameChanged (Component&) {}
  34244. void ComponentListener::componentBeingDeleted (Component&) {}
  34245. END_JUCE_NAMESPACE
  34246. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34247. /*** Start of inlined file: juce_Desktop.cpp ***/
  34248. BEGIN_JUCE_NAMESPACE
  34249. Desktop::Desktop()
  34250. : mouseClickCounter (0),
  34251. kioskModeComponent (0)
  34252. {
  34253. createMouseInputSources();
  34254. refreshMonitorSizes();
  34255. }
  34256. Desktop::~Desktop()
  34257. {
  34258. jassert (instance == this);
  34259. instance = 0;
  34260. // doh! If you don't delete all your windows before exiting, you're going to
  34261. // be leaking memory!
  34262. jassert (desktopComponents.size() == 0);
  34263. }
  34264. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34265. {
  34266. if (instance == 0)
  34267. instance = new Desktop();
  34268. return *instance;
  34269. }
  34270. Desktop* Desktop::instance = 0;
  34271. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34272. const bool clipToWorkArea);
  34273. void Desktop::refreshMonitorSizes()
  34274. {
  34275. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34276. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34277. monitorCoordsClipped.clear();
  34278. monitorCoordsUnclipped.clear();
  34279. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34280. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34281. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34282. if (oldClipped != monitorCoordsClipped
  34283. || oldUnclipped != monitorCoordsUnclipped)
  34284. {
  34285. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34286. {
  34287. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34288. if (p != 0)
  34289. p->handleScreenSizeChange();
  34290. }
  34291. }
  34292. }
  34293. int Desktop::getNumDisplayMonitors() const throw()
  34294. {
  34295. return monitorCoordsClipped.size();
  34296. }
  34297. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34298. {
  34299. return clippedToWorkArea ? monitorCoordsClipped [index]
  34300. : monitorCoordsUnclipped [index];
  34301. }
  34302. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34303. {
  34304. RectangleList rl;
  34305. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34306. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34307. return rl;
  34308. }
  34309. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34310. {
  34311. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34312. }
  34313. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34314. {
  34315. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34316. double bestDistance = 1.0e10;
  34317. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34318. {
  34319. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34320. if (rect.contains (position))
  34321. return rect;
  34322. const double distance = rect.getCentre().getDistanceFrom (position);
  34323. if (distance < bestDistance)
  34324. {
  34325. bestDistance = distance;
  34326. best = rect;
  34327. }
  34328. }
  34329. return best;
  34330. }
  34331. int Desktop::getNumComponents() const throw()
  34332. {
  34333. return desktopComponents.size();
  34334. }
  34335. Component* Desktop::getComponent (const int index) const throw()
  34336. {
  34337. return desktopComponents [index];
  34338. }
  34339. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34340. {
  34341. for (int i = desktopComponents.size(); --i >= 0;)
  34342. {
  34343. Component* const c = desktopComponents.getUnchecked(i);
  34344. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34345. if (c->contains (relative.getX(), relative.getY()))
  34346. return c->getComponentAt (relative.getX(), relative.getY());
  34347. }
  34348. return 0;
  34349. }
  34350. void Desktop::addDesktopComponent (Component* const c)
  34351. {
  34352. jassert (c != 0);
  34353. jassert (! desktopComponents.contains (c));
  34354. desktopComponents.addIfNotAlreadyThere (c);
  34355. }
  34356. void Desktop::removeDesktopComponent (Component* const c)
  34357. {
  34358. desktopComponents.removeValue (c);
  34359. }
  34360. void Desktop::componentBroughtToFront (Component* const c)
  34361. {
  34362. const int index = desktopComponents.indexOf (c);
  34363. jassert (index >= 0);
  34364. if (index >= 0)
  34365. {
  34366. int newIndex = -1;
  34367. if (! c->isAlwaysOnTop())
  34368. {
  34369. newIndex = desktopComponents.size();
  34370. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34371. --newIndex;
  34372. --newIndex;
  34373. }
  34374. desktopComponents.move (index, newIndex);
  34375. }
  34376. }
  34377. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34378. {
  34379. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34380. }
  34381. int Desktop::getMouseButtonClickCounter() throw()
  34382. {
  34383. return getInstance().mouseClickCounter;
  34384. }
  34385. void Desktop::incrementMouseClickCounter() throw()
  34386. {
  34387. ++mouseClickCounter;
  34388. }
  34389. int Desktop::getNumDraggingMouseSources() const throw()
  34390. {
  34391. int num = 0;
  34392. for (int i = mouseSources.size(); --i >= 0;)
  34393. if (mouseSources.getUnchecked(i)->isDragging())
  34394. ++num;
  34395. return num;
  34396. }
  34397. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34398. {
  34399. int num = 0;
  34400. for (int i = mouseSources.size(); --i >= 0;)
  34401. {
  34402. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34403. if (mi->isDragging())
  34404. {
  34405. if (index == num)
  34406. return mi;
  34407. ++num;
  34408. }
  34409. }
  34410. return 0;
  34411. }
  34412. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34413. {
  34414. focusListeners.add (listener);
  34415. }
  34416. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34417. {
  34418. focusListeners.remove (listener);
  34419. }
  34420. void Desktop::triggerFocusCallback()
  34421. {
  34422. triggerAsyncUpdate();
  34423. }
  34424. void Desktop::handleAsyncUpdate()
  34425. {
  34426. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34427. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34428. }
  34429. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34430. {
  34431. mouseListeners.add (listener);
  34432. resetTimer();
  34433. }
  34434. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34435. {
  34436. mouseListeners.remove (listener);
  34437. resetTimer();
  34438. }
  34439. void Desktop::timerCallback()
  34440. {
  34441. if (lastFakeMouseMove != getMousePosition())
  34442. sendMouseMove();
  34443. }
  34444. void Desktop::sendMouseMove()
  34445. {
  34446. if (! mouseListeners.isEmpty())
  34447. {
  34448. startTimer (20);
  34449. lastFakeMouseMove = getMousePosition();
  34450. Component* const target = findComponentAt (lastFakeMouseMove);
  34451. if (target != 0)
  34452. {
  34453. Component::BailOutChecker checker (target);
  34454. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34455. const Time now (Time::getCurrentTime());
  34456. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34457. target, target, now, pos, now, 0, false);
  34458. if (me.mods.isAnyMouseButtonDown())
  34459. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34460. else
  34461. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34462. }
  34463. }
  34464. }
  34465. void Desktop::resetTimer()
  34466. {
  34467. if (mouseListeners.size() == 0)
  34468. stopTimer();
  34469. else
  34470. startTimer (100);
  34471. lastFakeMouseMove = getMousePosition();
  34472. }
  34473. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34474. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34475. {
  34476. if (kioskModeComponent != componentToUse)
  34477. {
  34478. // agh! Don't delete a component without first stopping it being the kiosk comp
  34479. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34480. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34481. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34482. if (kioskModeComponent->isValidComponent())
  34483. {
  34484. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34485. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34486. }
  34487. kioskModeComponent = componentToUse;
  34488. if (kioskModeComponent != 0)
  34489. {
  34490. jassert (kioskModeComponent->isValidComponent());
  34491. // Only components that are already on the desktop can be put into kiosk mode!
  34492. jassert (kioskModeComponent->isOnDesktop());
  34493. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34494. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34495. }
  34496. }
  34497. }
  34498. END_JUCE_NAMESPACE
  34499. /*** End of inlined file: juce_Desktop.cpp ***/
  34500. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34501. BEGIN_JUCE_NAMESPACE
  34502. class ModalComponentManager::ModalItem : public ComponentListener
  34503. {
  34504. public:
  34505. ModalItem (Component* const comp, Callback* const callback)
  34506. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34507. {
  34508. if (callback != 0)
  34509. callbacks.add (callback);
  34510. jassert (comp != 0);
  34511. component->addComponentListener (this);
  34512. }
  34513. ~ModalItem()
  34514. {
  34515. if (! isDeleted)
  34516. component->removeComponentListener (this);
  34517. }
  34518. void componentBeingDeleted (Component&)
  34519. {
  34520. isDeleted = true;
  34521. cancel();
  34522. }
  34523. void componentVisibilityChanged (Component&)
  34524. {
  34525. if (! component->isShowing())
  34526. cancel();
  34527. }
  34528. void componentParentHierarchyChanged (Component&)
  34529. {
  34530. if (! component->isShowing())
  34531. cancel();
  34532. }
  34533. void cancel()
  34534. {
  34535. if (isActive)
  34536. {
  34537. isActive = false;
  34538. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34539. }
  34540. }
  34541. Component* component;
  34542. OwnedArray<Callback> callbacks;
  34543. int returnValue;
  34544. bool isActive, isDeleted;
  34545. private:
  34546. ModalItem (const ModalItem&);
  34547. ModalItem& operator= (const ModalItem&);
  34548. };
  34549. ModalComponentManager::ModalComponentManager()
  34550. {
  34551. }
  34552. ModalComponentManager::~ModalComponentManager()
  34553. {
  34554. clearSingletonInstance();
  34555. }
  34556. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34557. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34558. {
  34559. if (component != 0)
  34560. stack.add (new ModalItem (component, callback));
  34561. }
  34562. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34563. {
  34564. if (callback != 0)
  34565. {
  34566. ScopedPointer<Callback> callbackDeleter (callback);
  34567. for (int i = stack.size(); --i >= 0;)
  34568. {
  34569. ModalItem* const item = stack.getUnchecked(i);
  34570. if (item->component == component)
  34571. {
  34572. item->callbacks.add (callback);
  34573. callbackDeleter.release();
  34574. break;
  34575. }
  34576. }
  34577. }
  34578. }
  34579. void ModalComponentManager::endModal (Component* component)
  34580. {
  34581. for (int i = stack.size(); --i >= 0;)
  34582. {
  34583. ModalItem* const item = stack.getUnchecked(i);
  34584. if (item->component == component)
  34585. item->cancel();
  34586. }
  34587. }
  34588. void ModalComponentManager::endModal (Component* component, int returnValue)
  34589. {
  34590. for (int i = stack.size(); --i >= 0;)
  34591. {
  34592. ModalItem* const item = stack.getUnchecked(i);
  34593. if (item->component == component)
  34594. {
  34595. item->returnValue = returnValue;
  34596. item->cancel();
  34597. }
  34598. }
  34599. }
  34600. int ModalComponentManager::getNumModalComponents() const
  34601. {
  34602. int n = 0;
  34603. for (int i = 0; i < stack.size(); ++i)
  34604. if (stack.getUnchecked(i)->isActive)
  34605. ++n;
  34606. return n;
  34607. }
  34608. Component* ModalComponentManager::getModalComponent (const int index) const
  34609. {
  34610. int n = 0;
  34611. for (int i = stack.size(); --i >= 0;)
  34612. {
  34613. const ModalItem* const item = stack.getUnchecked(i);
  34614. if (item->isActive)
  34615. if (n++ == index)
  34616. return item->component;
  34617. }
  34618. return 0;
  34619. }
  34620. bool ModalComponentManager::isModal (Component* const comp) const
  34621. {
  34622. for (int i = stack.size(); --i >= 0;)
  34623. {
  34624. const ModalItem* const item = stack.getUnchecked(i);
  34625. if (item->isActive && item->component == comp)
  34626. return true;
  34627. }
  34628. return false;
  34629. }
  34630. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34631. {
  34632. return comp == getModalComponent (0);
  34633. }
  34634. void ModalComponentManager::handleAsyncUpdate()
  34635. {
  34636. for (int i = stack.size(); --i >= 0;)
  34637. {
  34638. const ModalItem* const item = stack.getUnchecked(i);
  34639. if (! item->isActive)
  34640. {
  34641. for (int j = item->callbacks.size(); --j >= 0;)
  34642. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34643. stack.remove (i);
  34644. }
  34645. }
  34646. }
  34647. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34648. {
  34649. public:
  34650. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34651. ~ReturnValueRetriever() {}
  34652. void modalStateFinished (int returnValue)
  34653. {
  34654. finished = true;
  34655. value = returnValue;
  34656. }
  34657. private:
  34658. int& value;
  34659. bool& finished;
  34660. ReturnValueRetriever (const ReturnValueRetriever&);
  34661. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34662. };
  34663. int ModalComponentManager::runEventLoopForCurrentComponent()
  34664. {
  34665. // This can only be run from the message thread!
  34666. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34667. Component* currentlyModal = getModalComponent (0);
  34668. if (currentlyModal == 0)
  34669. return 0;
  34670. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34671. int returnValue = 0;
  34672. bool finished = false;
  34673. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34674. JUCE_TRY
  34675. {
  34676. while (! finished)
  34677. {
  34678. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34679. break;
  34680. }
  34681. }
  34682. JUCE_CATCH_EXCEPTION
  34683. if (prevFocused != 0)
  34684. prevFocused->grabKeyboardFocus();
  34685. return returnValue;
  34686. }
  34687. END_JUCE_NAMESPACE
  34688. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34689. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34690. BEGIN_JUCE_NAMESPACE
  34691. ArrowButton::ArrowButton (const String& name,
  34692. float arrowDirectionInRadians,
  34693. const Colour& arrowColour)
  34694. : Button (name),
  34695. colour (arrowColour)
  34696. {
  34697. path.lineTo (0.0f, 1.0f);
  34698. path.lineTo (1.0f, 0.5f);
  34699. path.closeSubPath();
  34700. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34701. 0.5f, 0.5f));
  34702. setComponentEffect (&shadow);
  34703. buttonStateChanged();
  34704. }
  34705. ArrowButton::~ArrowButton()
  34706. {
  34707. }
  34708. void ArrowButton::paintButton (Graphics& g,
  34709. bool /*isMouseOverButton*/,
  34710. bool /*isButtonDown*/)
  34711. {
  34712. g.setColour (colour);
  34713. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34714. (float) offset,
  34715. (float) (getWidth() - 3),
  34716. (float) (getHeight() - 3),
  34717. false));
  34718. }
  34719. void ArrowButton::buttonStateChanged()
  34720. {
  34721. offset = (isDown()) ? 1 : 0;
  34722. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34723. 0.3f, -1, 0);
  34724. }
  34725. END_JUCE_NAMESPACE
  34726. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34727. /*** Start of inlined file: juce_Button.cpp ***/
  34728. BEGIN_JUCE_NAMESPACE
  34729. class Button::RepeatTimer : public Timer
  34730. {
  34731. public:
  34732. RepeatTimer (Button& owner_) : owner (owner_) {}
  34733. void timerCallback() { owner.repeatTimerCallback(); }
  34734. juce_UseDebuggingNewOperator
  34735. private:
  34736. Button& owner;
  34737. RepeatTimer (const RepeatTimer&);
  34738. RepeatTimer& operator= (const RepeatTimer&);
  34739. };
  34740. Button::Button (const String& name)
  34741. : Component (name),
  34742. text (name),
  34743. buttonPressTime (0),
  34744. lastTimeCallbackTime (0),
  34745. commandManagerToUse (0),
  34746. autoRepeatDelay (-1),
  34747. autoRepeatSpeed (0),
  34748. autoRepeatMinimumDelay (-1),
  34749. radioGroupId (0),
  34750. commandID (0),
  34751. connectedEdgeFlags (0),
  34752. buttonState (buttonNormal),
  34753. lastToggleState (false),
  34754. clickTogglesState (false),
  34755. needsToRelease (false),
  34756. needsRepainting (false),
  34757. isKeyDown (false),
  34758. triggerOnMouseDown (false),
  34759. generateTooltip (false)
  34760. {
  34761. setWantsKeyboardFocus (true);
  34762. isOn.addListener (this);
  34763. }
  34764. Button::~Button()
  34765. {
  34766. isOn.removeListener (this);
  34767. if (commandManagerToUse != 0)
  34768. commandManagerToUse->removeListener (this);
  34769. repeatTimer = 0;
  34770. clearShortcuts();
  34771. }
  34772. void Button::setButtonText (const String& newText)
  34773. {
  34774. if (text != newText)
  34775. {
  34776. text = newText;
  34777. repaint();
  34778. }
  34779. }
  34780. void Button::setTooltip (const String& newTooltip)
  34781. {
  34782. SettableTooltipClient::setTooltip (newTooltip);
  34783. generateTooltip = false;
  34784. }
  34785. const String Button::getTooltip()
  34786. {
  34787. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34788. {
  34789. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34790. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34791. for (int i = 0; i < keyPresses.size(); ++i)
  34792. {
  34793. const String key (keyPresses.getReference(i).getTextDescription());
  34794. tt << " [";
  34795. if (key.length() == 1)
  34796. tt << TRANS("shortcut") << ": '" << key << "']";
  34797. else
  34798. tt << key << ']';
  34799. }
  34800. return tt;
  34801. }
  34802. return SettableTooltipClient::getTooltip();
  34803. }
  34804. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34805. {
  34806. if (connectedEdgeFlags != connectedEdgeFlags_)
  34807. {
  34808. connectedEdgeFlags = connectedEdgeFlags_;
  34809. repaint();
  34810. }
  34811. }
  34812. void Button::setToggleState (const bool shouldBeOn,
  34813. const bool sendChangeNotification)
  34814. {
  34815. if (shouldBeOn != lastToggleState)
  34816. {
  34817. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34818. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34819. lastToggleState = shouldBeOn;
  34820. repaint();
  34821. if (sendChangeNotification)
  34822. {
  34823. Component::SafePointer<Component> deletionWatcher (this);
  34824. sendClickMessage (ModifierKeys());
  34825. if (deletionWatcher == 0)
  34826. return;
  34827. }
  34828. if (lastToggleState)
  34829. turnOffOtherButtonsInGroup (sendChangeNotification);
  34830. }
  34831. }
  34832. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34833. {
  34834. clickTogglesState = shouldToggle;
  34835. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34836. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34837. // it is that this button represents, and the button will update its state to reflect this
  34838. // in the applicationCommandListChanged() method.
  34839. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34840. }
  34841. bool Button::getClickingTogglesState() const throw()
  34842. {
  34843. return clickTogglesState;
  34844. }
  34845. void Button::valueChanged (Value& value)
  34846. {
  34847. if (value.refersToSameSourceAs (isOn))
  34848. setToggleState (isOn.getValue(), true);
  34849. }
  34850. void Button::setRadioGroupId (const int newGroupId)
  34851. {
  34852. if (radioGroupId != newGroupId)
  34853. {
  34854. radioGroupId = newGroupId;
  34855. if (lastToggleState)
  34856. turnOffOtherButtonsInGroup (true);
  34857. }
  34858. }
  34859. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34860. {
  34861. Component* const p = getParentComponent();
  34862. if (p != 0 && radioGroupId != 0)
  34863. {
  34864. Component::SafePointer<Component> deletionWatcher (this);
  34865. for (int i = p->getNumChildComponents(); --i >= 0;)
  34866. {
  34867. Component* const c = p->getChildComponent (i);
  34868. if (c != this)
  34869. {
  34870. Button* const b = dynamic_cast <Button*> (c);
  34871. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34872. {
  34873. b->setToggleState (false, sendChangeNotification);
  34874. if (deletionWatcher == 0)
  34875. return;
  34876. }
  34877. }
  34878. }
  34879. }
  34880. }
  34881. void Button::enablementChanged()
  34882. {
  34883. updateState (0);
  34884. repaint();
  34885. }
  34886. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34887. {
  34888. ButtonState state = buttonNormal;
  34889. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34890. {
  34891. Point<int> mousePos;
  34892. if (e == 0)
  34893. mousePos = getMouseXYRelative();
  34894. else
  34895. mousePos = e->getEventRelativeTo (this).getPosition();
  34896. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34897. const bool down = isMouseButtonDown();
  34898. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34899. state = buttonDown;
  34900. else if (over)
  34901. state = buttonOver;
  34902. }
  34903. setState (state);
  34904. return state;
  34905. }
  34906. void Button::setState (const ButtonState newState)
  34907. {
  34908. if (buttonState != newState)
  34909. {
  34910. buttonState = newState;
  34911. repaint();
  34912. if (buttonState == buttonDown)
  34913. {
  34914. buttonPressTime = Time::getApproximateMillisecondCounter();
  34915. lastTimeCallbackTime = buttonPressTime;
  34916. }
  34917. sendStateMessage();
  34918. }
  34919. }
  34920. bool Button::isDown() const throw()
  34921. {
  34922. return buttonState == buttonDown;
  34923. }
  34924. bool Button::isOver() const throw()
  34925. {
  34926. return buttonState != buttonNormal;
  34927. }
  34928. void Button::buttonStateChanged()
  34929. {
  34930. }
  34931. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34932. {
  34933. const uint32 now = Time::getApproximateMillisecondCounter();
  34934. return now > buttonPressTime ? now - buttonPressTime : 0;
  34935. }
  34936. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34937. {
  34938. triggerOnMouseDown = isTriggeredOnMouseDown;
  34939. }
  34940. void Button::clicked()
  34941. {
  34942. }
  34943. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34944. {
  34945. clicked();
  34946. }
  34947. static const int clickMessageId = 0x2f3f4f99;
  34948. void Button::triggerClick()
  34949. {
  34950. postCommandMessage (clickMessageId);
  34951. }
  34952. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34953. {
  34954. if (clickTogglesState)
  34955. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34956. sendClickMessage (modifiers);
  34957. }
  34958. void Button::flashButtonState()
  34959. {
  34960. if (isEnabled())
  34961. {
  34962. needsToRelease = true;
  34963. setState (buttonDown);
  34964. getRepeatTimer().startTimer (100);
  34965. }
  34966. }
  34967. void Button::handleCommandMessage (int commandId)
  34968. {
  34969. if (commandId == clickMessageId)
  34970. {
  34971. if (isEnabled())
  34972. {
  34973. flashButtonState();
  34974. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34975. }
  34976. }
  34977. else
  34978. {
  34979. Component::handleCommandMessage (commandId);
  34980. }
  34981. }
  34982. void Button::addButtonListener (Listener* const newListener)
  34983. {
  34984. buttonListeners.add (newListener);
  34985. }
  34986. void Button::removeButtonListener (Listener* const listener)
  34987. {
  34988. buttonListeners.remove (listener);
  34989. }
  34990. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34991. {
  34992. Component::BailOutChecker checker (this);
  34993. if (commandManagerToUse != 0 && commandID != 0)
  34994. {
  34995. ApplicationCommandTarget::InvocationInfo info (commandID);
  34996. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34997. info.originatingComponent = this;
  34998. commandManagerToUse->invoke (info, true);
  34999. }
  35000. clicked (modifiers);
  35001. if (! checker.shouldBailOut())
  35002. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35003. }
  35004. void Button::sendStateMessage()
  35005. {
  35006. Component::BailOutChecker checker (this);
  35007. buttonStateChanged();
  35008. if (! checker.shouldBailOut())
  35009. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35010. }
  35011. void Button::paint (Graphics& g)
  35012. {
  35013. if (needsToRelease && isEnabled())
  35014. {
  35015. needsToRelease = false;
  35016. needsRepainting = true;
  35017. }
  35018. paintButton (g, isOver(), isDown());
  35019. }
  35020. void Button::mouseEnter (const MouseEvent& e)
  35021. {
  35022. updateState (&e);
  35023. }
  35024. void Button::mouseExit (const MouseEvent& e)
  35025. {
  35026. updateState (&e);
  35027. }
  35028. void Button::mouseDown (const MouseEvent& e)
  35029. {
  35030. updateState (&e);
  35031. if (isDown())
  35032. {
  35033. if (autoRepeatDelay >= 0)
  35034. getRepeatTimer().startTimer (autoRepeatDelay);
  35035. if (triggerOnMouseDown)
  35036. internalClickCallback (e.mods);
  35037. }
  35038. }
  35039. void Button::mouseUp (const MouseEvent& e)
  35040. {
  35041. const bool wasDown = isDown();
  35042. updateState (&e);
  35043. if (wasDown && isOver() && ! triggerOnMouseDown)
  35044. internalClickCallback (e.mods);
  35045. }
  35046. void Button::mouseDrag (const MouseEvent& e)
  35047. {
  35048. const ButtonState oldState = buttonState;
  35049. updateState (&e);
  35050. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35051. getRepeatTimer().startTimer (autoRepeatSpeed);
  35052. }
  35053. void Button::focusGained (FocusChangeType)
  35054. {
  35055. updateState (0);
  35056. repaint();
  35057. }
  35058. void Button::focusLost (FocusChangeType)
  35059. {
  35060. updateState (0);
  35061. repaint();
  35062. }
  35063. void Button::setVisible (bool shouldBeVisible)
  35064. {
  35065. if (shouldBeVisible != isVisible())
  35066. {
  35067. Component::setVisible (shouldBeVisible);
  35068. if (! shouldBeVisible)
  35069. needsToRelease = false;
  35070. updateState (0);
  35071. }
  35072. else
  35073. {
  35074. Component::setVisible (shouldBeVisible);
  35075. }
  35076. }
  35077. void Button::parentHierarchyChanged()
  35078. {
  35079. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35080. if (newKeySource != keySource.getComponent())
  35081. {
  35082. if (keySource != 0)
  35083. keySource->removeKeyListener (this);
  35084. keySource = newKeySource;
  35085. if (keySource != 0)
  35086. keySource->addKeyListener (this);
  35087. }
  35088. }
  35089. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35090. const int commandID_,
  35091. const bool generateTooltip_)
  35092. {
  35093. commandID = commandID_;
  35094. generateTooltip = generateTooltip_;
  35095. if (commandManagerToUse != commandManagerToUse_)
  35096. {
  35097. if (commandManagerToUse != 0)
  35098. commandManagerToUse->removeListener (this);
  35099. commandManagerToUse = commandManagerToUse_;
  35100. if (commandManagerToUse != 0)
  35101. commandManagerToUse->addListener (this);
  35102. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35103. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35104. // it is that this button represents, and the button will update its state to reflect this
  35105. // in the applicationCommandListChanged() method.
  35106. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35107. }
  35108. if (commandManagerToUse != 0)
  35109. applicationCommandListChanged();
  35110. else
  35111. setEnabled (true);
  35112. }
  35113. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35114. {
  35115. if (info.commandID == commandID
  35116. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35117. {
  35118. flashButtonState();
  35119. }
  35120. }
  35121. void Button::applicationCommandListChanged()
  35122. {
  35123. if (commandManagerToUse != 0)
  35124. {
  35125. ApplicationCommandInfo info (0);
  35126. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35127. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35128. if (target != 0)
  35129. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35130. }
  35131. }
  35132. void Button::addShortcut (const KeyPress& key)
  35133. {
  35134. if (key.isValid())
  35135. {
  35136. jassert (! isRegisteredForShortcut (key)); // already registered!
  35137. shortcuts.add (key);
  35138. parentHierarchyChanged();
  35139. }
  35140. }
  35141. void Button::clearShortcuts()
  35142. {
  35143. shortcuts.clear();
  35144. parentHierarchyChanged();
  35145. }
  35146. bool Button::isShortcutPressed() const
  35147. {
  35148. if (! isCurrentlyBlockedByAnotherModalComponent())
  35149. {
  35150. for (int i = shortcuts.size(); --i >= 0;)
  35151. if (shortcuts.getReference(i).isCurrentlyDown())
  35152. return true;
  35153. }
  35154. return false;
  35155. }
  35156. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35157. {
  35158. for (int i = shortcuts.size(); --i >= 0;)
  35159. if (key == shortcuts.getReference(i))
  35160. return true;
  35161. return false;
  35162. }
  35163. bool Button::keyStateChanged (const bool, Component*)
  35164. {
  35165. if (! isEnabled())
  35166. return false;
  35167. const bool wasDown = isKeyDown;
  35168. isKeyDown = isShortcutPressed();
  35169. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35170. getRepeatTimer().startTimer (autoRepeatDelay);
  35171. updateState (0);
  35172. if (isEnabled() && wasDown && ! isKeyDown)
  35173. {
  35174. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35175. // (return immediately - this button may now have been deleted)
  35176. return true;
  35177. }
  35178. return wasDown || isKeyDown;
  35179. }
  35180. bool Button::keyPressed (const KeyPress&, Component*)
  35181. {
  35182. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35183. return isShortcutPressed();
  35184. }
  35185. bool Button::keyPressed (const KeyPress& key)
  35186. {
  35187. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35188. {
  35189. triggerClick();
  35190. return true;
  35191. }
  35192. return false;
  35193. }
  35194. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35195. const int repeatMillisecs,
  35196. const int minimumDelayInMillisecs) throw()
  35197. {
  35198. autoRepeatDelay = initialDelayMillisecs;
  35199. autoRepeatSpeed = repeatMillisecs;
  35200. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35201. }
  35202. void Button::repeatTimerCallback()
  35203. {
  35204. if (needsRepainting)
  35205. {
  35206. getRepeatTimer().stopTimer();
  35207. updateState (0);
  35208. needsRepainting = false;
  35209. }
  35210. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35211. {
  35212. int repeatSpeed = autoRepeatSpeed;
  35213. if (autoRepeatMinimumDelay >= 0)
  35214. {
  35215. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35216. timeHeldDown *= timeHeldDown;
  35217. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35218. }
  35219. repeatSpeed = jmax (1, repeatSpeed);
  35220. getRepeatTimer().startTimer (repeatSpeed);
  35221. const uint32 now = Time::getApproximateMillisecondCounter();
  35222. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35223. lastTimeCallbackTime = now;
  35224. Component::SafePointer<Component> deletionWatcher (this);
  35225. for (int i = numTimesToCallback; --i >= 0;)
  35226. {
  35227. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35228. if (deletionWatcher == 0 || ! isDown())
  35229. return;
  35230. }
  35231. }
  35232. else if (! needsToRelease)
  35233. {
  35234. getRepeatTimer().stopTimer();
  35235. }
  35236. }
  35237. Button::RepeatTimer& Button::getRepeatTimer()
  35238. {
  35239. if (repeatTimer == 0)
  35240. repeatTimer = new RepeatTimer (*this);
  35241. return *repeatTimer;
  35242. }
  35243. END_JUCE_NAMESPACE
  35244. /*** End of inlined file: juce_Button.cpp ***/
  35245. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35246. BEGIN_JUCE_NAMESPACE
  35247. DrawableButton::DrawableButton (const String& name,
  35248. const DrawableButton::ButtonStyle buttonStyle)
  35249. : Button (name),
  35250. style (buttonStyle),
  35251. edgeIndent (3)
  35252. {
  35253. if (buttonStyle == ImageOnButtonBackground)
  35254. {
  35255. backgroundOff = Colour (0xffbbbbff);
  35256. backgroundOn = Colour (0xff3333ff);
  35257. }
  35258. else
  35259. {
  35260. backgroundOff = Colours::transparentBlack;
  35261. backgroundOn = Colour (0xaabbbbff);
  35262. }
  35263. }
  35264. DrawableButton::~DrawableButton()
  35265. {
  35266. deleteImages();
  35267. }
  35268. void DrawableButton::deleteImages()
  35269. {
  35270. }
  35271. void DrawableButton::setImages (const Drawable* normal,
  35272. const Drawable* over,
  35273. const Drawable* down,
  35274. const Drawable* disabled,
  35275. const Drawable* normalOn,
  35276. const Drawable* overOn,
  35277. const Drawable* downOn,
  35278. const Drawable* disabledOn)
  35279. {
  35280. deleteImages();
  35281. jassert (normal != 0); // you really need to give it at least a normal image..
  35282. if (normal != 0)
  35283. normalImage = normal->createCopy();
  35284. if (over != 0)
  35285. overImage = over->createCopy();
  35286. if (down != 0)
  35287. downImage = down->createCopy();
  35288. if (disabled != 0)
  35289. disabledImage = disabled->createCopy();
  35290. if (normalOn != 0)
  35291. normalImageOn = normalOn->createCopy();
  35292. if (overOn != 0)
  35293. overImageOn = overOn->createCopy();
  35294. if (downOn != 0)
  35295. downImageOn = downOn->createCopy();
  35296. if (disabledOn != 0)
  35297. disabledImageOn = disabledOn->createCopy();
  35298. repaint();
  35299. }
  35300. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35301. {
  35302. if (style != newStyle)
  35303. {
  35304. style = newStyle;
  35305. repaint();
  35306. }
  35307. }
  35308. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35309. const Colour& toggledOnColour)
  35310. {
  35311. if (backgroundOff != toggledOffColour
  35312. || backgroundOn != toggledOnColour)
  35313. {
  35314. backgroundOff = toggledOffColour;
  35315. backgroundOn = toggledOnColour;
  35316. repaint();
  35317. }
  35318. }
  35319. const Colour& DrawableButton::getBackgroundColour() const throw()
  35320. {
  35321. return getToggleState() ? backgroundOn
  35322. : backgroundOff;
  35323. }
  35324. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35325. {
  35326. edgeIndent = numPixelsIndent;
  35327. repaint();
  35328. }
  35329. void DrawableButton::paintButton (Graphics& g,
  35330. bool isMouseOverButton,
  35331. bool isButtonDown)
  35332. {
  35333. Rectangle<int> imageSpace;
  35334. if (style == ImageOnButtonBackground)
  35335. {
  35336. const int insetX = getWidth() / 4;
  35337. const int insetY = getHeight() / 4;
  35338. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35339. getLookAndFeel().drawButtonBackground (g, *this,
  35340. getBackgroundColour(),
  35341. isMouseOverButton,
  35342. isButtonDown);
  35343. }
  35344. else
  35345. {
  35346. g.fillAll (getBackgroundColour());
  35347. const int textH = (style == ImageAboveTextLabel)
  35348. ? jmin (16, proportionOfHeight (0.25f))
  35349. : 0;
  35350. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35351. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35352. imageSpace.setBounds (indentX, indentY,
  35353. getWidth() - indentX * 2,
  35354. getHeight() - indentY * 2 - textH);
  35355. if (textH > 0)
  35356. {
  35357. g.setFont ((float) textH);
  35358. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  35359. g.drawFittedText (getButtonText(),
  35360. 2, getHeight() - textH - 1,
  35361. getWidth() - 4, textH,
  35362. Justification::centred, 1);
  35363. }
  35364. }
  35365. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35366. g.setOpacity (1.0f);
  35367. const Drawable* imageToDraw = 0;
  35368. if (isEnabled())
  35369. {
  35370. imageToDraw = getCurrentImage();
  35371. }
  35372. else
  35373. {
  35374. imageToDraw = getToggleState() ? disabledImageOn
  35375. : disabledImage;
  35376. if (imageToDraw == 0)
  35377. {
  35378. g.setOpacity (0.4f);
  35379. imageToDraw = getNormalImage();
  35380. }
  35381. }
  35382. if (imageToDraw != 0)
  35383. {
  35384. if (style == ImageRaw)
  35385. {
  35386. imageToDraw->draw (g, 1.0f);
  35387. }
  35388. else
  35389. {
  35390. imageToDraw->drawWithin (g,
  35391. imageSpace.getX(),
  35392. imageSpace.getY(),
  35393. imageSpace.getWidth(),
  35394. imageSpace.getHeight(),
  35395. RectanglePlacement::centred,
  35396. 1.0f);
  35397. }
  35398. }
  35399. }
  35400. const Drawable* DrawableButton::getCurrentImage() const throw()
  35401. {
  35402. if (isDown())
  35403. return getDownImage();
  35404. if (isOver())
  35405. return getOverImage();
  35406. return getNormalImage();
  35407. }
  35408. const Drawable* DrawableButton::getNormalImage() const throw()
  35409. {
  35410. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35411. : normalImage;
  35412. }
  35413. const Drawable* DrawableButton::getOverImage() const throw()
  35414. {
  35415. const Drawable* d = normalImage;
  35416. if (getToggleState())
  35417. {
  35418. if (overImageOn != 0)
  35419. d = overImageOn;
  35420. else if (normalImageOn != 0)
  35421. d = normalImageOn;
  35422. else if (overImage != 0)
  35423. d = overImage;
  35424. }
  35425. else
  35426. {
  35427. if (overImage != 0)
  35428. d = overImage;
  35429. }
  35430. return d;
  35431. }
  35432. const Drawable* DrawableButton::getDownImage() const throw()
  35433. {
  35434. const Drawable* d = normalImage;
  35435. if (getToggleState())
  35436. {
  35437. if (downImageOn != 0)
  35438. d = downImageOn;
  35439. else if (overImageOn != 0)
  35440. d = overImageOn;
  35441. else if (normalImageOn != 0)
  35442. d = normalImageOn;
  35443. else if (downImage != 0)
  35444. d = downImage;
  35445. else
  35446. d = getOverImage();
  35447. }
  35448. else
  35449. {
  35450. if (downImage != 0)
  35451. d = downImage;
  35452. else
  35453. d = getOverImage();
  35454. }
  35455. return d;
  35456. }
  35457. END_JUCE_NAMESPACE
  35458. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35459. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35460. BEGIN_JUCE_NAMESPACE
  35461. HyperlinkButton::HyperlinkButton (const String& linkText,
  35462. const URL& linkURL)
  35463. : Button (linkText),
  35464. url (linkURL),
  35465. font (14.0f, Font::underlined),
  35466. resizeFont (true),
  35467. justification (Justification::centred)
  35468. {
  35469. setMouseCursor (MouseCursor::PointingHandCursor);
  35470. setTooltip (linkURL.toString (false));
  35471. }
  35472. HyperlinkButton::~HyperlinkButton()
  35473. {
  35474. }
  35475. void HyperlinkButton::setFont (const Font& newFont,
  35476. const bool resizeToMatchComponentHeight,
  35477. const Justification& justificationType)
  35478. {
  35479. font = newFont;
  35480. resizeFont = resizeToMatchComponentHeight;
  35481. justification = justificationType;
  35482. repaint();
  35483. }
  35484. void HyperlinkButton::setURL (const URL& newURL) throw()
  35485. {
  35486. url = newURL;
  35487. setTooltip (newURL.toString (false));
  35488. }
  35489. const Font HyperlinkButton::getFontToUse() const
  35490. {
  35491. Font f (font);
  35492. if (resizeFont)
  35493. f.setHeight (getHeight() * 0.7f);
  35494. return f;
  35495. }
  35496. void HyperlinkButton::changeWidthToFitText()
  35497. {
  35498. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35499. }
  35500. void HyperlinkButton::colourChanged()
  35501. {
  35502. repaint();
  35503. }
  35504. void HyperlinkButton::clicked()
  35505. {
  35506. if (url.isWellFormed())
  35507. url.launchInDefaultBrowser();
  35508. }
  35509. void HyperlinkButton::paintButton (Graphics& g,
  35510. bool isMouseOverButton,
  35511. bool isButtonDown)
  35512. {
  35513. const Colour textColour (findColour (textColourId));
  35514. if (isEnabled())
  35515. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35516. : textColour);
  35517. else
  35518. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35519. g.setFont (getFontToUse());
  35520. g.drawText (getButtonText(),
  35521. 2, 0, getWidth() - 2, getHeight(),
  35522. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35523. true);
  35524. }
  35525. END_JUCE_NAMESPACE
  35526. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35527. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35528. BEGIN_JUCE_NAMESPACE
  35529. ImageButton::ImageButton (const String& text_)
  35530. : Button (text_),
  35531. scaleImageToFit (true),
  35532. preserveProportions (true),
  35533. alphaThreshold (0),
  35534. imageX (0),
  35535. imageY (0),
  35536. imageW (0),
  35537. imageH (0),
  35538. normalImage (0),
  35539. overImage (0),
  35540. downImage (0)
  35541. {
  35542. }
  35543. ImageButton::~ImageButton()
  35544. {
  35545. }
  35546. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35547. const bool rescaleImagesWhenButtonSizeChanges,
  35548. const bool preserveImageProportions,
  35549. const Image& normalImage_,
  35550. const float imageOpacityWhenNormal,
  35551. const Colour& overlayColourWhenNormal,
  35552. const Image& overImage_,
  35553. const float imageOpacityWhenOver,
  35554. const Colour& overlayColourWhenOver,
  35555. const Image& downImage_,
  35556. const float imageOpacityWhenDown,
  35557. const Colour& overlayColourWhenDown,
  35558. const float hitTestAlphaThreshold)
  35559. {
  35560. normalImage = normalImage_;
  35561. overImage = overImage_;
  35562. downImage = downImage_;
  35563. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35564. {
  35565. imageW = normalImage.getWidth();
  35566. imageH = normalImage.getHeight();
  35567. setSize (imageW, imageH);
  35568. }
  35569. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35570. preserveProportions = preserveImageProportions;
  35571. normalOpacity = imageOpacityWhenNormal;
  35572. normalOverlay = overlayColourWhenNormal;
  35573. overOpacity = imageOpacityWhenOver;
  35574. overOverlay = overlayColourWhenOver;
  35575. downOpacity = imageOpacityWhenDown;
  35576. downOverlay = overlayColourWhenDown;
  35577. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35578. repaint();
  35579. }
  35580. const Image ImageButton::getCurrentImage() const
  35581. {
  35582. if (isDown() || getToggleState())
  35583. return getDownImage();
  35584. if (isOver())
  35585. return getOverImage();
  35586. return getNormalImage();
  35587. }
  35588. const Image ImageButton::getNormalImage() const
  35589. {
  35590. return normalImage;
  35591. }
  35592. const Image ImageButton::getOverImage() const
  35593. {
  35594. return overImage.isValid() ? overImage
  35595. : normalImage;
  35596. }
  35597. const Image ImageButton::getDownImage() const
  35598. {
  35599. return downImage.isValid() ? downImage
  35600. : getOverImage();
  35601. }
  35602. void ImageButton::paintButton (Graphics& g,
  35603. bool isMouseOverButton,
  35604. bool isButtonDown)
  35605. {
  35606. if (! isEnabled())
  35607. {
  35608. isMouseOverButton = false;
  35609. isButtonDown = false;
  35610. }
  35611. Image im (getCurrentImage());
  35612. if (im.isValid())
  35613. {
  35614. const int iw = im.getWidth();
  35615. const int ih = im.getHeight();
  35616. imageW = getWidth();
  35617. imageH = getHeight();
  35618. imageX = (imageW - iw) >> 1;
  35619. imageY = (imageH - ih) >> 1;
  35620. if (scaleImageToFit)
  35621. {
  35622. if (preserveProportions)
  35623. {
  35624. int newW, newH;
  35625. const float imRatio = ih / (float)iw;
  35626. const float destRatio = imageH / (float)imageW;
  35627. if (imRatio > destRatio)
  35628. {
  35629. newW = roundToInt (imageH / imRatio);
  35630. newH = imageH;
  35631. }
  35632. else
  35633. {
  35634. newW = imageW;
  35635. newH = roundToInt (imageW * imRatio);
  35636. }
  35637. imageX = (imageW - newW) / 2;
  35638. imageY = (imageH - newH) / 2;
  35639. imageW = newW;
  35640. imageH = newH;
  35641. }
  35642. else
  35643. {
  35644. imageX = 0;
  35645. imageY = 0;
  35646. }
  35647. }
  35648. if (! scaleImageToFit)
  35649. {
  35650. imageW = iw;
  35651. imageH = ih;
  35652. }
  35653. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35654. isButtonDown ? downOverlay
  35655. : (isMouseOverButton ? overOverlay
  35656. : normalOverlay),
  35657. isButtonDown ? downOpacity
  35658. : (isMouseOverButton ? overOpacity
  35659. : normalOpacity),
  35660. *this);
  35661. }
  35662. }
  35663. bool ImageButton::hitTest (int x, int y)
  35664. {
  35665. if (alphaThreshold == 0)
  35666. return true;
  35667. Image im (getCurrentImage());
  35668. return im.isNull() || (imageW > 0 && imageH > 0
  35669. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35670. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35671. }
  35672. END_JUCE_NAMESPACE
  35673. /*** End of inlined file: juce_ImageButton.cpp ***/
  35674. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35675. BEGIN_JUCE_NAMESPACE
  35676. ShapeButton::ShapeButton (const String& text_,
  35677. const Colour& normalColour_,
  35678. const Colour& overColour_,
  35679. const Colour& downColour_)
  35680. : Button (text_),
  35681. normalColour (normalColour_),
  35682. overColour (overColour_),
  35683. downColour (downColour_),
  35684. maintainShapeProportions (false),
  35685. outlineWidth (0.0f)
  35686. {
  35687. }
  35688. ShapeButton::~ShapeButton()
  35689. {
  35690. }
  35691. void ShapeButton::setColours (const Colour& newNormalColour,
  35692. const Colour& newOverColour,
  35693. const Colour& newDownColour)
  35694. {
  35695. normalColour = newNormalColour;
  35696. overColour = newOverColour;
  35697. downColour = newDownColour;
  35698. }
  35699. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35700. const float newOutlineWidth)
  35701. {
  35702. outlineColour = newOutlineColour;
  35703. outlineWidth = newOutlineWidth;
  35704. }
  35705. void ShapeButton::setShape (const Path& newShape,
  35706. const bool resizeNowToFitThisShape,
  35707. const bool maintainShapeProportions_,
  35708. const bool hasShadow)
  35709. {
  35710. shape = newShape;
  35711. maintainShapeProportions = maintainShapeProportions_;
  35712. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35713. setComponentEffect ((hasShadow) ? &shadow : 0);
  35714. if (resizeNowToFitThisShape)
  35715. {
  35716. Rectangle<float> bounds (shape.getBounds());
  35717. if (hasShadow)
  35718. bounds.expand (4.0f, 4.0f);
  35719. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35720. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35721. 1 + (int) (bounds.getHeight() + outlineWidth));
  35722. }
  35723. }
  35724. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35725. {
  35726. if (! isEnabled())
  35727. {
  35728. isMouseOverButton = false;
  35729. isButtonDown = false;
  35730. }
  35731. g.setColour ((isButtonDown) ? downColour
  35732. : (isMouseOverButton) ? overColour
  35733. : normalColour);
  35734. int w = getWidth();
  35735. int h = getHeight();
  35736. if (getComponentEffect() != 0)
  35737. {
  35738. w -= 4;
  35739. h -= 4;
  35740. }
  35741. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35742. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35743. w - offset - outlineWidth,
  35744. h - offset - outlineWidth,
  35745. maintainShapeProportions));
  35746. g.fillPath (shape, trans);
  35747. if (outlineWidth > 0.0f)
  35748. {
  35749. g.setColour (outlineColour);
  35750. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35751. }
  35752. }
  35753. END_JUCE_NAMESPACE
  35754. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35755. /*** Start of inlined file: juce_TextButton.cpp ***/
  35756. BEGIN_JUCE_NAMESPACE
  35757. TextButton::TextButton (const String& name,
  35758. const String& toolTip)
  35759. : Button (name)
  35760. {
  35761. setTooltip (toolTip);
  35762. }
  35763. TextButton::~TextButton()
  35764. {
  35765. }
  35766. void TextButton::paintButton (Graphics& g,
  35767. bool isMouseOverButton,
  35768. bool isButtonDown)
  35769. {
  35770. getLookAndFeel().drawButtonBackground (g, *this,
  35771. findColour (getToggleState() ? buttonOnColourId
  35772. : buttonColourId),
  35773. isMouseOverButton,
  35774. isButtonDown);
  35775. getLookAndFeel().drawButtonText (g, *this,
  35776. isMouseOverButton,
  35777. isButtonDown);
  35778. }
  35779. void TextButton::colourChanged()
  35780. {
  35781. repaint();
  35782. }
  35783. const Font TextButton::getFont()
  35784. {
  35785. return Font (jmin (15.0f, getHeight() * 0.6f));
  35786. }
  35787. void TextButton::changeWidthToFitText (const int newHeight)
  35788. {
  35789. if (newHeight >= 0)
  35790. setSize (jmax (1, getWidth()), newHeight);
  35791. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35792. getHeight());
  35793. }
  35794. END_JUCE_NAMESPACE
  35795. /*** End of inlined file: juce_TextButton.cpp ***/
  35796. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35797. BEGIN_JUCE_NAMESPACE
  35798. ToggleButton::ToggleButton (const String& buttonText)
  35799. : Button (buttonText)
  35800. {
  35801. setClickingTogglesState (true);
  35802. }
  35803. ToggleButton::~ToggleButton()
  35804. {
  35805. }
  35806. void ToggleButton::paintButton (Graphics& g,
  35807. bool isMouseOverButton,
  35808. bool isButtonDown)
  35809. {
  35810. getLookAndFeel().drawToggleButton (g, *this,
  35811. isMouseOverButton,
  35812. isButtonDown);
  35813. }
  35814. void ToggleButton::changeWidthToFitText()
  35815. {
  35816. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35817. }
  35818. void ToggleButton::colourChanged()
  35819. {
  35820. repaint();
  35821. }
  35822. END_JUCE_NAMESPACE
  35823. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35824. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35825. BEGIN_JUCE_NAMESPACE
  35826. ToolbarButton::ToolbarButton (const int itemId_,
  35827. const String& buttonText,
  35828. Drawable* const normalImage_,
  35829. Drawable* const toggledOnImage_)
  35830. : ToolbarItemComponent (itemId_, buttonText, true),
  35831. normalImage (normalImage_),
  35832. toggledOnImage (toggledOnImage_)
  35833. {
  35834. jassert (normalImage_ != 0);
  35835. }
  35836. ToolbarButton::~ToolbarButton()
  35837. {
  35838. }
  35839. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35840. bool /*isToolbarVertical*/,
  35841. int& preferredSize,
  35842. int& minSize, int& maxSize)
  35843. {
  35844. preferredSize = minSize = maxSize = toolbarDepth;
  35845. return true;
  35846. }
  35847. void ToolbarButton::paintButtonArea (Graphics& g,
  35848. int width, int height,
  35849. bool /*isMouseOver*/,
  35850. bool /*isMouseDown*/)
  35851. {
  35852. Drawable* d = normalImage;
  35853. if (getToggleState() && toggledOnImage != 0)
  35854. d = toggledOnImage;
  35855. if (! isEnabled())
  35856. {
  35857. Image im (Image::ARGB, width, height, true);
  35858. {
  35859. Graphics g2 (im);
  35860. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35861. }
  35862. im.desaturate();
  35863. g.drawImageAt (im, 0, 0);
  35864. }
  35865. else
  35866. {
  35867. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35868. }
  35869. }
  35870. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35871. {
  35872. }
  35873. END_JUCE_NAMESPACE
  35874. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35875. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35876. BEGIN_JUCE_NAMESPACE
  35877. class CodeDocumentLine
  35878. {
  35879. public:
  35880. CodeDocumentLine (const juce_wchar* const line_,
  35881. const int lineLength_,
  35882. const int numNewLineChars,
  35883. const int lineStartInFile_)
  35884. : line (line_, lineLength_),
  35885. lineStartInFile (lineStartInFile_),
  35886. lineLength (lineLength_),
  35887. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35888. {
  35889. }
  35890. ~CodeDocumentLine()
  35891. {
  35892. }
  35893. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35894. {
  35895. const juce_wchar* const t = text;
  35896. int pos = 0;
  35897. while (t [pos] != 0)
  35898. {
  35899. const int startOfLine = pos;
  35900. int numNewLineChars = 0;
  35901. while (t[pos] != 0)
  35902. {
  35903. if (t[pos] == '\r')
  35904. {
  35905. ++numNewLineChars;
  35906. ++pos;
  35907. if (t[pos] == '\n')
  35908. {
  35909. ++numNewLineChars;
  35910. ++pos;
  35911. }
  35912. break;
  35913. }
  35914. if (t[pos] == '\n')
  35915. {
  35916. ++numNewLineChars;
  35917. ++pos;
  35918. break;
  35919. }
  35920. ++pos;
  35921. }
  35922. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35923. numNewLineChars, startOfLine));
  35924. }
  35925. jassert (pos == text.length());
  35926. }
  35927. bool endsWithLineBreak() const throw()
  35928. {
  35929. return lineLengthWithoutNewLines != lineLength;
  35930. }
  35931. void updateLength() throw()
  35932. {
  35933. lineLengthWithoutNewLines = lineLength = line.length();
  35934. while (lineLengthWithoutNewLines > 0
  35935. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35936. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35937. {
  35938. --lineLengthWithoutNewLines;
  35939. }
  35940. }
  35941. String line;
  35942. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35943. };
  35944. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35945. : document (document_),
  35946. currentLine (document_->lines[0]),
  35947. line (0),
  35948. position (0)
  35949. {
  35950. }
  35951. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35952. : document (other.document),
  35953. currentLine (other.currentLine),
  35954. line (other.line),
  35955. position (other.position)
  35956. {
  35957. }
  35958. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35959. {
  35960. document = other.document;
  35961. currentLine = other.currentLine;
  35962. line = other.line;
  35963. position = other.position;
  35964. return *this;
  35965. }
  35966. CodeDocument::Iterator::~Iterator() throw()
  35967. {
  35968. }
  35969. juce_wchar CodeDocument::Iterator::nextChar()
  35970. {
  35971. if (currentLine == 0)
  35972. return 0;
  35973. jassert (currentLine == document->lines.getUnchecked (line));
  35974. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35975. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35976. {
  35977. ++line;
  35978. currentLine = document->lines [line];
  35979. }
  35980. return result;
  35981. }
  35982. void CodeDocument::Iterator::skip()
  35983. {
  35984. if (currentLine != 0)
  35985. {
  35986. jassert (currentLine == document->lines.getUnchecked (line));
  35987. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35988. {
  35989. ++line;
  35990. currentLine = document->lines [line];
  35991. }
  35992. }
  35993. }
  35994. void CodeDocument::Iterator::skipToEndOfLine()
  35995. {
  35996. if (currentLine != 0)
  35997. {
  35998. jassert (currentLine == document->lines.getUnchecked (line));
  35999. ++line;
  36000. currentLine = document->lines [line];
  36001. if (currentLine != 0)
  36002. position = currentLine->lineStartInFile;
  36003. else
  36004. position = document->getNumCharacters();
  36005. }
  36006. }
  36007. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36008. {
  36009. if (currentLine == 0)
  36010. return 0;
  36011. jassert (currentLine == document->lines.getUnchecked (line));
  36012. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36013. }
  36014. void CodeDocument::Iterator::skipWhitespace()
  36015. {
  36016. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36017. skip();
  36018. }
  36019. bool CodeDocument::Iterator::isEOF() const throw()
  36020. {
  36021. return currentLine == 0;
  36022. }
  36023. CodeDocument::Position::Position() throw()
  36024. : owner (0), characterPos (0), line (0),
  36025. indexInLine (0), positionMaintained (false)
  36026. {
  36027. }
  36028. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36029. const int line_, const int indexInLine_) throw()
  36030. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36031. characterPos (0), line (line_),
  36032. indexInLine (indexInLine_), positionMaintained (false)
  36033. {
  36034. setLineAndIndex (line_, indexInLine_);
  36035. }
  36036. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36037. const int characterPos_) throw()
  36038. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36039. positionMaintained (false)
  36040. {
  36041. setPosition (characterPos_);
  36042. }
  36043. CodeDocument::Position::Position (const Position& other) throw()
  36044. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36045. indexInLine (other.indexInLine), positionMaintained (false)
  36046. {
  36047. jassert (*this == other);
  36048. }
  36049. CodeDocument::Position::~Position()
  36050. {
  36051. setPositionMaintained (false);
  36052. }
  36053. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36054. {
  36055. if (this != &other)
  36056. {
  36057. const bool wasPositionMaintained = positionMaintained;
  36058. if (owner != other.owner)
  36059. setPositionMaintained (false);
  36060. owner = other.owner;
  36061. line = other.line;
  36062. indexInLine = other.indexInLine;
  36063. characterPos = other.characterPos;
  36064. setPositionMaintained (wasPositionMaintained);
  36065. jassert (*this == other);
  36066. }
  36067. return *this;
  36068. }
  36069. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36070. {
  36071. jassert ((characterPos == other.characterPos)
  36072. == (line == other.line && indexInLine == other.indexInLine));
  36073. return characterPos == other.characterPos
  36074. && line == other.line
  36075. && indexInLine == other.indexInLine
  36076. && owner == other.owner;
  36077. }
  36078. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36079. {
  36080. return ! operator== (other);
  36081. }
  36082. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36083. {
  36084. jassert (owner != 0);
  36085. if (owner->lines.size() == 0)
  36086. {
  36087. line = 0;
  36088. indexInLine = 0;
  36089. characterPos = 0;
  36090. }
  36091. else
  36092. {
  36093. if (newLine >= owner->lines.size())
  36094. {
  36095. line = owner->lines.size() - 1;
  36096. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36097. jassert (l != 0);
  36098. indexInLine = l->lineLengthWithoutNewLines;
  36099. characterPos = l->lineStartInFile + indexInLine;
  36100. }
  36101. else
  36102. {
  36103. line = jmax (0, newLine);
  36104. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36105. jassert (l != 0);
  36106. if (l->lineLengthWithoutNewLines > 0)
  36107. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36108. else
  36109. indexInLine = 0;
  36110. characterPos = l->lineStartInFile + indexInLine;
  36111. }
  36112. }
  36113. }
  36114. void CodeDocument::Position::setPosition (const int newPosition)
  36115. {
  36116. jassert (owner != 0);
  36117. line = 0;
  36118. indexInLine = 0;
  36119. characterPos = 0;
  36120. if (newPosition > 0)
  36121. {
  36122. int lineStart = 0;
  36123. int lineEnd = owner->lines.size();
  36124. for (;;)
  36125. {
  36126. if (lineEnd - lineStart < 4)
  36127. {
  36128. for (int i = lineStart; i < lineEnd; ++i)
  36129. {
  36130. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36131. int index = newPosition - l->lineStartInFile;
  36132. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36133. {
  36134. line = i;
  36135. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36136. characterPos = l->lineStartInFile + indexInLine;
  36137. }
  36138. }
  36139. break;
  36140. }
  36141. else
  36142. {
  36143. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36144. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36145. if (newPosition >= mid->lineStartInFile)
  36146. lineStart = midIndex;
  36147. else
  36148. lineEnd = midIndex;
  36149. }
  36150. }
  36151. }
  36152. }
  36153. void CodeDocument::Position::moveBy (int characterDelta)
  36154. {
  36155. jassert (owner != 0);
  36156. if (characterDelta == 1)
  36157. {
  36158. setPosition (getPosition());
  36159. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36160. if (line < owner->lines.size())
  36161. {
  36162. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36163. if (indexInLine + characterDelta < l->lineLength
  36164. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36165. ++characterDelta;
  36166. }
  36167. }
  36168. setPosition (characterPos + characterDelta);
  36169. }
  36170. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36171. {
  36172. CodeDocument::Position p (*this);
  36173. p.moveBy (characterDelta);
  36174. return p;
  36175. }
  36176. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36177. {
  36178. CodeDocument::Position p (*this);
  36179. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36180. return p;
  36181. }
  36182. const juce_wchar CodeDocument::Position::getCharacter() const
  36183. {
  36184. const CodeDocumentLine* const l = owner->lines [line];
  36185. return l == 0 ? 0 : l->line [getIndexInLine()];
  36186. }
  36187. const String CodeDocument::Position::getLineText() const
  36188. {
  36189. const CodeDocumentLine* const l = owner->lines [line];
  36190. return l == 0 ? String::empty : l->line;
  36191. }
  36192. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36193. {
  36194. if (isMaintained != positionMaintained)
  36195. {
  36196. positionMaintained = isMaintained;
  36197. if (owner != 0)
  36198. {
  36199. if (isMaintained)
  36200. {
  36201. jassert (! owner->positionsToMaintain.contains (this));
  36202. owner->positionsToMaintain.add (this);
  36203. }
  36204. else
  36205. {
  36206. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36207. jassert (owner->positionsToMaintain.contains (this));
  36208. owner->positionsToMaintain.removeValue (this);
  36209. }
  36210. }
  36211. }
  36212. }
  36213. CodeDocument::CodeDocument()
  36214. : undoManager (std::numeric_limits<int>::max(), 10000),
  36215. currentActionIndex (0),
  36216. indexOfSavedState (-1),
  36217. maximumLineLength (-1),
  36218. newLineChars ("\r\n")
  36219. {
  36220. }
  36221. CodeDocument::~CodeDocument()
  36222. {
  36223. }
  36224. const String CodeDocument::getAllContent() const
  36225. {
  36226. return getTextBetween (Position (this, 0),
  36227. Position (this, lines.size(), 0));
  36228. }
  36229. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36230. {
  36231. if (end.getPosition() <= start.getPosition())
  36232. return String::empty;
  36233. const int startLine = start.getLineNumber();
  36234. const int endLine = end.getLineNumber();
  36235. if (startLine == endLine)
  36236. {
  36237. CodeDocumentLine* const line = lines [startLine];
  36238. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36239. }
  36240. String result;
  36241. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36242. String::Concatenator concatenator (result);
  36243. const int maxLine = jmin (lines.size() - 1, endLine);
  36244. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36245. {
  36246. const CodeDocumentLine* line = lines.getUnchecked(i);
  36247. int len = line->lineLength;
  36248. if (i == startLine)
  36249. {
  36250. const int index = start.getIndexInLine();
  36251. concatenator.append (line->line.substring (index, len));
  36252. }
  36253. else if (i == endLine)
  36254. {
  36255. len = end.getIndexInLine();
  36256. concatenator.append (line->line.substring (0, len));
  36257. }
  36258. else
  36259. {
  36260. concatenator.append (line->line);
  36261. }
  36262. }
  36263. return result;
  36264. }
  36265. int CodeDocument::getNumCharacters() const throw()
  36266. {
  36267. const CodeDocumentLine* const lastLine = lines.getLast();
  36268. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36269. }
  36270. const String CodeDocument::getLine (const int lineIndex) const throw()
  36271. {
  36272. const CodeDocumentLine* const line = lines [lineIndex];
  36273. return (line == 0) ? String::empty : line->line;
  36274. }
  36275. int CodeDocument::getMaximumLineLength() throw()
  36276. {
  36277. if (maximumLineLength < 0)
  36278. {
  36279. maximumLineLength = 0;
  36280. for (int i = lines.size(); --i >= 0;)
  36281. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36282. }
  36283. return maximumLineLength;
  36284. }
  36285. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36286. {
  36287. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36288. }
  36289. void CodeDocument::insertText (const Position& position, const String& text)
  36290. {
  36291. insert (text, position.getPosition(), true);
  36292. }
  36293. void CodeDocument::replaceAllContent (const String& newContent)
  36294. {
  36295. remove (0, getNumCharacters(), true);
  36296. insert (newContent, 0, true);
  36297. }
  36298. bool CodeDocument::loadFromStream (InputStream& stream)
  36299. {
  36300. replaceAllContent (stream.readEntireStreamAsString());
  36301. setSavePoint();
  36302. clearUndoHistory();
  36303. return true;
  36304. }
  36305. bool CodeDocument::writeToStream (OutputStream& stream)
  36306. {
  36307. for (int i = 0; i < lines.size(); ++i)
  36308. {
  36309. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36310. const char* utf8 = temp.toUTF8();
  36311. if (! stream.write (utf8, (int) strlen (utf8)))
  36312. return false;
  36313. }
  36314. return true;
  36315. }
  36316. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36317. {
  36318. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36319. newLineChars = newLine;
  36320. }
  36321. void CodeDocument::newTransaction()
  36322. {
  36323. undoManager.beginNewTransaction (String::empty);
  36324. }
  36325. void CodeDocument::undo()
  36326. {
  36327. newTransaction();
  36328. undoManager.undo();
  36329. }
  36330. void CodeDocument::redo()
  36331. {
  36332. undoManager.redo();
  36333. }
  36334. void CodeDocument::clearUndoHistory()
  36335. {
  36336. undoManager.clearUndoHistory();
  36337. }
  36338. void CodeDocument::setSavePoint() throw()
  36339. {
  36340. indexOfSavedState = currentActionIndex;
  36341. }
  36342. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36343. {
  36344. return currentActionIndex != indexOfSavedState;
  36345. }
  36346. static int getCodeCharacterCategory (const juce_wchar character) throw()
  36347. {
  36348. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36349. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36350. }
  36351. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36352. {
  36353. Position p (position);
  36354. const int maxDistance = 256;
  36355. int i = 0;
  36356. while (i < maxDistance
  36357. && CharacterFunctions::isWhitespace (p.getCharacter())
  36358. && (i == 0 || (p.getCharacter() != '\n'
  36359. && p.getCharacter() != '\r')))
  36360. {
  36361. ++i;
  36362. p.moveBy (1);
  36363. }
  36364. if (i == 0)
  36365. {
  36366. const int type = getCodeCharacterCategory (p.getCharacter());
  36367. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  36368. {
  36369. ++i;
  36370. p.moveBy (1);
  36371. }
  36372. while (i < maxDistance
  36373. && CharacterFunctions::isWhitespace (p.getCharacter())
  36374. && (i == 0 || (p.getCharacter() != '\n'
  36375. && p.getCharacter() != '\r')))
  36376. {
  36377. ++i;
  36378. p.moveBy (1);
  36379. }
  36380. }
  36381. return p;
  36382. }
  36383. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36384. {
  36385. Position p (position);
  36386. const int maxDistance = 256;
  36387. int i = 0;
  36388. bool stoppedAtLineStart = false;
  36389. while (i < maxDistance)
  36390. {
  36391. const juce_wchar c = p.movedBy (-1).getCharacter();
  36392. if (c == '\r' || c == '\n')
  36393. {
  36394. stoppedAtLineStart = true;
  36395. if (i > 0)
  36396. break;
  36397. }
  36398. if (! CharacterFunctions::isWhitespace (c))
  36399. break;
  36400. p.moveBy (-1);
  36401. ++i;
  36402. }
  36403. if (i < maxDistance && ! stoppedAtLineStart)
  36404. {
  36405. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  36406. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  36407. {
  36408. p.moveBy (-1);
  36409. ++i;
  36410. }
  36411. }
  36412. return p;
  36413. }
  36414. void CodeDocument::checkLastLineStatus()
  36415. {
  36416. while (lines.size() > 0
  36417. && lines.getLast()->lineLength == 0
  36418. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36419. {
  36420. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36421. lines.removeLast();
  36422. }
  36423. const CodeDocumentLine* const lastLine = lines.getLast();
  36424. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36425. {
  36426. // check that there's an empty line at the end if the preceding one ends in a newline..
  36427. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36428. }
  36429. }
  36430. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36431. {
  36432. listeners.add (listener);
  36433. }
  36434. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36435. {
  36436. listeners.remove (listener);
  36437. }
  36438. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36439. {
  36440. Position startPos (this, startLine, 0);
  36441. Position endPos (this, endLine, 0);
  36442. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36443. }
  36444. class CodeDocumentInsertAction : public UndoableAction
  36445. {
  36446. CodeDocument& owner;
  36447. const String text;
  36448. int insertPos;
  36449. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36450. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36451. public:
  36452. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36453. : owner (owner_),
  36454. text (text_),
  36455. insertPos (insertPos_)
  36456. {
  36457. }
  36458. ~CodeDocumentInsertAction() {}
  36459. bool perform()
  36460. {
  36461. owner.currentActionIndex++;
  36462. owner.insert (text, insertPos, false);
  36463. return true;
  36464. }
  36465. bool undo()
  36466. {
  36467. owner.currentActionIndex--;
  36468. owner.remove (insertPos, insertPos + text.length(), false);
  36469. return true;
  36470. }
  36471. int getSizeInUnits() { return text.length() + 32; }
  36472. };
  36473. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36474. {
  36475. if (text.isEmpty())
  36476. return;
  36477. if (undoable)
  36478. {
  36479. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36480. }
  36481. else
  36482. {
  36483. Position pos (this, insertPos);
  36484. const int firstAffectedLine = pos.getLineNumber();
  36485. int lastAffectedLine = firstAffectedLine + 1;
  36486. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36487. String textInsideOriginalLine (text);
  36488. if (firstLine != 0)
  36489. {
  36490. const int index = pos.getIndexInLine();
  36491. textInsideOriginalLine = firstLine->line.substring (0, index)
  36492. + textInsideOriginalLine
  36493. + firstLine->line.substring (index);
  36494. }
  36495. maximumLineLength = -1;
  36496. Array <CodeDocumentLine*> newLines;
  36497. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36498. jassert (newLines.size() > 0);
  36499. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36500. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36501. lines.set (firstAffectedLine, newFirstLine);
  36502. if (newLines.size() > 1)
  36503. {
  36504. for (int i = 1; i < newLines.size(); ++i)
  36505. {
  36506. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36507. lines.insert (firstAffectedLine + i, l);
  36508. }
  36509. lastAffectedLine = lines.size();
  36510. }
  36511. int i, lineStart = newFirstLine->lineStartInFile;
  36512. for (i = firstAffectedLine; i < lines.size(); ++i)
  36513. {
  36514. CodeDocumentLine* const l = lines.getUnchecked (i);
  36515. l->lineStartInFile = lineStart;
  36516. lineStart += l->lineLength;
  36517. }
  36518. checkLastLineStatus();
  36519. const int newTextLength = text.length();
  36520. for (i = 0; i < positionsToMaintain.size(); ++i)
  36521. {
  36522. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36523. if (p->getPosition() >= insertPos)
  36524. p->setPosition (p->getPosition() + newTextLength);
  36525. }
  36526. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36527. }
  36528. }
  36529. class CodeDocumentDeleteAction : public UndoableAction
  36530. {
  36531. CodeDocument& owner;
  36532. int startPos, endPos;
  36533. String removedText;
  36534. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36535. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36536. public:
  36537. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36538. : owner (owner_),
  36539. startPos (startPos_),
  36540. endPos (endPos_)
  36541. {
  36542. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36543. CodeDocument::Position (&owner, endPos));
  36544. }
  36545. ~CodeDocumentDeleteAction() {}
  36546. bool perform()
  36547. {
  36548. owner.currentActionIndex++;
  36549. owner.remove (startPos, endPos, false);
  36550. return true;
  36551. }
  36552. bool undo()
  36553. {
  36554. owner.currentActionIndex--;
  36555. owner.insert (removedText, startPos, false);
  36556. return true;
  36557. }
  36558. int getSizeInUnits() { return removedText.length() + 32; }
  36559. };
  36560. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36561. {
  36562. if (endPos <= startPos)
  36563. return;
  36564. if (undoable)
  36565. {
  36566. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36567. }
  36568. else
  36569. {
  36570. Position startPosition (this, startPos);
  36571. Position endPosition (this, endPos);
  36572. maximumLineLength = -1;
  36573. const int firstAffectedLine = startPosition.getLineNumber();
  36574. const int endLine = endPosition.getLineNumber();
  36575. int lastAffectedLine = firstAffectedLine + 1;
  36576. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36577. if (firstAffectedLine == endLine)
  36578. {
  36579. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36580. + firstLine->line.substring (endPosition.getIndexInLine());
  36581. firstLine->updateLength();
  36582. }
  36583. else
  36584. {
  36585. lastAffectedLine = lines.size();
  36586. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36587. jassert (lastLine != 0);
  36588. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36589. + lastLine->line.substring (endPosition.getIndexInLine());
  36590. firstLine->updateLength();
  36591. int numLinesToRemove = endLine - firstAffectedLine;
  36592. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36593. }
  36594. int i;
  36595. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36596. {
  36597. CodeDocumentLine* const l = lines.getUnchecked (i);
  36598. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36599. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36600. }
  36601. checkLastLineStatus();
  36602. const int totalChars = getNumCharacters();
  36603. for (i = 0; i < positionsToMaintain.size(); ++i)
  36604. {
  36605. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36606. if (p->getPosition() > startPosition.getPosition())
  36607. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36608. if (p->getPosition() > totalChars)
  36609. p->setPosition (totalChars);
  36610. }
  36611. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36612. }
  36613. }
  36614. END_JUCE_NAMESPACE
  36615. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36616. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36617. BEGIN_JUCE_NAMESPACE
  36618. class CodeEditorComponent::CaretComponent : public Component,
  36619. public Timer
  36620. {
  36621. public:
  36622. CaretComponent (CodeEditorComponent& owner_)
  36623. : owner (owner_)
  36624. {
  36625. setAlwaysOnTop (true);
  36626. setInterceptsMouseClicks (false, false);
  36627. }
  36628. ~CaretComponent()
  36629. {
  36630. }
  36631. void paint (Graphics& g)
  36632. {
  36633. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36634. }
  36635. void timerCallback()
  36636. {
  36637. setVisible (shouldBeShown() && ! isVisible());
  36638. }
  36639. void updatePosition()
  36640. {
  36641. startTimer (400);
  36642. setVisible (shouldBeShown());
  36643. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36644. }
  36645. private:
  36646. CodeEditorComponent& owner;
  36647. CaretComponent (const CaretComponent&);
  36648. CaretComponent& operator= (const CaretComponent&);
  36649. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36650. };
  36651. class CodeEditorComponent::CodeEditorLine
  36652. {
  36653. public:
  36654. CodeEditorLine() throw()
  36655. : highlightColumnStart (0), highlightColumnEnd (0)
  36656. {
  36657. }
  36658. ~CodeEditorLine() throw()
  36659. {
  36660. }
  36661. bool update (CodeDocument& document, int lineNum,
  36662. CodeDocument::Iterator& source,
  36663. CodeTokeniser* analyser, const int spacesPerTab,
  36664. const CodeDocument::Position& selectionStart,
  36665. const CodeDocument::Position& selectionEnd)
  36666. {
  36667. Array <SyntaxToken> newTokens;
  36668. newTokens.ensureStorageAllocated (8);
  36669. if (analyser == 0)
  36670. {
  36671. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36672. }
  36673. else if (lineNum < document.getNumLines())
  36674. {
  36675. const CodeDocument::Position pos (&document, lineNum, 0);
  36676. createTokens (pos.getPosition(), pos.getLineText(),
  36677. source, analyser, newTokens);
  36678. }
  36679. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36680. int newHighlightStart = 0;
  36681. int newHighlightEnd = 0;
  36682. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36683. {
  36684. const String line (document.getLine (lineNum));
  36685. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36686. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36687. line, spacesPerTab);
  36688. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36689. line, spacesPerTab);
  36690. }
  36691. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36692. {
  36693. highlightColumnStart = newHighlightStart;
  36694. highlightColumnEnd = newHighlightEnd;
  36695. }
  36696. else
  36697. {
  36698. if (tokens.size() == newTokens.size())
  36699. {
  36700. bool allTheSame = true;
  36701. for (int i = newTokens.size(); --i >= 0;)
  36702. {
  36703. if (tokens.getReference(i) != newTokens.getReference(i))
  36704. {
  36705. allTheSame = false;
  36706. break;
  36707. }
  36708. }
  36709. if (allTheSame)
  36710. return false;
  36711. }
  36712. }
  36713. tokens.swapWithArray (newTokens);
  36714. return true;
  36715. }
  36716. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36717. float x, const int y, const int baselineOffset, const int lineHeight,
  36718. const Colour& highlightColour) const
  36719. {
  36720. if (highlightColumnStart < highlightColumnEnd)
  36721. {
  36722. g.setColour (highlightColour);
  36723. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36724. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36725. }
  36726. int lastType = std::numeric_limits<int>::min();
  36727. for (int i = 0; i < tokens.size(); ++i)
  36728. {
  36729. SyntaxToken& token = tokens.getReference(i);
  36730. if (lastType != token.tokenType)
  36731. {
  36732. lastType = token.tokenType;
  36733. g.setColour (owner.getColourForTokenType (lastType));
  36734. }
  36735. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36736. if (i < tokens.size() - 1)
  36737. {
  36738. if (token.width < 0)
  36739. token.width = font.getStringWidthFloat (token.text);
  36740. x += token.width;
  36741. }
  36742. }
  36743. }
  36744. private:
  36745. struct SyntaxToken
  36746. {
  36747. String text;
  36748. int tokenType;
  36749. float width;
  36750. SyntaxToken (const String& text_, const int type) throw()
  36751. : text (text_), tokenType (type), width (-1.0f)
  36752. {
  36753. }
  36754. bool operator!= (const SyntaxToken& other) const throw()
  36755. {
  36756. return text != other.text || tokenType != other.tokenType;
  36757. }
  36758. };
  36759. Array <SyntaxToken> tokens;
  36760. int highlightColumnStart, highlightColumnEnd;
  36761. static void createTokens (int startPosition, const String& lineText,
  36762. CodeDocument::Iterator& source,
  36763. CodeTokeniser* analyser,
  36764. Array <SyntaxToken>& newTokens)
  36765. {
  36766. CodeDocument::Iterator lastIterator (source);
  36767. const int lineLength = lineText.length();
  36768. for (;;)
  36769. {
  36770. int tokenType = analyser->readNextToken (source);
  36771. int tokenStart = lastIterator.getPosition();
  36772. int tokenEnd = source.getPosition();
  36773. if (tokenEnd <= tokenStart)
  36774. break;
  36775. tokenEnd -= startPosition;
  36776. if (tokenEnd > 0)
  36777. {
  36778. tokenStart -= startPosition;
  36779. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36780. tokenType));
  36781. if (tokenEnd >= lineLength)
  36782. break;
  36783. }
  36784. lastIterator = source;
  36785. }
  36786. source = lastIterator;
  36787. }
  36788. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36789. {
  36790. int x = 0;
  36791. for (int i = 0; i < tokens.size(); ++i)
  36792. {
  36793. SyntaxToken& t = tokens.getReference(i);
  36794. for (;;)
  36795. {
  36796. int tabPos = t.text.indexOfChar ('\t');
  36797. if (tabPos < 0)
  36798. break;
  36799. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36800. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36801. }
  36802. x += t.text.length();
  36803. }
  36804. }
  36805. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36806. {
  36807. jassert (index <= line.length());
  36808. int col = 0;
  36809. for (int i = 0; i < index; ++i)
  36810. {
  36811. if (line[i] != '\t')
  36812. ++col;
  36813. else
  36814. col += spacesPerTab - (col % spacesPerTab);
  36815. }
  36816. return col;
  36817. }
  36818. };
  36819. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36820. CodeTokeniser* const codeTokeniser_)
  36821. : document (document_),
  36822. firstLineOnScreen (0),
  36823. gutter (5),
  36824. spacesPerTab (4),
  36825. lineHeight (0),
  36826. linesOnScreen (0),
  36827. columnsOnScreen (0),
  36828. scrollbarThickness (16),
  36829. columnToTryToMaintain (-1),
  36830. useSpacesForTabs (false),
  36831. xOffset (0),
  36832. codeTokeniser (codeTokeniser_)
  36833. {
  36834. caretPos = CodeDocument::Position (&document_, 0, 0);
  36835. caretPos.setPositionMaintained (true);
  36836. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36837. selectionStart.setPositionMaintained (true);
  36838. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36839. selectionEnd.setPositionMaintained (true);
  36840. setOpaque (true);
  36841. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36842. setWantsKeyboardFocus (true);
  36843. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36844. verticalScrollBar->setSingleStepSize (1.0);
  36845. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36846. horizontalScrollBar->setSingleStepSize (1.0);
  36847. addAndMakeVisible (caret = new CaretComponent (*this));
  36848. Font f (12.0f);
  36849. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36850. setFont (f);
  36851. resetToDefaultColours();
  36852. verticalScrollBar->addListener (this);
  36853. horizontalScrollBar->addListener (this);
  36854. document.addListener (this);
  36855. }
  36856. CodeEditorComponent::~CodeEditorComponent()
  36857. {
  36858. document.removeListener (this);
  36859. deleteAllChildren();
  36860. }
  36861. void CodeEditorComponent::loadContent (const String& newContent)
  36862. {
  36863. clearCachedIterators (0);
  36864. document.replaceAllContent (newContent);
  36865. document.clearUndoHistory();
  36866. document.setSavePoint();
  36867. caretPos.setPosition (0);
  36868. selectionStart.setPosition (0);
  36869. selectionEnd.setPosition (0);
  36870. scrollToLine (0);
  36871. }
  36872. bool CodeEditorComponent::isTextInputActive() const
  36873. {
  36874. return true;
  36875. }
  36876. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36877. const CodeDocument::Position& affectedTextEnd)
  36878. {
  36879. clearCachedIterators (affectedTextStart.getLineNumber());
  36880. triggerAsyncUpdate();
  36881. caret->updatePosition();
  36882. columnToTryToMaintain = -1;
  36883. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36884. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36885. deselectAll();
  36886. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36887. || caretPos.getPosition() < affectedTextStart.getPosition())
  36888. moveCaretTo (affectedTextStart, false);
  36889. updateScrollBars();
  36890. }
  36891. void CodeEditorComponent::resized()
  36892. {
  36893. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36894. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36895. lines.clear();
  36896. rebuildLineTokens();
  36897. caret->updatePosition();
  36898. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36899. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36900. updateScrollBars();
  36901. }
  36902. void CodeEditorComponent::paint (Graphics& g)
  36903. {
  36904. handleUpdateNowIfNeeded();
  36905. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36906. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36907. g.setFont (font);
  36908. const int baselineOffset = (int) font.getAscent();
  36909. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36910. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36911. const Rectangle<int> clip (g.getClipBounds());
  36912. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36913. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36914. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36915. {
  36916. lines.getUnchecked(j)->draw (*this, g, font,
  36917. (float) (gutter - xOffset * charWidth),
  36918. lineHeight * j, baselineOffset, lineHeight,
  36919. highlightColour);
  36920. }
  36921. }
  36922. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36923. {
  36924. if (scrollbarThickness != thickness)
  36925. {
  36926. scrollbarThickness = thickness;
  36927. resized();
  36928. }
  36929. }
  36930. void CodeEditorComponent::handleAsyncUpdate()
  36931. {
  36932. rebuildLineTokens();
  36933. }
  36934. void CodeEditorComponent::rebuildLineTokens()
  36935. {
  36936. cancelPendingUpdate();
  36937. const int numNeeded = linesOnScreen + 1;
  36938. int minLineToRepaint = numNeeded;
  36939. int maxLineToRepaint = 0;
  36940. if (numNeeded != lines.size())
  36941. {
  36942. lines.clear();
  36943. for (int i = numNeeded; --i >= 0;)
  36944. lines.add (new CodeEditorLine());
  36945. minLineToRepaint = 0;
  36946. maxLineToRepaint = numNeeded;
  36947. }
  36948. jassert (numNeeded == lines.size());
  36949. CodeDocument::Iterator source (&document);
  36950. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36951. for (int i = 0; i < numNeeded; ++i)
  36952. {
  36953. CodeEditorLine* const line = lines.getUnchecked(i);
  36954. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36955. selectionStart, selectionEnd))
  36956. {
  36957. minLineToRepaint = jmin (minLineToRepaint, i);
  36958. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36959. }
  36960. }
  36961. if (minLineToRepaint <= maxLineToRepaint)
  36962. {
  36963. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36964. verticalScrollBar->getX() - gutter,
  36965. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36966. }
  36967. }
  36968. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36969. {
  36970. caretPos = newPos;
  36971. columnToTryToMaintain = -1;
  36972. if (highlighting)
  36973. {
  36974. if (dragType == notDragging)
  36975. {
  36976. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36977. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36978. dragType = draggingSelectionStart;
  36979. else
  36980. dragType = draggingSelectionEnd;
  36981. }
  36982. if (dragType == draggingSelectionStart)
  36983. {
  36984. selectionStart = caretPos;
  36985. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36986. {
  36987. const CodeDocument::Position temp (selectionStart);
  36988. selectionStart = selectionEnd;
  36989. selectionEnd = temp;
  36990. dragType = draggingSelectionEnd;
  36991. }
  36992. }
  36993. else
  36994. {
  36995. selectionEnd = caretPos;
  36996. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36997. {
  36998. const CodeDocument::Position temp (selectionStart);
  36999. selectionStart = selectionEnd;
  37000. selectionEnd = temp;
  37001. dragType = draggingSelectionStart;
  37002. }
  37003. }
  37004. triggerAsyncUpdate();
  37005. }
  37006. else
  37007. {
  37008. deselectAll();
  37009. }
  37010. caret->updatePosition();
  37011. scrollToKeepCaretOnScreen();
  37012. updateScrollBars();
  37013. }
  37014. void CodeEditorComponent::deselectAll()
  37015. {
  37016. if (selectionStart != selectionEnd)
  37017. triggerAsyncUpdate();
  37018. selectionStart = caretPos;
  37019. selectionEnd = caretPos;
  37020. }
  37021. void CodeEditorComponent::updateScrollBars()
  37022. {
  37023. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37024. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  37025. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37026. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  37027. }
  37028. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37029. {
  37030. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37031. newFirstLineOnScreen);
  37032. if (newFirstLineOnScreen != firstLineOnScreen)
  37033. {
  37034. firstLineOnScreen = newFirstLineOnScreen;
  37035. caret->updatePosition();
  37036. updateCachedIterators (firstLineOnScreen);
  37037. triggerAsyncUpdate();
  37038. }
  37039. }
  37040. void CodeEditorComponent::scrollToColumnInternal (double column)
  37041. {
  37042. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37043. if (xOffset != newOffset)
  37044. {
  37045. xOffset = newOffset;
  37046. caret->updatePosition();
  37047. repaint();
  37048. }
  37049. }
  37050. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37051. {
  37052. scrollToLineInternal (newFirstLineOnScreen);
  37053. updateScrollBars();
  37054. }
  37055. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37056. {
  37057. scrollToColumnInternal (newFirstColumnOnScreen);
  37058. updateScrollBars();
  37059. }
  37060. void CodeEditorComponent::scrollBy (int deltaLines)
  37061. {
  37062. scrollToLine (firstLineOnScreen + deltaLines);
  37063. }
  37064. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37065. {
  37066. if (caretPos.getLineNumber() < firstLineOnScreen)
  37067. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37068. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37069. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37070. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37071. if (column >= xOffset + columnsOnScreen - 1)
  37072. scrollToColumn (column + 1 - columnsOnScreen);
  37073. else if (column < xOffset)
  37074. scrollToColumn (column);
  37075. }
  37076. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37077. {
  37078. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37079. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37080. roundToInt (charWidth),
  37081. lineHeight);
  37082. }
  37083. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37084. {
  37085. const int line = y / lineHeight + firstLineOnScreen;
  37086. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37087. const int index = columnToIndex (line, column);
  37088. return CodeDocument::Position (&document, line, index);
  37089. }
  37090. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37091. {
  37092. document.deleteSection (selectionStart, selectionEnd);
  37093. if (newText.isNotEmpty())
  37094. document.insertText (caretPos, newText);
  37095. scrollToKeepCaretOnScreen();
  37096. }
  37097. void CodeEditorComponent::insertTabAtCaret()
  37098. {
  37099. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37100. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37101. {
  37102. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37103. }
  37104. if (useSpacesForTabs)
  37105. {
  37106. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37107. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37108. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37109. }
  37110. else
  37111. {
  37112. insertTextAtCaret ("\t");
  37113. }
  37114. }
  37115. void CodeEditorComponent::cut()
  37116. {
  37117. insertTextAtCaret (String::empty);
  37118. }
  37119. void CodeEditorComponent::copy()
  37120. {
  37121. newTransaction();
  37122. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37123. if (selection.isNotEmpty())
  37124. SystemClipboard::copyTextToClipboard (selection);
  37125. }
  37126. void CodeEditorComponent::copyThenCut()
  37127. {
  37128. copy();
  37129. cut();
  37130. newTransaction();
  37131. }
  37132. void CodeEditorComponent::paste()
  37133. {
  37134. newTransaction();
  37135. const String clip (SystemClipboard::getTextFromClipboard());
  37136. if (clip.isNotEmpty())
  37137. insertTextAtCaret (clip);
  37138. newTransaction();
  37139. }
  37140. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37141. {
  37142. newTransaction();
  37143. if (moveInWholeWordSteps)
  37144. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37145. else
  37146. moveCaretTo (caretPos.movedBy (-1), selecting);
  37147. }
  37148. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37149. {
  37150. newTransaction();
  37151. if (moveInWholeWordSteps)
  37152. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37153. else
  37154. moveCaretTo (caretPos.movedBy (1), selecting);
  37155. }
  37156. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37157. {
  37158. CodeDocument::Position pos (caretPos);
  37159. const int newLineNum = pos.getLineNumber() + delta;
  37160. if (columnToTryToMaintain < 0)
  37161. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37162. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37163. const int colToMaintain = columnToTryToMaintain;
  37164. moveCaretTo (pos, selecting);
  37165. columnToTryToMaintain = colToMaintain;
  37166. }
  37167. void CodeEditorComponent::cursorDown (const bool selecting)
  37168. {
  37169. newTransaction();
  37170. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37171. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37172. else
  37173. moveLineDelta (1, selecting);
  37174. }
  37175. void CodeEditorComponent::cursorUp (const bool selecting)
  37176. {
  37177. newTransaction();
  37178. if (caretPos.getLineNumber() == 0)
  37179. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37180. else
  37181. moveLineDelta (-1, selecting);
  37182. }
  37183. void CodeEditorComponent::pageDown (const bool selecting)
  37184. {
  37185. newTransaction();
  37186. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37187. moveLineDelta (linesOnScreen, selecting);
  37188. }
  37189. void CodeEditorComponent::pageUp (const bool selecting)
  37190. {
  37191. newTransaction();
  37192. scrollBy (-linesOnScreen);
  37193. moveLineDelta (-linesOnScreen, selecting);
  37194. }
  37195. void CodeEditorComponent::scrollUp()
  37196. {
  37197. newTransaction();
  37198. scrollBy (1);
  37199. if (caretPos.getLineNumber() < firstLineOnScreen)
  37200. moveLineDelta (1, false);
  37201. }
  37202. void CodeEditorComponent::scrollDown()
  37203. {
  37204. newTransaction();
  37205. scrollBy (-1);
  37206. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37207. moveLineDelta (-1, false);
  37208. }
  37209. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37210. {
  37211. newTransaction();
  37212. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37213. }
  37214. static int findFirstNonWhitespaceChar (const String& line) throw()
  37215. {
  37216. const int len = line.length();
  37217. for (int i = 0; i < len; ++i)
  37218. if (! CharacterFunctions::isWhitespace (line [i]))
  37219. return i;
  37220. return 0;
  37221. }
  37222. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37223. {
  37224. newTransaction();
  37225. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  37226. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37227. index = 0;
  37228. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37229. }
  37230. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37231. {
  37232. newTransaction();
  37233. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37234. }
  37235. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37236. {
  37237. newTransaction();
  37238. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37239. }
  37240. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37241. {
  37242. if (moveInWholeWordSteps)
  37243. {
  37244. cut(); // in case something is already highlighted
  37245. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37246. }
  37247. else
  37248. {
  37249. if (selectionStart == selectionEnd)
  37250. selectionStart.moveBy (-1);
  37251. }
  37252. cut();
  37253. }
  37254. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37255. {
  37256. if (moveInWholeWordSteps)
  37257. {
  37258. cut(); // in case something is already highlighted
  37259. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37260. }
  37261. else
  37262. {
  37263. if (selectionStart == selectionEnd)
  37264. selectionEnd.moveBy (1);
  37265. else
  37266. newTransaction();
  37267. }
  37268. cut();
  37269. }
  37270. void CodeEditorComponent::selectAll()
  37271. {
  37272. newTransaction();
  37273. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37274. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37275. }
  37276. void CodeEditorComponent::undo()
  37277. {
  37278. document.undo();
  37279. scrollToKeepCaretOnScreen();
  37280. }
  37281. void CodeEditorComponent::redo()
  37282. {
  37283. document.redo();
  37284. scrollToKeepCaretOnScreen();
  37285. }
  37286. void CodeEditorComponent::newTransaction()
  37287. {
  37288. document.newTransaction();
  37289. startTimer (600);
  37290. }
  37291. void CodeEditorComponent::timerCallback()
  37292. {
  37293. newTransaction();
  37294. }
  37295. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37296. {
  37297. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37298. }
  37299. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37300. {
  37301. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37302. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37303. }
  37304. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37305. {
  37306. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37307. CodeDocument::Position (&document, range.getEnd()));
  37308. }
  37309. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37310. {
  37311. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37312. const bool shiftDown = key.getModifiers().isShiftDown();
  37313. if (key.isKeyCode (KeyPress::leftKey))
  37314. {
  37315. cursorLeft (moveInWholeWordSteps, shiftDown);
  37316. }
  37317. else if (key.isKeyCode (KeyPress::rightKey))
  37318. {
  37319. cursorRight (moveInWholeWordSteps, shiftDown);
  37320. }
  37321. else if (key.isKeyCode (KeyPress::upKey))
  37322. {
  37323. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37324. scrollDown();
  37325. #if JUCE_MAC
  37326. else if (key.getModifiers().isCommandDown())
  37327. goToStartOfDocument (shiftDown);
  37328. #endif
  37329. else
  37330. cursorUp (shiftDown);
  37331. }
  37332. else if (key.isKeyCode (KeyPress::downKey))
  37333. {
  37334. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37335. scrollUp();
  37336. #if JUCE_MAC
  37337. else if (key.getModifiers().isCommandDown())
  37338. goToEndOfDocument (shiftDown);
  37339. #endif
  37340. else
  37341. cursorDown (shiftDown);
  37342. }
  37343. else if (key.isKeyCode (KeyPress::pageDownKey))
  37344. {
  37345. pageDown (shiftDown);
  37346. }
  37347. else if (key.isKeyCode (KeyPress::pageUpKey))
  37348. {
  37349. pageUp (shiftDown);
  37350. }
  37351. else if (key.isKeyCode (KeyPress::homeKey))
  37352. {
  37353. if (moveInWholeWordSteps)
  37354. goToStartOfDocument (shiftDown);
  37355. else
  37356. goToStartOfLine (shiftDown);
  37357. }
  37358. else if (key.isKeyCode (KeyPress::endKey))
  37359. {
  37360. if (moveInWholeWordSteps)
  37361. goToEndOfDocument (shiftDown);
  37362. else
  37363. goToEndOfLine (shiftDown);
  37364. }
  37365. else if (key.isKeyCode (KeyPress::backspaceKey))
  37366. {
  37367. backspace (moveInWholeWordSteps);
  37368. }
  37369. else if (key.isKeyCode (KeyPress::deleteKey))
  37370. {
  37371. deleteForward (moveInWholeWordSteps);
  37372. }
  37373. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37374. {
  37375. copy();
  37376. }
  37377. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37378. {
  37379. copyThenCut();
  37380. }
  37381. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37382. {
  37383. paste();
  37384. }
  37385. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37386. {
  37387. undo();
  37388. }
  37389. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37390. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37391. {
  37392. redo();
  37393. }
  37394. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37395. {
  37396. selectAll();
  37397. }
  37398. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37399. {
  37400. insertTabAtCaret();
  37401. }
  37402. else if (key == KeyPress::returnKey)
  37403. {
  37404. newTransaction();
  37405. insertTextAtCaret (document.getNewLineCharacters());
  37406. }
  37407. else if (key.isKeyCode (KeyPress::escapeKey))
  37408. {
  37409. newTransaction();
  37410. }
  37411. else if (key.getTextCharacter() >= ' ')
  37412. {
  37413. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37414. }
  37415. else
  37416. {
  37417. return false;
  37418. }
  37419. return true;
  37420. }
  37421. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37422. {
  37423. newTransaction();
  37424. dragType = notDragging;
  37425. if (! e.mods.isPopupMenu())
  37426. {
  37427. beginDragAutoRepeat (100);
  37428. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37429. }
  37430. else
  37431. {
  37432. /*PopupMenu m;
  37433. addPopupMenuItems (m, &e);
  37434. const int result = m.show();
  37435. if (result != 0)
  37436. performPopupMenuAction (result);
  37437. */
  37438. }
  37439. }
  37440. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37441. {
  37442. if (! e.mods.isPopupMenu())
  37443. moveCaretTo (getPositionAt (e.x, e.y), true);
  37444. }
  37445. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37446. {
  37447. newTransaction();
  37448. beginDragAutoRepeat (0);
  37449. dragType = notDragging;
  37450. }
  37451. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37452. {
  37453. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37454. CodeDocument::Position tokenEnd (tokenStart);
  37455. if (e.getNumberOfClicks() > 2)
  37456. {
  37457. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37458. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37459. }
  37460. else
  37461. {
  37462. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37463. tokenEnd.moveBy (1);
  37464. tokenStart = tokenEnd;
  37465. while (tokenStart.getIndexInLine() > 0
  37466. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37467. tokenStart.moveBy (-1);
  37468. }
  37469. moveCaretTo (tokenEnd, false);
  37470. moveCaretTo (tokenStart, true);
  37471. }
  37472. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37473. {
  37474. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  37475. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  37476. {
  37477. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  37478. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  37479. }
  37480. else
  37481. {
  37482. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37483. }
  37484. }
  37485. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37486. {
  37487. if (scrollBarThatHasMoved == verticalScrollBar)
  37488. scrollToLineInternal ((int) newRangeStart);
  37489. else
  37490. scrollToColumnInternal (newRangeStart);
  37491. }
  37492. void CodeEditorComponent::focusGained (FocusChangeType)
  37493. {
  37494. caret->updatePosition();
  37495. }
  37496. void CodeEditorComponent::focusLost (FocusChangeType)
  37497. {
  37498. caret->updatePosition();
  37499. }
  37500. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37501. {
  37502. useSpacesForTabs = insertSpaces;
  37503. if (spacesPerTab != numSpaces)
  37504. {
  37505. spacesPerTab = numSpaces;
  37506. triggerAsyncUpdate();
  37507. }
  37508. }
  37509. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37510. {
  37511. const String line (document.getLine (lineNum));
  37512. jassert (index <= line.length());
  37513. int col = 0;
  37514. for (int i = 0; i < index; ++i)
  37515. {
  37516. if (line[i] != '\t')
  37517. ++col;
  37518. else
  37519. col += getTabSize() - (col % getTabSize());
  37520. }
  37521. return col;
  37522. }
  37523. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37524. {
  37525. const String line (document.getLine (lineNum));
  37526. const int lineLength = line.length();
  37527. int i, col = 0;
  37528. for (i = 0; i < lineLength; ++i)
  37529. {
  37530. if (line[i] != '\t')
  37531. ++col;
  37532. else
  37533. col += getTabSize() - (col % getTabSize());
  37534. if (col > column)
  37535. break;
  37536. }
  37537. return i;
  37538. }
  37539. void CodeEditorComponent::setFont (const Font& newFont)
  37540. {
  37541. font = newFont;
  37542. charWidth = font.getStringWidthFloat ("0");
  37543. lineHeight = roundToInt (font.getHeight());
  37544. resized();
  37545. }
  37546. void CodeEditorComponent::resetToDefaultColours()
  37547. {
  37548. coloursForTokenCategories.clear();
  37549. if (codeTokeniser != 0)
  37550. {
  37551. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37552. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37553. }
  37554. }
  37555. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37556. {
  37557. jassert (tokenType < 256);
  37558. while (coloursForTokenCategories.size() < tokenType)
  37559. coloursForTokenCategories.add (Colours::black);
  37560. coloursForTokenCategories.set (tokenType, colour);
  37561. repaint();
  37562. }
  37563. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37564. {
  37565. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37566. return findColour (CodeEditorComponent::defaultTextColourId);
  37567. return coloursForTokenCategories.getReference (tokenType);
  37568. }
  37569. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37570. {
  37571. int i;
  37572. for (i = cachedIterators.size(); --i >= 0;)
  37573. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37574. break;
  37575. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37576. }
  37577. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37578. {
  37579. const int maxNumCachedPositions = 5000;
  37580. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37581. if (cachedIterators.size() == 0)
  37582. cachedIterators.add (new CodeDocument::Iterator (&document));
  37583. if (codeTokeniser == 0)
  37584. return;
  37585. for (;;)
  37586. {
  37587. CodeDocument::Iterator* last = cachedIterators.getLast();
  37588. if (last->getLine() >= maxLineNum)
  37589. break;
  37590. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37591. cachedIterators.add (t);
  37592. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37593. for (;;)
  37594. {
  37595. codeTokeniser->readNextToken (*t);
  37596. if (t->getLine() >= targetLine)
  37597. break;
  37598. if (t->isEOF())
  37599. return;
  37600. }
  37601. }
  37602. }
  37603. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37604. {
  37605. if (codeTokeniser == 0)
  37606. return;
  37607. for (int i = cachedIterators.size(); --i >= 0;)
  37608. {
  37609. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37610. if (t->getPosition() <= position)
  37611. {
  37612. source = *t;
  37613. break;
  37614. }
  37615. }
  37616. while (source.getPosition() < position)
  37617. {
  37618. const CodeDocument::Iterator original (source);
  37619. codeTokeniser->readNextToken (source);
  37620. if (source.getPosition() > position || source.isEOF())
  37621. {
  37622. source = original;
  37623. break;
  37624. }
  37625. }
  37626. }
  37627. END_JUCE_NAMESPACE
  37628. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37629. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37630. BEGIN_JUCE_NAMESPACE
  37631. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37632. {
  37633. }
  37634. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37635. {
  37636. }
  37637. namespace CppTokeniser
  37638. {
  37639. static bool isIdentifierStart (const juce_wchar c) throw()
  37640. {
  37641. return CharacterFunctions::isLetter (c)
  37642. || c == '_' || c == '@';
  37643. }
  37644. static bool isIdentifierBody (const juce_wchar c) throw()
  37645. {
  37646. return CharacterFunctions::isLetterOrDigit (c)
  37647. || c == '_' || c == '@';
  37648. }
  37649. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37650. {
  37651. static const juce_wchar* const keywords2Char[] =
  37652. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37653. static const juce_wchar* const keywords3Char[] =
  37654. { JUCE_T("for"), JUCE_T("int"), JUCE_T("new"), JUCE_T("try"), JUCE_T("xor"), JUCE_T("and"), JUCE_T("asm"), JUCE_T("not"), 0 };
  37655. static const juce_wchar* const keywords4Char[] =
  37656. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37657. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37658. static const juce_wchar* const keywords5Char[] =
  37659. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37660. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37661. static const juce_wchar* const keywords6Char[] =
  37662. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37663. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37664. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37665. static const juce_wchar* const keywordsOther[] =
  37666. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37667. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37668. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37669. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37670. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37671. const juce_wchar* const* k;
  37672. switch (tokenLength)
  37673. {
  37674. case 2: k = keywords2Char; break;
  37675. case 3: k = keywords3Char; break;
  37676. case 4: k = keywords4Char; break;
  37677. case 5: k = keywords5Char; break;
  37678. case 6: k = keywords6Char; break;
  37679. default:
  37680. if (tokenLength < 2 || tokenLength > 16)
  37681. return false;
  37682. k = keywordsOther;
  37683. break;
  37684. }
  37685. int i = 0;
  37686. while (k[i] != 0)
  37687. {
  37688. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37689. return true;
  37690. ++i;
  37691. }
  37692. return false;
  37693. }
  37694. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37695. {
  37696. int tokenLength = 0;
  37697. juce_wchar possibleIdentifier [19];
  37698. while (isIdentifierBody (source.peekNextChar()))
  37699. {
  37700. const juce_wchar c = source.nextChar();
  37701. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37702. possibleIdentifier [tokenLength] = c;
  37703. ++tokenLength;
  37704. }
  37705. if (tokenLength > 1 && tokenLength <= 16)
  37706. {
  37707. possibleIdentifier [tokenLength] = 0;
  37708. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37709. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37710. }
  37711. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37712. }
  37713. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37714. {
  37715. const juce_wchar c = source.peekNextChar();
  37716. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37717. source.skip();
  37718. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37719. return false;
  37720. return true;
  37721. }
  37722. static bool isHexDigit (const juce_wchar c) throw()
  37723. {
  37724. return (c >= '0' && c <= '9')
  37725. || (c >= 'a' && c <= 'f')
  37726. || (c >= 'A' && c <= 'F');
  37727. }
  37728. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37729. {
  37730. if (source.nextChar() != '0')
  37731. return false;
  37732. juce_wchar c = source.nextChar();
  37733. if (c != 'x' && c != 'X')
  37734. return false;
  37735. int numDigits = 0;
  37736. while (isHexDigit (source.peekNextChar()))
  37737. {
  37738. ++numDigits;
  37739. source.skip();
  37740. }
  37741. if (numDigits == 0)
  37742. return false;
  37743. return skipNumberSuffix (source);
  37744. }
  37745. static bool isOctalDigit (const juce_wchar c) throw()
  37746. {
  37747. return c >= '0' && c <= '7';
  37748. }
  37749. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37750. {
  37751. if (source.nextChar() != '0')
  37752. return false;
  37753. if (! isOctalDigit (source.nextChar()))
  37754. return false;
  37755. while (isOctalDigit (source.peekNextChar()))
  37756. source.skip();
  37757. return skipNumberSuffix (source);
  37758. }
  37759. static bool isDecimalDigit (const juce_wchar c) throw()
  37760. {
  37761. return c >= '0' && c <= '9';
  37762. }
  37763. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37764. {
  37765. int numChars = 0;
  37766. while (isDecimalDigit (source.peekNextChar()))
  37767. {
  37768. ++numChars;
  37769. source.skip();
  37770. }
  37771. if (numChars == 0)
  37772. return false;
  37773. return skipNumberSuffix (source);
  37774. }
  37775. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37776. {
  37777. int numDigits = 0;
  37778. while (isDecimalDigit (source.peekNextChar()))
  37779. {
  37780. source.skip();
  37781. ++numDigits;
  37782. }
  37783. const bool hasPoint = (source.peekNextChar() == '.');
  37784. if (hasPoint)
  37785. {
  37786. source.skip();
  37787. while (isDecimalDigit (source.peekNextChar()))
  37788. {
  37789. source.skip();
  37790. ++numDigits;
  37791. }
  37792. }
  37793. if (numDigits == 0)
  37794. return false;
  37795. juce_wchar c = source.peekNextChar();
  37796. const bool hasExponent = (c == 'e' || c == 'E');
  37797. if (hasExponent)
  37798. {
  37799. source.skip();
  37800. c = source.peekNextChar();
  37801. if (c == '+' || c == '-')
  37802. source.skip();
  37803. int numExpDigits = 0;
  37804. while (isDecimalDigit (source.peekNextChar()))
  37805. {
  37806. source.skip();
  37807. ++numExpDigits;
  37808. }
  37809. if (numExpDigits == 0)
  37810. return false;
  37811. }
  37812. c = source.peekNextChar();
  37813. if (c == 'f' || c == 'F')
  37814. source.skip();
  37815. else if (! (hasExponent || hasPoint))
  37816. return false;
  37817. return true;
  37818. }
  37819. static int parseNumber (CodeDocument::Iterator& source)
  37820. {
  37821. const CodeDocument::Iterator original (source);
  37822. if (parseFloatLiteral (source))
  37823. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37824. source = original;
  37825. if (parseHexLiteral (source))
  37826. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37827. source = original;
  37828. if (parseOctalLiteral (source))
  37829. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37830. source = original;
  37831. if (parseDecimalLiteral (source))
  37832. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37833. source = original;
  37834. source.skip();
  37835. return CPlusPlusCodeTokeniser::tokenType_error;
  37836. }
  37837. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37838. {
  37839. const juce_wchar quote = source.nextChar();
  37840. for (;;)
  37841. {
  37842. const juce_wchar c = source.nextChar();
  37843. if (c == quote || c == 0)
  37844. break;
  37845. if (c == '\\')
  37846. source.skip();
  37847. }
  37848. }
  37849. static void skipComment (CodeDocument::Iterator& source) throw()
  37850. {
  37851. bool lastWasStar = false;
  37852. for (;;)
  37853. {
  37854. const juce_wchar c = source.nextChar();
  37855. if (c == 0 || (c == '/' && lastWasStar))
  37856. break;
  37857. lastWasStar = (c == '*');
  37858. }
  37859. }
  37860. }
  37861. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37862. {
  37863. int result = tokenType_error;
  37864. source.skipWhitespace();
  37865. juce_wchar firstChar = source.peekNextChar();
  37866. switch (firstChar)
  37867. {
  37868. case 0:
  37869. source.skip();
  37870. break;
  37871. case '0':
  37872. case '1':
  37873. case '2':
  37874. case '3':
  37875. case '4':
  37876. case '5':
  37877. case '6':
  37878. case '7':
  37879. case '8':
  37880. case '9':
  37881. result = CppTokeniser::parseNumber (source);
  37882. break;
  37883. case '.':
  37884. result = CppTokeniser::parseNumber (source);
  37885. if (result == tokenType_error)
  37886. result = tokenType_punctuation;
  37887. break;
  37888. case ',':
  37889. case ';':
  37890. case ':':
  37891. source.skip();
  37892. result = tokenType_punctuation;
  37893. break;
  37894. case '(':
  37895. case ')':
  37896. case '{':
  37897. case '}':
  37898. case '[':
  37899. case ']':
  37900. source.skip();
  37901. result = tokenType_bracket;
  37902. break;
  37903. case '"':
  37904. case '\'':
  37905. CppTokeniser::skipQuotedString (source);
  37906. result = tokenType_stringLiteral;
  37907. break;
  37908. case '+':
  37909. result = tokenType_operator;
  37910. source.skip();
  37911. if (source.peekNextChar() == '+')
  37912. source.skip();
  37913. else if (source.peekNextChar() == '=')
  37914. source.skip();
  37915. break;
  37916. case '-':
  37917. source.skip();
  37918. result = CppTokeniser::parseNumber (source);
  37919. if (result == tokenType_error)
  37920. {
  37921. result = tokenType_operator;
  37922. if (source.peekNextChar() == '-')
  37923. source.skip();
  37924. else if (source.peekNextChar() == '=')
  37925. source.skip();
  37926. }
  37927. break;
  37928. case '*':
  37929. case '%':
  37930. case '=':
  37931. case '!':
  37932. result = tokenType_operator;
  37933. source.skip();
  37934. if (source.peekNextChar() == '=')
  37935. source.skip();
  37936. break;
  37937. case '/':
  37938. result = tokenType_operator;
  37939. source.skip();
  37940. if (source.peekNextChar() == '=')
  37941. {
  37942. source.skip();
  37943. }
  37944. else if (source.peekNextChar() == '/')
  37945. {
  37946. result = tokenType_comment;
  37947. source.skipToEndOfLine();
  37948. }
  37949. else if (source.peekNextChar() == '*')
  37950. {
  37951. source.skip();
  37952. result = tokenType_comment;
  37953. CppTokeniser::skipComment (source);
  37954. }
  37955. break;
  37956. case '?':
  37957. case '~':
  37958. source.skip();
  37959. result = tokenType_operator;
  37960. break;
  37961. case '<':
  37962. source.skip();
  37963. result = tokenType_operator;
  37964. if (source.peekNextChar() == '=')
  37965. {
  37966. source.skip();
  37967. }
  37968. else if (source.peekNextChar() == '<')
  37969. {
  37970. source.skip();
  37971. if (source.peekNextChar() == '=')
  37972. source.skip();
  37973. }
  37974. break;
  37975. case '>':
  37976. source.skip();
  37977. result = tokenType_operator;
  37978. if (source.peekNextChar() == '=')
  37979. {
  37980. source.skip();
  37981. }
  37982. else if (source.peekNextChar() == '<')
  37983. {
  37984. source.skip();
  37985. if (source.peekNextChar() == '=')
  37986. source.skip();
  37987. }
  37988. break;
  37989. case '|':
  37990. source.skip();
  37991. result = tokenType_operator;
  37992. if (source.peekNextChar() == '=')
  37993. {
  37994. source.skip();
  37995. }
  37996. else if (source.peekNextChar() == '|')
  37997. {
  37998. source.skip();
  37999. if (source.peekNextChar() == '=')
  38000. source.skip();
  38001. }
  38002. break;
  38003. case '&':
  38004. source.skip();
  38005. result = tokenType_operator;
  38006. if (source.peekNextChar() == '=')
  38007. {
  38008. source.skip();
  38009. }
  38010. else if (source.peekNextChar() == '&')
  38011. {
  38012. source.skip();
  38013. if (source.peekNextChar() == '=')
  38014. source.skip();
  38015. }
  38016. break;
  38017. case '^':
  38018. source.skip();
  38019. result = tokenType_operator;
  38020. if (source.peekNextChar() == '=')
  38021. {
  38022. source.skip();
  38023. }
  38024. else if (source.peekNextChar() == '^')
  38025. {
  38026. source.skip();
  38027. if (source.peekNextChar() == '=')
  38028. source.skip();
  38029. }
  38030. break;
  38031. case '#':
  38032. result = tokenType_preprocessor;
  38033. source.skipToEndOfLine();
  38034. break;
  38035. default:
  38036. if (CppTokeniser::isIdentifierStart (firstChar))
  38037. result = CppTokeniser::parseIdentifier (source);
  38038. else
  38039. source.skip();
  38040. break;
  38041. }
  38042. return result;
  38043. }
  38044. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38045. {
  38046. const char* const types[] =
  38047. {
  38048. "Error",
  38049. "Comment",
  38050. "C++ keyword",
  38051. "Identifier",
  38052. "Integer literal",
  38053. "Float literal",
  38054. "String literal",
  38055. "Operator",
  38056. "Bracket",
  38057. "Punctuation",
  38058. "Preprocessor line",
  38059. 0
  38060. };
  38061. return StringArray (types);
  38062. }
  38063. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38064. {
  38065. const uint32 colours[] =
  38066. {
  38067. 0xffcc0000, // error
  38068. 0xff00aa00, // comment
  38069. 0xff0000cc, // keyword
  38070. 0xff000000, // identifier
  38071. 0xff880000, // int literal
  38072. 0xff885500, // float literal
  38073. 0xff990099, // string literal
  38074. 0xff225500, // operator
  38075. 0xff000055, // bracket
  38076. 0xff004400, // punctuation
  38077. 0xff660000 // preprocessor
  38078. };
  38079. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38080. return Colour (colours [tokenType]);
  38081. return Colours::black;
  38082. }
  38083. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38084. {
  38085. return CppTokeniser::isReservedKeyword (token, token.length());
  38086. }
  38087. END_JUCE_NAMESPACE
  38088. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38089. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38090. BEGIN_JUCE_NAMESPACE
  38091. ComboBox::ComboBox (const String& name)
  38092. : Component (name),
  38093. lastCurrentId (0),
  38094. isButtonDown (false),
  38095. separatorPending (false),
  38096. menuActive (false),
  38097. label (0)
  38098. {
  38099. noChoicesMessage = TRANS("(no choices)");
  38100. setRepaintsOnMouseActivity (true);
  38101. lookAndFeelChanged();
  38102. currentId.addListener (this);
  38103. }
  38104. ComboBox::~ComboBox()
  38105. {
  38106. currentId.removeListener (this);
  38107. if (menuActive)
  38108. PopupMenu::dismissAllActiveMenus();
  38109. label = 0;
  38110. deleteAllChildren();
  38111. }
  38112. void ComboBox::setEditableText (const bool isEditable)
  38113. {
  38114. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38115. {
  38116. label->setEditable (isEditable, isEditable, false);
  38117. setWantsKeyboardFocus (! isEditable);
  38118. resized();
  38119. }
  38120. }
  38121. bool ComboBox::isTextEditable() const throw()
  38122. {
  38123. return label->isEditable();
  38124. }
  38125. void ComboBox::setJustificationType (const Justification& justification)
  38126. {
  38127. label->setJustificationType (justification);
  38128. }
  38129. const Justification ComboBox::getJustificationType() const throw()
  38130. {
  38131. return label->getJustificationType();
  38132. }
  38133. void ComboBox::setTooltip (const String& newTooltip)
  38134. {
  38135. SettableTooltipClient::setTooltip (newTooltip);
  38136. label->setTooltip (newTooltip);
  38137. }
  38138. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38139. {
  38140. // you can't add empty strings to the list..
  38141. jassert (newItemText.isNotEmpty());
  38142. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38143. jassert (newItemId != 0);
  38144. // you shouldn't use duplicate item IDs!
  38145. jassert (getItemForId (newItemId) == 0);
  38146. if (newItemText.isNotEmpty() && newItemId != 0)
  38147. {
  38148. if (separatorPending)
  38149. {
  38150. separatorPending = false;
  38151. ItemInfo* const item = new ItemInfo();
  38152. item->itemId = 0;
  38153. item->isEnabled = false;
  38154. item->isHeading = false;
  38155. items.add (item);
  38156. }
  38157. ItemInfo* const item = new ItemInfo();
  38158. item->name = newItemText;
  38159. item->itemId = newItemId;
  38160. item->isEnabled = true;
  38161. item->isHeading = false;
  38162. items.add (item);
  38163. }
  38164. }
  38165. void ComboBox::addSeparator()
  38166. {
  38167. separatorPending = (items.size() > 0);
  38168. }
  38169. void ComboBox::addSectionHeading (const String& headingName)
  38170. {
  38171. // you can't add empty strings to the list..
  38172. jassert (headingName.isNotEmpty());
  38173. if (headingName.isNotEmpty())
  38174. {
  38175. if (separatorPending)
  38176. {
  38177. separatorPending = false;
  38178. ItemInfo* const item = new ItemInfo();
  38179. item->itemId = 0;
  38180. item->isEnabled = false;
  38181. item->isHeading = false;
  38182. items.add (item);
  38183. }
  38184. ItemInfo* const item = new ItemInfo();
  38185. item->name = headingName;
  38186. item->itemId = 0;
  38187. item->isEnabled = true;
  38188. item->isHeading = true;
  38189. items.add (item);
  38190. }
  38191. }
  38192. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38193. {
  38194. ItemInfo* const item = getItemForId (itemId);
  38195. if (item != 0)
  38196. item->isEnabled = shouldBeEnabled;
  38197. }
  38198. void ComboBox::changeItemText (const int itemId, const String& newText)
  38199. {
  38200. ItemInfo* const item = getItemForId (itemId);
  38201. jassert (item != 0);
  38202. if (item != 0)
  38203. item->name = newText;
  38204. }
  38205. void ComboBox::clear (const bool dontSendChangeMessage)
  38206. {
  38207. items.clear();
  38208. separatorPending = false;
  38209. if (! label->isEditable())
  38210. setSelectedItemIndex (-1, dontSendChangeMessage);
  38211. }
  38212. bool ComboBox::ItemInfo::isSeparator() const throw()
  38213. {
  38214. return name.isEmpty();
  38215. }
  38216. bool ComboBox::ItemInfo::isRealItem() const throw()
  38217. {
  38218. return ! (isHeading || name.isEmpty());
  38219. }
  38220. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38221. {
  38222. if (itemId != 0)
  38223. {
  38224. for (int i = items.size(); --i >= 0;)
  38225. if (items.getUnchecked(i)->itemId == itemId)
  38226. return items.getUnchecked(i);
  38227. }
  38228. return 0;
  38229. }
  38230. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38231. {
  38232. int n = 0;
  38233. for (int i = 0; i < items.size(); ++i)
  38234. {
  38235. ItemInfo* const item = items.getUnchecked(i);
  38236. if (item->isRealItem())
  38237. if (n++ == index)
  38238. return item;
  38239. }
  38240. return 0;
  38241. }
  38242. int ComboBox::getNumItems() const throw()
  38243. {
  38244. int n = 0;
  38245. for (int i = items.size(); --i >= 0;)
  38246. if (items.getUnchecked(i)->isRealItem())
  38247. ++n;
  38248. return n;
  38249. }
  38250. const String ComboBox::getItemText (const int index) const
  38251. {
  38252. const ItemInfo* const item = getItemForIndex (index);
  38253. if (item != 0)
  38254. return item->name;
  38255. return String::empty;
  38256. }
  38257. int ComboBox::getItemId (const int index) const throw()
  38258. {
  38259. const ItemInfo* const item = getItemForIndex (index);
  38260. return (item != 0) ? item->itemId : 0;
  38261. }
  38262. int ComboBox::indexOfItemId (const int itemId) const throw()
  38263. {
  38264. int n = 0;
  38265. for (int i = 0; i < items.size(); ++i)
  38266. {
  38267. const ItemInfo* const item = items.getUnchecked(i);
  38268. if (item->isRealItem())
  38269. {
  38270. if (item->itemId == itemId)
  38271. return n;
  38272. ++n;
  38273. }
  38274. }
  38275. return -1;
  38276. }
  38277. int ComboBox::getSelectedItemIndex() const
  38278. {
  38279. int index = indexOfItemId (currentId.getValue());
  38280. if (getText() != getItemText (index))
  38281. index = -1;
  38282. return index;
  38283. }
  38284. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38285. {
  38286. setSelectedId (getItemId (index), dontSendChangeMessage);
  38287. }
  38288. int ComboBox::getSelectedId() const throw()
  38289. {
  38290. const ItemInfo* const item = getItemForId (currentId.getValue());
  38291. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38292. }
  38293. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38294. {
  38295. const ItemInfo* const item = getItemForId (newItemId);
  38296. const String newItemText (item != 0 ? item->name : String::empty);
  38297. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38298. {
  38299. if (! dontSendChangeMessage)
  38300. triggerAsyncUpdate();
  38301. label->setText (newItemText, false);
  38302. lastCurrentId = newItemId;
  38303. currentId = newItemId;
  38304. repaint(); // for the benefit of the 'none selected' text
  38305. }
  38306. }
  38307. void ComboBox::valueChanged (Value&)
  38308. {
  38309. if (lastCurrentId != (int) currentId.getValue())
  38310. setSelectedId (currentId.getValue(), false);
  38311. }
  38312. const String ComboBox::getText() const
  38313. {
  38314. return label->getText();
  38315. }
  38316. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38317. {
  38318. for (int i = items.size(); --i >= 0;)
  38319. {
  38320. const ItemInfo* const item = items.getUnchecked(i);
  38321. if (item->isRealItem()
  38322. && item->name == newText)
  38323. {
  38324. setSelectedId (item->itemId, dontSendChangeMessage);
  38325. return;
  38326. }
  38327. }
  38328. lastCurrentId = 0;
  38329. currentId = 0;
  38330. if (label->getText() != newText)
  38331. {
  38332. label->setText (newText, false);
  38333. if (! dontSendChangeMessage)
  38334. triggerAsyncUpdate();
  38335. }
  38336. repaint();
  38337. }
  38338. void ComboBox::showEditor()
  38339. {
  38340. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38341. label->showEditor();
  38342. }
  38343. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38344. {
  38345. if (textWhenNothingSelected != newMessage)
  38346. {
  38347. textWhenNothingSelected = newMessage;
  38348. repaint();
  38349. }
  38350. }
  38351. const String ComboBox::getTextWhenNothingSelected() const
  38352. {
  38353. return textWhenNothingSelected;
  38354. }
  38355. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38356. {
  38357. noChoicesMessage = newMessage;
  38358. }
  38359. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38360. {
  38361. return noChoicesMessage;
  38362. }
  38363. void ComboBox::paint (Graphics& g)
  38364. {
  38365. getLookAndFeel().drawComboBox (g,
  38366. getWidth(),
  38367. getHeight(),
  38368. isButtonDown,
  38369. label->getRight(),
  38370. 0,
  38371. getWidth() - label->getRight(),
  38372. getHeight(),
  38373. *this);
  38374. if (textWhenNothingSelected.isNotEmpty()
  38375. && label->getText().isEmpty()
  38376. && ! label->isBeingEdited())
  38377. {
  38378. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38379. g.setFont (label->getFont());
  38380. g.drawFittedText (textWhenNothingSelected,
  38381. label->getX() + 2, label->getY() + 1,
  38382. label->getWidth() - 4, label->getHeight() - 2,
  38383. label->getJustificationType(),
  38384. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38385. }
  38386. }
  38387. void ComboBox::resized()
  38388. {
  38389. if (getHeight() > 0 && getWidth() > 0)
  38390. getLookAndFeel().positionComboBoxText (*this, *label);
  38391. }
  38392. void ComboBox::enablementChanged()
  38393. {
  38394. repaint();
  38395. }
  38396. void ComboBox::lookAndFeelChanged()
  38397. {
  38398. repaint();
  38399. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38400. if (label != 0)
  38401. {
  38402. newLabel->setEditable (label->isEditable());
  38403. newLabel->setJustificationType (label->getJustificationType());
  38404. newLabel->setTooltip (label->getTooltip());
  38405. newLabel->setText (label->getText(), false);
  38406. }
  38407. label = newLabel;
  38408. addAndMakeVisible (newLabel);
  38409. newLabel->addListener (this);
  38410. newLabel->addMouseListener (this, false);
  38411. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38412. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38413. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38414. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38415. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38416. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38417. resized();
  38418. }
  38419. void ComboBox::colourChanged()
  38420. {
  38421. lookAndFeelChanged();
  38422. }
  38423. bool ComboBox::keyPressed (const KeyPress& key)
  38424. {
  38425. bool used = false;
  38426. if (key.isKeyCode (KeyPress::upKey)
  38427. || key.isKeyCode (KeyPress::leftKey))
  38428. {
  38429. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38430. used = true;
  38431. }
  38432. else if (key.isKeyCode (KeyPress::downKey)
  38433. || key.isKeyCode (KeyPress::rightKey))
  38434. {
  38435. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38436. used = true;
  38437. }
  38438. else if (key.isKeyCode (KeyPress::returnKey))
  38439. {
  38440. showPopup();
  38441. used = true;
  38442. }
  38443. return used;
  38444. }
  38445. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38446. {
  38447. // only forward key events that aren't used by this component
  38448. return isKeyDown
  38449. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38450. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38451. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38452. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38453. }
  38454. void ComboBox::focusGained (FocusChangeType)
  38455. {
  38456. repaint();
  38457. }
  38458. void ComboBox::focusLost (FocusChangeType)
  38459. {
  38460. repaint();
  38461. }
  38462. void ComboBox::labelTextChanged (Label*)
  38463. {
  38464. triggerAsyncUpdate();
  38465. }
  38466. class ComboBox::Callback : public ModalComponentManager::Callback
  38467. {
  38468. public:
  38469. Callback (ComboBox* const box_)
  38470. : box (box_)
  38471. {
  38472. }
  38473. void modalStateFinished (int returnValue)
  38474. {
  38475. if (box != 0)
  38476. {
  38477. box->menuActive = false;
  38478. if (returnValue != 0)
  38479. box->setSelectedId (returnValue);
  38480. }
  38481. }
  38482. private:
  38483. Component::SafePointer<ComboBox> box;
  38484. Callback (const Callback&);
  38485. Callback& operator= (const Callback&);
  38486. };
  38487. void ComboBox::showPopup()
  38488. {
  38489. if (! menuActive)
  38490. {
  38491. const int selectedId = getSelectedId();
  38492. PopupMenu menu;
  38493. menu.setLookAndFeel (&getLookAndFeel());
  38494. for (int i = 0; i < items.size(); ++i)
  38495. {
  38496. const ItemInfo* const item = items.getUnchecked(i);
  38497. if (item->isSeparator())
  38498. menu.addSeparator();
  38499. else if (item->isHeading)
  38500. menu.addSectionHeader (item->name);
  38501. else
  38502. menu.addItem (item->itemId, item->name,
  38503. item->isEnabled, item->itemId == selectedId);
  38504. }
  38505. if (items.size() == 0)
  38506. menu.addItem (1, noChoicesMessage, false);
  38507. menuActive = true;
  38508. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38509. new Callback (this));
  38510. }
  38511. }
  38512. void ComboBox::mouseDown (const MouseEvent& e)
  38513. {
  38514. beginDragAutoRepeat (300);
  38515. isButtonDown = isEnabled();
  38516. if (isButtonDown
  38517. && (e.eventComponent == this || ! label->isEditable()))
  38518. {
  38519. showPopup();
  38520. }
  38521. }
  38522. void ComboBox::mouseDrag (const MouseEvent& e)
  38523. {
  38524. beginDragAutoRepeat (50);
  38525. if (isButtonDown && ! e.mouseWasClicked())
  38526. showPopup();
  38527. }
  38528. void ComboBox::mouseUp (const MouseEvent& e2)
  38529. {
  38530. if (isButtonDown)
  38531. {
  38532. isButtonDown = false;
  38533. repaint();
  38534. const MouseEvent e (e2.getEventRelativeTo (this));
  38535. if (reallyContains (e.x, e.y, true)
  38536. && (e2.eventComponent == this || ! label->isEditable()))
  38537. {
  38538. showPopup();
  38539. }
  38540. }
  38541. }
  38542. void ComboBox::addListener (Listener* const listener)
  38543. {
  38544. listeners.add (listener);
  38545. }
  38546. void ComboBox::removeListener (Listener* const listener)
  38547. {
  38548. listeners.remove (listener);
  38549. }
  38550. void ComboBox::handleAsyncUpdate()
  38551. {
  38552. Component::BailOutChecker checker (this);
  38553. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38554. }
  38555. END_JUCE_NAMESPACE
  38556. /*** End of inlined file: juce_ComboBox.cpp ***/
  38557. /*** Start of inlined file: juce_Label.cpp ***/
  38558. BEGIN_JUCE_NAMESPACE
  38559. Label::Label (const String& componentName,
  38560. const String& labelText)
  38561. : Component (componentName),
  38562. textValue (labelText),
  38563. lastTextValue (labelText),
  38564. font (15.0f),
  38565. justification (Justification::centredLeft),
  38566. ownerComponent (0),
  38567. horizontalBorderSize (5),
  38568. verticalBorderSize (1),
  38569. minimumHorizontalScale (0.7f),
  38570. editSingleClick (false),
  38571. editDoubleClick (false),
  38572. lossOfFocusDiscardsChanges (false)
  38573. {
  38574. setColour (TextEditor::textColourId, Colours::black);
  38575. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38576. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38577. textValue.addListener (this);
  38578. }
  38579. Label::~Label()
  38580. {
  38581. textValue.removeListener (this);
  38582. if (ownerComponent != 0)
  38583. ownerComponent->removeComponentListener (this);
  38584. editor = 0;
  38585. }
  38586. void Label::setText (const String& newText,
  38587. const bool broadcastChangeMessage)
  38588. {
  38589. hideEditor (true);
  38590. if (lastTextValue != newText)
  38591. {
  38592. lastTextValue = newText;
  38593. textValue = newText;
  38594. repaint();
  38595. textWasChanged();
  38596. if (ownerComponent != 0)
  38597. componentMovedOrResized (*ownerComponent, true, true);
  38598. if (broadcastChangeMessage)
  38599. callChangeListeners();
  38600. }
  38601. }
  38602. const String Label::getText (const bool returnActiveEditorContents) const
  38603. {
  38604. return (returnActiveEditorContents && isBeingEdited())
  38605. ? editor->getText()
  38606. : textValue.toString();
  38607. }
  38608. void Label::valueChanged (Value&)
  38609. {
  38610. if (lastTextValue != textValue.toString())
  38611. setText (textValue.toString(), true);
  38612. }
  38613. void Label::setFont (const Font& newFont)
  38614. {
  38615. if (font != newFont)
  38616. {
  38617. font = newFont;
  38618. repaint();
  38619. }
  38620. }
  38621. const Font& Label::getFont() const throw()
  38622. {
  38623. return font;
  38624. }
  38625. void Label::setEditable (const bool editOnSingleClick,
  38626. const bool editOnDoubleClick,
  38627. const bool lossOfFocusDiscardsChanges_)
  38628. {
  38629. editSingleClick = editOnSingleClick;
  38630. editDoubleClick = editOnDoubleClick;
  38631. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38632. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38633. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38634. }
  38635. void Label::setJustificationType (const Justification& newJustification)
  38636. {
  38637. if (justification != newJustification)
  38638. {
  38639. justification = newJustification;
  38640. repaint();
  38641. }
  38642. }
  38643. void Label::setBorderSize (int h, int v)
  38644. {
  38645. if (horizontalBorderSize != h || verticalBorderSize != v)
  38646. {
  38647. horizontalBorderSize = h;
  38648. verticalBorderSize = v;
  38649. repaint();
  38650. }
  38651. }
  38652. Component* Label::getAttachedComponent() const
  38653. {
  38654. return static_cast<Component*> (ownerComponent);
  38655. }
  38656. void Label::attachToComponent (Component* owner,
  38657. const bool onLeft)
  38658. {
  38659. if (ownerComponent != 0)
  38660. ownerComponent->removeComponentListener (this);
  38661. ownerComponent = owner;
  38662. leftOfOwnerComp = onLeft;
  38663. if (ownerComponent != 0)
  38664. {
  38665. setVisible (owner->isVisible());
  38666. ownerComponent->addComponentListener (this);
  38667. componentParentHierarchyChanged (*ownerComponent);
  38668. componentMovedOrResized (*ownerComponent, true, true);
  38669. }
  38670. }
  38671. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38672. {
  38673. if (leftOfOwnerComp)
  38674. {
  38675. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38676. component.getHeight());
  38677. setTopRightPosition (component.getX(), component.getY());
  38678. }
  38679. else
  38680. {
  38681. setSize (component.getWidth(),
  38682. 8 + roundToInt (getFont().getHeight()));
  38683. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38684. }
  38685. }
  38686. void Label::componentParentHierarchyChanged (Component& component)
  38687. {
  38688. if (component.getParentComponent() != 0)
  38689. component.getParentComponent()->addChildComponent (this);
  38690. }
  38691. void Label::componentVisibilityChanged (Component& component)
  38692. {
  38693. setVisible (component.isVisible());
  38694. }
  38695. void Label::textWasEdited()
  38696. {
  38697. }
  38698. void Label::textWasChanged()
  38699. {
  38700. }
  38701. void Label::showEditor()
  38702. {
  38703. if (editor == 0)
  38704. {
  38705. addAndMakeVisible (editor = createEditorComponent());
  38706. editor->setText (getText(), false);
  38707. editor->addListener (this);
  38708. editor->grabKeyboardFocus();
  38709. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38710. editor->addListener (this);
  38711. resized();
  38712. repaint();
  38713. editorShown (editor);
  38714. enterModalState (false);
  38715. editor->grabKeyboardFocus();
  38716. }
  38717. }
  38718. void Label::editorShown (TextEditor* /*editorComponent*/)
  38719. {
  38720. }
  38721. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38722. {
  38723. }
  38724. bool Label::updateFromTextEditorContents()
  38725. {
  38726. jassert (editor != 0);
  38727. const String newText (editor->getText());
  38728. if (textValue.toString() != newText)
  38729. {
  38730. lastTextValue = newText;
  38731. textValue = newText;
  38732. repaint();
  38733. textWasChanged();
  38734. if (ownerComponent != 0)
  38735. componentMovedOrResized (*ownerComponent, true, true);
  38736. return true;
  38737. }
  38738. return false;
  38739. }
  38740. void Label::hideEditor (const bool discardCurrentEditorContents)
  38741. {
  38742. if (editor != 0)
  38743. {
  38744. Component::SafePointer<Component> deletionChecker (this);
  38745. editorAboutToBeHidden (editor);
  38746. const bool changed = (! discardCurrentEditorContents)
  38747. && updateFromTextEditorContents();
  38748. editor = 0;
  38749. repaint();
  38750. if (changed)
  38751. textWasEdited();
  38752. if (deletionChecker != 0)
  38753. exitModalState (0);
  38754. if (changed && deletionChecker != 0)
  38755. callChangeListeners();
  38756. }
  38757. }
  38758. void Label::inputAttemptWhenModal()
  38759. {
  38760. if (editor != 0)
  38761. {
  38762. if (lossOfFocusDiscardsChanges)
  38763. textEditorEscapeKeyPressed (*editor);
  38764. else
  38765. textEditorReturnKeyPressed (*editor);
  38766. }
  38767. }
  38768. bool Label::isBeingEdited() const throw()
  38769. {
  38770. return editor != 0;
  38771. }
  38772. TextEditor* Label::createEditorComponent()
  38773. {
  38774. TextEditor* const ed = new TextEditor (getName());
  38775. ed->setFont (font);
  38776. // copy these colours from our own settings..
  38777. const int cols[] = { TextEditor::backgroundColourId,
  38778. TextEditor::textColourId,
  38779. TextEditor::highlightColourId,
  38780. TextEditor::highlightedTextColourId,
  38781. TextEditor::caretColourId,
  38782. TextEditor::outlineColourId,
  38783. TextEditor::focusedOutlineColourId,
  38784. TextEditor::shadowColourId };
  38785. for (int i = 0; i < numElementsInArray (cols); ++i)
  38786. ed->setColour (cols[i], findColour (cols[i]));
  38787. return ed;
  38788. }
  38789. void Label::paint (Graphics& g)
  38790. {
  38791. getLookAndFeel().drawLabel (g, *this);
  38792. }
  38793. void Label::mouseUp (const MouseEvent& e)
  38794. {
  38795. if (editSingleClick
  38796. && e.mouseWasClicked()
  38797. && contains (e.x, e.y)
  38798. && ! e.mods.isPopupMenu())
  38799. {
  38800. showEditor();
  38801. }
  38802. }
  38803. void Label::mouseDoubleClick (const MouseEvent& e)
  38804. {
  38805. if (editDoubleClick && ! e.mods.isPopupMenu())
  38806. showEditor();
  38807. }
  38808. void Label::resized()
  38809. {
  38810. if (editor != 0)
  38811. editor->setBoundsInset (BorderSize (0));
  38812. }
  38813. void Label::focusGained (FocusChangeType cause)
  38814. {
  38815. if (editSingleClick && cause == focusChangedByTabKey)
  38816. showEditor();
  38817. }
  38818. void Label::enablementChanged()
  38819. {
  38820. repaint();
  38821. }
  38822. void Label::colourChanged()
  38823. {
  38824. repaint();
  38825. }
  38826. void Label::setMinimumHorizontalScale (const float newScale)
  38827. {
  38828. if (minimumHorizontalScale != newScale)
  38829. {
  38830. minimumHorizontalScale = newScale;
  38831. repaint();
  38832. }
  38833. }
  38834. // We'll use a custom focus traverser here to make sure focus goes from the
  38835. // text editor to another component rather than back to the label itself.
  38836. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38837. {
  38838. public:
  38839. LabelKeyboardFocusTraverser() {}
  38840. Component* getNextComponent (Component* current)
  38841. {
  38842. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38843. ? current->getParentComponent() : current);
  38844. }
  38845. Component* getPreviousComponent (Component* current)
  38846. {
  38847. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38848. ? current->getParentComponent() : current);
  38849. }
  38850. };
  38851. KeyboardFocusTraverser* Label::createFocusTraverser()
  38852. {
  38853. return new LabelKeyboardFocusTraverser();
  38854. }
  38855. void Label::addListener (Listener* const listener)
  38856. {
  38857. listeners.add (listener);
  38858. }
  38859. void Label::removeListener (Listener* const listener)
  38860. {
  38861. listeners.remove (listener);
  38862. }
  38863. void Label::callChangeListeners()
  38864. {
  38865. Component::BailOutChecker checker (this);
  38866. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38867. }
  38868. void Label::textEditorTextChanged (TextEditor& ed)
  38869. {
  38870. if (editor != 0)
  38871. {
  38872. jassert (&ed == editor);
  38873. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38874. {
  38875. if (lossOfFocusDiscardsChanges)
  38876. textEditorEscapeKeyPressed (ed);
  38877. else
  38878. textEditorReturnKeyPressed (ed);
  38879. }
  38880. }
  38881. }
  38882. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38883. {
  38884. if (editor != 0)
  38885. {
  38886. jassert (&ed == editor);
  38887. (void) ed;
  38888. const bool changed = updateFromTextEditorContents();
  38889. hideEditor (true);
  38890. if (changed)
  38891. {
  38892. Component::SafePointer<Component> deletionChecker (this);
  38893. textWasEdited();
  38894. if (deletionChecker != 0)
  38895. callChangeListeners();
  38896. }
  38897. }
  38898. }
  38899. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38900. {
  38901. if (editor != 0)
  38902. {
  38903. jassert (&ed == editor);
  38904. (void) ed;
  38905. editor->setText (textValue.toString(), false);
  38906. hideEditor (true);
  38907. }
  38908. }
  38909. void Label::textEditorFocusLost (TextEditor& ed)
  38910. {
  38911. textEditorTextChanged (ed);
  38912. }
  38913. END_JUCE_NAMESPACE
  38914. /*** End of inlined file: juce_Label.cpp ***/
  38915. /*** Start of inlined file: juce_ListBox.cpp ***/
  38916. BEGIN_JUCE_NAMESPACE
  38917. class ListBoxRowComponent : public Component,
  38918. public TooltipClient
  38919. {
  38920. public:
  38921. ListBoxRowComponent (ListBox& owner_)
  38922. : owner (owner_),
  38923. row (-1),
  38924. selected (false),
  38925. isDragging (false)
  38926. {
  38927. }
  38928. ~ListBoxRowComponent()
  38929. {
  38930. deleteAllChildren();
  38931. }
  38932. void paint (Graphics& g)
  38933. {
  38934. if (owner.getModel() != 0)
  38935. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38936. }
  38937. void update (const int row_, const bool selected_)
  38938. {
  38939. if (row != row_ || selected != selected_)
  38940. {
  38941. repaint();
  38942. row = row_;
  38943. selected = selected_;
  38944. }
  38945. if (owner.getModel() != 0)
  38946. {
  38947. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38948. if (customComp != 0)
  38949. {
  38950. addAndMakeVisible (customComp);
  38951. customComp->setBounds (getLocalBounds());
  38952. for (int i = getNumChildComponents(); --i >= 0;)
  38953. if (getChildComponent (i) != customComp)
  38954. delete getChildComponent (i);
  38955. }
  38956. else
  38957. {
  38958. deleteAllChildren();
  38959. }
  38960. }
  38961. }
  38962. void mouseDown (const MouseEvent& e)
  38963. {
  38964. isDragging = false;
  38965. selectRowOnMouseUp = false;
  38966. if (isEnabled())
  38967. {
  38968. if (! selected)
  38969. {
  38970. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38971. if (owner.getModel() != 0)
  38972. owner.getModel()->listBoxItemClicked (row, e);
  38973. }
  38974. else
  38975. {
  38976. selectRowOnMouseUp = true;
  38977. }
  38978. }
  38979. }
  38980. void mouseUp (const MouseEvent& e)
  38981. {
  38982. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38983. {
  38984. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38985. if (owner.getModel() != 0)
  38986. owner.getModel()->listBoxItemClicked (row, e);
  38987. }
  38988. }
  38989. void mouseDoubleClick (const MouseEvent& e)
  38990. {
  38991. if (owner.getModel() != 0 && isEnabled())
  38992. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38993. }
  38994. void mouseDrag (const MouseEvent& e)
  38995. {
  38996. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38997. {
  38998. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38999. if (selectedRows.size() > 0)
  39000. {
  39001. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39002. if (dragDescription.isNotEmpty())
  39003. {
  39004. isDragging = true;
  39005. owner.startDragAndDrop (e, dragDescription);
  39006. }
  39007. }
  39008. }
  39009. }
  39010. void resized()
  39011. {
  39012. if (getNumChildComponents() > 0)
  39013. getChildComponent(0)->setBounds (getLocalBounds());
  39014. }
  39015. const String getTooltip()
  39016. {
  39017. if (owner.getModel() != 0)
  39018. return owner.getModel()->getTooltipForRow (row);
  39019. return String::empty;
  39020. }
  39021. juce_UseDebuggingNewOperator
  39022. bool neededFlag;
  39023. private:
  39024. ListBox& owner;
  39025. int row;
  39026. bool selected, isDragging, selectRowOnMouseUp;
  39027. ListBoxRowComponent (const ListBoxRowComponent&);
  39028. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39029. };
  39030. class ListViewport : public Viewport
  39031. {
  39032. public:
  39033. int firstIndex, firstWholeIndex, lastWholeIndex;
  39034. bool hasUpdated;
  39035. ListViewport (ListBox& owner_)
  39036. : owner (owner_)
  39037. {
  39038. setWantsKeyboardFocus (false);
  39039. setViewedComponent (new Component());
  39040. getViewedComponent()->addMouseListener (this, false);
  39041. getViewedComponent()->setWantsKeyboardFocus (false);
  39042. }
  39043. ~ListViewport()
  39044. {
  39045. getViewedComponent()->removeMouseListener (this);
  39046. getViewedComponent()->deleteAllChildren();
  39047. }
  39048. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39049. {
  39050. return static_cast <ListBoxRowComponent*>
  39051. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  39052. }
  39053. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39054. {
  39055. const int index = getIndexOfChildComponent (rowComponent);
  39056. const int num = getViewedComponent()->getNumChildComponents();
  39057. for (int i = num; --i >= 0;)
  39058. if (((firstIndex + i) % jmax (1, num)) == index)
  39059. return firstIndex + i;
  39060. return -1;
  39061. }
  39062. Component* getComponentForRowIfOnscreen (const int row) const throw()
  39063. {
  39064. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  39065. ? getComponentForRow (row) : 0;
  39066. }
  39067. void visibleAreaChanged (int, int, int, int)
  39068. {
  39069. updateVisibleArea (true);
  39070. if (owner.getModel() != 0)
  39071. owner.getModel()->listWasScrolled();
  39072. }
  39073. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39074. {
  39075. hasUpdated = false;
  39076. const int newX = getViewedComponent()->getX();
  39077. int newY = getViewedComponent()->getY();
  39078. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39079. const int newH = owner.totalItems * owner.getRowHeight();
  39080. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39081. newY = getMaximumVisibleHeight() - newH;
  39082. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39083. if (makeSureItUpdatesContent && ! hasUpdated)
  39084. updateContents();
  39085. }
  39086. void updateContents()
  39087. {
  39088. hasUpdated = true;
  39089. const int rowHeight = owner.getRowHeight();
  39090. if (rowHeight > 0)
  39091. {
  39092. const int y = getViewPositionY();
  39093. const int w = getViewedComponent()->getWidth();
  39094. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39095. while (numNeeded > getViewedComponent()->getNumChildComponents())
  39096. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  39097. jassert (numNeeded >= 0);
  39098. while (numNeeded < getViewedComponent()->getNumChildComponents())
  39099. {
  39100. Component* const rowToRemove
  39101. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  39102. delete rowToRemove;
  39103. }
  39104. firstIndex = y / rowHeight;
  39105. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39106. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39107. for (int i = 0; i < numNeeded; ++i)
  39108. {
  39109. const int row = i + firstIndex;
  39110. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39111. if (rowComp != 0)
  39112. {
  39113. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39114. rowComp->update (row, owner.isRowSelected (row));
  39115. }
  39116. }
  39117. }
  39118. if (owner.headerComponent != 0)
  39119. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39120. owner.outlineThickness,
  39121. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39122. getViewedComponent()->getWidth()),
  39123. owner.headerComponent->getHeight());
  39124. }
  39125. void paint (Graphics& g)
  39126. {
  39127. if (isOpaque())
  39128. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39129. }
  39130. bool keyPressed (const KeyPress& key)
  39131. {
  39132. if (key.isKeyCode (KeyPress::upKey)
  39133. || key.isKeyCode (KeyPress::downKey)
  39134. || key.isKeyCode (KeyPress::pageUpKey)
  39135. || key.isKeyCode (KeyPress::pageDownKey)
  39136. || key.isKeyCode (KeyPress::homeKey)
  39137. || key.isKeyCode (KeyPress::endKey))
  39138. {
  39139. // we want to avoid these keypresses going to the viewport, and instead allow
  39140. // them to pass up to our listbox..
  39141. return false;
  39142. }
  39143. return Viewport::keyPressed (key);
  39144. }
  39145. juce_UseDebuggingNewOperator
  39146. private:
  39147. ListBox& owner;
  39148. ListViewport (const ListViewport&);
  39149. ListViewport& operator= (const ListViewport&);
  39150. };
  39151. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39152. : Component (name),
  39153. model (model_),
  39154. totalItems (0),
  39155. rowHeight (22),
  39156. minimumRowWidth (0),
  39157. outlineThickness (0),
  39158. lastRowSelected (-1),
  39159. mouseMoveSelects (false),
  39160. multipleSelection (false),
  39161. hasDoneInitialUpdate (false)
  39162. {
  39163. addAndMakeVisible (viewport = new ListViewport (*this));
  39164. setWantsKeyboardFocus (true);
  39165. colourChanged();
  39166. }
  39167. ListBox::~ListBox()
  39168. {
  39169. headerComponent = 0;
  39170. viewport = 0;
  39171. }
  39172. void ListBox::setModel (ListBoxModel* const newModel)
  39173. {
  39174. if (model != newModel)
  39175. {
  39176. model = newModel;
  39177. updateContent();
  39178. }
  39179. }
  39180. void ListBox::setMultipleSelectionEnabled (bool b)
  39181. {
  39182. multipleSelection = b;
  39183. }
  39184. void ListBox::setMouseMoveSelectsRows (bool b)
  39185. {
  39186. mouseMoveSelects = b;
  39187. if (b)
  39188. addMouseListener (this, true);
  39189. }
  39190. void ListBox::paint (Graphics& g)
  39191. {
  39192. if (! hasDoneInitialUpdate)
  39193. updateContent();
  39194. g.fillAll (findColour (backgroundColourId));
  39195. }
  39196. void ListBox::paintOverChildren (Graphics& g)
  39197. {
  39198. if (outlineThickness > 0)
  39199. {
  39200. g.setColour (findColour (outlineColourId));
  39201. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39202. }
  39203. }
  39204. void ListBox::resized()
  39205. {
  39206. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39207. outlineThickness,
  39208. outlineThickness,
  39209. outlineThickness));
  39210. viewport->setSingleStepSizes (20, getRowHeight());
  39211. viewport->updateVisibleArea (false);
  39212. }
  39213. void ListBox::visibilityChanged()
  39214. {
  39215. viewport->updateVisibleArea (true);
  39216. }
  39217. Viewport* ListBox::getViewport() const throw()
  39218. {
  39219. return viewport;
  39220. }
  39221. void ListBox::updateContent()
  39222. {
  39223. hasDoneInitialUpdate = true;
  39224. totalItems = (model != 0) ? model->getNumRows() : 0;
  39225. bool selectionChanged = false;
  39226. if (selected [selected.size() - 1] >= totalItems)
  39227. {
  39228. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39229. lastRowSelected = getSelectedRow (0);
  39230. selectionChanged = true;
  39231. }
  39232. viewport->updateVisibleArea (isVisible());
  39233. viewport->resized();
  39234. if (selectionChanged && model != 0)
  39235. model->selectedRowsChanged (lastRowSelected);
  39236. }
  39237. void ListBox::selectRow (const int row,
  39238. bool dontScroll,
  39239. bool deselectOthersFirst)
  39240. {
  39241. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39242. }
  39243. void ListBox::selectRowInternal (const int row,
  39244. bool dontScroll,
  39245. bool deselectOthersFirst,
  39246. bool isMouseClick)
  39247. {
  39248. if (! multipleSelection)
  39249. deselectOthersFirst = true;
  39250. if ((! isRowSelected (row))
  39251. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39252. {
  39253. if (((unsigned int) row) < (unsigned int) totalItems)
  39254. {
  39255. if (deselectOthersFirst)
  39256. selected.clear();
  39257. selected.addRange (Range<int> (row, row + 1));
  39258. if (getHeight() == 0 || getWidth() == 0)
  39259. dontScroll = true;
  39260. viewport->hasUpdated = false;
  39261. if (row < viewport->firstWholeIndex && ! dontScroll)
  39262. {
  39263. viewport->setViewPosition (viewport->getViewPositionX(),
  39264. row * getRowHeight());
  39265. }
  39266. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  39267. {
  39268. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  39269. if (row >= lastRowSelected + rowsOnScreen
  39270. && rowsOnScreen < totalItems - 1
  39271. && ! isMouseClick)
  39272. {
  39273. viewport->setViewPosition (viewport->getViewPositionX(),
  39274. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  39275. * getRowHeight());
  39276. }
  39277. else
  39278. {
  39279. viewport->setViewPosition (viewport->getViewPositionX(),
  39280. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39281. }
  39282. }
  39283. if (! viewport->hasUpdated)
  39284. viewport->updateContents();
  39285. lastRowSelected = row;
  39286. model->selectedRowsChanged (row);
  39287. }
  39288. else
  39289. {
  39290. if (deselectOthersFirst)
  39291. deselectAllRows();
  39292. }
  39293. }
  39294. }
  39295. void ListBox::deselectRow (const int row)
  39296. {
  39297. if (selected.contains (row))
  39298. {
  39299. selected.removeRange (Range <int> (row, row + 1));
  39300. if (row == lastRowSelected)
  39301. lastRowSelected = getSelectedRow (0);
  39302. viewport->updateContents();
  39303. model->selectedRowsChanged (lastRowSelected);
  39304. }
  39305. }
  39306. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39307. const bool sendNotificationEventToModel)
  39308. {
  39309. selected = setOfRowsToBeSelected;
  39310. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39311. if (! isRowSelected (lastRowSelected))
  39312. lastRowSelected = getSelectedRow (0);
  39313. viewport->updateContents();
  39314. if ((model != 0) && sendNotificationEventToModel)
  39315. model->selectedRowsChanged (lastRowSelected);
  39316. }
  39317. const SparseSet<int> ListBox::getSelectedRows() const
  39318. {
  39319. return selected;
  39320. }
  39321. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39322. {
  39323. if (multipleSelection && (firstRow != lastRow))
  39324. {
  39325. const int numRows = totalItems - 1;
  39326. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39327. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39328. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39329. jmax (firstRow, lastRow) + 1));
  39330. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39331. }
  39332. selectRowInternal (lastRow, false, false, true);
  39333. }
  39334. void ListBox::flipRowSelection (const int row)
  39335. {
  39336. if (isRowSelected (row))
  39337. deselectRow (row);
  39338. else
  39339. selectRowInternal (row, false, false, true);
  39340. }
  39341. void ListBox::deselectAllRows()
  39342. {
  39343. if (! selected.isEmpty())
  39344. {
  39345. selected.clear();
  39346. lastRowSelected = -1;
  39347. viewport->updateContents();
  39348. if (model != 0)
  39349. model->selectedRowsChanged (lastRowSelected);
  39350. }
  39351. }
  39352. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39353. const ModifierKeys& mods)
  39354. {
  39355. if (multipleSelection && mods.isCommandDown())
  39356. {
  39357. flipRowSelection (row);
  39358. }
  39359. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39360. {
  39361. selectRangeOfRows (lastRowSelected, row);
  39362. }
  39363. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39364. {
  39365. selectRowInternal (row, false, true, true);
  39366. }
  39367. }
  39368. int ListBox::getNumSelectedRows() const
  39369. {
  39370. return selected.size();
  39371. }
  39372. int ListBox::getSelectedRow (const int index) const
  39373. {
  39374. return (((unsigned int) index) < (unsigned int) selected.size())
  39375. ? selected [index] : -1;
  39376. }
  39377. bool ListBox::isRowSelected (const int row) const
  39378. {
  39379. return selected.contains (row);
  39380. }
  39381. int ListBox::getLastRowSelected() const
  39382. {
  39383. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39384. }
  39385. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39386. {
  39387. if (((unsigned int) x) < (unsigned int) getWidth())
  39388. {
  39389. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39390. if (((unsigned int) row) < (unsigned int) totalItems)
  39391. return row;
  39392. }
  39393. return -1;
  39394. }
  39395. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39396. {
  39397. if (((unsigned int) x) < (unsigned int) getWidth())
  39398. {
  39399. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39400. return jlimit (0, totalItems, row);
  39401. }
  39402. return -1;
  39403. }
  39404. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39405. {
  39406. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39407. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  39408. }
  39409. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39410. {
  39411. return viewport->getRowNumberOfComponent (rowComponent);
  39412. }
  39413. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39414. const bool relativeToComponentTopLeft) const throw()
  39415. {
  39416. int y = viewport->getY() + rowHeight * rowNumber;
  39417. if (relativeToComponentTopLeft)
  39418. y -= viewport->getViewPositionY();
  39419. return Rectangle<int> (viewport->getX(), y,
  39420. viewport->getViewedComponent()->getWidth(), rowHeight);
  39421. }
  39422. void ListBox::setVerticalPosition (const double proportion)
  39423. {
  39424. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39425. viewport->setViewPosition (viewport->getViewPositionX(),
  39426. jmax (0, roundToInt (proportion * offscreen)));
  39427. }
  39428. double ListBox::getVerticalPosition() const
  39429. {
  39430. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39431. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39432. : 0;
  39433. }
  39434. int ListBox::getVisibleRowWidth() const throw()
  39435. {
  39436. return viewport->getViewWidth();
  39437. }
  39438. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39439. {
  39440. if (row < viewport->firstWholeIndex)
  39441. {
  39442. viewport->setViewPosition (viewport->getViewPositionX(),
  39443. row * getRowHeight());
  39444. }
  39445. else if (row >= viewport->lastWholeIndex)
  39446. {
  39447. viewport->setViewPosition (viewport->getViewPositionX(),
  39448. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39449. }
  39450. }
  39451. bool ListBox::keyPressed (const KeyPress& key)
  39452. {
  39453. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39454. const bool multiple = multipleSelection
  39455. && (lastRowSelected >= 0)
  39456. && (key.getModifiers().isShiftDown()
  39457. || key.getModifiers().isCtrlDown()
  39458. || key.getModifiers().isCommandDown());
  39459. if (key.isKeyCode (KeyPress::upKey))
  39460. {
  39461. if (multiple)
  39462. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39463. else
  39464. selectRow (jmax (0, lastRowSelected - 1));
  39465. }
  39466. else if (key.isKeyCode (KeyPress::returnKey)
  39467. && isRowSelected (lastRowSelected))
  39468. {
  39469. if (model != 0)
  39470. model->returnKeyPressed (lastRowSelected);
  39471. }
  39472. else if (key.isKeyCode (KeyPress::pageUpKey))
  39473. {
  39474. if (multiple)
  39475. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39476. else
  39477. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39478. }
  39479. else if (key.isKeyCode (KeyPress::pageDownKey))
  39480. {
  39481. if (multiple)
  39482. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39483. else
  39484. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39485. }
  39486. else if (key.isKeyCode (KeyPress::homeKey))
  39487. {
  39488. if (multiple && key.getModifiers().isShiftDown())
  39489. selectRangeOfRows (lastRowSelected, 0);
  39490. else
  39491. selectRow (0);
  39492. }
  39493. else if (key.isKeyCode (KeyPress::endKey))
  39494. {
  39495. if (multiple && key.getModifiers().isShiftDown())
  39496. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39497. else
  39498. selectRow (totalItems - 1);
  39499. }
  39500. else if (key.isKeyCode (KeyPress::downKey))
  39501. {
  39502. if (multiple)
  39503. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39504. else
  39505. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39506. }
  39507. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39508. && isRowSelected (lastRowSelected))
  39509. {
  39510. if (model != 0)
  39511. model->deleteKeyPressed (lastRowSelected);
  39512. }
  39513. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39514. {
  39515. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39516. }
  39517. else
  39518. {
  39519. return false;
  39520. }
  39521. return true;
  39522. }
  39523. bool ListBox::keyStateChanged (const bool isKeyDown)
  39524. {
  39525. return isKeyDown
  39526. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39527. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39528. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39529. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39530. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39531. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39532. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39533. }
  39534. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39535. {
  39536. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39537. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39538. }
  39539. void ListBox::mouseMove (const MouseEvent& e)
  39540. {
  39541. if (mouseMoveSelects)
  39542. {
  39543. const MouseEvent e2 (e.getEventRelativeTo (this));
  39544. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39545. }
  39546. }
  39547. void ListBox::mouseExit (const MouseEvent& e)
  39548. {
  39549. mouseMove (e);
  39550. }
  39551. void ListBox::mouseUp (const MouseEvent& e)
  39552. {
  39553. if (e.mouseWasClicked() && model != 0)
  39554. model->backgroundClicked();
  39555. }
  39556. void ListBox::setRowHeight (const int newHeight)
  39557. {
  39558. rowHeight = jmax (1, newHeight);
  39559. viewport->setSingleStepSizes (20, rowHeight);
  39560. updateContent();
  39561. }
  39562. int ListBox::getNumRowsOnScreen() const throw()
  39563. {
  39564. return viewport->getMaximumVisibleHeight() / rowHeight;
  39565. }
  39566. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39567. {
  39568. minimumRowWidth = newMinimumWidth;
  39569. updateContent();
  39570. }
  39571. int ListBox::getVisibleContentWidth() const throw()
  39572. {
  39573. return viewport->getMaximumVisibleWidth();
  39574. }
  39575. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39576. {
  39577. return viewport->getVerticalScrollBar();
  39578. }
  39579. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39580. {
  39581. return viewport->getHorizontalScrollBar();
  39582. }
  39583. void ListBox::colourChanged()
  39584. {
  39585. setOpaque (findColour (backgroundColourId).isOpaque());
  39586. viewport->setOpaque (isOpaque());
  39587. repaint();
  39588. }
  39589. void ListBox::setOutlineThickness (const int outlineThickness_)
  39590. {
  39591. outlineThickness = outlineThickness_;
  39592. resized();
  39593. }
  39594. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39595. {
  39596. if (newHeaderComponent != headerComponent)
  39597. {
  39598. headerComponent = newHeaderComponent;
  39599. addAndMakeVisible (newHeaderComponent);
  39600. ListBox::resized();
  39601. }
  39602. }
  39603. void ListBox::repaintRow (const int rowNumber) throw()
  39604. {
  39605. repaint (getRowPosition (rowNumber, true));
  39606. }
  39607. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39608. {
  39609. Rectangle<int> imageArea;
  39610. const int firstRow = getRowContainingPosition (0, 0);
  39611. int i;
  39612. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39613. {
  39614. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39615. if (rowComp != 0 && isRowSelected (firstRow + i))
  39616. {
  39617. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39618. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39619. imageArea = imageArea.getUnion (rowRect);
  39620. }
  39621. }
  39622. imageArea = imageArea.getIntersection (getLocalBounds());
  39623. imageX = imageArea.getX();
  39624. imageY = imageArea.getY();
  39625. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39626. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39627. {
  39628. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39629. if (rowComp != 0 && isRowSelected (firstRow + i))
  39630. {
  39631. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39632. Graphics g (snapshot);
  39633. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39634. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  39635. rowComp->paintEntireComponent (g);
  39636. }
  39637. }
  39638. return snapshot;
  39639. }
  39640. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39641. {
  39642. DragAndDropContainer* const dragContainer
  39643. = DragAndDropContainer::findParentDragContainerFor (this);
  39644. if (dragContainer != 0)
  39645. {
  39646. int x, y;
  39647. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39648. dragImage.multiplyAllAlphas (0.6f);
  39649. MouseEvent e2 (e.getEventRelativeTo (this));
  39650. const Point<int> p (x - e2.x, y - e2.y);
  39651. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39652. }
  39653. else
  39654. {
  39655. // to be able to do a drag-and-drop operation, the listbox needs to
  39656. // be inside a component which is also a DragAndDropContainer.
  39657. jassertfalse;
  39658. }
  39659. }
  39660. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39661. {
  39662. (void) existingComponentToUpdate;
  39663. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39664. return 0;
  39665. }
  39666. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  39667. {
  39668. }
  39669. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  39670. {
  39671. }
  39672. void ListBoxModel::backgroundClicked()
  39673. {
  39674. }
  39675. void ListBoxModel::selectedRowsChanged (int)
  39676. {
  39677. }
  39678. void ListBoxModel::deleteKeyPressed (int)
  39679. {
  39680. }
  39681. void ListBoxModel::returnKeyPressed (int)
  39682. {
  39683. }
  39684. void ListBoxModel::listWasScrolled()
  39685. {
  39686. }
  39687. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  39688. {
  39689. return String::empty;
  39690. }
  39691. const String ListBoxModel::getTooltipForRow (int)
  39692. {
  39693. return String::empty;
  39694. }
  39695. END_JUCE_NAMESPACE
  39696. /*** End of inlined file: juce_ListBox.cpp ***/
  39697. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39698. BEGIN_JUCE_NAMESPACE
  39699. ProgressBar::ProgressBar (double& progress_)
  39700. : progress (progress_),
  39701. displayPercentage (true),
  39702. lastCallbackTime (0)
  39703. {
  39704. currentValue = jlimit (0.0, 1.0, progress);
  39705. }
  39706. ProgressBar::~ProgressBar()
  39707. {
  39708. }
  39709. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39710. {
  39711. displayPercentage = shouldDisplayPercentage;
  39712. repaint();
  39713. }
  39714. void ProgressBar::setTextToDisplay (const String& text)
  39715. {
  39716. displayPercentage = false;
  39717. displayedMessage = text;
  39718. }
  39719. void ProgressBar::lookAndFeelChanged()
  39720. {
  39721. setOpaque (findColour (backgroundColourId).isOpaque());
  39722. }
  39723. void ProgressBar::colourChanged()
  39724. {
  39725. lookAndFeelChanged();
  39726. }
  39727. void ProgressBar::paint (Graphics& g)
  39728. {
  39729. String text;
  39730. if (displayPercentage)
  39731. {
  39732. if (currentValue >= 0 && currentValue <= 1.0)
  39733. text << roundToInt (currentValue * 100.0) << '%';
  39734. }
  39735. else
  39736. {
  39737. text = displayedMessage;
  39738. }
  39739. getLookAndFeel().drawProgressBar (g, *this,
  39740. getWidth(), getHeight(),
  39741. currentValue, text);
  39742. }
  39743. void ProgressBar::visibilityChanged()
  39744. {
  39745. if (isVisible())
  39746. startTimer (30);
  39747. else
  39748. stopTimer();
  39749. }
  39750. void ProgressBar::timerCallback()
  39751. {
  39752. double newProgress = progress;
  39753. const uint32 now = Time::getMillisecondCounter();
  39754. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39755. lastCallbackTime = now;
  39756. if (currentValue != newProgress
  39757. || newProgress < 0 || newProgress >= 1.0
  39758. || currentMessage != displayedMessage)
  39759. {
  39760. if (currentValue < newProgress
  39761. && newProgress >= 0 && newProgress < 1.0
  39762. && currentValue >= 0 && currentValue < 1.0)
  39763. {
  39764. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39765. newProgress);
  39766. }
  39767. currentValue = newProgress;
  39768. currentMessage = displayedMessage;
  39769. repaint();
  39770. }
  39771. }
  39772. END_JUCE_NAMESPACE
  39773. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39774. /*** Start of inlined file: juce_Slider.cpp ***/
  39775. BEGIN_JUCE_NAMESPACE
  39776. class SliderPopupDisplayComponent : public BubbleComponent
  39777. {
  39778. public:
  39779. SliderPopupDisplayComponent (Slider* const owner_)
  39780. : owner (owner_),
  39781. font (15.0f, Font::bold)
  39782. {
  39783. setAlwaysOnTop (true);
  39784. }
  39785. ~SliderPopupDisplayComponent()
  39786. {
  39787. }
  39788. void paintContent (Graphics& g, int w, int h)
  39789. {
  39790. g.setFont (font);
  39791. g.setColour (Colours::black);
  39792. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39793. }
  39794. void getContentSize (int& w, int& h)
  39795. {
  39796. w = font.getStringWidth (text) + 18;
  39797. h = (int) (font.getHeight() * 1.6f);
  39798. }
  39799. void updatePosition (const String& newText)
  39800. {
  39801. if (text != newText)
  39802. {
  39803. text = newText;
  39804. repaint();
  39805. }
  39806. BubbleComponent::setPosition (owner);
  39807. }
  39808. juce_UseDebuggingNewOperator
  39809. private:
  39810. Slider* owner;
  39811. Font font;
  39812. String text;
  39813. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39814. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39815. };
  39816. Slider::Slider (const String& name)
  39817. : Component (name),
  39818. lastCurrentValue (0),
  39819. lastValueMin (0),
  39820. lastValueMax (0),
  39821. minimum (0),
  39822. maximum (10),
  39823. interval (0),
  39824. skewFactor (1.0),
  39825. velocityModeSensitivity (1.0),
  39826. velocityModeOffset (0.0),
  39827. velocityModeThreshold (1),
  39828. rotaryStart (float_Pi * 1.2f),
  39829. rotaryEnd (float_Pi * 2.8f),
  39830. numDecimalPlaces (7),
  39831. sliderRegionStart (0),
  39832. sliderRegionSize (1),
  39833. sliderBeingDragged (-1),
  39834. pixelsForFullDragExtent (250),
  39835. style (LinearHorizontal),
  39836. textBoxPos (TextBoxLeft),
  39837. textBoxWidth (80),
  39838. textBoxHeight (20),
  39839. incDecButtonMode (incDecButtonsNotDraggable),
  39840. editableText (true),
  39841. doubleClickToValue (false),
  39842. isVelocityBased (false),
  39843. userKeyOverridesVelocity (true),
  39844. rotaryStop (true),
  39845. incDecButtonsSideBySide (false),
  39846. sendChangeOnlyOnRelease (false),
  39847. popupDisplayEnabled (false),
  39848. menuEnabled (false),
  39849. menuShown (false),
  39850. scrollWheelEnabled (true),
  39851. snapsToMousePos (true),
  39852. valueBox (0),
  39853. incButton (0),
  39854. decButton (0),
  39855. popupDisplay (0),
  39856. parentForPopupDisplay (0)
  39857. {
  39858. setWantsKeyboardFocus (false);
  39859. setRepaintsOnMouseActivity (true);
  39860. lookAndFeelChanged();
  39861. updateText();
  39862. currentValue.addListener (this);
  39863. valueMin.addListener (this);
  39864. valueMax.addListener (this);
  39865. }
  39866. Slider::~Slider()
  39867. {
  39868. currentValue.removeListener (this);
  39869. valueMin.removeListener (this);
  39870. valueMax.removeListener (this);
  39871. popupDisplay = 0;
  39872. deleteAllChildren();
  39873. }
  39874. void Slider::handleAsyncUpdate()
  39875. {
  39876. cancelPendingUpdate();
  39877. Component::BailOutChecker checker (this);
  39878. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39879. }
  39880. void Slider::sendDragStart()
  39881. {
  39882. startedDragging();
  39883. Component::BailOutChecker checker (this);
  39884. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39885. }
  39886. void Slider::sendDragEnd()
  39887. {
  39888. stoppedDragging();
  39889. sliderBeingDragged = -1;
  39890. Component::BailOutChecker checker (this);
  39891. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39892. }
  39893. void Slider::addListener (Listener* const listener)
  39894. {
  39895. listeners.add (listener);
  39896. }
  39897. void Slider::removeListener (Listener* const listener)
  39898. {
  39899. listeners.remove (listener);
  39900. }
  39901. void Slider::setSliderStyle (const SliderStyle newStyle)
  39902. {
  39903. if (style != newStyle)
  39904. {
  39905. style = newStyle;
  39906. repaint();
  39907. lookAndFeelChanged();
  39908. }
  39909. }
  39910. void Slider::setRotaryParameters (const float startAngleRadians,
  39911. const float endAngleRadians,
  39912. const bool stopAtEnd)
  39913. {
  39914. // make sure the values are sensible..
  39915. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39916. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39917. jassert (rotaryStart < rotaryEnd);
  39918. rotaryStart = startAngleRadians;
  39919. rotaryEnd = endAngleRadians;
  39920. rotaryStop = stopAtEnd;
  39921. }
  39922. void Slider::setVelocityBasedMode (const bool velBased)
  39923. {
  39924. isVelocityBased = velBased;
  39925. }
  39926. void Slider::setVelocityModeParameters (const double sensitivity,
  39927. const int threshold,
  39928. const double offset,
  39929. const bool userCanPressKeyToSwapMode)
  39930. {
  39931. jassert (threshold >= 0);
  39932. jassert (sensitivity > 0);
  39933. jassert (offset >= 0);
  39934. velocityModeSensitivity = sensitivity;
  39935. velocityModeOffset = offset;
  39936. velocityModeThreshold = threshold;
  39937. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39938. }
  39939. void Slider::setSkewFactor (const double factor)
  39940. {
  39941. skewFactor = factor;
  39942. }
  39943. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39944. {
  39945. if (maximum > minimum)
  39946. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39947. / (maximum - minimum));
  39948. }
  39949. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39950. {
  39951. jassert (distanceForFullScaleDrag > 0);
  39952. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39953. }
  39954. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39955. {
  39956. if (incDecButtonMode != mode)
  39957. {
  39958. incDecButtonMode = mode;
  39959. lookAndFeelChanged();
  39960. }
  39961. }
  39962. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39963. const bool isReadOnly,
  39964. const int textEntryBoxWidth,
  39965. const int textEntryBoxHeight)
  39966. {
  39967. if (textBoxPos != newPosition
  39968. || editableText != (! isReadOnly)
  39969. || textBoxWidth != textEntryBoxWidth
  39970. || textBoxHeight != textEntryBoxHeight)
  39971. {
  39972. textBoxPos = newPosition;
  39973. editableText = ! isReadOnly;
  39974. textBoxWidth = textEntryBoxWidth;
  39975. textBoxHeight = textEntryBoxHeight;
  39976. repaint();
  39977. lookAndFeelChanged();
  39978. }
  39979. }
  39980. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39981. {
  39982. editableText = shouldBeEditable;
  39983. if (valueBox != 0)
  39984. valueBox->setEditable (shouldBeEditable && isEnabled());
  39985. }
  39986. void Slider::showTextBox()
  39987. {
  39988. jassert (editableText); // this should probably be avoided in read-only sliders.
  39989. if (valueBox != 0)
  39990. valueBox->showEditor();
  39991. }
  39992. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39993. {
  39994. if (valueBox != 0)
  39995. {
  39996. valueBox->hideEditor (discardCurrentEditorContents);
  39997. if (discardCurrentEditorContents)
  39998. updateText();
  39999. }
  40000. }
  40001. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40002. {
  40003. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40004. }
  40005. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40006. {
  40007. snapsToMousePos = shouldSnapToMouse;
  40008. }
  40009. void Slider::setPopupDisplayEnabled (const bool enabled,
  40010. Component* const parentComponentToUse)
  40011. {
  40012. popupDisplayEnabled = enabled;
  40013. parentForPopupDisplay = parentComponentToUse;
  40014. }
  40015. void Slider::colourChanged()
  40016. {
  40017. lookAndFeelChanged();
  40018. }
  40019. void Slider::lookAndFeelChanged()
  40020. {
  40021. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40022. : getTextFromValue (currentValue.getValue()));
  40023. deleteAllChildren();
  40024. valueBox = 0;
  40025. LookAndFeel& lf = getLookAndFeel();
  40026. if (textBoxPos != NoTextBox)
  40027. {
  40028. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40029. valueBox->setWantsKeyboardFocus (false);
  40030. valueBox->setText (previousTextBoxContent, false);
  40031. valueBox->setEditable (editableText && isEnabled());
  40032. valueBox->addListener (this);
  40033. if (style == LinearBar)
  40034. valueBox->addMouseListener (this, false);
  40035. valueBox->setTooltip (getTooltip());
  40036. }
  40037. if (style == IncDecButtons)
  40038. {
  40039. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40040. incButton->addButtonListener (this);
  40041. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40042. decButton->addButtonListener (this);
  40043. if (incDecButtonMode != incDecButtonsNotDraggable)
  40044. {
  40045. incButton->addMouseListener (this, false);
  40046. decButton->addMouseListener (this, false);
  40047. }
  40048. else
  40049. {
  40050. incButton->setRepeatSpeed (300, 100, 20);
  40051. incButton->addMouseListener (decButton, false);
  40052. decButton->setRepeatSpeed (300, 100, 20);
  40053. decButton->addMouseListener (incButton, false);
  40054. }
  40055. incButton->setTooltip (getTooltip());
  40056. decButton->setTooltip (getTooltip());
  40057. }
  40058. setComponentEffect (lf.getSliderEffect());
  40059. resized();
  40060. repaint();
  40061. }
  40062. void Slider::setRange (const double newMin,
  40063. const double newMax,
  40064. const double newInt)
  40065. {
  40066. if (minimum != newMin
  40067. || maximum != newMax
  40068. || interval != newInt)
  40069. {
  40070. minimum = newMin;
  40071. maximum = newMax;
  40072. interval = newInt;
  40073. // figure out the number of DPs needed to display all values at this
  40074. // interval setting.
  40075. numDecimalPlaces = 7;
  40076. if (newInt != 0)
  40077. {
  40078. int v = abs ((int) (newInt * 10000000));
  40079. while ((v % 10) == 0)
  40080. {
  40081. --numDecimalPlaces;
  40082. v /= 10;
  40083. }
  40084. }
  40085. // keep the current values inside the new range..
  40086. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40087. {
  40088. setValue (getValue(), false, false);
  40089. }
  40090. else
  40091. {
  40092. setMinValue (getMinValue(), false, false);
  40093. setMaxValue (getMaxValue(), false, false);
  40094. }
  40095. updateText();
  40096. }
  40097. }
  40098. void Slider::triggerChangeMessage (const bool synchronous)
  40099. {
  40100. if (synchronous)
  40101. handleAsyncUpdate();
  40102. else
  40103. triggerAsyncUpdate();
  40104. valueChanged();
  40105. }
  40106. void Slider::valueChanged (Value& value)
  40107. {
  40108. if (value.refersToSameSourceAs (currentValue))
  40109. {
  40110. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40111. setValue (currentValue.getValue(), false, false);
  40112. }
  40113. else if (value.refersToSameSourceAs (valueMin))
  40114. setMinValue (valueMin.getValue(), false, false, true);
  40115. else if (value.refersToSameSourceAs (valueMax))
  40116. setMaxValue (valueMax.getValue(), false, false, true);
  40117. }
  40118. double Slider::getValue() const
  40119. {
  40120. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40121. // methods to get the two values.
  40122. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40123. return currentValue.getValue();
  40124. }
  40125. void Slider::setValue (double newValue,
  40126. const bool sendUpdateMessage,
  40127. const bool sendMessageSynchronously)
  40128. {
  40129. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40130. // methods to set the two values.
  40131. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40132. newValue = constrainedValue (newValue);
  40133. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40134. {
  40135. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40136. newValue = jlimit ((double) valueMin.getValue(),
  40137. (double) valueMax.getValue(),
  40138. newValue);
  40139. }
  40140. if (newValue != lastCurrentValue)
  40141. {
  40142. if (valueBox != 0)
  40143. valueBox->hideEditor (true);
  40144. lastCurrentValue = newValue;
  40145. currentValue = newValue;
  40146. updateText();
  40147. repaint();
  40148. if (popupDisplay != 0)
  40149. {
  40150. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40151. ->updatePosition (getTextFromValue (newValue));
  40152. popupDisplay->repaint();
  40153. }
  40154. if (sendUpdateMessage)
  40155. triggerChangeMessage (sendMessageSynchronously);
  40156. }
  40157. }
  40158. double Slider::getMinValue() const
  40159. {
  40160. // The minimum value only applies to sliders that are in two- or three-value mode.
  40161. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40162. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40163. return valueMin.getValue();
  40164. }
  40165. double Slider::getMaxValue() const
  40166. {
  40167. // The maximum value only applies to sliders that are in two- or three-value mode.
  40168. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40169. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40170. return valueMax.getValue();
  40171. }
  40172. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40173. {
  40174. // The minimum value only applies to sliders that are in two- or three-value mode.
  40175. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40176. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40177. newValue = constrainedValue (newValue);
  40178. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40179. {
  40180. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40181. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40182. newValue = jmin ((double) valueMax.getValue(), newValue);
  40183. }
  40184. else
  40185. {
  40186. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40187. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40188. newValue = jmin (lastCurrentValue, newValue);
  40189. }
  40190. if (lastValueMin != newValue)
  40191. {
  40192. lastValueMin = newValue;
  40193. valueMin = newValue;
  40194. repaint();
  40195. if (popupDisplay != 0)
  40196. {
  40197. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40198. ->updatePosition (getTextFromValue (newValue));
  40199. popupDisplay->repaint();
  40200. }
  40201. if (sendUpdateMessage)
  40202. triggerChangeMessage (sendMessageSynchronously);
  40203. }
  40204. }
  40205. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40206. {
  40207. // The maximum value only applies to sliders that are in two- or three-value mode.
  40208. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40209. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40210. newValue = constrainedValue (newValue);
  40211. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40212. {
  40213. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40214. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40215. newValue = jmax ((double) valueMin.getValue(), newValue);
  40216. }
  40217. else
  40218. {
  40219. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40220. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40221. newValue = jmax (lastCurrentValue, newValue);
  40222. }
  40223. if (lastValueMax != newValue)
  40224. {
  40225. lastValueMax = newValue;
  40226. valueMax = newValue;
  40227. repaint();
  40228. if (popupDisplay != 0)
  40229. {
  40230. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40231. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40232. popupDisplay->repaint();
  40233. }
  40234. if (sendUpdateMessage)
  40235. triggerChangeMessage (sendMessageSynchronously);
  40236. }
  40237. }
  40238. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40239. const double valueToSetOnDoubleClick)
  40240. {
  40241. doubleClickToValue = isDoubleClickEnabled;
  40242. doubleClickReturnValue = valueToSetOnDoubleClick;
  40243. }
  40244. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40245. {
  40246. isEnabled_ = doubleClickToValue;
  40247. return doubleClickReturnValue;
  40248. }
  40249. void Slider::updateText()
  40250. {
  40251. if (valueBox != 0)
  40252. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40253. }
  40254. void Slider::setTextValueSuffix (const String& suffix)
  40255. {
  40256. if (textSuffix != suffix)
  40257. {
  40258. textSuffix = suffix;
  40259. updateText();
  40260. }
  40261. }
  40262. const String Slider::getTextValueSuffix() const
  40263. {
  40264. return textSuffix;
  40265. }
  40266. const String Slider::getTextFromValue (double v)
  40267. {
  40268. if (getNumDecimalPlacesToDisplay() > 0)
  40269. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40270. else
  40271. return String (roundToInt (v)) + getTextValueSuffix();
  40272. }
  40273. double Slider::getValueFromText (const String& text)
  40274. {
  40275. String t (text.trimStart());
  40276. if (t.endsWith (textSuffix))
  40277. t = t.substring (0, t.length() - textSuffix.length());
  40278. while (t.startsWithChar ('+'))
  40279. t = t.substring (1).trimStart();
  40280. return t.initialSectionContainingOnly ("0123456789.,-")
  40281. .getDoubleValue();
  40282. }
  40283. double Slider::proportionOfLengthToValue (double proportion)
  40284. {
  40285. if (skewFactor != 1.0 && proportion > 0.0)
  40286. proportion = exp (log (proportion) / skewFactor);
  40287. return minimum + (maximum - minimum) * proportion;
  40288. }
  40289. double Slider::valueToProportionOfLength (double value)
  40290. {
  40291. const double n = (value - minimum) / (maximum - minimum);
  40292. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40293. }
  40294. double Slider::snapValue (double attemptedValue, const bool)
  40295. {
  40296. return attemptedValue;
  40297. }
  40298. void Slider::startedDragging()
  40299. {
  40300. }
  40301. void Slider::stoppedDragging()
  40302. {
  40303. }
  40304. void Slider::valueChanged()
  40305. {
  40306. }
  40307. void Slider::enablementChanged()
  40308. {
  40309. repaint();
  40310. }
  40311. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40312. {
  40313. menuEnabled = menuEnabled_;
  40314. }
  40315. void Slider::setScrollWheelEnabled (const bool enabled)
  40316. {
  40317. scrollWheelEnabled = enabled;
  40318. }
  40319. void Slider::labelTextChanged (Label* label)
  40320. {
  40321. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40322. if (newValue != (double) currentValue.getValue())
  40323. {
  40324. sendDragStart();
  40325. setValue (newValue, true, true);
  40326. sendDragEnd();
  40327. }
  40328. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40329. }
  40330. void Slider::buttonClicked (Button* button)
  40331. {
  40332. if (style == IncDecButtons)
  40333. {
  40334. sendDragStart();
  40335. if (button == incButton)
  40336. setValue (snapValue (getValue() + interval, false), true, true);
  40337. else if (button == decButton)
  40338. setValue (snapValue (getValue() - interval, false), true, true);
  40339. sendDragEnd();
  40340. }
  40341. }
  40342. double Slider::constrainedValue (double value) const
  40343. {
  40344. if (interval > 0)
  40345. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40346. if (value <= minimum || maximum <= minimum)
  40347. value = minimum;
  40348. else if (value >= maximum)
  40349. value = maximum;
  40350. return value;
  40351. }
  40352. float Slider::getLinearSliderPos (const double value)
  40353. {
  40354. double sliderPosProportional;
  40355. if (maximum > minimum)
  40356. {
  40357. if (value < minimum)
  40358. {
  40359. sliderPosProportional = 0.0;
  40360. }
  40361. else if (value > maximum)
  40362. {
  40363. sliderPosProportional = 1.0;
  40364. }
  40365. else
  40366. {
  40367. sliderPosProportional = valueToProportionOfLength (value);
  40368. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40369. }
  40370. }
  40371. else
  40372. {
  40373. sliderPosProportional = 0.5;
  40374. }
  40375. if (isVertical() || style == IncDecButtons)
  40376. sliderPosProportional = 1.0 - sliderPosProportional;
  40377. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40378. }
  40379. bool Slider::isHorizontal() const
  40380. {
  40381. return style == LinearHorizontal
  40382. || style == LinearBar
  40383. || style == TwoValueHorizontal
  40384. || style == ThreeValueHorizontal;
  40385. }
  40386. bool Slider::isVertical() const
  40387. {
  40388. return style == LinearVertical
  40389. || style == TwoValueVertical
  40390. || style == ThreeValueVertical;
  40391. }
  40392. bool Slider::incDecDragDirectionIsHorizontal() const
  40393. {
  40394. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40395. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40396. }
  40397. float Slider::getPositionOfValue (const double value)
  40398. {
  40399. if (isHorizontal() || isVertical())
  40400. {
  40401. return getLinearSliderPos (value);
  40402. }
  40403. else
  40404. {
  40405. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40406. return 0.0f;
  40407. }
  40408. }
  40409. void Slider::paint (Graphics& g)
  40410. {
  40411. if (style != IncDecButtons)
  40412. {
  40413. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40414. {
  40415. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40416. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40417. getLookAndFeel().drawRotarySlider (g,
  40418. sliderRect.getX(),
  40419. sliderRect.getY(),
  40420. sliderRect.getWidth(),
  40421. sliderRect.getHeight(),
  40422. sliderPos,
  40423. rotaryStart, rotaryEnd,
  40424. *this);
  40425. }
  40426. else
  40427. {
  40428. getLookAndFeel().drawLinearSlider (g,
  40429. sliderRect.getX(),
  40430. sliderRect.getY(),
  40431. sliderRect.getWidth(),
  40432. sliderRect.getHeight(),
  40433. getLinearSliderPos (lastCurrentValue),
  40434. getLinearSliderPos (lastValueMin),
  40435. getLinearSliderPos (lastValueMax),
  40436. style,
  40437. *this);
  40438. }
  40439. if (style == LinearBar && valueBox == 0)
  40440. {
  40441. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40442. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40443. }
  40444. }
  40445. }
  40446. void Slider::resized()
  40447. {
  40448. int minXSpace = 0;
  40449. int minYSpace = 0;
  40450. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40451. minXSpace = 30;
  40452. else
  40453. minYSpace = 15;
  40454. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40455. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40456. if (style == LinearBar)
  40457. {
  40458. if (valueBox != 0)
  40459. valueBox->setBounds (getLocalBounds());
  40460. }
  40461. else
  40462. {
  40463. if (textBoxPos == NoTextBox)
  40464. {
  40465. sliderRect = getLocalBounds();
  40466. }
  40467. else if (textBoxPos == TextBoxLeft)
  40468. {
  40469. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40470. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40471. }
  40472. else if (textBoxPos == TextBoxRight)
  40473. {
  40474. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40475. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40476. }
  40477. else if (textBoxPos == TextBoxAbove)
  40478. {
  40479. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40480. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40481. }
  40482. else if (textBoxPos == TextBoxBelow)
  40483. {
  40484. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40485. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40486. }
  40487. }
  40488. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40489. if (style == LinearBar)
  40490. {
  40491. const int barIndent = 1;
  40492. sliderRegionStart = barIndent;
  40493. sliderRegionSize = getWidth() - barIndent * 2;
  40494. sliderRect.setBounds (sliderRegionStart, barIndent,
  40495. sliderRegionSize, getHeight() - barIndent * 2);
  40496. }
  40497. else if (isHorizontal())
  40498. {
  40499. sliderRegionStart = sliderRect.getX() + indent;
  40500. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40501. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40502. sliderRegionSize, sliderRect.getHeight());
  40503. }
  40504. else if (isVertical())
  40505. {
  40506. sliderRegionStart = sliderRect.getY() + indent;
  40507. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40508. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40509. sliderRect.getWidth(), sliderRegionSize);
  40510. }
  40511. else
  40512. {
  40513. sliderRegionStart = 0;
  40514. sliderRegionSize = 100;
  40515. }
  40516. if (style == IncDecButtons)
  40517. {
  40518. Rectangle<int> buttonRect (sliderRect);
  40519. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40520. buttonRect.expand (-2, 0);
  40521. else
  40522. buttonRect.expand (0, -2);
  40523. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40524. if (incDecButtonsSideBySide)
  40525. {
  40526. decButton->setBounds (buttonRect.getX(),
  40527. buttonRect.getY(),
  40528. buttonRect.getWidth() / 2,
  40529. buttonRect.getHeight());
  40530. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40531. incButton->setBounds (buttonRect.getCentreX(),
  40532. buttonRect.getY(),
  40533. buttonRect.getWidth() / 2,
  40534. buttonRect.getHeight());
  40535. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40536. }
  40537. else
  40538. {
  40539. incButton->setBounds (buttonRect.getX(),
  40540. buttonRect.getY(),
  40541. buttonRect.getWidth(),
  40542. buttonRect.getHeight() / 2);
  40543. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40544. decButton->setBounds (buttonRect.getX(),
  40545. buttonRect.getCentreY(),
  40546. buttonRect.getWidth(),
  40547. buttonRect.getHeight() / 2);
  40548. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40549. }
  40550. }
  40551. }
  40552. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40553. {
  40554. repaint();
  40555. }
  40556. void Slider::mouseDown (const MouseEvent& e)
  40557. {
  40558. mouseWasHidden = false;
  40559. incDecDragged = false;
  40560. mouseXWhenLastDragged = e.x;
  40561. mouseYWhenLastDragged = e.y;
  40562. mouseDragStartX = e.getMouseDownX();
  40563. mouseDragStartY = e.getMouseDownY();
  40564. if (isEnabled())
  40565. {
  40566. if (e.mods.isPopupMenu() && menuEnabled)
  40567. {
  40568. menuShown = true;
  40569. PopupMenu m;
  40570. m.setLookAndFeel (&getLookAndFeel());
  40571. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40572. m.addSeparator();
  40573. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40574. {
  40575. PopupMenu rotaryMenu;
  40576. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40577. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40578. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40579. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40580. }
  40581. const int r = m.show();
  40582. if (r == 1)
  40583. {
  40584. setVelocityBasedMode (! isVelocityBased);
  40585. }
  40586. else if (r == 2)
  40587. {
  40588. setSliderStyle (Rotary);
  40589. }
  40590. else if (r == 3)
  40591. {
  40592. setSliderStyle (RotaryHorizontalDrag);
  40593. }
  40594. else if (r == 4)
  40595. {
  40596. setSliderStyle (RotaryVerticalDrag);
  40597. }
  40598. }
  40599. else if (maximum > minimum)
  40600. {
  40601. menuShown = false;
  40602. if (valueBox != 0)
  40603. valueBox->hideEditor (true);
  40604. sliderBeingDragged = 0;
  40605. if (style == TwoValueHorizontal
  40606. || style == TwoValueVertical
  40607. || style == ThreeValueHorizontal
  40608. || style == ThreeValueVertical)
  40609. {
  40610. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40611. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40612. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40613. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40614. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40615. {
  40616. if (maxPosDistance <= minPosDistance)
  40617. sliderBeingDragged = 2;
  40618. else
  40619. sliderBeingDragged = 1;
  40620. }
  40621. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40622. {
  40623. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40624. sliderBeingDragged = 1;
  40625. else if (normalPosDistance >= maxPosDistance)
  40626. sliderBeingDragged = 2;
  40627. }
  40628. }
  40629. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40630. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40631. * valueToProportionOfLength (currentValue.getValue());
  40632. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40633. : ((sliderBeingDragged == 1) ? valueMin
  40634. : currentValue)).getValue();
  40635. valueOnMouseDown = valueWhenLastDragged;
  40636. if (popupDisplayEnabled)
  40637. {
  40638. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40639. popupDisplay = popup;
  40640. if (parentForPopupDisplay != 0)
  40641. {
  40642. parentForPopupDisplay->addChildComponent (popup);
  40643. }
  40644. else
  40645. {
  40646. popup->addToDesktop (0);
  40647. }
  40648. popup->setVisible (true);
  40649. }
  40650. sendDragStart();
  40651. mouseDrag (e);
  40652. }
  40653. }
  40654. }
  40655. void Slider::mouseUp (const MouseEvent&)
  40656. {
  40657. if (isEnabled()
  40658. && (! menuShown)
  40659. && (maximum > minimum)
  40660. && (style != IncDecButtons || incDecDragged))
  40661. {
  40662. restoreMouseIfHidden();
  40663. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40664. triggerChangeMessage (false);
  40665. sendDragEnd();
  40666. popupDisplay = 0;
  40667. if (style == IncDecButtons)
  40668. {
  40669. incButton->setState (Button::buttonNormal);
  40670. decButton->setState (Button::buttonNormal);
  40671. }
  40672. }
  40673. }
  40674. void Slider::restoreMouseIfHidden()
  40675. {
  40676. if (mouseWasHidden)
  40677. {
  40678. mouseWasHidden = false;
  40679. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40680. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40681. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40682. : ((sliderBeingDragged == 1) ? getMinValue()
  40683. : (double) currentValue.getValue());
  40684. Point<int> mousePos;
  40685. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40686. {
  40687. mousePos = Desktop::getLastMouseDownPosition();
  40688. if (style == RotaryHorizontalDrag)
  40689. {
  40690. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40691. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40692. }
  40693. else
  40694. {
  40695. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40696. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40697. }
  40698. }
  40699. else
  40700. {
  40701. const int pixelPos = (int) getLinearSliderPos (pos);
  40702. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40703. isVertical() ? pixelPos : (getHeight() / 2)));
  40704. }
  40705. Desktop::setMousePosition (mousePos);
  40706. }
  40707. }
  40708. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40709. {
  40710. if (isEnabled()
  40711. && style != IncDecButtons
  40712. && style != Rotary
  40713. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40714. {
  40715. restoreMouseIfHidden();
  40716. }
  40717. }
  40718. static double smallestAngleBetween (double a1, double a2)
  40719. {
  40720. return jmin (std::abs (a1 - a2),
  40721. std::abs (a1 + double_Pi * 2.0 - a2),
  40722. std::abs (a2 + double_Pi * 2.0 - a1));
  40723. }
  40724. void Slider::mouseDrag (const MouseEvent& e)
  40725. {
  40726. if (isEnabled()
  40727. && (! menuShown)
  40728. && (maximum > minimum))
  40729. {
  40730. if (style == Rotary)
  40731. {
  40732. int dx = e.x - sliderRect.getCentreX();
  40733. int dy = e.y - sliderRect.getCentreY();
  40734. if (dx * dx + dy * dy > 25)
  40735. {
  40736. double angle = std::atan2 ((double) dx, (double) -dy);
  40737. while (angle < 0.0)
  40738. angle += double_Pi * 2.0;
  40739. if (rotaryStop && ! e.mouseWasClicked())
  40740. {
  40741. if (std::abs (angle - lastAngle) > double_Pi)
  40742. {
  40743. if (angle >= lastAngle)
  40744. angle -= double_Pi * 2.0;
  40745. else
  40746. angle += double_Pi * 2.0;
  40747. }
  40748. if (angle >= lastAngle)
  40749. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40750. else
  40751. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40752. }
  40753. else
  40754. {
  40755. while (angle < rotaryStart)
  40756. angle += double_Pi * 2.0;
  40757. if (angle > rotaryEnd)
  40758. {
  40759. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40760. angle = rotaryStart;
  40761. else
  40762. angle = rotaryEnd;
  40763. }
  40764. }
  40765. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40766. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40767. lastAngle = angle;
  40768. }
  40769. }
  40770. else
  40771. {
  40772. if (style == LinearBar && e.mouseWasClicked()
  40773. && valueBox != 0 && valueBox->isEditable())
  40774. return;
  40775. if (style == IncDecButtons && ! incDecDragged)
  40776. {
  40777. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40778. return;
  40779. incDecDragged = true;
  40780. mouseDragStartX = e.x;
  40781. mouseDragStartY = e.y;
  40782. }
  40783. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40784. : false))
  40785. || ((maximum - minimum) / sliderRegionSize < interval))
  40786. {
  40787. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40788. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40789. if (style == RotaryHorizontalDrag
  40790. || style == RotaryVerticalDrag
  40791. || style == IncDecButtons
  40792. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40793. && ! snapsToMousePos))
  40794. {
  40795. const int mouseDiff = (style == RotaryHorizontalDrag
  40796. || style == LinearHorizontal
  40797. || style == LinearBar
  40798. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40799. ? e.x - mouseDragStartX
  40800. : mouseDragStartY - e.y;
  40801. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40802. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40803. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40804. if (style == IncDecButtons)
  40805. {
  40806. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40807. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40808. }
  40809. }
  40810. else
  40811. {
  40812. if (isVertical())
  40813. scaledMousePos = 1.0 - scaledMousePos;
  40814. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40815. }
  40816. }
  40817. else
  40818. {
  40819. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40820. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40821. ? e.x - mouseXWhenLastDragged
  40822. : e.y - mouseYWhenLastDragged;
  40823. const double maxSpeed = jmax (200, sliderRegionSize);
  40824. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40825. if (speed != 0)
  40826. {
  40827. speed = 0.2 * velocityModeSensitivity
  40828. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40829. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40830. / maxSpeed))));
  40831. if (mouseDiff < 0)
  40832. speed = -speed;
  40833. if (isVertical() || style == RotaryVerticalDrag
  40834. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40835. speed = -speed;
  40836. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40837. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40838. e.source.enableUnboundedMouseMovement (true, false);
  40839. mouseWasHidden = true;
  40840. }
  40841. }
  40842. }
  40843. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40844. if (sliderBeingDragged == 0)
  40845. {
  40846. setValue (snapValue (valueWhenLastDragged, true),
  40847. ! sendChangeOnlyOnRelease, true);
  40848. }
  40849. else if (sliderBeingDragged == 1)
  40850. {
  40851. setMinValue (snapValue (valueWhenLastDragged, true),
  40852. ! sendChangeOnlyOnRelease, false, true);
  40853. if (e.mods.isShiftDown())
  40854. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40855. else
  40856. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40857. }
  40858. else
  40859. {
  40860. jassert (sliderBeingDragged == 2);
  40861. setMaxValue (snapValue (valueWhenLastDragged, true),
  40862. ! sendChangeOnlyOnRelease, false, true);
  40863. if (e.mods.isShiftDown())
  40864. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40865. else
  40866. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40867. }
  40868. mouseXWhenLastDragged = e.x;
  40869. mouseYWhenLastDragged = e.y;
  40870. }
  40871. }
  40872. void Slider::mouseDoubleClick (const MouseEvent&)
  40873. {
  40874. if (doubleClickToValue
  40875. && isEnabled()
  40876. && style != IncDecButtons
  40877. && minimum <= doubleClickReturnValue
  40878. && maximum >= doubleClickReturnValue)
  40879. {
  40880. sendDragStart();
  40881. setValue (doubleClickReturnValue, true, true);
  40882. sendDragEnd();
  40883. }
  40884. }
  40885. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40886. {
  40887. if (scrollWheelEnabled && isEnabled()
  40888. && style != TwoValueHorizontal
  40889. && style != TwoValueVertical)
  40890. {
  40891. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40892. {
  40893. if (valueBox != 0)
  40894. valueBox->hideEditor (false);
  40895. const double value = (double) currentValue.getValue();
  40896. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40897. const double currentPos = valueToProportionOfLength (value);
  40898. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40899. double delta = (newValue != value)
  40900. ? jmax (std::abs (newValue - value), interval) : 0;
  40901. if (value > newValue)
  40902. delta = -delta;
  40903. sendDragStart();
  40904. setValue (snapValue (value + delta, false), true, true);
  40905. sendDragEnd();
  40906. }
  40907. }
  40908. else
  40909. {
  40910. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40911. }
  40912. }
  40913. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40914. {
  40915. }
  40916. void SliderListener::sliderDragEnded (Slider*)
  40917. {
  40918. }
  40919. END_JUCE_NAMESPACE
  40920. /*** End of inlined file: juce_Slider.cpp ***/
  40921. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40922. BEGIN_JUCE_NAMESPACE
  40923. class DragOverlayComp : public Component
  40924. {
  40925. public:
  40926. DragOverlayComp (const Image& image_)
  40927. : image (image_)
  40928. {
  40929. image.duplicateIfShared();
  40930. image.multiplyAllAlphas (0.8f);
  40931. setAlwaysOnTop (true);
  40932. }
  40933. ~DragOverlayComp()
  40934. {
  40935. }
  40936. void paint (Graphics& g)
  40937. {
  40938. g.drawImageAt (image, 0, 0);
  40939. }
  40940. private:
  40941. Image image;
  40942. DragOverlayComp (const DragOverlayComp&);
  40943. DragOverlayComp& operator= (const DragOverlayComp&);
  40944. };
  40945. TableHeaderComponent::TableHeaderComponent()
  40946. : columnsChanged (false),
  40947. columnsResized (false),
  40948. sortChanged (false),
  40949. menuActive (true),
  40950. stretchToFit (false),
  40951. columnIdBeingResized (0),
  40952. columnIdBeingDragged (0),
  40953. columnIdUnderMouse (0),
  40954. lastDeliberateWidth (0)
  40955. {
  40956. }
  40957. TableHeaderComponent::~TableHeaderComponent()
  40958. {
  40959. dragOverlayComp = 0;
  40960. }
  40961. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40962. {
  40963. menuActive = hasMenu;
  40964. }
  40965. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40966. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40967. {
  40968. if (onlyCountVisibleColumns)
  40969. {
  40970. int num = 0;
  40971. for (int i = columns.size(); --i >= 0;)
  40972. if (columns.getUnchecked(i)->isVisible())
  40973. ++num;
  40974. return num;
  40975. }
  40976. else
  40977. {
  40978. return columns.size();
  40979. }
  40980. }
  40981. const String TableHeaderComponent::getColumnName (const int columnId) const
  40982. {
  40983. const ColumnInfo* const ci = getInfoForId (columnId);
  40984. return ci != 0 ? ci->name : String::empty;
  40985. }
  40986. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40987. {
  40988. ColumnInfo* const ci = getInfoForId (columnId);
  40989. if (ci != 0 && ci->name != newName)
  40990. {
  40991. ci->name = newName;
  40992. sendColumnsChanged();
  40993. }
  40994. }
  40995. void TableHeaderComponent::addColumn (const String& columnName,
  40996. const int columnId,
  40997. const int width,
  40998. const int minimumWidth,
  40999. const int maximumWidth,
  41000. const int propertyFlags,
  41001. const int insertIndex)
  41002. {
  41003. // can't have a duplicate or null ID!
  41004. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41005. jassert (width > 0);
  41006. ColumnInfo* const ci = new ColumnInfo();
  41007. ci->name = columnName;
  41008. ci->id = columnId;
  41009. ci->width = width;
  41010. ci->lastDeliberateWidth = width;
  41011. ci->minimumWidth = minimumWidth;
  41012. ci->maximumWidth = maximumWidth;
  41013. if (ci->maximumWidth < 0)
  41014. ci->maximumWidth = std::numeric_limits<int>::max();
  41015. jassert (ci->maximumWidth >= ci->minimumWidth);
  41016. ci->propertyFlags = propertyFlags;
  41017. columns.insert (insertIndex, ci);
  41018. sendColumnsChanged();
  41019. }
  41020. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41021. {
  41022. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41023. if (index >= 0)
  41024. {
  41025. columns.remove (index);
  41026. sortChanged = true;
  41027. sendColumnsChanged();
  41028. }
  41029. }
  41030. void TableHeaderComponent::removeAllColumns()
  41031. {
  41032. if (columns.size() > 0)
  41033. {
  41034. columns.clear();
  41035. sendColumnsChanged();
  41036. }
  41037. }
  41038. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41039. {
  41040. const int currentIndex = getIndexOfColumnId (columnId, false);
  41041. newIndex = visibleIndexToTotalIndex (newIndex);
  41042. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41043. {
  41044. columns.move (currentIndex, newIndex);
  41045. sendColumnsChanged();
  41046. }
  41047. }
  41048. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41049. {
  41050. const ColumnInfo* const ci = getInfoForId (columnId);
  41051. return ci != 0 ? ci->width : 0;
  41052. }
  41053. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41054. {
  41055. ColumnInfo* const ci = getInfoForId (columnId);
  41056. if (ci != 0 && ci->width != newWidth)
  41057. {
  41058. const int numColumns = getNumColumns (true);
  41059. ci->lastDeliberateWidth = ci->width
  41060. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41061. if (stretchToFit)
  41062. {
  41063. const int index = getIndexOfColumnId (columnId, true) + 1;
  41064. if (((unsigned int) index) < (unsigned int) numColumns)
  41065. {
  41066. const int x = getColumnPosition (index).getX();
  41067. if (lastDeliberateWidth == 0)
  41068. lastDeliberateWidth = getTotalWidth();
  41069. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41070. }
  41071. }
  41072. repaint();
  41073. columnsResized = true;
  41074. triggerAsyncUpdate();
  41075. }
  41076. }
  41077. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41078. {
  41079. int n = 0;
  41080. for (int i = 0; i < columns.size(); ++i)
  41081. {
  41082. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41083. {
  41084. if (columns.getUnchecked(i)->id == columnId)
  41085. return n;
  41086. ++n;
  41087. }
  41088. }
  41089. return -1;
  41090. }
  41091. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41092. {
  41093. if (onlyCountVisibleColumns)
  41094. index = visibleIndexToTotalIndex (index);
  41095. const ColumnInfo* const ci = columns [index];
  41096. return (ci != 0) ? ci->id : 0;
  41097. }
  41098. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41099. {
  41100. int x = 0, width = 0, n = 0;
  41101. for (int i = 0; i < columns.size(); ++i)
  41102. {
  41103. x += width;
  41104. if (columns.getUnchecked(i)->isVisible())
  41105. {
  41106. width = columns.getUnchecked(i)->width;
  41107. if (n++ == index)
  41108. break;
  41109. }
  41110. else
  41111. {
  41112. width = 0;
  41113. }
  41114. }
  41115. return Rectangle<int> (x, 0, width, getHeight());
  41116. }
  41117. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41118. {
  41119. if (xToFind >= 0)
  41120. {
  41121. int x = 0;
  41122. for (int i = 0; i < columns.size(); ++i)
  41123. {
  41124. const ColumnInfo* const ci = columns.getUnchecked(i);
  41125. if (ci->isVisible())
  41126. {
  41127. x += ci->width;
  41128. if (xToFind < x)
  41129. return ci->id;
  41130. }
  41131. }
  41132. }
  41133. return 0;
  41134. }
  41135. int TableHeaderComponent::getTotalWidth() const
  41136. {
  41137. int w = 0;
  41138. for (int i = columns.size(); --i >= 0;)
  41139. if (columns.getUnchecked(i)->isVisible())
  41140. w += columns.getUnchecked(i)->width;
  41141. return w;
  41142. }
  41143. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41144. {
  41145. stretchToFit = shouldStretchToFit;
  41146. lastDeliberateWidth = getTotalWidth();
  41147. resized();
  41148. }
  41149. bool TableHeaderComponent::isStretchToFitActive() const
  41150. {
  41151. return stretchToFit;
  41152. }
  41153. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41154. {
  41155. if (stretchToFit && getWidth() > 0
  41156. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41157. {
  41158. lastDeliberateWidth = targetTotalWidth;
  41159. resizeColumnsToFit (0, targetTotalWidth);
  41160. }
  41161. }
  41162. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41163. {
  41164. targetTotalWidth = jmax (targetTotalWidth, 0);
  41165. StretchableObjectResizer sor;
  41166. int i;
  41167. for (i = firstColumnIndex; i < columns.size(); ++i)
  41168. {
  41169. ColumnInfo* const ci = columns.getUnchecked(i);
  41170. if (ci->isVisible())
  41171. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41172. }
  41173. sor.resizeToFit (targetTotalWidth);
  41174. int visIndex = 0;
  41175. for (i = firstColumnIndex; i < columns.size(); ++i)
  41176. {
  41177. ColumnInfo* const ci = columns.getUnchecked(i);
  41178. if (ci->isVisible())
  41179. {
  41180. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41181. (int) std::floor (sor.getItemSize (visIndex++)));
  41182. if (newWidth != ci->width)
  41183. {
  41184. ci->width = newWidth;
  41185. repaint();
  41186. columnsResized = true;
  41187. triggerAsyncUpdate();
  41188. }
  41189. }
  41190. }
  41191. }
  41192. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41193. {
  41194. ColumnInfo* const ci = getInfoForId (columnId);
  41195. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41196. {
  41197. if (shouldBeVisible)
  41198. ci->propertyFlags |= visible;
  41199. else
  41200. ci->propertyFlags &= ~visible;
  41201. sendColumnsChanged();
  41202. resized();
  41203. }
  41204. }
  41205. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41206. {
  41207. const ColumnInfo* const ci = getInfoForId (columnId);
  41208. return ci != 0 && ci->isVisible();
  41209. }
  41210. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41211. {
  41212. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41213. {
  41214. for (int i = columns.size(); --i >= 0;)
  41215. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41216. ColumnInfo* const ci = getInfoForId (columnId);
  41217. if (ci != 0)
  41218. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41219. reSortTable();
  41220. }
  41221. }
  41222. int TableHeaderComponent::getSortColumnId() const
  41223. {
  41224. for (int i = columns.size(); --i >= 0;)
  41225. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41226. return columns.getUnchecked(i)->id;
  41227. return 0;
  41228. }
  41229. bool TableHeaderComponent::isSortedForwards() const
  41230. {
  41231. for (int i = columns.size(); --i >= 0;)
  41232. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41233. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41234. return true;
  41235. }
  41236. void TableHeaderComponent::reSortTable()
  41237. {
  41238. sortChanged = true;
  41239. repaint();
  41240. triggerAsyncUpdate();
  41241. }
  41242. const String TableHeaderComponent::toString() const
  41243. {
  41244. String s;
  41245. XmlElement doc ("TABLELAYOUT");
  41246. doc.setAttribute ("sortedCol", getSortColumnId());
  41247. doc.setAttribute ("sortForwards", isSortedForwards());
  41248. for (int i = 0; i < columns.size(); ++i)
  41249. {
  41250. const ColumnInfo* const ci = columns.getUnchecked (i);
  41251. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41252. e->setAttribute ("id", ci->id);
  41253. e->setAttribute ("visible", ci->isVisible());
  41254. e->setAttribute ("width", ci->width);
  41255. }
  41256. return doc.createDocument (String::empty, true, false);
  41257. }
  41258. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41259. {
  41260. XmlDocument doc (storedVersion);
  41261. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41262. int index = 0;
  41263. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41264. {
  41265. forEachXmlChildElement (*storedXml, col)
  41266. {
  41267. const int tabId = col->getIntAttribute ("id");
  41268. ColumnInfo* const ci = getInfoForId (tabId);
  41269. if (ci != 0)
  41270. {
  41271. columns.move (columns.indexOf (ci), index);
  41272. ci->width = col->getIntAttribute ("width");
  41273. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41274. }
  41275. ++index;
  41276. }
  41277. columnsResized = true;
  41278. sendColumnsChanged();
  41279. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41280. storedXml->getBoolAttribute ("sortForwards", true));
  41281. }
  41282. }
  41283. void TableHeaderComponent::addListener (Listener* const newListener)
  41284. {
  41285. listeners.addIfNotAlreadyThere (newListener);
  41286. }
  41287. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41288. {
  41289. listeners.removeValue (listenerToRemove);
  41290. }
  41291. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41292. {
  41293. const ColumnInfo* const ci = getInfoForId (columnId);
  41294. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41295. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41296. }
  41297. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41298. {
  41299. for (int i = 0; i < columns.size(); ++i)
  41300. {
  41301. const ColumnInfo* const ci = columns.getUnchecked(i);
  41302. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41303. menu.addItem (ci->id, ci->name,
  41304. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41305. isColumnVisible (ci->id));
  41306. }
  41307. }
  41308. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41309. {
  41310. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41311. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41312. }
  41313. void TableHeaderComponent::paint (Graphics& g)
  41314. {
  41315. LookAndFeel& lf = getLookAndFeel();
  41316. lf.drawTableHeaderBackground (g, *this);
  41317. const Rectangle<int> clip (g.getClipBounds());
  41318. int x = 0;
  41319. for (int i = 0; i < columns.size(); ++i)
  41320. {
  41321. const ColumnInfo* const ci = columns.getUnchecked(i);
  41322. if (ci->isVisible())
  41323. {
  41324. if (x + ci->width > clip.getX()
  41325. && (ci->id != columnIdBeingDragged
  41326. || dragOverlayComp == 0
  41327. || ! dragOverlayComp->isVisible()))
  41328. {
  41329. g.saveState();
  41330. g.setOrigin (x, 0);
  41331. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41332. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41333. ci->id == columnIdUnderMouse,
  41334. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41335. ci->propertyFlags);
  41336. g.restoreState();
  41337. }
  41338. x += ci->width;
  41339. if (x >= clip.getRight())
  41340. break;
  41341. }
  41342. }
  41343. }
  41344. void TableHeaderComponent::resized()
  41345. {
  41346. }
  41347. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41348. {
  41349. updateColumnUnderMouse (e.x, e.y);
  41350. }
  41351. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41352. {
  41353. updateColumnUnderMouse (e.x, e.y);
  41354. }
  41355. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41356. {
  41357. updateColumnUnderMouse (e.x, e.y);
  41358. }
  41359. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41360. {
  41361. repaint();
  41362. columnIdBeingResized = 0;
  41363. columnIdBeingDragged = 0;
  41364. if (columnIdUnderMouse != 0)
  41365. {
  41366. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41367. if (e.mods.isPopupMenu())
  41368. columnClicked (columnIdUnderMouse, e.mods);
  41369. }
  41370. if (menuActive && e.mods.isPopupMenu())
  41371. showColumnChooserMenu (columnIdUnderMouse);
  41372. }
  41373. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41374. {
  41375. if (columnIdBeingResized == 0
  41376. && columnIdBeingDragged == 0
  41377. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41378. {
  41379. dragOverlayComp = 0;
  41380. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41381. if (columnIdBeingResized != 0)
  41382. {
  41383. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41384. initialColumnWidth = ci->width;
  41385. }
  41386. else
  41387. {
  41388. beginDrag (e);
  41389. }
  41390. }
  41391. if (columnIdBeingResized != 0)
  41392. {
  41393. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41394. if (ci != 0)
  41395. {
  41396. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41397. initialColumnWidth + e.getDistanceFromDragStartX());
  41398. if (stretchToFit)
  41399. {
  41400. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41401. int minWidthOnRight = 0;
  41402. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41403. if (columns.getUnchecked (i)->isVisible())
  41404. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41405. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41406. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41407. }
  41408. setColumnWidth (columnIdBeingResized, w);
  41409. }
  41410. }
  41411. else if (columnIdBeingDragged != 0)
  41412. {
  41413. if (e.y >= -50 && e.y < getHeight() + 50)
  41414. {
  41415. if (dragOverlayComp != 0)
  41416. {
  41417. dragOverlayComp->setVisible (true);
  41418. dragOverlayComp->setBounds (jlimit (0,
  41419. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41420. e.x - draggingColumnOffset),
  41421. 0,
  41422. dragOverlayComp->getWidth(),
  41423. getHeight());
  41424. for (int i = columns.size(); --i >= 0;)
  41425. {
  41426. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41427. int newIndex = currentIndex;
  41428. if (newIndex > 0)
  41429. {
  41430. // if the previous column isn't draggable, we can't move our column
  41431. // past it, because that'd change the undraggable column's position..
  41432. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41433. if ((previous->propertyFlags & draggable) != 0)
  41434. {
  41435. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41436. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41437. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41438. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41439. {
  41440. --newIndex;
  41441. }
  41442. }
  41443. }
  41444. if (newIndex < columns.size() - 1)
  41445. {
  41446. // if the next column isn't draggable, we can't move our column
  41447. // past it, because that'd change the undraggable column's position..
  41448. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41449. if ((nextCol->propertyFlags & draggable) != 0)
  41450. {
  41451. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41452. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41453. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41454. > abs (dragOverlayComp->getRight() - rightOfNext))
  41455. {
  41456. ++newIndex;
  41457. }
  41458. }
  41459. }
  41460. if (newIndex != currentIndex)
  41461. moveColumn (columnIdBeingDragged, newIndex);
  41462. else
  41463. break;
  41464. }
  41465. }
  41466. }
  41467. else
  41468. {
  41469. endDrag (draggingColumnOriginalIndex);
  41470. }
  41471. }
  41472. }
  41473. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41474. {
  41475. if (columnIdBeingDragged == 0)
  41476. {
  41477. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41478. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41479. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41480. {
  41481. columnIdBeingDragged = 0;
  41482. }
  41483. else
  41484. {
  41485. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41486. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41487. const int temp = columnIdBeingDragged;
  41488. columnIdBeingDragged = 0;
  41489. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41490. columnIdBeingDragged = temp;
  41491. dragOverlayComp->setBounds (columnRect);
  41492. for (int i = listeners.size(); --i >= 0;)
  41493. {
  41494. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41495. i = jmin (i, listeners.size() - 1);
  41496. }
  41497. }
  41498. }
  41499. }
  41500. void TableHeaderComponent::endDrag (const int finalIndex)
  41501. {
  41502. if (columnIdBeingDragged != 0)
  41503. {
  41504. moveColumn (columnIdBeingDragged, finalIndex);
  41505. columnIdBeingDragged = 0;
  41506. repaint();
  41507. for (int i = listeners.size(); --i >= 0;)
  41508. {
  41509. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41510. i = jmin (i, listeners.size() - 1);
  41511. }
  41512. }
  41513. }
  41514. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41515. {
  41516. mouseDrag (e);
  41517. for (int i = columns.size(); --i >= 0;)
  41518. if (columns.getUnchecked (i)->isVisible())
  41519. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41520. columnIdBeingResized = 0;
  41521. repaint();
  41522. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41523. updateColumnUnderMouse (e.x, e.y);
  41524. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41525. columnClicked (columnIdUnderMouse, e.mods);
  41526. dragOverlayComp = 0;
  41527. }
  41528. const MouseCursor TableHeaderComponent::getMouseCursor()
  41529. {
  41530. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41531. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41532. return Component::getMouseCursor();
  41533. }
  41534. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41535. {
  41536. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41537. }
  41538. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41539. {
  41540. for (int i = columns.size(); --i >= 0;)
  41541. if (columns.getUnchecked(i)->id == id)
  41542. return columns.getUnchecked(i);
  41543. return 0;
  41544. }
  41545. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41546. {
  41547. int n = 0;
  41548. for (int i = 0; i < columns.size(); ++i)
  41549. {
  41550. if (columns.getUnchecked(i)->isVisible())
  41551. {
  41552. if (n == visibleIndex)
  41553. return i;
  41554. ++n;
  41555. }
  41556. }
  41557. return -1;
  41558. }
  41559. void TableHeaderComponent::sendColumnsChanged()
  41560. {
  41561. if (stretchToFit && lastDeliberateWidth > 0)
  41562. resizeAllColumnsToFit (lastDeliberateWidth);
  41563. repaint();
  41564. columnsChanged = true;
  41565. triggerAsyncUpdate();
  41566. }
  41567. void TableHeaderComponent::handleAsyncUpdate()
  41568. {
  41569. const bool changed = columnsChanged || sortChanged;
  41570. const bool sized = columnsResized || changed;
  41571. const bool sorted = sortChanged;
  41572. columnsChanged = false;
  41573. columnsResized = false;
  41574. sortChanged = false;
  41575. if (sorted)
  41576. {
  41577. for (int i = listeners.size(); --i >= 0;)
  41578. {
  41579. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41580. i = jmin (i, listeners.size() - 1);
  41581. }
  41582. }
  41583. if (changed)
  41584. {
  41585. for (int i = listeners.size(); --i >= 0;)
  41586. {
  41587. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41588. i = jmin (i, listeners.size() - 1);
  41589. }
  41590. }
  41591. if (sized)
  41592. {
  41593. for (int i = listeners.size(); --i >= 0;)
  41594. {
  41595. listeners.getUnchecked(i)->tableColumnsResized (this);
  41596. i = jmin (i, listeners.size() - 1);
  41597. }
  41598. }
  41599. }
  41600. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41601. {
  41602. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41603. {
  41604. const int draggableDistance = 3;
  41605. int x = 0;
  41606. for (int i = 0; i < columns.size(); ++i)
  41607. {
  41608. const ColumnInfo* const ci = columns.getUnchecked(i);
  41609. if (ci->isVisible())
  41610. {
  41611. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41612. && (ci->propertyFlags & resizable) != 0)
  41613. return ci->id;
  41614. x += ci->width;
  41615. }
  41616. }
  41617. }
  41618. return 0;
  41619. }
  41620. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41621. {
  41622. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41623. ? getColumnIdAtX (x) : 0;
  41624. if (newCol != columnIdUnderMouse)
  41625. {
  41626. columnIdUnderMouse = newCol;
  41627. repaint();
  41628. }
  41629. }
  41630. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41631. {
  41632. PopupMenu m;
  41633. addMenuItems (m, columnIdClicked);
  41634. if (m.getNumItems() > 0)
  41635. {
  41636. m.setLookAndFeel (&getLookAndFeel());
  41637. const int result = m.show();
  41638. if (result != 0)
  41639. reactToMenuItem (result, columnIdClicked);
  41640. }
  41641. }
  41642. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41643. {
  41644. }
  41645. END_JUCE_NAMESPACE
  41646. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41647. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41648. BEGIN_JUCE_NAMESPACE
  41649. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41650. class TableListRowComp : public Component,
  41651. public TooltipClient
  41652. {
  41653. public:
  41654. TableListRowComp (TableListBox& owner_)
  41655. : owner (owner_),
  41656. row (-1),
  41657. isSelected (false)
  41658. {
  41659. }
  41660. ~TableListRowComp()
  41661. {
  41662. deleteAllChildren();
  41663. }
  41664. void paint (Graphics& g)
  41665. {
  41666. TableListBoxModel* const model = owner.getModel();
  41667. if (model != 0)
  41668. {
  41669. const TableHeaderComponent* const header = owner.getHeader();
  41670. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41671. const int numColumns = header->getNumColumns (true);
  41672. for (int i = 0; i < numColumns; ++i)
  41673. {
  41674. if (! columnsWithComponents [i])
  41675. {
  41676. const int columnId = header->getColumnIdOfIndex (i, true);
  41677. Rectangle<int> columnRect (header->getColumnPosition (i));
  41678. columnRect.setSize (columnRect.getWidth(), getHeight());
  41679. g.saveState();
  41680. g.reduceClipRegion (columnRect);
  41681. g.setOrigin (columnRect.getX(), 0);
  41682. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41683. g.restoreState();
  41684. }
  41685. }
  41686. }
  41687. }
  41688. void update (const int newRow, const bool isNowSelected)
  41689. {
  41690. if (newRow != row || isNowSelected != isSelected)
  41691. {
  41692. row = newRow;
  41693. isSelected = isNowSelected;
  41694. repaint();
  41695. deleteAllChildren();
  41696. }
  41697. if (row < owner.getNumRows())
  41698. {
  41699. jassert (row >= 0);
  41700. const Identifier tagPropertyName ("_tableLastUseNum");
  41701. const int newTag = Random::getSystemRandom().nextInt();
  41702. const TableHeaderComponent* const header = owner.getHeader();
  41703. const int numColumns = header->getNumColumns (true);
  41704. columnsWithComponents.clear();
  41705. if (owner.getModel() != 0)
  41706. {
  41707. for (int i = 0; i < numColumns; ++i)
  41708. {
  41709. const int columnId = header->getColumnIdOfIndex (i, true);
  41710. Component* const newComp
  41711. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41712. findChildComponentForColumn (columnId));
  41713. if (newComp != 0)
  41714. {
  41715. addAndMakeVisible (newComp);
  41716. newComp->getProperties().set (tagPropertyName, newTag);
  41717. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41718. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41719. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41720. columnsWithComponents.setBit (i);
  41721. }
  41722. }
  41723. }
  41724. for (int i = getNumChildComponents(); --i >= 0;)
  41725. {
  41726. Component* const c = getChildComponent (i);
  41727. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41728. delete c;
  41729. }
  41730. }
  41731. else
  41732. {
  41733. columnsWithComponents.clear();
  41734. deleteAllChildren();
  41735. }
  41736. }
  41737. void resized()
  41738. {
  41739. for (int i = getNumChildComponents(); --i >= 0;)
  41740. {
  41741. Component* const c = getChildComponent (i);
  41742. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41743. if (columnId != 0)
  41744. {
  41745. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41746. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41747. }
  41748. }
  41749. }
  41750. void mouseDown (const MouseEvent& e)
  41751. {
  41752. isDragging = false;
  41753. selectRowOnMouseUp = false;
  41754. if (isEnabled())
  41755. {
  41756. if (! isSelected)
  41757. {
  41758. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41759. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41760. if (columnId != 0 && owner.getModel() != 0)
  41761. owner.getModel()->cellClicked (row, columnId, e);
  41762. }
  41763. else
  41764. {
  41765. selectRowOnMouseUp = true;
  41766. }
  41767. }
  41768. }
  41769. void mouseDrag (const MouseEvent& e)
  41770. {
  41771. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41772. {
  41773. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41774. if (selectedRows.size() > 0)
  41775. {
  41776. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41777. if (dragDescription.isNotEmpty())
  41778. {
  41779. isDragging = true;
  41780. owner.startDragAndDrop (e, dragDescription);
  41781. }
  41782. }
  41783. }
  41784. }
  41785. void mouseUp (const MouseEvent& e)
  41786. {
  41787. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41788. {
  41789. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41790. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41791. if (columnId != 0 && owner.getModel() != 0)
  41792. owner.getModel()->cellClicked (row, columnId, e);
  41793. }
  41794. }
  41795. void mouseDoubleClick (const MouseEvent& e)
  41796. {
  41797. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41798. if (columnId != 0 && owner.getModel() != 0)
  41799. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41800. }
  41801. const String getTooltip()
  41802. {
  41803. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41804. if (columnId != 0 && owner.getModel() != 0)
  41805. return owner.getModel()->getCellTooltip (row, columnId);
  41806. return String::empty;
  41807. }
  41808. Component* findChildComponentForColumn (const int columnId) const
  41809. {
  41810. for (int i = getNumChildComponents(); --i >= 0;)
  41811. {
  41812. Component* const c = getChildComponent (i);
  41813. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41814. return c;
  41815. }
  41816. return 0;
  41817. }
  41818. juce_UseDebuggingNewOperator
  41819. private:
  41820. TableListBox& owner;
  41821. int row;
  41822. bool isSelected, isDragging, selectRowOnMouseUp;
  41823. BigInteger columnsWithComponents;
  41824. TableListRowComp (const TableListRowComp&);
  41825. TableListRowComp& operator= (const TableListRowComp&);
  41826. };
  41827. class TableListBoxHeader : public TableHeaderComponent
  41828. {
  41829. public:
  41830. TableListBoxHeader (TableListBox& owner_)
  41831. : owner (owner_)
  41832. {
  41833. }
  41834. ~TableListBoxHeader()
  41835. {
  41836. }
  41837. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41838. {
  41839. if (owner.isAutoSizeMenuOptionShown())
  41840. {
  41841. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41842. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41843. menu.addSeparator();
  41844. }
  41845. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41846. }
  41847. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41848. {
  41849. if (menuReturnId == 0xf836743)
  41850. {
  41851. owner.autoSizeColumn (columnIdClicked);
  41852. }
  41853. else if (menuReturnId == 0xf836744)
  41854. {
  41855. owner.autoSizeAllColumns();
  41856. }
  41857. else
  41858. {
  41859. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41860. }
  41861. }
  41862. juce_UseDebuggingNewOperator
  41863. private:
  41864. TableListBox& owner;
  41865. TableListBoxHeader (const TableListBoxHeader&);
  41866. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41867. };
  41868. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41869. : ListBox (name, 0),
  41870. model (model_),
  41871. autoSizeOptionsShown (true)
  41872. {
  41873. ListBox::model = this;
  41874. header = new TableListBoxHeader (*this);
  41875. header->setSize (100, 28);
  41876. header->addListener (this);
  41877. setHeaderComponent (header);
  41878. }
  41879. TableListBox::~TableListBox()
  41880. {
  41881. header = 0;
  41882. }
  41883. void TableListBox::setModel (TableListBoxModel* const newModel)
  41884. {
  41885. if (model != newModel)
  41886. {
  41887. model = newModel;
  41888. updateContent();
  41889. }
  41890. }
  41891. int TableListBox::getHeaderHeight() const
  41892. {
  41893. return header->getHeight();
  41894. }
  41895. void TableListBox::setHeaderHeight (const int newHeight)
  41896. {
  41897. header->setSize (header->getWidth(), newHeight);
  41898. resized();
  41899. }
  41900. void TableListBox::autoSizeColumn (const int columnId)
  41901. {
  41902. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41903. if (width > 0)
  41904. header->setColumnWidth (columnId, width);
  41905. }
  41906. void TableListBox::autoSizeAllColumns()
  41907. {
  41908. for (int i = 0; i < header->getNumColumns (true); ++i)
  41909. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41910. }
  41911. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41912. {
  41913. autoSizeOptionsShown = shouldBeShown;
  41914. }
  41915. bool TableListBox::isAutoSizeMenuOptionShown() const
  41916. {
  41917. return autoSizeOptionsShown;
  41918. }
  41919. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41920. const int rowNumber,
  41921. const bool relativeToComponentTopLeft) const
  41922. {
  41923. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41924. if (relativeToComponentTopLeft)
  41925. headerCell.translate (header->getX(), 0);
  41926. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41927. return Rectangle<int> (headerCell.getX(), row.getY(),
  41928. headerCell.getWidth(), row.getHeight());
  41929. }
  41930. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41931. {
  41932. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41933. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41934. }
  41935. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41936. {
  41937. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41938. if (scrollbar != 0)
  41939. {
  41940. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41941. double x = scrollbar->getCurrentRangeStart();
  41942. const double w = scrollbar->getCurrentRangeSize();
  41943. if (pos.getX() < x)
  41944. x = pos.getX();
  41945. else if (pos.getRight() > x + w)
  41946. x += jmax (0.0, pos.getRight() - (x + w));
  41947. scrollbar->setCurrentRangeStart (x);
  41948. }
  41949. }
  41950. int TableListBox::getNumRows()
  41951. {
  41952. return model != 0 ? model->getNumRows() : 0;
  41953. }
  41954. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41955. {
  41956. }
  41957. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41958. {
  41959. if (existingComponentToUpdate == 0)
  41960. existingComponentToUpdate = new TableListRowComp (*this);
  41961. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41962. return existingComponentToUpdate;
  41963. }
  41964. void TableListBox::selectedRowsChanged (int row)
  41965. {
  41966. if (model != 0)
  41967. model->selectedRowsChanged (row);
  41968. }
  41969. void TableListBox::deleteKeyPressed (int row)
  41970. {
  41971. if (model != 0)
  41972. model->deleteKeyPressed (row);
  41973. }
  41974. void TableListBox::returnKeyPressed (int row)
  41975. {
  41976. if (model != 0)
  41977. model->returnKeyPressed (row);
  41978. }
  41979. void TableListBox::backgroundClicked()
  41980. {
  41981. if (model != 0)
  41982. model->backgroundClicked();
  41983. }
  41984. void TableListBox::listWasScrolled()
  41985. {
  41986. if (model != 0)
  41987. model->listWasScrolled();
  41988. }
  41989. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41990. {
  41991. setMinimumContentWidth (header->getTotalWidth());
  41992. repaint();
  41993. updateColumnComponents();
  41994. }
  41995. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41996. {
  41997. setMinimumContentWidth (header->getTotalWidth());
  41998. repaint();
  41999. updateColumnComponents();
  42000. }
  42001. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42002. {
  42003. if (model != 0)
  42004. model->sortOrderChanged (header->getSortColumnId(),
  42005. header->isSortedForwards());
  42006. }
  42007. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42008. {
  42009. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42010. repaint();
  42011. }
  42012. void TableListBox::resized()
  42013. {
  42014. ListBox::resized();
  42015. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42016. setMinimumContentWidth (header->getTotalWidth());
  42017. }
  42018. void TableListBox::updateColumnComponents() const
  42019. {
  42020. const int firstRow = getRowContainingPosition (0, 0);
  42021. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42022. {
  42023. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42024. if (rowComp != 0)
  42025. rowComp->resized();
  42026. }
  42027. }
  42028. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42029. {
  42030. }
  42031. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42032. {
  42033. }
  42034. void TableListBoxModel::backgroundClicked()
  42035. {
  42036. }
  42037. void TableListBoxModel::sortOrderChanged (int, const bool)
  42038. {
  42039. }
  42040. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42041. {
  42042. return 0;
  42043. }
  42044. void TableListBoxModel::selectedRowsChanged (int)
  42045. {
  42046. }
  42047. void TableListBoxModel::deleteKeyPressed (int)
  42048. {
  42049. }
  42050. void TableListBoxModel::returnKeyPressed (int)
  42051. {
  42052. }
  42053. void TableListBoxModel::listWasScrolled()
  42054. {
  42055. }
  42056. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42057. {
  42058. return String::empty;
  42059. }
  42060. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42061. {
  42062. return String::empty;
  42063. }
  42064. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42065. {
  42066. (void) existingComponentToUpdate;
  42067. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42068. return 0;
  42069. }
  42070. END_JUCE_NAMESPACE
  42071. /*** End of inlined file: juce_TableListBox.cpp ***/
  42072. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42073. BEGIN_JUCE_NAMESPACE
  42074. // a word or space that can't be broken down any further
  42075. struct TextAtom
  42076. {
  42077. String atomText;
  42078. float width;
  42079. uint16 numChars;
  42080. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42081. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42082. const String getText (const juce_wchar passwordCharacter) const
  42083. {
  42084. if (passwordCharacter == 0)
  42085. return atomText;
  42086. else
  42087. return String::repeatedString (String::charToString (passwordCharacter),
  42088. atomText.length());
  42089. }
  42090. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42091. {
  42092. if (passwordCharacter == 0)
  42093. return atomText.substring (0, numChars);
  42094. else if (isNewLine())
  42095. return String::empty;
  42096. else
  42097. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42098. }
  42099. };
  42100. // a run of text with a single font and colour
  42101. class TextEditor::UniformTextSection
  42102. {
  42103. public:
  42104. UniformTextSection (const String& text,
  42105. const Font& font_,
  42106. const Colour& colour_,
  42107. const juce_wchar passwordCharacter)
  42108. : font (font_),
  42109. colour (colour_)
  42110. {
  42111. initialiseAtoms (text, passwordCharacter);
  42112. }
  42113. UniformTextSection (const UniformTextSection& other)
  42114. : font (other.font),
  42115. colour (other.colour)
  42116. {
  42117. atoms.ensureStorageAllocated (other.atoms.size());
  42118. for (int i = 0; i < other.atoms.size(); ++i)
  42119. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42120. }
  42121. ~UniformTextSection()
  42122. {
  42123. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42124. }
  42125. void clear()
  42126. {
  42127. for (int i = atoms.size(); --i >= 0;)
  42128. delete getAtom(i);
  42129. atoms.clear();
  42130. }
  42131. int getNumAtoms() const
  42132. {
  42133. return atoms.size();
  42134. }
  42135. TextAtom* getAtom (const int index) const throw()
  42136. {
  42137. return atoms.getUnchecked (index);
  42138. }
  42139. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42140. {
  42141. if (other.atoms.size() > 0)
  42142. {
  42143. TextAtom* const lastAtom = atoms.getLast();
  42144. int i = 0;
  42145. if (lastAtom != 0)
  42146. {
  42147. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42148. {
  42149. TextAtom* const first = other.getAtom(0);
  42150. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42151. {
  42152. lastAtom->atomText += first->atomText;
  42153. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42154. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42155. delete first;
  42156. ++i;
  42157. }
  42158. }
  42159. }
  42160. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42161. while (i < other.atoms.size())
  42162. {
  42163. atoms.add (other.getAtom(i));
  42164. ++i;
  42165. }
  42166. }
  42167. }
  42168. UniformTextSection* split (const int indexToBreakAt,
  42169. const juce_wchar passwordCharacter)
  42170. {
  42171. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42172. font, colour,
  42173. passwordCharacter);
  42174. int index = 0;
  42175. for (int i = 0; i < atoms.size(); ++i)
  42176. {
  42177. TextAtom* const atom = getAtom(i);
  42178. const int nextIndex = index + atom->numChars;
  42179. if (index == indexToBreakAt)
  42180. {
  42181. int j;
  42182. for (j = i; j < atoms.size(); ++j)
  42183. section2->atoms.add (getAtom (j));
  42184. for (j = atoms.size(); --j >= i;)
  42185. atoms.remove (j);
  42186. break;
  42187. }
  42188. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42189. {
  42190. TextAtom* const secondAtom = new TextAtom();
  42191. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42192. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42193. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42194. section2->atoms.add (secondAtom);
  42195. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42196. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42197. atom->numChars = (uint16) (indexToBreakAt - index);
  42198. int j;
  42199. for (j = i + 1; j < atoms.size(); ++j)
  42200. section2->atoms.add (getAtom (j));
  42201. for (j = atoms.size(); --j > i;)
  42202. atoms.remove (j);
  42203. break;
  42204. }
  42205. index = nextIndex;
  42206. }
  42207. return section2;
  42208. }
  42209. void appendAllText (String::Concatenator& concatenator) const
  42210. {
  42211. for (int i = 0; i < atoms.size(); ++i)
  42212. concatenator.append (getAtom(i)->atomText);
  42213. }
  42214. void appendSubstring (String::Concatenator& concatenator,
  42215. const Range<int>& range) const
  42216. {
  42217. int index = 0;
  42218. for (int i = 0; i < atoms.size(); ++i)
  42219. {
  42220. const TextAtom* const atom = getAtom (i);
  42221. const int nextIndex = index + atom->numChars;
  42222. if (range.getStart() < nextIndex)
  42223. {
  42224. if (range.getEnd() <= index)
  42225. break;
  42226. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42227. if (! r.isEmpty())
  42228. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42229. }
  42230. index = nextIndex;
  42231. }
  42232. }
  42233. int getTotalLength() const
  42234. {
  42235. int total = 0;
  42236. for (int i = atoms.size(); --i >= 0;)
  42237. total += getAtom(i)->numChars;
  42238. return total;
  42239. }
  42240. void setFont (const Font& newFont,
  42241. const juce_wchar passwordCharacter)
  42242. {
  42243. if (font != newFont)
  42244. {
  42245. font = newFont;
  42246. for (int i = atoms.size(); --i >= 0;)
  42247. {
  42248. TextAtom* const atom = atoms.getUnchecked(i);
  42249. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42250. }
  42251. }
  42252. }
  42253. juce_UseDebuggingNewOperator
  42254. Font font;
  42255. Colour colour;
  42256. private:
  42257. Array <TextAtom*> atoms;
  42258. void initialiseAtoms (const String& textToParse,
  42259. const juce_wchar passwordCharacter)
  42260. {
  42261. int i = 0;
  42262. const int len = textToParse.length();
  42263. const juce_wchar* const text = textToParse;
  42264. while (i < len)
  42265. {
  42266. int start = i;
  42267. // create a whitespace atom unless it starts with non-ws
  42268. if (CharacterFunctions::isWhitespace (text[i])
  42269. && text[i] != '\r'
  42270. && text[i] != '\n')
  42271. {
  42272. while (i < len
  42273. && CharacterFunctions::isWhitespace (text[i])
  42274. && text[i] != '\r'
  42275. && text[i] != '\n')
  42276. {
  42277. ++i;
  42278. }
  42279. }
  42280. else
  42281. {
  42282. if (text[i] == '\r')
  42283. {
  42284. ++i;
  42285. if ((i < len) && (text[i] == '\n'))
  42286. {
  42287. ++start;
  42288. ++i;
  42289. }
  42290. }
  42291. else if (text[i] == '\n')
  42292. {
  42293. ++i;
  42294. }
  42295. else
  42296. {
  42297. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42298. ++i;
  42299. }
  42300. }
  42301. TextAtom* const atom = new TextAtom();
  42302. atom->atomText = String (text + start, i - start);
  42303. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42304. atom->numChars = (uint16) (i - start);
  42305. atoms.add (atom);
  42306. }
  42307. }
  42308. UniformTextSection& operator= (const UniformTextSection& other);
  42309. };
  42310. class TextEditor::Iterator
  42311. {
  42312. public:
  42313. Iterator (const Array <UniformTextSection*>& sections_,
  42314. const float wordWrapWidth_,
  42315. const juce_wchar passwordCharacter_)
  42316. : indexInText (0),
  42317. lineY (0),
  42318. lineHeight (0),
  42319. maxDescent (0),
  42320. atomX (0),
  42321. atomRight (0),
  42322. atom (0),
  42323. currentSection (0),
  42324. sections (sections_),
  42325. sectionIndex (0),
  42326. atomIndex (0),
  42327. wordWrapWidth (wordWrapWidth_),
  42328. passwordCharacter (passwordCharacter_)
  42329. {
  42330. jassert (wordWrapWidth_ > 0);
  42331. if (sections.size() > 0)
  42332. {
  42333. currentSection = sections.getUnchecked (sectionIndex);
  42334. if (currentSection != 0)
  42335. beginNewLine();
  42336. }
  42337. }
  42338. Iterator (const Iterator& other)
  42339. : indexInText (other.indexInText),
  42340. lineY (other.lineY),
  42341. lineHeight (other.lineHeight),
  42342. maxDescent (other.maxDescent),
  42343. atomX (other.atomX),
  42344. atomRight (other.atomRight),
  42345. atom (other.atom),
  42346. currentSection (other.currentSection),
  42347. sections (other.sections),
  42348. sectionIndex (other.sectionIndex),
  42349. atomIndex (other.atomIndex),
  42350. wordWrapWidth (other.wordWrapWidth),
  42351. passwordCharacter (other.passwordCharacter),
  42352. tempAtom (other.tempAtom)
  42353. {
  42354. }
  42355. ~Iterator()
  42356. {
  42357. }
  42358. bool next()
  42359. {
  42360. if (atom == &tempAtom)
  42361. {
  42362. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42363. if (numRemaining > 0)
  42364. {
  42365. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42366. atomX = 0;
  42367. if (tempAtom.numChars > 0)
  42368. lineY += lineHeight;
  42369. indexInText += tempAtom.numChars;
  42370. GlyphArrangement g;
  42371. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42372. int split;
  42373. for (split = 0; split < g.getNumGlyphs(); ++split)
  42374. if (shouldWrap (g.getGlyph (split).getRight()))
  42375. break;
  42376. if (split > 0 && split <= numRemaining)
  42377. {
  42378. tempAtom.numChars = (uint16) split;
  42379. tempAtom.width = g.getGlyph (split - 1).getRight();
  42380. atomRight = atomX + tempAtom.width;
  42381. return true;
  42382. }
  42383. }
  42384. }
  42385. bool forceNewLine = false;
  42386. if (sectionIndex >= sections.size())
  42387. {
  42388. moveToEndOfLastAtom();
  42389. return false;
  42390. }
  42391. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42392. {
  42393. if (atomIndex >= currentSection->getNumAtoms())
  42394. {
  42395. if (++sectionIndex >= sections.size())
  42396. {
  42397. moveToEndOfLastAtom();
  42398. return false;
  42399. }
  42400. atomIndex = 0;
  42401. currentSection = sections.getUnchecked (sectionIndex);
  42402. }
  42403. else
  42404. {
  42405. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42406. if (! lastAtom->isWhitespace())
  42407. {
  42408. // handle the case where the last atom in a section is actually part of the same
  42409. // word as the first atom of the next section...
  42410. float right = atomRight + lastAtom->width;
  42411. float lineHeight2 = lineHeight;
  42412. float maxDescent2 = maxDescent;
  42413. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42414. {
  42415. const UniformTextSection* const s = sections.getUnchecked (section);
  42416. if (s->getNumAtoms() == 0)
  42417. break;
  42418. const TextAtom* const nextAtom = s->getAtom (0);
  42419. if (nextAtom->isWhitespace())
  42420. break;
  42421. right += nextAtom->width;
  42422. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42423. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42424. if (shouldWrap (right))
  42425. {
  42426. lineHeight = lineHeight2;
  42427. maxDescent = maxDescent2;
  42428. forceNewLine = true;
  42429. break;
  42430. }
  42431. if (s->getNumAtoms() > 1)
  42432. break;
  42433. }
  42434. }
  42435. }
  42436. }
  42437. if (atom != 0)
  42438. {
  42439. atomX = atomRight;
  42440. indexInText += atom->numChars;
  42441. if (atom->isNewLine())
  42442. beginNewLine();
  42443. }
  42444. atom = currentSection->getAtom (atomIndex);
  42445. atomRight = atomX + atom->width;
  42446. ++atomIndex;
  42447. if (shouldWrap (atomRight) || forceNewLine)
  42448. {
  42449. if (atom->isWhitespace())
  42450. {
  42451. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42452. atomRight = jmin (atomRight, wordWrapWidth);
  42453. }
  42454. else
  42455. {
  42456. atomRight = atom->width;
  42457. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42458. {
  42459. tempAtom = *atom;
  42460. tempAtom.width = 0;
  42461. tempAtom.numChars = 0;
  42462. atom = &tempAtom;
  42463. if (atomX > 0)
  42464. beginNewLine();
  42465. return next();
  42466. }
  42467. beginNewLine();
  42468. return true;
  42469. }
  42470. }
  42471. return true;
  42472. }
  42473. void beginNewLine()
  42474. {
  42475. atomX = 0;
  42476. lineY += lineHeight;
  42477. int tempSectionIndex = sectionIndex;
  42478. int tempAtomIndex = atomIndex;
  42479. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42480. lineHeight = section->font.getHeight();
  42481. maxDescent = section->font.getDescent();
  42482. float x = (atom != 0) ? atom->width : 0;
  42483. while (! shouldWrap (x))
  42484. {
  42485. if (tempSectionIndex >= sections.size())
  42486. break;
  42487. bool checkSize = false;
  42488. if (tempAtomIndex >= section->getNumAtoms())
  42489. {
  42490. if (++tempSectionIndex >= sections.size())
  42491. break;
  42492. tempAtomIndex = 0;
  42493. section = sections.getUnchecked (tempSectionIndex);
  42494. checkSize = true;
  42495. }
  42496. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42497. if (nextAtom == 0)
  42498. break;
  42499. x += nextAtom->width;
  42500. if (shouldWrap (x) || nextAtom->isNewLine())
  42501. break;
  42502. if (checkSize)
  42503. {
  42504. lineHeight = jmax (lineHeight, section->font.getHeight());
  42505. maxDescent = jmax (maxDescent, section->font.getDescent());
  42506. }
  42507. ++tempAtomIndex;
  42508. }
  42509. }
  42510. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42511. {
  42512. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42513. {
  42514. if (lastSection != currentSection)
  42515. {
  42516. lastSection = currentSection;
  42517. g.setColour (currentSection->colour);
  42518. g.setFont (currentSection->font);
  42519. }
  42520. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42521. GlyphArrangement ga;
  42522. ga.addLineOfText (currentSection->font,
  42523. atom->getTrimmedText (passwordCharacter),
  42524. atomX,
  42525. (float) roundToInt (lineY + lineHeight - maxDescent));
  42526. ga.draw (g);
  42527. }
  42528. }
  42529. void drawSelection (Graphics& g,
  42530. const Range<int>& selection) const
  42531. {
  42532. const int startX = roundToInt (indexToX (selection.getStart()));
  42533. const int endX = roundToInt (indexToX (selection.getEnd()));
  42534. const int y = roundToInt (lineY);
  42535. const int nextY = roundToInt (lineY + lineHeight);
  42536. g.fillRect (startX, y, endX - startX, nextY - y);
  42537. }
  42538. void drawSelectedText (Graphics& g,
  42539. const Range<int>& selection,
  42540. const Colour& selectedTextColour) const
  42541. {
  42542. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42543. {
  42544. GlyphArrangement ga;
  42545. ga.addLineOfText (currentSection->font,
  42546. atom->getTrimmedText (passwordCharacter),
  42547. atomX,
  42548. (float) roundToInt (lineY + lineHeight - maxDescent));
  42549. if (selection.getEnd() < indexInText + atom->numChars)
  42550. {
  42551. GlyphArrangement ga2 (ga);
  42552. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42553. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42554. g.setColour (currentSection->colour);
  42555. ga2.draw (g);
  42556. }
  42557. if (selection.getStart() > indexInText)
  42558. {
  42559. GlyphArrangement ga2 (ga);
  42560. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42561. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42562. g.setColour (currentSection->colour);
  42563. ga2.draw (g);
  42564. }
  42565. g.setColour (selectedTextColour);
  42566. ga.draw (g);
  42567. }
  42568. }
  42569. float indexToX (const int indexToFind) const
  42570. {
  42571. if (indexToFind <= indexInText)
  42572. return atomX;
  42573. if (indexToFind >= indexInText + atom->numChars)
  42574. return atomRight;
  42575. GlyphArrangement g;
  42576. g.addLineOfText (currentSection->font,
  42577. atom->getText (passwordCharacter),
  42578. atomX, 0.0f);
  42579. if (indexToFind - indexInText >= g.getNumGlyphs())
  42580. return atomRight;
  42581. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42582. }
  42583. int xToIndex (const float xToFind) const
  42584. {
  42585. if (xToFind <= atomX || atom->isNewLine())
  42586. return indexInText;
  42587. if (xToFind >= atomRight)
  42588. return indexInText + atom->numChars;
  42589. GlyphArrangement g;
  42590. g.addLineOfText (currentSection->font,
  42591. atom->getText (passwordCharacter),
  42592. atomX, 0.0f);
  42593. int j;
  42594. for (j = 0; j < g.getNumGlyphs(); ++j)
  42595. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42596. break;
  42597. return indexInText + j;
  42598. }
  42599. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42600. {
  42601. while (next())
  42602. {
  42603. if (indexInText + atom->numChars > index)
  42604. {
  42605. cx = indexToX (index);
  42606. cy = lineY;
  42607. lineHeight_ = lineHeight;
  42608. return true;
  42609. }
  42610. }
  42611. cx = atomX;
  42612. cy = lineY;
  42613. lineHeight_ = lineHeight;
  42614. return false;
  42615. }
  42616. juce_UseDebuggingNewOperator
  42617. int indexInText;
  42618. float lineY, lineHeight, maxDescent;
  42619. float atomX, atomRight;
  42620. const TextAtom* atom;
  42621. const UniformTextSection* currentSection;
  42622. private:
  42623. const Array <UniformTextSection*>& sections;
  42624. int sectionIndex, atomIndex;
  42625. const float wordWrapWidth;
  42626. const juce_wchar passwordCharacter;
  42627. TextAtom tempAtom;
  42628. Iterator& operator= (const Iterator&);
  42629. void moveToEndOfLastAtom()
  42630. {
  42631. if (atom != 0)
  42632. {
  42633. atomX = atomRight;
  42634. if (atom->isNewLine())
  42635. {
  42636. atomX = 0.0f;
  42637. lineY += lineHeight;
  42638. }
  42639. }
  42640. }
  42641. bool shouldWrap (const float x) const
  42642. {
  42643. return (x - 0.0001f) >= wordWrapWidth;
  42644. }
  42645. };
  42646. class TextEditor::InsertAction : public UndoableAction
  42647. {
  42648. TextEditor& owner;
  42649. const String text;
  42650. const int insertIndex, oldCaretPos, newCaretPos;
  42651. const Font font;
  42652. const Colour colour;
  42653. InsertAction (const InsertAction&);
  42654. InsertAction& operator= (const InsertAction&);
  42655. public:
  42656. InsertAction (TextEditor& owner_,
  42657. const String& text_,
  42658. const int insertIndex_,
  42659. const Font& font_,
  42660. const Colour& colour_,
  42661. const int oldCaretPos_,
  42662. const int newCaretPos_)
  42663. : owner (owner_),
  42664. text (text_),
  42665. insertIndex (insertIndex_),
  42666. oldCaretPos (oldCaretPos_),
  42667. newCaretPos (newCaretPos_),
  42668. font (font_),
  42669. colour (colour_)
  42670. {
  42671. }
  42672. ~InsertAction()
  42673. {
  42674. }
  42675. bool perform()
  42676. {
  42677. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42678. return true;
  42679. }
  42680. bool undo()
  42681. {
  42682. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42683. return true;
  42684. }
  42685. int getSizeInUnits()
  42686. {
  42687. return text.length() + 16;
  42688. }
  42689. };
  42690. class TextEditor::RemoveAction : public UndoableAction
  42691. {
  42692. TextEditor& owner;
  42693. const Range<int> range;
  42694. const int oldCaretPos, newCaretPos;
  42695. Array <UniformTextSection*> removedSections;
  42696. RemoveAction (const RemoveAction&);
  42697. RemoveAction& operator= (const RemoveAction&);
  42698. public:
  42699. RemoveAction (TextEditor& owner_,
  42700. const Range<int> range_,
  42701. const int oldCaretPos_,
  42702. const int newCaretPos_,
  42703. const Array <UniformTextSection*>& removedSections_)
  42704. : owner (owner_),
  42705. range (range_),
  42706. oldCaretPos (oldCaretPos_),
  42707. newCaretPos (newCaretPos_),
  42708. removedSections (removedSections_)
  42709. {
  42710. }
  42711. ~RemoveAction()
  42712. {
  42713. for (int i = removedSections.size(); --i >= 0;)
  42714. {
  42715. UniformTextSection* const section = removedSections.getUnchecked (i);
  42716. section->clear();
  42717. delete section;
  42718. }
  42719. }
  42720. bool perform()
  42721. {
  42722. owner.remove (range, 0, newCaretPos);
  42723. return true;
  42724. }
  42725. bool undo()
  42726. {
  42727. owner.reinsert (range.getStart(), removedSections);
  42728. owner.moveCursorTo (oldCaretPos, false);
  42729. return true;
  42730. }
  42731. int getSizeInUnits()
  42732. {
  42733. int n = 0;
  42734. for (int i = removedSections.size(); --i >= 0;)
  42735. n += removedSections.getUnchecked (i)->getTotalLength();
  42736. return n + 16;
  42737. }
  42738. };
  42739. class TextEditor::TextHolderComponent : public Component,
  42740. public Timer,
  42741. public Value::Listener
  42742. {
  42743. public:
  42744. TextHolderComponent (TextEditor& owner_)
  42745. : owner (owner_)
  42746. {
  42747. setWantsKeyboardFocus (false);
  42748. setInterceptsMouseClicks (false, true);
  42749. owner.getTextValue().addListener (this);
  42750. }
  42751. ~TextHolderComponent()
  42752. {
  42753. owner.getTextValue().removeListener (this);
  42754. }
  42755. void paint (Graphics& g)
  42756. {
  42757. owner.drawContent (g);
  42758. }
  42759. void timerCallback()
  42760. {
  42761. owner.timerCallbackInt();
  42762. }
  42763. const MouseCursor getMouseCursor()
  42764. {
  42765. return owner.getMouseCursor();
  42766. }
  42767. void valueChanged (Value&)
  42768. {
  42769. owner.textWasChangedByValue();
  42770. }
  42771. private:
  42772. TextEditor& owner;
  42773. TextHolderComponent (const TextHolderComponent&);
  42774. TextHolderComponent& operator= (const TextHolderComponent&);
  42775. };
  42776. class TextEditorViewport : public Viewport
  42777. {
  42778. public:
  42779. TextEditorViewport (TextEditor* const owner_)
  42780. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42781. {
  42782. }
  42783. ~TextEditorViewport()
  42784. {
  42785. }
  42786. void visibleAreaChanged (int, int, int, int)
  42787. {
  42788. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42789. // appear and disappear, causing the wrap width to change.
  42790. {
  42791. const float wordWrapWidth = owner->getWordWrapWidth();
  42792. if (wordWrapWidth != lastWordWrapWidth)
  42793. {
  42794. lastWordWrapWidth = wordWrapWidth;
  42795. rentrant = true;
  42796. owner->updateTextHolderSize();
  42797. rentrant = false;
  42798. }
  42799. }
  42800. }
  42801. private:
  42802. TextEditor* const owner;
  42803. float lastWordWrapWidth;
  42804. bool rentrant;
  42805. TextEditorViewport (const TextEditorViewport&);
  42806. TextEditorViewport& operator= (const TextEditorViewport&);
  42807. };
  42808. namespace TextEditorDefs
  42809. {
  42810. const int flashSpeedIntervalMs = 380;
  42811. const int textChangeMessageId = 0x10003001;
  42812. const int returnKeyMessageId = 0x10003002;
  42813. const int escapeKeyMessageId = 0x10003003;
  42814. const int focusLossMessageId = 0x10003004;
  42815. const int maxActionsPerTransaction = 100;
  42816. }
  42817. TextEditor::TextEditor (const String& name,
  42818. const juce_wchar passwordCharacter_)
  42819. : Component (name),
  42820. borderSize (1, 1, 1, 3),
  42821. readOnly (false),
  42822. multiline (false),
  42823. wordWrap (false),
  42824. returnKeyStartsNewLine (false),
  42825. caretVisible (true),
  42826. popupMenuEnabled (true),
  42827. selectAllTextWhenFocused (false),
  42828. scrollbarVisible (true),
  42829. wasFocused (false),
  42830. caretFlashState (true),
  42831. keepCursorOnScreen (true),
  42832. tabKeyUsed (false),
  42833. menuActive (false),
  42834. valueTextNeedsUpdating (false),
  42835. cursorX (0),
  42836. cursorY (0),
  42837. cursorHeight (0),
  42838. maxTextLength (0),
  42839. leftIndent (4),
  42840. topIndent (4),
  42841. lastTransactionTime (0),
  42842. currentFont (14.0f),
  42843. totalNumChars (0),
  42844. caretPosition (0),
  42845. passwordCharacter (passwordCharacter_),
  42846. dragType (notDragging)
  42847. {
  42848. setOpaque (true);
  42849. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42850. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42851. viewport->setWantsKeyboardFocus (false);
  42852. viewport->setScrollBarsShown (false, false);
  42853. setMouseCursor (MouseCursor::IBeamCursor);
  42854. setWantsKeyboardFocus (true);
  42855. }
  42856. TextEditor::~TextEditor()
  42857. {
  42858. textValue.referTo (Value());
  42859. clearInternal (0);
  42860. viewport = 0;
  42861. textHolder = 0;
  42862. }
  42863. void TextEditor::newTransaction()
  42864. {
  42865. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42866. undoManager.beginNewTransaction();
  42867. }
  42868. void TextEditor::doUndoRedo (const bool isRedo)
  42869. {
  42870. if (! isReadOnly())
  42871. {
  42872. if (isRedo ? undoManager.redo()
  42873. : undoManager.undo())
  42874. {
  42875. scrollToMakeSureCursorIsVisible();
  42876. repaint();
  42877. textChanged();
  42878. }
  42879. }
  42880. }
  42881. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42882. const bool shouldWordWrap)
  42883. {
  42884. if (multiline != shouldBeMultiLine
  42885. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42886. {
  42887. multiline = shouldBeMultiLine;
  42888. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42889. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42890. scrollbarVisible && multiline);
  42891. viewport->setViewPosition (0, 0);
  42892. resized();
  42893. scrollToMakeSureCursorIsVisible();
  42894. }
  42895. }
  42896. bool TextEditor::isMultiLine() const
  42897. {
  42898. return multiline;
  42899. }
  42900. void TextEditor::setScrollbarsShown (bool shown)
  42901. {
  42902. if (scrollbarVisible != shown)
  42903. {
  42904. scrollbarVisible = shown;
  42905. shown = shown && isMultiLine();
  42906. viewport->setScrollBarsShown (shown, shown);
  42907. }
  42908. }
  42909. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42910. {
  42911. if (readOnly != shouldBeReadOnly)
  42912. {
  42913. readOnly = shouldBeReadOnly;
  42914. enablementChanged();
  42915. }
  42916. }
  42917. bool TextEditor::isReadOnly() const
  42918. {
  42919. return readOnly || ! isEnabled();
  42920. }
  42921. bool TextEditor::isTextInputActive() const
  42922. {
  42923. return ! isReadOnly();
  42924. }
  42925. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42926. {
  42927. returnKeyStartsNewLine = shouldStartNewLine;
  42928. }
  42929. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42930. {
  42931. tabKeyUsed = shouldTabKeyBeUsed;
  42932. }
  42933. void TextEditor::setPopupMenuEnabled (const bool b)
  42934. {
  42935. popupMenuEnabled = b;
  42936. }
  42937. void TextEditor::setSelectAllWhenFocused (const bool b)
  42938. {
  42939. selectAllTextWhenFocused = b;
  42940. }
  42941. const Font TextEditor::getFont() const
  42942. {
  42943. return currentFont;
  42944. }
  42945. void TextEditor::setFont (const Font& newFont)
  42946. {
  42947. currentFont = newFont;
  42948. scrollToMakeSureCursorIsVisible();
  42949. }
  42950. void TextEditor::applyFontToAllText (const Font& newFont)
  42951. {
  42952. currentFont = newFont;
  42953. const Colour overallColour (findColour (textColourId));
  42954. for (int i = sections.size(); --i >= 0;)
  42955. {
  42956. UniformTextSection* const uts = sections.getUnchecked (i);
  42957. uts->setFont (newFont, passwordCharacter);
  42958. uts->colour = overallColour;
  42959. }
  42960. coalesceSimilarSections();
  42961. updateTextHolderSize();
  42962. scrollToMakeSureCursorIsVisible();
  42963. repaint();
  42964. }
  42965. void TextEditor::colourChanged()
  42966. {
  42967. setOpaque (findColour (backgroundColourId).isOpaque());
  42968. repaint();
  42969. }
  42970. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42971. {
  42972. caretVisible = shouldCaretBeVisible;
  42973. if (shouldCaretBeVisible)
  42974. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42975. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42976. : MouseCursor::NormalCursor);
  42977. }
  42978. void TextEditor::setInputRestrictions (const int maxLen,
  42979. const String& chars)
  42980. {
  42981. maxTextLength = jmax (0, maxLen);
  42982. allowedCharacters = chars;
  42983. }
  42984. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42985. {
  42986. textToShowWhenEmpty = text;
  42987. colourForTextWhenEmpty = colourToUse;
  42988. }
  42989. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42990. {
  42991. if (passwordCharacter != newPasswordCharacter)
  42992. {
  42993. passwordCharacter = newPasswordCharacter;
  42994. resized();
  42995. repaint();
  42996. }
  42997. }
  42998. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42999. {
  43000. viewport->setScrollBarThickness (newThicknessPixels);
  43001. }
  43002. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43003. {
  43004. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43005. }
  43006. void TextEditor::clear()
  43007. {
  43008. clearInternal (0);
  43009. updateTextHolderSize();
  43010. undoManager.clearUndoHistory();
  43011. }
  43012. void TextEditor::setText (const String& newText,
  43013. const bool sendTextChangeMessage)
  43014. {
  43015. const int newLength = newText.length();
  43016. if (newLength != getTotalNumChars() || getText() != newText)
  43017. {
  43018. const int oldCursorPos = caretPosition;
  43019. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43020. clearInternal (0);
  43021. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43022. // if you're adding text with line-feeds to a single-line text editor, it
  43023. // ain't gonna look right!
  43024. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43025. if (cursorWasAtEnd && ! isMultiLine())
  43026. moveCursorTo (getTotalNumChars(), false);
  43027. else
  43028. moveCursorTo (oldCursorPos, false);
  43029. if (sendTextChangeMessage)
  43030. textChanged();
  43031. updateTextHolderSize();
  43032. scrollToMakeSureCursorIsVisible();
  43033. undoManager.clearUndoHistory();
  43034. repaint();
  43035. }
  43036. }
  43037. Value& TextEditor::getTextValue()
  43038. {
  43039. if (valueTextNeedsUpdating)
  43040. {
  43041. valueTextNeedsUpdating = false;
  43042. textValue = getText();
  43043. }
  43044. return textValue;
  43045. }
  43046. void TextEditor::textWasChangedByValue()
  43047. {
  43048. if (textValue.getValueSource().getReferenceCount() > 1)
  43049. setText (textValue.getValue());
  43050. }
  43051. void TextEditor::textChanged()
  43052. {
  43053. updateTextHolderSize();
  43054. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43055. if (textValue.getValueSource().getReferenceCount() > 1)
  43056. {
  43057. valueTextNeedsUpdating = false;
  43058. textValue = getText();
  43059. }
  43060. }
  43061. void TextEditor::returnPressed()
  43062. {
  43063. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43064. }
  43065. void TextEditor::escapePressed()
  43066. {
  43067. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43068. }
  43069. void TextEditor::addListener (Listener* const newListener)
  43070. {
  43071. listeners.add (newListener);
  43072. }
  43073. void TextEditor::removeListener (Listener* const listenerToRemove)
  43074. {
  43075. listeners.remove (listenerToRemove);
  43076. }
  43077. void TextEditor::timerCallbackInt()
  43078. {
  43079. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43080. if (caretFlashState != newState)
  43081. {
  43082. caretFlashState = newState;
  43083. if (caretFlashState)
  43084. wasFocused = true;
  43085. if (caretVisible
  43086. && hasKeyboardFocus (false)
  43087. && ! isReadOnly())
  43088. {
  43089. repaintCaret();
  43090. }
  43091. }
  43092. const unsigned int now = Time::getApproximateMillisecondCounter();
  43093. if (now > lastTransactionTime + 200)
  43094. newTransaction();
  43095. }
  43096. void TextEditor::repaintCaret()
  43097. {
  43098. if (! findColour (caretColourId).isTransparent())
  43099. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43100. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43101. 4,
  43102. roundToInt (cursorHeight) + 2);
  43103. }
  43104. void TextEditor::repaintText (const Range<int>& range)
  43105. {
  43106. if (! range.isEmpty())
  43107. {
  43108. float x = 0, y = 0, lh = currentFont.getHeight();
  43109. const float wordWrapWidth = getWordWrapWidth();
  43110. if (wordWrapWidth > 0)
  43111. {
  43112. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43113. i.getCharPosition (range.getStart(), x, y, lh);
  43114. const int y1 = (int) y;
  43115. int y2;
  43116. if (range.getEnd() >= getTotalNumChars())
  43117. {
  43118. y2 = textHolder->getHeight();
  43119. }
  43120. else
  43121. {
  43122. i.getCharPosition (range.getEnd(), x, y, lh);
  43123. y2 = (int) (y + lh * 2.0f);
  43124. }
  43125. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43126. }
  43127. }
  43128. }
  43129. void TextEditor::moveCaret (int newCaretPos)
  43130. {
  43131. if (newCaretPos < 0)
  43132. newCaretPos = 0;
  43133. else if (newCaretPos > getTotalNumChars())
  43134. newCaretPos = getTotalNumChars();
  43135. if (newCaretPos != getCaretPosition())
  43136. {
  43137. repaintCaret();
  43138. caretFlashState = true;
  43139. caretPosition = newCaretPos;
  43140. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43141. scrollToMakeSureCursorIsVisible();
  43142. repaintCaret();
  43143. }
  43144. }
  43145. void TextEditor::setCaretPosition (const int newIndex)
  43146. {
  43147. moveCursorTo (newIndex, false);
  43148. }
  43149. int TextEditor::getCaretPosition() const
  43150. {
  43151. return caretPosition;
  43152. }
  43153. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43154. const int desiredCaretY)
  43155. {
  43156. updateCaretPosition();
  43157. int vx = roundToInt (cursorX) - desiredCaretX;
  43158. int vy = roundToInt (cursorY) - desiredCaretY;
  43159. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43160. {
  43161. vx += desiredCaretX - proportionOfWidth (0.2f);
  43162. }
  43163. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43164. {
  43165. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43166. }
  43167. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43168. if (! isMultiLine())
  43169. {
  43170. vy = viewport->getViewPositionY();
  43171. }
  43172. else
  43173. {
  43174. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43175. const int curH = roundToInt (cursorHeight);
  43176. if (desiredCaretY < 0)
  43177. {
  43178. vy = jmax (0, desiredCaretY + vy);
  43179. }
  43180. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43181. {
  43182. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43183. }
  43184. }
  43185. viewport->setViewPosition (vx, vy);
  43186. }
  43187. const Rectangle<int> TextEditor::getCaretRectangle()
  43188. {
  43189. updateCaretPosition();
  43190. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43191. roundToInt (cursorY) - viewport->getY(),
  43192. 1, roundToInt (cursorHeight));
  43193. }
  43194. float TextEditor::getWordWrapWidth() const
  43195. {
  43196. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43197. : 1.0e10f;
  43198. }
  43199. void TextEditor::updateTextHolderSize()
  43200. {
  43201. const float wordWrapWidth = getWordWrapWidth();
  43202. if (wordWrapWidth > 0)
  43203. {
  43204. float maxWidth = 0.0f;
  43205. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43206. while (i.next())
  43207. maxWidth = jmax (maxWidth, i.atomRight);
  43208. const int w = leftIndent + roundToInt (maxWidth);
  43209. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43210. currentFont.getHeight()));
  43211. textHolder->setSize (w + 1, h + 1);
  43212. }
  43213. }
  43214. int TextEditor::getTextWidth() const
  43215. {
  43216. return textHolder->getWidth();
  43217. }
  43218. int TextEditor::getTextHeight() const
  43219. {
  43220. return textHolder->getHeight();
  43221. }
  43222. void TextEditor::setIndents (const int newLeftIndent,
  43223. const int newTopIndent)
  43224. {
  43225. leftIndent = newLeftIndent;
  43226. topIndent = newTopIndent;
  43227. }
  43228. void TextEditor::setBorder (const BorderSize& border)
  43229. {
  43230. borderSize = border;
  43231. resized();
  43232. }
  43233. const BorderSize TextEditor::getBorder() const
  43234. {
  43235. return borderSize;
  43236. }
  43237. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43238. {
  43239. keepCursorOnScreen = shouldScrollToShowCursor;
  43240. }
  43241. void TextEditor::updateCaretPosition()
  43242. {
  43243. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43244. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43245. }
  43246. void TextEditor::scrollToMakeSureCursorIsVisible()
  43247. {
  43248. updateCaretPosition();
  43249. if (keepCursorOnScreen)
  43250. {
  43251. int x = viewport->getViewPositionX();
  43252. int y = viewport->getViewPositionY();
  43253. const int relativeCursorX = roundToInt (cursorX) - x;
  43254. const int relativeCursorY = roundToInt (cursorY) - y;
  43255. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43256. {
  43257. x += relativeCursorX - proportionOfWidth (0.2f);
  43258. }
  43259. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43260. {
  43261. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43262. }
  43263. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43264. if (! isMultiLine())
  43265. {
  43266. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43267. }
  43268. else
  43269. {
  43270. const int curH = roundToInt (cursorHeight);
  43271. if (relativeCursorY < 0)
  43272. {
  43273. y = jmax (0, relativeCursorY + y);
  43274. }
  43275. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43276. {
  43277. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43278. }
  43279. }
  43280. viewport->setViewPosition (x, y);
  43281. }
  43282. }
  43283. void TextEditor::moveCursorTo (const int newPosition,
  43284. const bool isSelecting)
  43285. {
  43286. if (isSelecting)
  43287. {
  43288. moveCaret (newPosition);
  43289. const Range<int> oldSelection (selection);
  43290. if (dragType == notDragging)
  43291. {
  43292. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43293. dragType = draggingSelectionStart;
  43294. else
  43295. dragType = draggingSelectionEnd;
  43296. }
  43297. if (dragType == draggingSelectionStart)
  43298. {
  43299. if (getCaretPosition() >= selection.getEnd())
  43300. dragType = draggingSelectionEnd;
  43301. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43302. }
  43303. else
  43304. {
  43305. if (getCaretPosition() < selection.getStart())
  43306. dragType = draggingSelectionStart;
  43307. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43308. }
  43309. repaintText (selection.getUnionWith (oldSelection));
  43310. }
  43311. else
  43312. {
  43313. dragType = notDragging;
  43314. repaintText (selection);
  43315. moveCaret (newPosition);
  43316. selection = Range<int>::emptyRange (getCaretPosition());
  43317. }
  43318. }
  43319. int TextEditor::getTextIndexAt (const int x,
  43320. const int y)
  43321. {
  43322. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43323. (float) (y + viewport->getViewPositionY() - topIndent));
  43324. }
  43325. void TextEditor::insertTextAtCaret (const String& newText_)
  43326. {
  43327. String newText (newText_);
  43328. if (allowedCharacters.isNotEmpty())
  43329. newText = newText.retainCharacters (allowedCharacters);
  43330. if ((! returnKeyStartsNewLine) && newText == "\n")
  43331. {
  43332. returnPressed();
  43333. return;
  43334. }
  43335. if (! isMultiLine())
  43336. newText = newText.replaceCharacters ("\r\n", " ");
  43337. else
  43338. newText = newText.replace ("\r\n", "\n");
  43339. const int newCaretPos = selection.getStart() + newText.length();
  43340. const int insertIndex = selection.getStart();
  43341. remove (selection, getUndoManager(),
  43342. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43343. if (maxTextLength > 0)
  43344. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43345. if (newText.isNotEmpty())
  43346. insert (newText,
  43347. insertIndex,
  43348. currentFont,
  43349. findColour (textColourId),
  43350. getUndoManager(),
  43351. newCaretPos);
  43352. textChanged();
  43353. }
  43354. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43355. {
  43356. moveCursorTo (newSelection.getStart(), false);
  43357. moveCursorTo (newSelection.getEnd(), true);
  43358. }
  43359. void TextEditor::copy()
  43360. {
  43361. if (passwordCharacter == 0)
  43362. {
  43363. const String selectedText (getHighlightedText());
  43364. if (selectedText.isNotEmpty())
  43365. SystemClipboard::copyTextToClipboard (selectedText);
  43366. }
  43367. }
  43368. void TextEditor::paste()
  43369. {
  43370. if (! isReadOnly())
  43371. {
  43372. const String clip (SystemClipboard::getTextFromClipboard());
  43373. if (clip.isNotEmpty())
  43374. insertTextAtCaret (clip);
  43375. }
  43376. }
  43377. void TextEditor::cut()
  43378. {
  43379. if (! isReadOnly())
  43380. {
  43381. moveCaret (selection.getEnd());
  43382. insertTextAtCaret (String::empty);
  43383. }
  43384. }
  43385. void TextEditor::drawContent (Graphics& g)
  43386. {
  43387. const float wordWrapWidth = getWordWrapWidth();
  43388. if (wordWrapWidth > 0)
  43389. {
  43390. g.setOrigin (leftIndent, topIndent);
  43391. const Rectangle<int> clip (g.getClipBounds());
  43392. Colour selectedTextColour;
  43393. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43394. while (i.lineY + 200.0 < clip.getY() && i.next())
  43395. {}
  43396. if (! selection.isEmpty())
  43397. {
  43398. g.setColour (findColour (highlightColourId)
  43399. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43400. selectedTextColour = findColour (highlightedTextColourId);
  43401. Iterator i2 (i);
  43402. while (i2.next() && i2.lineY < clip.getBottom())
  43403. {
  43404. if (i2.lineY + i2.lineHeight >= clip.getY()
  43405. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43406. {
  43407. i2.drawSelection (g, selection);
  43408. }
  43409. }
  43410. }
  43411. const UniformTextSection* lastSection = 0;
  43412. while (i.next() && i.lineY < clip.getBottom())
  43413. {
  43414. if (i.lineY + i.lineHeight >= clip.getY())
  43415. {
  43416. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43417. {
  43418. i.drawSelectedText (g, selection, selectedTextColour);
  43419. lastSection = 0;
  43420. }
  43421. else
  43422. {
  43423. i.draw (g, lastSection);
  43424. }
  43425. }
  43426. }
  43427. }
  43428. }
  43429. void TextEditor::paint (Graphics& g)
  43430. {
  43431. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43432. }
  43433. void TextEditor::paintOverChildren (Graphics& g)
  43434. {
  43435. if (caretFlashState
  43436. && hasKeyboardFocus (false)
  43437. && caretVisible
  43438. && ! isReadOnly())
  43439. {
  43440. g.setColour (findColour (caretColourId));
  43441. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43442. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43443. 2.0f, cursorHeight);
  43444. }
  43445. if (textToShowWhenEmpty.isNotEmpty()
  43446. && (! hasKeyboardFocus (false))
  43447. && getTotalNumChars() == 0)
  43448. {
  43449. g.setColour (colourForTextWhenEmpty);
  43450. g.setFont (getFont());
  43451. if (isMultiLine())
  43452. {
  43453. g.drawText (textToShowWhenEmpty,
  43454. 0, 0, getWidth(), getHeight(),
  43455. Justification::centred, true);
  43456. }
  43457. else
  43458. {
  43459. g.drawText (textToShowWhenEmpty,
  43460. leftIndent, topIndent,
  43461. viewport->getWidth() - leftIndent,
  43462. viewport->getHeight() - topIndent,
  43463. Justification::centredLeft, true);
  43464. }
  43465. }
  43466. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43467. }
  43468. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43469. {
  43470. public:
  43471. TextEditorMenuPerformer (TextEditor* const editor_)
  43472. : editor (editor_)
  43473. {
  43474. }
  43475. void modalStateFinished (int returnValue)
  43476. {
  43477. if (editor != 0 && returnValue != 0)
  43478. editor->performPopupMenuAction (returnValue);
  43479. }
  43480. private:
  43481. Component::SafePointer<TextEditor> editor;
  43482. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43483. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43484. };
  43485. void TextEditor::mouseDown (const MouseEvent& e)
  43486. {
  43487. beginDragAutoRepeat (100);
  43488. newTransaction();
  43489. if (wasFocused || ! selectAllTextWhenFocused)
  43490. {
  43491. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43492. {
  43493. moveCursorTo (getTextIndexAt (e.x, e.y),
  43494. e.mods.isShiftDown());
  43495. }
  43496. else
  43497. {
  43498. PopupMenu m;
  43499. m.setLookAndFeel (&getLookAndFeel());
  43500. addPopupMenuItems (m, &e);
  43501. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43502. }
  43503. }
  43504. }
  43505. void TextEditor::mouseDrag (const MouseEvent& e)
  43506. {
  43507. if (wasFocused || ! selectAllTextWhenFocused)
  43508. {
  43509. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43510. {
  43511. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43512. }
  43513. }
  43514. }
  43515. void TextEditor::mouseUp (const MouseEvent& e)
  43516. {
  43517. newTransaction();
  43518. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43519. if (wasFocused || ! selectAllTextWhenFocused)
  43520. {
  43521. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43522. {
  43523. moveCaret (getTextIndexAt (e.x, e.y));
  43524. }
  43525. }
  43526. wasFocused = true;
  43527. }
  43528. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43529. {
  43530. int tokenEnd = getTextIndexAt (e.x, e.y);
  43531. int tokenStart = tokenEnd;
  43532. if (e.getNumberOfClicks() > 3)
  43533. {
  43534. tokenStart = 0;
  43535. tokenEnd = getTotalNumChars();
  43536. }
  43537. else
  43538. {
  43539. const String t (getText());
  43540. const int totalLength = getTotalNumChars();
  43541. while (tokenEnd < totalLength)
  43542. {
  43543. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43544. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43545. ++tokenEnd;
  43546. else
  43547. break;
  43548. }
  43549. tokenStart = tokenEnd;
  43550. while (tokenStart > 0)
  43551. {
  43552. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43553. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43554. --tokenStart;
  43555. else
  43556. break;
  43557. }
  43558. if (e.getNumberOfClicks() > 2)
  43559. {
  43560. while (tokenEnd < totalLength)
  43561. {
  43562. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43563. ++tokenEnd;
  43564. else
  43565. break;
  43566. }
  43567. while (tokenStart > 0)
  43568. {
  43569. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43570. --tokenStart;
  43571. else
  43572. break;
  43573. }
  43574. }
  43575. }
  43576. moveCursorTo (tokenEnd, false);
  43577. moveCursorTo (tokenStart, true);
  43578. }
  43579. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43580. {
  43581. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43582. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43583. }
  43584. bool TextEditor::keyPressed (const KeyPress& key)
  43585. {
  43586. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43587. return false;
  43588. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43589. if (key.isKeyCode (KeyPress::leftKey)
  43590. || key.isKeyCode (KeyPress::upKey))
  43591. {
  43592. newTransaction();
  43593. int newPos;
  43594. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43595. newPos = indexAtPosition (cursorX, cursorY - 1);
  43596. else if (moveInWholeWordSteps)
  43597. newPos = findWordBreakBefore (getCaretPosition());
  43598. else
  43599. newPos = getCaretPosition() - 1;
  43600. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43601. }
  43602. else if (key.isKeyCode (KeyPress::rightKey)
  43603. || key.isKeyCode (KeyPress::downKey))
  43604. {
  43605. newTransaction();
  43606. int newPos;
  43607. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43608. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43609. else if (moveInWholeWordSteps)
  43610. newPos = findWordBreakAfter (getCaretPosition());
  43611. else
  43612. newPos = getCaretPosition() + 1;
  43613. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43614. }
  43615. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43616. {
  43617. newTransaction();
  43618. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43619. key.getModifiers().isShiftDown());
  43620. }
  43621. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43622. {
  43623. newTransaction();
  43624. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43625. key.getModifiers().isShiftDown());
  43626. }
  43627. else if (key.isKeyCode (KeyPress::homeKey))
  43628. {
  43629. newTransaction();
  43630. if (isMultiLine() && ! moveInWholeWordSteps)
  43631. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43632. key.getModifiers().isShiftDown());
  43633. else
  43634. moveCursorTo (0, key.getModifiers().isShiftDown());
  43635. }
  43636. else if (key.isKeyCode (KeyPress::endKey))
  43637. {
  43638. newTransaction();
  43639. if (isMultiLine() && ! moveInWholeWordSteps)
  43640. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43641. key.getModifiers().isShiftDown());
  43642. else
  43643. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43644. }
  43645. else if (key.isKeyCode (KeyPress::backspaceKey))
  43646. {
  43647. if (moveInWholeWordSteps)
  43648. {
  43649. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43650. }
  43651. else
  43652. {
  43653. if (selection.isEmpty() && selection.getStart() > 0)
  43654. selection.setStart (selection.getEnd() - 1);
  43655. }
  43656. cut();
  43657. }
  43658. else if (key.isKeyCode (KeyPress::deleteKey))
  43659. {
  43660. if (key.getModifiers().isShiftDown())
  43661. copy();
  43662. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43663. selection.setEnd (selection.getStart() + 1);
  43664. cut();
  43665. }
  43666. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43667. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43668. {
  43669. newTransaction();
  43670. copy();
  43671. }
  43672. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43673. {
  43674. newTransaction();
  43675. copy();
  43676. cut();
  43677. }
  43678. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43679. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43680. {
  43681. newTransaction();
  43682. paste();
  43683. }
  43684. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43685. {
  43686. newTransaction();
  43687. doUndoRedo (false);
  43688. }
  43689. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43690. {
  43691. newTransaction();
  43692. doUndoRedo (true);
  43693. }
  43694. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43695. {
  43696. newTransaction();
  43697. moveCursorTo (getTotalNumChars(), false);
  43698. moveCursorTo (0, true);
  43699. }
  43700. else if (key == KeyPress::returnKey)
  43701. {
  43702. newTransaction();
  43703. insertTextAtCaret ("\n");
  43704. }
  43705. else if (key.isKeyCode (KeyPress::escapeKey))
  43706. {
  43707. newTransaction();
  43708. moveCursorTo (getCaretPosition(), false);
  43709. escapePressed();
  43710. }
  43711. else if (key.getTextCharacter() >= ' '
  43712. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43713. {
  43714. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43715. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43716. }
  43717. else
  43718. {
  43719. return false;
  43720. }
  43721. return true;
  43722. }
  43723. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43724. {
  43725. if (! isKeyDown)
  43726. return false;
  43727. #if JUCE_WINDOWS
  43728. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43729. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43730. #endif
  43731. // (overridden to avoid forwarding key events to the parent)
  43732. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43733. }
  43734. const int baseMenuItemID = 0x7fff0000;
  43735. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43736. {
  43737. const bool writable = ! isReadOnly();
  43738. if (passwordCharacter == 0)
  43739. {
  43740. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43741. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43742. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43743. }
  43744. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43745. m.addSeparator();
  43746. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43747. m.addSeparator();
  43748. if (getUndoManager() != 0)
  43749. {
  43750. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43751. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43752. }
  43753. }
  43754. void TextEditor::performPopupMenuAction (const int menuItemID)
  43755. {
  43756. switch (menuItemID)
  43757. {
  43758. case baseMenuItemID + 1:
  43759. copy();
  43760. cut();
  43761. break;
  43762. case baseMenuItemID + 2:
  43763. copy();
  43764. break;
  43765. case baseMenuItemID + 3:
  43766. paste();
  43767. break;
  43768. case baseMenuItemID + 4:
  43769. cut();
  43770. break;
  43771. case baseMenuItemID + 5:
  43772. moveCursorTo (getTotalNumChars(), false);
  43773. moveCursorTo (0, true);
  43774. break;
  43775. case baseMenuItemID + 6:
  43776. doUndoRedo (false);
  43777. break;
  43778. case baseMenuItemID + 7:
  43779. doUndoRedo (true);
  43780. break;
  43781. default:
  43782. break;
  43783. }
  43784. }
  43785. void TextEditor::focusGained (FocusChangeType)
  43786. {
  43787. newTransaction();
  43788. caretFlashState = true;
  43789. if (selectAllTextWhenFocused)
  43790. {
  43791. moveCursorTo (0, false);
  43792. moveCursorTo (getTotalNumChars(), true);
  43793. }
  43794. repaint();
  43795. if (caretVisible)
  43796. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43797. ComponentPeer* const peer = getPeer();
  43798. if (peer != 0 && ! isReadOnly())
  43799. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43800. }
  43801. void TextEditor::focusLost (FocusChangeType)
  43802. {
  43803. newTransaction();
  43804. wasFocused = false;
  43805. textHolder->stopTimer();
  43806. caretFlashState = false;
  43807. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43808. repaint();
  43809. }
  43810. void TextEditor::resized()
  43811. {
  43812. viewport->setBoundsInset (borderSize);
  43813. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43814. updateTextHolderSize();
  43815. if (! isMultiLine())
  43816. {
  43817. scrollToMakeSureCursorIsVisible();
  43818. }
  43819. else
  43820. {
  43821. updateCaretPosition();
  43822. }
  43823. }
  43824. void TextEditor::handleCommandMessage (const int commandId)
  43825. {
  43826. Component::BailOutChecker checker (this);
  43827. switch (commandId)
  43828. {
  43829. case TextEditorDefs::textChangeMessageId:
  43830. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43831. break;
  43832. case TextEditorDefs::returnKeyMessageId:
  43833. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43834. break;
  43835. case TextEditorDefs::escapeKeyMessageId:
  43836. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43837. break;
  43838. case TextEditorDefs::focusLossMessageId:
  43839. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43840. break;
  43841. default:
  43842. jassertfalse;
  43843. break;
  43844. }
  43845. }
  43846. void TextEditor::enablementChanged()
  43847. {
  43848. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43849. : MouseCursor::IBeamCursor);
  43850. repaint();
  43851. }
  43852. UndoManager* TextEditor::getUndoManager() throw()
  43853. {
  43854. return isReadOnly() ? 0 : &undoManager;
  43855. }
  43856. void TextEditor::clearInternal (UndoManager* const um)
  43857. {
  43858. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43859. }
  43860. void TextEditor::insert (const String& text,
  43861. const int insertIndex,
  43862. const Font& font,
  43863. const Colour& colour,
  43864. UndoManager* const um,
  43865. const int caretPositionToMoveTo)
  43866. {
  43867. if (text.isNotEmpty())
  43868. {
  43869. if (um != 0)
  43870. {
  43871. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43872. newTransaction();
  43873. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43874. caretPosition, caretPositionToMoveTo));
  43875. }
  43876. else
  43877. {
  43878. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43879. // a line gets moved due to word wrap
  43880. int index = 0;
  43881. int nextIndex = 0;
  43882. for (int i = 0; i < sections.size(); ++i)
  43883. {
  43884. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43885. if (insertIndex == index)
  43886. {
  43887. sections.insert (i, new UniformTextSection (text,
  43888. font, colour,
  43889. passwordCharacter));
  43890. break;
  43891. }
  43892. else if (insertIndex > index && insertIndex < nextIndex)
  43893. {
  43894. splitSection (i, insertIndex - index);
  43895. sections.insert (i + 1, new UniformTextSection (text,
  43896. font, colour,
  43897. passwordCharacter));
  43898. break;
  43899. }
  43900. index = nextIndex;
  43901. }
  43902. if (nextIndex == insertIndex)
  43903. sections.add (new UniformTextSection (text,
  43904. font, colour,
  43905. passwordCharacter));
  43906. coalesceSimilarSections();
  43907. totalNumChars = -1;
  43908. valueTextNeedsUpdating = true;
  43909. moveCursorTo (caretPositionToMoveTo, false);
  43910. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43911. }
  43912. }
  43913. }
  43914. void TextEditor::reinsert (const int insertIndex,
  43915. const Array <UniformTextSection*>& sectionsToInsert)
  43916. {
  43917. int index = 0;
  43918. int nextIndex = 0;
  43919. for (int i = 0; i < sections.size(); ++i)
  43920. {
  43921. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43922. if (insertIndex == index)
  43923. {
  43924. for (int j = sectionsToInsert.size(); --j >= 0;)
  43925. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43926. break;
  43927. }
  43928. else if (insertIndex > index && insertIndex < nextIndex)
  43929. {
  43930. splitSection (i, insertIndex - index);
  43931. for (int j = sectionsToInsert.size(); --j >= 0;)
  43932. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43933. break;
  43934. }
  43935. index = nextIndex;
  43936. }
  43937. if (nextIndex == insertIndex)
  43938. {
  43939. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43940. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43941. }
  43942. coalesceSimilarSections();
  43943. totalNumChars = -1;
  43944. valueTextNeedsUpdating = true;
  43945. }
  43946. void TextEditor::remove (const Range<int>& range,
  43947. UndoManager* const um,
  43948. const int caretPositionToMoveTo)
  43949. {
  43950. if (! range.isEmpty())
  43951. {
  43952. int index = 0;
  43953. for (int i = 0; i < sections.size(); ++i)
  43954. {
  43955. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43956. if (range.getStart() > index && range.getStart() < nextIndex)
  43957. {
  43958. splitSection (i, range.getStart() - index);
  43959. --i;
  43960. }
  43961. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43962. {
  43963. splitSection (i, range.getEnd() - index);
  43964. --i;
  43965. }
  43966. else
  43967. {
  43968. index = nextIndex;
  43969. if (index > range.getEnd())
  43970. break;
  43971. }
  43972. }
  43973. index = 0;
  43974. if (um != 0)
  43975. {
  43976. Array <UniformTextSection*> removedSections;
  43977. for (int i = 0; i < sections.size(); ++i)
  43978. {
  43979. if (range.getEnd() <= range.getStart())
  43980. break;
  43981. UniformTextSection* const section = sections.getUnchecked (i);
  43982. const int nextIndex = index + section->getTotalLength();
  43983. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43984. removedSections.add (new UniformTextSection (*section));
  43985. index = nextIndex;
  43986. }
  43987. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43988. newTransaction();
  43989. um->perform (new RemoveAction (*this, range, caretPosition,
  43990. caretPositionToMoveTo, removedSections));
  43991. }
  43992. else
  43993. {
  43994. Range<int> remainingRange (range);
  43995. for (int i = 0; i < sections.size(); ++i)
  43996. {
  43997. UniformTextSection* const section = sections.getUnchecked (i);
  43998. const int nextIndex = index + section->getTotalLength();
  43999. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44000. {
  44001. sections.remove(i);
  44002. section->clear();
  44003. delete section;
  44004. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44005. if (remainingRange.isEmpty())
  44006. break;
  44007. --i;
  44008. }
  44009. else
  44010. {
  44011. index = nextIndex;
  44012. }
  44013. }
  44014. coalesceSimilarSections();
  44015. totalNumChars = -1;
  44016. valueTextNeedsUpdating = true;
  44017. moveCursorTo (caretPositionToMoveTo, false);
  44018. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44019. }
  44020. }
  44021. }
  44022. const String TextEditor::getText() const
  44023. {
  44024. String t;
  44025. t.preallocateStorage (getTotalNumChars());
  44026. String::Concatenator concatenator (t);
  44027. for (int i = 0; i < sections.size(); ++i)
  44028. sections.getUnchecked (i)->appendAllText (concatenator);
  44029. return t;
  44030. }
  44031. const String TextEditor::getTextInRange (const Range<int>& range) const
  44032. {
  44033. String t;
  44034. if (! range.isEmpty())
  44035. {
  44036. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44037. String::Concatenator concatenator (t);
  44038. int index = 0;
  44039. for (int i = 0; i < sections.size(); ++i)
  44040. {
  44041. const UniformTextSection* const s = sections.getUnchecked (i);
  44042. const int nextIndex = index + s->getTotalLength();
  44043. if (range.getStart() < nextIndex)
  44044. {
  44045. if (range.getEnd() <= index)
  44046. break;
  44047. s->appendSubstring (concatenator, range - index);
  44048. }
  44049. index = nextIndex;
  44050. }
  44051. }
  44052. return t;
  44053. }
  44054. const String TextEditor::getHighlightedText() const
  44055. {
  44056. return getTextInRange (selection);
  44057. }
  44058. int TextEditor::getTotalNumChars() const
  44059. {
  44060. if (totalNumChars < 0)
  44061. {
  44062. totalNumChars = 0;
  44063. for (int i = sections.size(); --i >= 0;)
  44064. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44065. }
  44066. return totalNumChars;
  44067. }
  44068. bool TextEditor::isEmpty() const
  44069. {
  44070. return getTotalNumChars() == 0;
  44071. }
  44072. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44073. {
  44074. const float wordWrapWidth = getWordWrapWidth();
  44075. if (wordWrapWidth > 0 && sections.size() > 0)
  44076. {
  44077. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44078. i.getCharPosition (index, cx, cy, lineHeight);
  44079. }
  44080. else
  44081. {
  44082. cx = cy = 0;
  44083. lineHeight = currentFont.getHeight();
  44084. }
  44085. }
  44086. int TextEditor::indexAtPosition (const float x, const float y)
  44087. {
  44088. const float wordWrapWidth = getWordWrapWidth();
  44089. if (wordWrapWidth > 0)
  44090. {
  44091. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44092. while (i.next())
  44093. {
  44094. if (i.lineY + i.lineHeight > y)
  44095. {
  44096. if (i.lineY > y)
  44097. return jmax (0, i.indexInText - 1);
  44098. if (i.atomX >= x)
  44099. return i.indexInText;
  44100. if (x < i.atomRight)
  44101. return i.xToIndex (x);
  44102. }
  44103. }
  44104. }
  44105. return getTotalNumChars();
  44106. }
  44107. static int getCharacterCategory (const juce_wchar character)
  44108. {
  44109. return CharacterFunctions::isLetterOrDigit (character)
  44110. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  44111. }
  44112. int TextEditor::findWordBreakAfter (const int position) const
  44113. {
  44114. const String t (getTextInRange (Range<int> (position, position + 512)));
  44115. const int totalLength = t.length();
  44116. int i = 0;
  44117. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44118. ++i;
  44119. const int type = getCharacterCategory (t[i]);
  44120. while (i < totalLength && type == getCharacterCategory (t[i]))
  44121. ++i;
  44122. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44123. ++i;
  44124. return position + i;
  44125. }
  44126. int TextEditor::findWordBreakBefore (const int position) const
  44127. {
  44128. if (position <= 0)
  44129. return 0;
  44130. const int startOfBuffer = jmax (0, position - 512);
  44131. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44132. int i = position - startOfBuffer;
  44133. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44134. --i;
  44135. if (i > 0)
  44136. {
  44137. const int type = getCharacterCategory (t [i - 1]);
  44138. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  44139. --i;
  44140. }
  44141. jassert (startOfBuffer + i >= 0);
  44142. return startOfBuffer + i;
  44143. }
  44144. void TextEditor::splitSection (const int sectionIndex,
  44145. const int charToSplitAt)
  44146. {
  44147. jassert (sections[sectionIndex] != 0);
  44148. sections.insert (sectionIndex + 1,
  44149. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44150. }
  44151. void TextEditor::coalesceSimilarSections()
  44152. {
  44153. for (int i = 0; i < sections.size() - 1; ++i)
  44154. {
  44155. UniformTextSection* const s1 = sections.getUnchecked (i);
  44156. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44157. if (s1->font == s2->font
  44158. && s1->colour == s2->colour)
  44159. {
  44160. s1->append (*s2, passwordCharacter);
  44161. sections.remove (i + 1);
  44162. delete s2;
  44163. --i;
  44164. }
  44165. }
  44166. }
  44167. END_JUCE_NAMESPACE
  44168. /*** End of inlined file: juce_TextEditor.cpp ***/
  44169. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44170. BEGIN_JUCE_NAMESPACE
  44171. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44172. class ToolbarSpacerComp : public ToolbarItemComponent
  44173. {
  44174. public:
  44175. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44176. : ToolbarItemComponent (itemId_, String::empty, false),
  44177. fixedSize (fixedSize_),
  44178. drawBar (drawBar_)
  44179. {
  44180. }
  44181. ~ToolbarSpacerComp()
  44182. {
  44183. }
  44184. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44185. int& preferredSize, int& minSize, int& maxSize)
  44186. {
  44187. if (fixedSize <= 0)
  44188. {
  44189. preferredSize = toolbarThickness * 2;
  44190. minSize = 4;
  44191. maxSize = 32768;
  44192. }
  44193. else
  44194. {
  44195. maxSize = roundToInt (toolbarThickness * fixedSize);
  44196. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44197. preferredSize = maxSize;
  44198. if (getEditingMode() == editableOnPalette)
  44199. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44200. }
  44201. return true;
  44202. }
  44203. void paintButtonArea (Graphics&, int, int, bool, bool)
  44204. {
  44205. }
  44206. void contentAreaChanged (const Rectangle<int>&)
  44207. {
  44208. }
  44209. int getResizeOrder() const throw()
  44210. {
  44211. return fixedSize <= 0 ? 0 : 1;
  44212. }
  44213. void paint (Graphics& g)
  44214. {
  44215. const int w = getWidth();
  44216. const int h = getHeight();
  44217. if (drawBar)
  44218. {
  44219. g.setColour (findColour (Toolbar::separatorColourId, true));
  44220. const float thickness = 0.2f;
  44221. if (isToolbarVertical())
  44222. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44223. else
  44224. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44225. }
  44226. if (getEditingMode() != normalMode && ! drawBar)
  44227. {
  44228. g.setColour (findColour (Toolbar::separatorColourId, true));
  44229. const int indentX = jmin (2, (w - 3) / 2);
  44230. const int indentY = jmin (2, (h - 3) / 2);
  44231. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44232. if (fixedSize <= 0)
  44233. {
  44234. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44235. if (isToolbarVertical())
  44236. {
  44237. x1 = w * 0.5f;
  44238. y1 = h * 0.4f;
  44239. x2 = x1;
  44240. y2 = indentX * 2.0f;
  44241. x3 = x1;
  44242. y3 = h * 0.6f;
  44243. x4 = x1;
  44244. y4 = h - y2;
  44245. hw = w * 0.15f;
  44246. hl = w * 0.2f;
  44247. }
  44248. else
  44249. {
  44250. x1 = w * 0.4f;
  44251. y1 = h * 0.5f;
  44252. x2 = indentX * 2.0f;
  44253. y2 = y1;
  44254. x3 = w * 0.6f;
  44255. y3 = y1;
  44256. x4 = w - x2;
  44257. y4 = y1;
  44258. hw = h * 0.15f;
  44259. hl = h * 0.2f;
  44260. }
  44261. Path p;
  44262. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44263. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44264. g.fillPath (p);
  44265. }
  44266. }
  44267. }
  44268. juce_UseDebuggingNewOperator
  44269. private:
  44270. const float fixedSize;
  44271. const bool drawBar;
  44272. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44273. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44274. };
  44275. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44276. {
  44277. public:
  44278. MissingItemsComponent (Toolbar& owner_, const int height_)
  44279. : PopupMenuCustomComponent (true),
  44280. owner (owner_),
  44281. height (height_)
  44282. {
  44283. for (int i = owner_.items.size(); --i >= 0;)
  44284. {
  44285. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44286. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44287. {
  44288. oldIndexes.insert (0, i);
  44289. addAndMakeVisible (tc, 0);
  44290. }
  44291. }
  44292. layout (400);
  44293. }
  44294. ~MissingItemsComponent()
  44295. {
  44296. // deleting the toolbar while its menu it open??
  44297. jassert (owner.isValidComponent());
  44298. for (int i = 0; i < getNumChildComponents(); ++i)
  44299. {
  44300. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44301. if (tc != 0)
  44302. {
  44303. tc->setVisible (false);
  44304. const int index = oldIndexes.remove (i);
  44305. owner.addChildComponent (tc, index);
  44306. --i;
  44307. }
  44308. }
  44309. owner.resized();
  44310. }
  44311. void layout (const int preferredWidth)
  44312. {
  44313. const int indent = 8;
  44314. int x = indent;
  44315. int y = indent;
  44316. int maxX = 0;
  44317. for (int i = 0; i < getNumChildComponents(); ++i)
  44318. {
  44319. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44320. if (tc != 0)
  44321. {
  44322. int preferredSize = 1, minSize = 1, maxSize = 1;
  44323. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44324. {
  44325. if (x + preferredSize > preferredWidth && x > indent)
  44326. {
  44327. x = indent;
  44328. y += height;
  44329. }
  44330. tc->setBounds (x, y, preferredSize, height);
  44331. x += preferredSize;
  44332. maxX = jmax (maxX, x);
  44333. }
  44334. }
  44335. }
  44336. setSize (maxX + 8, y + height + 8);
  44337. }
  44338. void getIdealSize (int& idealWidth, int& idealHeight)
  44339. {
  44340. idealWidth = getWidth();
  44341. idealHeight = getHeight();
  44342. }
  44343. juce_UseDebuggingNewOperator
  44344. private:
  44345. Toolbar& owner;
  44346. const int height;
  44347. Array <int> oldIndexes;
  44348. MissingItemsComponent (const MissingItemsComponent&);
  44349. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44350. };
  44351. Toolbar::Toolbar()
  44352. : vertical (false),
  44353. isEditingActive (false),
  44354. toolbarStyle (Toolbar::iconsOnly)
  44355. {
  44356. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44357. missingItemsButton->setAlwaysOnTop (true);
  44358. missingItemsButton->addButtonListener (this);
  44359. }
  44360. Toolbar::~Toolbar()
  44361. {
  44362. animator.cancelAllAnimations (true);
  44363. deleteAllChildren();
  44364. }
  44365. void Toolbar::setVertical (const bool shouldBeVertical)
  44366. {
  44367. if (vertical != shouldBeVertical)
  44368. {
  44369. vertical = shouldBeVertical;
  44370. resized();
  44371. }
  44372. }
  44373. void Toolbar::clear()
  44374. {
  44375. for (int i = items.size(); --i >= 0;)
  44376. {
  44377. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44378. items.remove (i);
  44379. delete tc;
  44380. }
  44381. resized();
  44382. }
  44383. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44384. {
  44385. if (itemId == ToolbarItemFactory::separatorBarId)
  44386. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44387. else if (itemId == ToolbarItemFactory::spacerId)
  44388. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44389. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44390. return new ToolbarSpacerComp (itemId, 0, false);
  44391. return factory.createItem (itemId);
  44392. }
  44393. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44394. const int itemId,
  44395. const int insertIndex)
  44396. {
  44397. // An ID can't be zero - this might indicate a mistake somewhere?
  44398. jassert (itemId != 0);
  44399. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44400. if (tc != 0)
  44401. {
  44402. #if JUCE_DEBUG
  44403. Array <int> allowedIds;
  44404. factory.getAllToolbarItemIds (allowedIds);
  44405. // If your factory can create an item for a given ID, it must also return
  44406. // that ID from its getAllToolbarItemIds() method!
  44407. jassert (allowedIds.contains (itemId));
  44408. #endif
  44409. items.insert (insertIndex, tc);
  44410. addAndMakeVisible (tc, insertIndex);
  44411. }
  44412. }
  44413. void Toolbar::addItem (ToolbarItemFactory& factory,
  44414. const int itemId,
  44415. const int insertIndex)
  44416. {
  44417. addItemInternal (factory, itemId, insertIndex);
  44418. resized();
  44419. }
  44420. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44421. {
  44422. Array <int> ids;
  44423. factoryToUse.getDefaultItemSet (ids);
  44424. clear();
  44425. for (int i = 0; i < ids.size(); ++i)
  44426. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44427. resized();
  44428. }
  44429. void Toolbar::removeToolbarItem (const int itemIndex)
  44430. {
  44431. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44432. if (tc != 0)
  44433. {
  44434. items.removeValue (tc);
  44435. delete tc;
  44436. resized();
  44437. }
  44438. }
  44439. int Toolbar::getNumItems() const throw()
  44440. {
  44441. return items.size();
  44442. }
  44443. int Toolbar::getItemId (const int itemIndex) const throw()
  44444. {
  44445. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44446. return tc != 0 ? tc->getItemId() : 0;
  44447. }
  44448. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44449. {
  44450. return items [itemIndex];
  44451. }
  44452. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44453. {
  44454. for (;;)
  44455. {
  44456. index += delta;
  44457. ToolbarItemComponent* const tc = getItemComponent (index);
  44458. if (tc == 0)
  44459. break;
  44460. if (tc->isActive)
  44461. return tc;
  44462. }
  44463. return 0;
  44464. }
  44465. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44466. {
  44467. if (toolbarStyle != newStyle)
  44468. {
  44469. toolbarStyle = newStyle;
  44470. updateAllItemPositions (false);
  44471. }
  44472. }
  44473. const String Toolbar::toString() const
  44474. {
  44475. String s ("TB:");
  44476. for (int i = 0; i < getNumItems(); ++i)
  44477. s << getItemId(i) << ' ';
  44478. return s.trimEnd();
  44479. }
  44480. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44481. const String& savedVersion)
  44482. {
  44483. if (! savedVersion.startsWith ("TB:"))
  44484. return false;
  44485. StringArray tokens;
  44486. tokens.addTokens (savedVersion.substring (3), false);
  44487. clear();
  44488. for (int i = 0; i < tokens.size(); ++i)
  44489. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44490. resized();
  44491. return true;
  44492. }
  44493. void Toolbar::paint (Graphics& g)
  44494. {
  44495. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44496. }
  44497. int Toolbar::getThickness() const throw()
  44498. {
  44499. return vertical ? getWidth() : getHeight();
  44500. }
  44501. int Toolbar::getLength() const throw()
  44502. {
  44503. return vertical ? getHeight() : getWidth();
  44504. }
  44505. void Toolbar::setEditingActive (const bool active)
  44506. {
  44507. if (isEditingActive != active)
  44508. {
  44509. isEditingActive = active;
  44510. updateAllItemPositions (false);
  44511. }
  44512. }
  44513. void Toolbar::resized()
  44514. {
  44515. updateAllItemPositions (false);
  44516. }
  44517. void Toolbar::updateAllItemPositions (const bool animate)
  44518. {
  44519. if (getWidth() > 0 && getHeight() > 0)
  44520. {
  44521. StretchableObjectResizer resizer;
  44522. int i;
  44523. for (i = 0; i < items.size(); ++i)
  44524. {
  44525. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44526. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44527. : ToolbarItemComponent::normalMode);
  44528. tc->setStyle (toolbarStyle);
  44529. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44530. int preferredSize = 1, minSize = 1, maxSize = 1;
  44531. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44532. preferredSize, minSize, maxSize))
  44533. {
  44534. tc->isActive = true;
  44535. resizer.addItem (preferredSize, minSize, maxSize,
  44536. spacer != 0 ? spacer->getResizeOrder() : 2);
  44537. }
  44538. else
  44539. {
  44540. tc->isActive = false;
  44541. tc->setVisible (false);
  44542. }
  44543. }
  44544. resizer.resizeToFit (getLength());
  44545. int totalLength = 0;
  44546. for (i = 0; i < resizer.getNumItems(); ++i)
  44547. totalLength += (int) resizer.getItemSize (i);
  44548. const bool itemsOffTheEnd = totalLength > getLength();
  44549. const int extrasButtonSize = getThickness() / 2;
  44550. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44551. missingItemsButton->setVisible (itemsOffTheEnd);
  44552. missingItemsButton->setEnabled (! isEditingActive);
  44553. if (vertical)
  44554. missingItemsButton->setCentrePosition (getWidth() / 2,
  44555. getHeight() - 4 - extrasButtonSize / 2);
  44556. else
  44557. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44558. getHeight() / 2);
  44559. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44560. : missingItemsButton->getX()) - 4
  44561. : getLength();
  44562. int pos = 0, activeIndex = 0;
  44563. for (i = 0; i < items.size(); ++i)
  44564. {
  44565. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44566. if (tc->isActive)
  44567. {
  44568. const int size = (int) resizer.getItemSize (activeIndex++);
  44569. Rectangle<int> newBounds;
  44570. if (vertical)
  44571. newBounds.setBounds (0, pos, getWidth(), size);
  44572. else
  44573. newBounds.setBounds (pos, 0, size, getHeight());
  44574. if (animate)
  44575. {
  44576. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  44577. }
  44578. else
  44579. {
  44580. animator.cancelAnimation (tc, false);
  44581. tc->setBounds (newBounds);
  44582. }
  44583. pos += size;
  44584. tc->setVisible (pos <= maxLength
  44585. && ((! tc->isBeingDragged)
  44586. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44587. }
  44588. }
  44589. }
  44590. }
  44591. void Toolbar::buttonClicked (Button*)
  44592. {
  44593. jassert (missingItemsButton->isShowing());
  44594. if (missingItemsButton->isShowing())
  44595. {
  44596. PopupMenu m;
  44597. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44598. m.showAt (missingItemsButton);
  44599. }
  44600. }
  44601. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44602. Component* /*sourceComponent*/)
  44603. {
  44604. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44605. }
  44606. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44607. {
  44608. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44609. if (tc != 0)
  44610. {
  44611. if (getNumItems() == 0)
  44612. {
  44613. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44614. {
  44615. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44616. if (palette != 0)
  44617. palette->replaceComponent (tc);
  44618. }
  44619. else
  44620. {
  44621. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44622. }
  44623. items.add (tc);
  44624. addChildComponent (tc);
  44625. updateAllItemPositions (false);
  44626. }
  44627. else
  44628. {
  44629. for (int i = getNumItems(); --i >= 0;)
  44630. {
  44631. int currentIndex = getIndexOfChildComponent (tc);
  44632. if (currentIndex < 0)
  44633. {
  44634. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44635. {
  44636. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44637. if (palette != 0)
  44638. palette->replaceComponent (tc);
  44639. }
  44640. else
  44641. {
  44642. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44643. }
  44644. items.add (tc);
  44645. addChildComponent (tc);
  44646. currentIndex = getIndexOfChildComponent (tc);
  44647. updateAllItemPositions (true);
  44648. }
  44649. int newIndex = currentIndex;
  44650. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44651. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44652. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  44653. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44654. if (prev != 0)
  44655. {
  44656. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  44657. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44658. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44659. {
  44660. newIndex = getIndexOfChildComponent (prev);
  44661. }
  44662. }
  44663. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44664. if (next != 0)
  44665. {
  44666. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  44667. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44668. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44669. {
  44670. newIndex = getIndexOfChildComponent (next) + 1;
  44671. }
  44672. }
  44673. if (newIndex != currentIndex)
  44674. {
  44675. items.removeValue (tc);
  44676. removeChildComponent (tc);
  44677. addChildComponent (tc, newIndex);
  44678. items.insert (newIndex, tc);
  44679. updateAllItemPositions (true);
  44680. }
  44681. else
  44682. {
  44683. break;
  44684. }
  44685. }
  44686. }
  44687. }
  44688. }
  44689. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44690. {
  44691. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44692. if (tc != 0)
  44693. {
  44694. if (isParentOf (tc))
  44695. {
  44696. items.removeValue (tc);
  44697. removeChildComponent (tc);
  44698. updateAllItemPositions (true);
  44699. }
  44700. }
  44701. }
  44702. void Toolbar::itemDropped (const String&, Component*, int, int)
  44703. {
  44704. }
  44705. void Toolbar::mouseDown (const MouseEvent& e)
  44706. {
  44707. if (e.mods.isPopupMenu())
  44708. {
  44709. }
  44710. }
  44711. class ToolbarCustomisationDialog : public DialogWindow
  44712. {
  44713. public:
  44714. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44715. Toolbar* const toolbar_,
  44716. const int optionFlags)
  44717. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44718. toolbar (toolbar_)
  44719. {
  44720. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44721. setResizable (true, true);
  44722. setResizeLimits (400, 300, 1500, 1000);
  44723. positionNearBar();
  44724. }
  44725. ~ToolbarCustomisationDialog()
  44726. {
  44727. setContentComponent (0, true);
  44728. }
  44729. void closeButtonPressed()
  44730. {
  44731. setVisible (false);
  44732. }
  44733. bool canModalEventBeSentToComponent (const Component* comp)
  44734. {
  44735. return toolbar->isParentOf (comp);
  44736. }
  44737. void positionNearBar()
  44738. {
  44739. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44740. const int tbx = toolbar->getScreenX();
  44741. const int tby = toolbar->getScreenY();
  44742. const int gap = 8;
  44743. int x, y;
  44744. if (toolbar->isVertical())
  44745. {
  44746. y = tby;
  44747. if (tbx > screenSize.getCentreX())
  44748. x = tbx - getWidth() - gap;
  44749. else
  44750. x = tbx + toolbar->getWidth() + gap;
  44751. }
  44752. else
  44753. {
  44754. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44755. if (tby > screenSize.getCentreY())
  44756. y = tby - getHeight() - gap;
  44757. else
  44758. y = tby + toolbar->getHeight() + gap;
  44759. }
  44760. setTopLeftPosition (x, y);
  44761. }
  44762. private:
  44763. Toolbar* const toolbar;
  44764. class CustomiserPanel : public Component,
  44765. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44766. private ButtonListener
  44767. {
  44768. public:
  44769. CustomiserPanel (ToolbarItemFactory& factory_,
  44770. Toolbar* const toolbar_,
  44771. const int optionFlags)
  44772. : factory (factory_),
  44773. toolbar (toolbar_),
  44774. styleBox (0),
  44775. defaultButton (0)
  44776. {
  44777. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44778. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44779. | Toolbar::allowIconsWithTextChoice
  44780. | Toolbar::allowTextOnlyChoice)) != 0)
  44781. {
  44782. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44783. styleBox->setEditableText (false);
  44784. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44785. styleBox->addItem (TRANS("Show icons only"), 1);
  44786. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44787. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44788. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44789. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44790. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44791. styleBox->setSelectedId (1);
  44792. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44793. styleBox->setSelectedId (2);
  44794. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44795. styleBox->setSelectedId (3);
  44796. styleBox->addListener (this);
  44797. }
  44798. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44799. {
  44800. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44801. defaultButton->addButtonListener (this);
  44802. }
  44803. addAndMakeVisible (instructions = new Label (String::empty,
  44804. 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.")));
  44805. instructions->setFont (Font (13.0f));
  44806. setSize (500, 300);
  44807. }
  44808. ~CustomiserPanel()
  44809. {
  44810. deleteAllChildren();
  44811. }
  44812. void comboBoxChanged (ComboBox*)
  44813. {
  44814. if (styleBox->getSelectedId() == 1)
  44815. toolbar->setStyle (Toolbar::iconsOnly);
  44816. else if (styleBox->getSelectedId() == 2)
  44817. toolbar->setStyle (Toolbar::iconsWithText);
  44818. else if (styleBox->getSelectedId() == 3)
  44819. toolbar->setStyle (Toolbar::textOnly);
  44820. palette->resized(); // to make it update the styles
  44821. }
  44822. void buttonClicked (Button*)
  44823. {
  44824. toolbar->addDefaultItems (factory);
  44825. }
  44826. void paint (Graphics& g)
  44827. {
  44828. Colour background;
  44829. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44830. if (dw != 0)
  44831. background = dw->getBackgroundColour();
  44832. g.setColour (background.contrasting().withAlpha (0.3f));
  44833. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44834. }
  44835. void resized()
  44836. {
  44837. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44838. if (styleBox != 0)
  44839. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44840. if (defaultButton != 0)
  44841. {
  44842. defaultButton->changeWidthToFitText (22);
  44843. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44844. }
  44845. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44846. }
  44847. private:
  44848. ToolbarItemFactory& factory;
  44849. Toolbar* const toolbar;
  44850. Label* instructions;
  44851. ToolbarItemPalette* palette;
  44852. ComboBox* styleBox;
  44853. TextButton* defaultButton;
  44854. };
  44855. };
  44856. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44857. {
  44858. setEditingActive (true);
  44859. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44860. dw.runModalLoop();
  44861. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44862. setEditingActive (false);
  44863. }
  44864. END_JUCE_NAMESPACE
  44865. /*** End of inlined file: juce_Toolbar.cpp ***/
  44866. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44867. BEGIN_JUCE_NAMESPACE
  44868. ToolbarItemFactory::ToolbarItemFactory()
  44869. {
  44870. }
  44871. ToolbarItemFactory::~ToolbarItemFactory()
  44872. {
  44873. }
  44874. class ItemDragAndDropOverlayComponent : public Component
  44875. {
  44876. public:
  44877. ItemDragAndDropOverlayComponent()
  44878. : isDragging (false)
  44879. {
  44880. setAlwaysOnTop (true);
  44881. setRepaintsOnMouseActivity (true);
  44882. setMouseCursor (MouseCursor::DraggingHandCursor);
  44883. }
  44884. ~ItemDragAndDropOverlayComponent()
  44885. {
  44886. }
  44887. void paint (Graphics& g)
  44888. {
  44889. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44890. if (isMouseOverOrDragging()
  44891. && tc != 0
  44892. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44893. {
  44894. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44895. g.drawRect (0, 0, getWidth(), getHeight(),
  44896. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44897. }
  44898. }
  44899. void mouseDown (const MouseEvent& e)
  44900. {
  44901. isDragging = false;
  44902. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44903. if (tc != 0)
  44904. {
  44905. tc->dragOffsetX = e.x;
  44906. tc->dragOffsetY = e.y;
  44907. }
  44908. }
  44909. void mouseDrag (const MouseEvent& e)
  44910. {
  44911. if (! (isDragging || e.mouseWasClicked()))
  44912. {
  44913. isDragging = true;
  44914. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44915. if (dnd != 0)
  44916. {
  44917. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44918. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44919. if (tc != 0)
  44920. {
  44921. tc->isBeingDragged = true;
  44922. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44923. tc->setVisible (false);
  44924. }
  44925. }
  44926. }
  44927. }
  44928. void mouseUp (const MouseEvent&)
  44929. {
  44930. isDragging = false;
  44931. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44932. if (tc != 0)
  44933. {
  44934. tc->isBeingDragged = false;
  44935. Toolbar* const tb = tc->getToolbar();
  44936. if (tb != 0)
  44937. tb->updateAllItemPositions (true);
  44938. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44939. delete tc;
  44940. }
  44941. }
  44942. void parentSizeChanged()
  44943. {
  44944. setBounds (0, 0, getParentWidth(), getParentHeight());
  44945. }
  44946. juce_UseDebuggingNewOperator
  44947. private:
  44948. bool isDragging;
  44949. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44950. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44951. };
  44952. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44953. const String& labelText,
  44954. const bool isBeingUsedAsAButton_)
  44955. : Button (labelText),
  44956. itemId (itemId_),
  44957. mode (normalMode),
  44958. toolbarStyle (Toolbar::iconsOnly),
  44959. dragOffsetX (0),
  44960. dragOffsetY (0),
  44961. isActive (true),
  44962. isBeingDragged (false),
  44963. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44964. {
  44965. // Your item ID can't be 0!
  44966. jassert (itemId_ != 0);
  44967. }
  44968. ToolbarItemComponent::~ToolbarItemComponent()
  44969. {
  44970. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44971. overlayComp = 0;
  44972. }
  44973. Toolbar* ToolbarItemComponent::getToolbar() const
  44974. {
  44975. return dynamic_cast <Toolbar*> (getParentComponent());
  44976. }
  44977. bool ToolbarItemComponent::isToolbarVertical() const
  44978. {
  44979. const Toolbar* const t = getToolbar();
  44980. return t != 0 && t->isVertical();
  44981. }
  44982. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44983. {
  44984. if (toolbarStyle != newStyle)
  44985. {
  44986. toolbarStyle = newStyle;
  44987. repaint();
  44988. resized();
  44989. }
  44990. }
  44991. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44992. {
  44993. if (isBeingUsedAsAButton)
  44994. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44995. over, down, *this);
  44996. if (toolbarStyle != Toolbar::iconsOnly)
  44997. {
  44998. const int indent = contentArea.getX();
  44999. int y = indent;
  45000. int h = getHeight() - indent * 2;
  45001. if (toolbarStyle == Toolbar::iconsWithText)
  45002. {
  45003. y = contentArea.getBottom() + indent / 2;
  45004. h -= contentArea.getHeight();
  45005. }
  45006. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45007. getButtonText(), *this);
  45008. }
  45009. if (! contentArea.isEmpty())
  45010. {
  45011. g.saveState();
  45012. g.setOrigin (contentArea.getX(), contentArea.getY());
  45013. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  45014. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45015. g.restoreState();
  45016. }
  45017. }
  45018. void ToolbarItemComponent::resized()
  45019. {
  45020. if (toolbarStyle != Toolbar::textOnly)
  45021. {
  45022. const int indent = jmin (proportionOfWidth (0.08f),
  45023. proportionOfHeight (0.08f));
  45024. contentArea = Rectangle<int> (indent, indent,
  45025. getWidth() - indent * 2,
  45026. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45027. : (getHeight() - indent * 2));
  45028. }
  45029. else
  45030. {
  45031. contentArea = Rectangle<int>();
  45032. }
  45033. contentAreaChanged (contentArea);
  45034. }
  45035. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45036. {
  45037. if (mode != newMode)
  45038. {
  45039. mode = newMode;
  45040. repaint();
  45041. if (mode == normalMode)
  45042. {
  45043. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45044. overlayComp = 0;
  45045. }
  45046. else if (overlayComp == 0)
  45047. {
  45048. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45049. overlayComp->parentSizeChanged();
  45050. }
  45051. resized();
  45052. }
  45053. }
  45054. END_JUCE_NAMESPACE
  45055. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45056. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45057. BEGIN_JUCE_NAMESPACE
  45058. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45059. Toolbar* const toolbar_)
  45060. : factory (factory_),
  45061. toolbar (toolbar_)
  45062. {
  45063. Component* const itemHolder = new Component();
  45064. Array <int> allIds;
  45065. factory_.getAllToolbarItemIds (allIds);
  45066. for (int i = 0; i < allIds.size(); ++i)
  45067. {
  45068. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45069. jassert (tc != 0);
  45070. if (tc != 0)
  45071. {
  45072. itemHolder->addAndMakeVisible (tc);
  45073. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45074. }
  45075. }
  45076. viewport = new Viewport();
  45077. viewport->setViewedComponent (itemHolder);
  45078. addAndMakeVisible (viewport);
  45079. }
  45080. ToolbarItemPalette::~ToolbarItemPalette()
  45081. {
  45082. viewport->getViewedComponent()->deleteAllChildren();
  45083. deleteAllChildren();
  45084. }
  45085. void ToolbarItemPalette::resized()
  45086. {
  45087. viewport->setBoundsInset (BorderSize (1));
  45088. Component* const itemHolder = viewport->getViewedComponent();
  45089. const int indent = 8;
  45090. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  45091. const int height = toolbar->getThickness();
  45092. int x = indent;
  45093. int y = indent;
  45094. int maxX = 0;
  45095. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45096. {
  45097. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45098. if (tc != 0)
  45099. {
  45100. tc->setStyle (toolbar->getStyle());
  45101. int preferredSize = 1, minSize = 1, maxSize = 1;
  45102. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45103. {
  45104. if (x + preferredSize > preferredWidth && x > indent)
  45105. {
  45106. x = indent;
  45107. y += height;
  45108. }
  45109. tc->setBounds (x, y, preferredSize, height);
  45110. x += preferredSize + 8;
  45111. maxX = jmax (maxX, x);
  45112. }
  45113. }
  45114. }
  45115. itemHolder->setSize (maxX, y + height + 8);
  45116. }
  45117. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45118. {
  45119. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45120. jassert (tc != 0);
  45121. if (tc != 0)
  45122. {
  45123. tc->setBounds (comp->getBounds());
  45124. tc->setStyle (toolbar->getStyle());
  45125. tc->setEditingMode (comp->getEditingMode());
  45126. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45127. }
  45128. }
  45129. END_JUCE_NAMESPACE
  45130. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45131. /*** Start of inlined file: juce_TreeView.cpp ***/
  45132. BEGIN_JUCE_NAMESPACE
  45133. class TreeViewContentComponent : public Component,
  45134. public TooltipClient
  45135. {
  45136. public:
  45137. TreeViewContentComponent (TreeView& owner_)
  45138. : owner (owner_),
  45139. buttonUnderMouse (0),
  45140. isDragging (false)
  45141. {
  45142. }
  45143. ~TreeViewContentComponent()
  45144. {
  45145. deleteAllChildren();
  45146. }
  45147. void mouseDown (const MouseEvent& e)
  45148. {
  45149. updateButtonUnderMouse (e);
  45150. isDragging = false;
  45151. needSelectionOnMouseUp = false;
  45152. Rectangle<int> pos;
  45153. TreeViewItem* const item = findItemAt (e.y, pos);
  45154. if (item == 0)
  45155. return;
  45156. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45157. // as selection clicks)
  45158. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45159. {
  45160. if (e.x >= pos.getX() - owner.getIndentSize())
  45161. item->setOpen (! item->isOpen());
  45162. // (clicks to the left of an open/close button are ignored)
  45163. }
  45164. else
  45165. {
  45166. // mouse-down inside the body of the item..
  45167. if (! owner.isMultiSelectEnabled())
  45168. item->setSelected (true, true);
  45169. else if (item->isSelected())
  45170. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45171. else
  45172. selectBasedOnModifiers (item, e.mods);
  45173. if (e.x >= pos.getX())
  45174. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45175. }
  45176. }
  45177. void mouseUp (const MouseEvent& e)
  45178. {
  45179. updateButtonUnderMouse (e);
  45180. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45181. {
  45182. Rectangle<int> pos;
  45183. TreeViewItem* const item = findItemAt (e.y, pos);
  45184. if (item != 0)
  45185. selectBasedOnModifiers (item, e.mods);
  45186. }
  45187. }
  45188. void mouseDoubleClick (const MouseEvent& e)
  45189. {
  45190. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45191. {
  45192. Rectangle<int> pos;
  45193. TreeViewItem* const item = findItemAt (e.y, pos);
  45194. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45195. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45196. }
  45197. }
  45198. void mouseDrag (const MouseEvent& e)
  45199. {
  45200. if (isEnabled()
  45201. && ! (isDragging || e.mouseWasClicked()
  45202. || e.getDistanceFromDragStart() < 5
  45203. || e.mods.isPopupMenu()))
  45204. {
  45205. isDragging = true;
  45206. Rectangle<int> pos;
  45207. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45208. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45209. {
  45210. const String dragDescription (item->getDragSourceDescription());
  45211. if (dragDescription.isNotEmpty())
  45212. {
  45213. DragAndDropContainer* const dragContainer
  45214. = DragAndDropContainer::findParentDragContainerFor (this);
  45215. if (dragContainer != 0)
  45216. {
  45217. pos.setSize (pos.getWidth(), item->itemHeight);
  45218. Image dragImage (Component::createComponentSnapshot (pos, true));
  45219. dragImage.multiplyAllAlphas (0.6f);
  45220. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45221. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45222. }
  45223. else
  45224. {
  45225. // to be able to do a drag-and-drop operation, the treeview needs to
  45226. // be inside a component which is also a DragAndDropContainer.
  45227. jassertfalse;
  45228. }
  45229. }
  45230. }
  45231. }
  45232. }
  45233. void mouseMove (const MouseEvent& e)
  45234. {
  45235. updateButtonUnderMouse (e);
  45236. }
  45237. void mouseExit (const MouseEvent& e)
  45238. {
  45239. updateButtonUnderMouse (e);
  45240. }
  45241. void paint (Graphics& g)
  45242. {
  45243. if (owner.rootItem != 0)
  45244. {
  45245. owner.handleAsyncUpdate();
  45246. if (! owner.rootItemVisible)
  45247. g.setOrigin (0, -owner.rootItem->itemHeight);
  45248. owner.rootItem->paintRecursively (g, getWidth());
  45249. }
  45250. }
  45251. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45252. {
  45253. if (owner.rootItem != 0)
  45254. {
  45255. owner.handleAsyncUpdate();
  45256. if (! owner.rootItemVisible)
  45257. y += owner.rootItem->itemHeight;
  45258. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45259. if (ti != 0)
  45260. itemPosition = ti->getItemPosition (false);
  45261. return ti;
  45262. }
  45263. return 0;
  45264. }
  45265. void updateComponents()
  45266. {
  45267. const int visibleTop = -getY();
  45268. const int visibleBottom = visibleTop + getParentHeight();
  45269. BigInteger itemsToKeep;
  45270. {
  45271. TreeViewItem* item = owner.rootItem;
  45272. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45273. while (item != 0 && y < visibleBottom)
  45274. {
  45275. y += item->itemHeight;
  45276. if (y >= visibleTop)
  45277. {
  45278. const int index = rowComponentIds.indexOf (item->uid);
  45279. if (index < 0)
  45280. {
  45281. Component* const comp = item->createItemComponent();
  45282. if (comp != 0)
  45283. {
  45284. addAndMakeVisible (comp);
  45285. itemsToKeep.setBit (rowComponentItems.size());
  45286. rowComponentItems.add (item);
  45287. rowComponentIds.add (item->uid);
  45288. rowComponents.add (comp);
  45289. }
  45290. }
  45291. else
  45292. {
  45293. itemsToKeep.setBit (index);
  45294. }
  45295. }
  45296. item = item->getNextVisibleItem (true);
  45297. }
  45298. }
  45299. for (int i = rowComponentItems.size(); --i >= 0;)
  45300. {
  45301. Component* const comp = rowComponents.getUnchecked(i);
  45302. bool keep = false;
  45303. if (isParentOf (comp))
  45304. {
  45305. if (itemsToKeep[i])
  45306. {
  45307. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  45308. Rectangle<int> pos (item->getItemPosition (false));
  45309. pos.setSize (pos.getWidth(), item->itemHeight);
  45310. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45311. {
  45312. keep = true;
  45313. comp->setBounds (pos);
  45314. }
  45315. }
  45316. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  45317. {
  45318. keep = true;
  45319. comp->setSize (0, 0);
  45320. }
  45321. }
  45322. if (! keep)
  45323. {
  45324. delete comp;
  45325. rowComponents.remove (i);
  45326. rowComponentIds.remove (i);
  45327. rowComponentItems.remove (i);
  45328. }
  45329. }
  45330. }
  45331. void updateButtonUnderMouse (const MouseEvent& e)
  45332. {
  45333. TreeViewItem* newItem = 0;
  45334. if (owner.openCloseButtonsVisible)
  45335. {
  45336. Rectangle<int> pos;
  45337. TreeViewItem* item = findItemAt (e.y, pos);
  45338. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45339. {
  45340. newItem = item;
  45341. if (! newItem->mightContainSubItems())
  45342. newItem = 0;
  45343. }
  45344. }
  45345. if (buttonUnderMouse != newItem)
  45346. {
  45347. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45348. {
  45349. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45350. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45351. }
  45352. buttonUnderMouse = newItem;
  45353. if (buttonUnderMouse != 0)
  45354. {
  45355. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45356. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45357. }
  45358. }
  45359. }
  45360. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45361. {
  45362. return item == buttonUnderMouse;
  45363. }
  45364. void resized()
  45365. {
  45366. owner.itemsChanged();
  45367. }
  45368. const String getTooltip()
  45369. {
  45370. Rectangle<int> pos;
  45371. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45372. if (item != 0)
  45373. return item->getTooltip();
  45374. return owner.getTooltip();
  45375. }
  45376. juce_UseDebuggingNewOperator
  45377. private:
  45378. TreeView& owner;
  45379. Array <TreeViewItem*> rowComponentItems;
  45380. Array <int> rowComponentIds;
  45381. Array <Component*> rowComponents;
  45382. TreeViewItem* buttonUnderMouse;
  45383. bool isDragging, needSelectionOnMouseUp;
  45384. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45385. {
  45386. TreeViewItem* firstSelected = 0;
  45387. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45388. {
  45389. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45390. jassert (lastSelected != 0);
  45391. int rowStart = firstSelected->getRowNumberInTree();
  45392. int rowEnd = lastSelected->getRowNumberInTree();
  45393. if (rowStart > rowEnd)
  45394. swapVariables (rowStart, rowEnd);
  45395. int ourRow = item->getRowNumberInTree();
  45396. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45397. if (ourRow > otherEnd)
  45398. swapVariables (ourRow, otherEnd);
  45399. for (int i = ourRow; i <= otherEnd; ++i)
  45400. owner.getItemOnRow (i)->setSelected (true, false);
  45401. }
  45402. else
  45403. {
  45404. const bool cmd = modifiers.isCommandDown();
  45405. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45406. }
  45407. }
  45408. bool containsItem (TreeViewItem* const item) const
  45409. {
  45410. for (int i = rowComponentItems.size(); --i >= 0;)
  45411. if (rowComponentItems.getUnchecked(i) == item)
  45412. return true;
  45413. return false;
  45414. }
  45415. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45416. {
  45417. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45418. {
  45419. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45420. if (source->isDragging())
  45421. {
  45422. Component* const underMouse = source->getComponentUnderMouse();
  45423. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45424. return true;
  45425. }
  45426. }
  45427. return false;
  45428. }
  45429. TreeViewContentComponent (const TreeViewContentComponent&);
  45430. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45431. };
  45432. class TreeView::TreeViewport : public Viewport
  45433. {
  45434. public:
  45435. TreeViewport() throw() : lastX (-1) {}
  45436. ~TreeViewport() throw() {}
  45437. void updateComponents (const bool triggerResize = false)
  45438. {
  45439. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45440. if (tvc != 0)
  45441. {
  45442. if (triggerResize)
  45443. tvc->resized();
  45444. else
  45445. tvc->updateComponents();
  45446. }
  45447. repaint();
  45448. }
  45449. void visibleAreaChanged (int x, int, int, int)
  45450. {
  45451. const bool hasScrolledSideways = (x != lastX);
  45452. lastX = x;
  45453. updateComponents (hasScrolledSideways);
  45454. }
  45455. juce_UseDebuggingNewOperator
  45456. private:
  45457. int lastX;
  45458. TreeViewport (const TreeViewport&);
  45459. TreeViewport& operator= (const TreeViewport&);
  45460. };
  45461. TreeView::TreeView (const String& componentName)
  45462. : Component (componentName),
  45463. rootItem (0),
  45464. indentSize (24),
  45465. defaultOpenness (false),
  45466. needsRecalculating (true),
  45467. rootItemVisible (true),
  45468. multiSelectEnabled (false),
  45469. openCloseButtonsVisible (true)
  45470. {
  45471. addAndMakeVisible (viewport = new TreeViewport());
  45472. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45473. viewport->setWantsKeyboardFocus (false);
  45474. setWantsKeyboardFocus (true);
  45475. }
  45476. TreeView::~TreeView()
  45477. {
  45478. if (rootItem != 0)
  45479. rootItem->setOwnerView (0);
  45480. }
  45481. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45482. {
  45483. if (rootItem != newRootItem)
  45484. {
  45485. if (newRootItem != 0)
  45486. {
  45487. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45488. if (newRootItem->ownerView != 0)
  45489. newRootItem->ownerView->setRootItem (0);
  45490. }
  45491. if (rootItem != 0)
  45492. rootItem->setOwnerView (0);
  45493. rootItem = newRootItem;
  45494. if (newRootItem != 0)
  45495. newRootItem->setOwnerView (this);
  45496. needsRecalculating = true;
  45497. handleAsyncUpdate();
  45498. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45499. {
  45500. rootItem->setOpen (false); // force a re-open
  45501. rootItem->setOpen (true);
  45502. }
  45503. }
  45504. }
  45505. void TreeView::deleteRootItem()
  45506. {
  45507. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45508. setRootItem (0);
  45509. }
  45510. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45511. {
  45512. rootItemVisible = shouldBeVisible;
  45513. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45514. {
  45515. rootItem->setOpen (false); // force a re-open
  45516. rootItem->setOpen (true);
  45517. }
  45518. itemsChanged();
  45519. }
  45520. void TreeView::colourChanged()
  45521. {
  45522. setOpaque (findColour (backgroundColourId).isOpaque());
  45523. repaint();
  45524. }
  45525. void TreeView::setIndentSize (const int newIndentSize)
  45526. {
  45527. if (indentSize != newIndentSize)
  45528. {
  45529. indentSize = newIndentSize;
  45530. resized();
  45531. }
  45532. }
  45533. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45534. {
  45535. if (defaultOpenness != isOpenByDefault)
  45536. {
  45537. defaultOpenness = isOpenByDefault;
  45538. itemsChanged();
  45539. }
  45540. }
  45541. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45542. {
  45543. multiSelectEnabled = canMultiSelect;
  45544. }
  45545. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45546. {
  45547. if (openCloseButtonsVisible != shouldBeVisible)
  45548. {
  45549. openCloseButtonsVisible = shouldBeVisible;
  45550. itemsChanged();
  45551. }
  45552. }
  45553. Viewport* TreeView::getViewport() const throw()
  45554. {
  45555. return viewport;
  45556. }
  45557. void TreeView::clearSelectedItems()
  45558. {
  45559. if (rootItem != 0)
  45560. rootItem->deselectAllRecursively();
  45561. }
  45562. int TreeView::getNumSelectedItems() const throw()
  45563. {
  45564. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45565. }
  45566. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45567. {
  45568. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45569. }
  45570. int TreeView::getNumRowsInTree() const
  45571. {
  45572. if (rootItem != 0)
  45573. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45574. return 0;
  45575. }
  45576. TreeViewItem* TreeView::getItemOnRow (int index) const
  45577. {
  45578. if (! rootItemVisible)
  45579. ++index;
  45580. if (rootItem != 0 && index >= 0)
  45581. return rootItem->getItemOnRow (index);
  45582. return 0;
  45583. }
  45584. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45585. {
  45586. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45587. Rectangle<int> pos;
  45588. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45589. }
  45590. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45591. {
  45592. if (rootItem == 0)
  45593. return 0;
  45594. return rootItem->findItemFromIdentifierString (identifierString);
  45595. }
  45596. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45597. {
  45598. XmlElement* e = 0;
  45599. if (rootItem != 0)
  45600. {
  45601. e = rootItem->getOpennessState();
  45602. if (e != 0 && alsoIncludeScrollPosition)
  45603. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45604. }
  45605. return e;
  45606. }
  45607. void TreeView::restoreOpennessState (const XmlElement& newState)
  45608. {
  45609. if (rootItem != 0)
  45610. {
  45611. rootItem->restoreOpennessState (newState);
  45612. if (newState.hasAttribute ("scrollPos"))
  45613. viewport->setViewPosition (viewport->getViewPositionX(),
  45614. newState.getIntAttribute ("scrollPos"));
  45615. }
  45616. }
  45617. void TreeView::paint (Graphics& g)
  45618. {
  45619. g.fillAll (findColour (backgroundColourId));
  45620. }
  45621. void TreeView::resized()
  45622. {
  45623. viewport->setBounds (getLocalBounds());
  45624. itemsChanged();
  45625. handleAsyncUpdate();
  45626. }
  45627. void TreeView::enablementChanged()
  45628. {
  45629. repaint();
  45630. }
  45631. void TreeView::moveSelectedRow (int delta)
  45632. {
  45633. if (delta == 0)
  45634. return;
  45635. int rowSelected = 0;
  45636. TreeViewItem* const firstSelected = getSelectedItem (0);
  45637. if (firstSelected != 0)
  45638. rowSelected = firstSelected->getRowNumberInTree();
  45639. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45640. for (;;)
  45641. {
  45642. TreeViewItem* item = getItemOnRow (rowSelected);
  45643. if (item != 0)
  45644. {
  45645. if (! item->canBeSelected())
  45646. {
  45647. // if the row we want to highlight doesn't allow it, try skipping
  45648. // to the next item..
  45649. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45650. rowSelected + (delta < 0 ? -1 : 1));
  45651. if (rowSelected != nextRowToTry)
  45652. {
  45653. rowSelected = nextRowToTry;
  45654. continue;
  45655. }
  45656. else
  45657. {
  45658. break;
  45659. }
  45660. }
  45661. item->setSelected (true, true);
  45662. scrollToKeepItemVisible (item);
  45663. }
  45664. break;
  45665. }
  45666. }
  45667. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45668. {
  45669. if (item != 0 && item->ownerView == this)
  45670. {
  45671. handleAsyncUpdate();
  45672. item = item->getDeepestOpenParentItem();
  45673. int y = item->y;
  45674. int viewTop = viewport->getViewPositionY();
  45675. if (y < viewTop)
  45676. {
  45677. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45678. }
  45679. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45680. {
  45681. viewport->setViewPosition (viewport->getViewPositionX(),
  45682. (y + item->itemHeight) - viewport->getViewHeight());
  45683. }
  45684. }
  45685. }
  45686. bool TreeView::keyPressed (const KeyPress& key)
  45687. {
  45688. if (key.isKeyCode (KeyPress::upKey))
  45689. {
  45690. moveSelectedRow (-1);
  45691. }
  45692. else if (key.isKeyCode (KeyPress::downKey))
  45693. {
  45694. moveSelectedRow (1);
  45695. }
  45696. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45697. {
  45698. if (rootItem != 0)
  45699. {
  45700. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45701. if (key.isKeyCode (KeyPress::pageUpKey))
  45702. rowsOnScreen = -rowsOnScreen;
  45703. moveSelectedRow (rowsOnScreen);
  45704. }
  45705. }
  45706. else if (key.isKeyCode (KeyPress::homeKey))
  45707. {
  45708. moveSelectedRow (-0x3fffffff);
  45709. }
  45710. else if (key.isKeyCode (KeyPress::endKey))
  45711. {
  45712. moveSelectedRow (0x3fffffff);
  45713. }
  45714. else if (key.isKeyCode (KeyPress::returnKey))
  45715. {
  45716. TreeViewItem* const firstSelected = getSelectedItem (0);
  45717. if (firstSelected != 0)
  45718. firstSelected->setOpen (! firstSelected->isOpen());
  45719. }
  45720. else if (key.isKeyCode (KeyPress::leftKey))
  45721. {
  45722. TreeViewItem* const firstSelected = getSelectedItem (0);
  45723. if (firstSelected != 0)
  45724. {
  45725. if (firstSelected->isOpen())
  45726. {
  45727. firstSelected->setOpen (false);
  45728. }
  45729. else
  45730. {
  45731. TreeViewItem* parent = firstSelected->parentItem;
  45732. if ((! rootItemVisible) && parent == rootItem)
  45733. parent = 0;
  45734. if (parent != 0)
  45735. {
  45736. parent->setSelected (true, true);
  45737. scrollToKeepItemVisible (parent);
  45738. }
  45739. }
  45740. }
  45741. }
  45742. else if (key.isKeyCode (KeyPress::rightKey))
  45743. {
  45744. TreeViewItem* const firstSelected = getSelectedItem (0);
  45745. if (firstSelected != 0)
  45746. {
  45747. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45748. moveSelectedRow (1);
  45749. else
  45750. firstSelected->setOpen (true);
  45751. }
  45752. }
  45753. else
  45754. {
  45755. return false;
  45756. }
  45757. return true;
  45758. }
  45759. void TreeView::itemsChanged() throw()
  45760. {
  45761. needsRecalculating = true;
  45762. repaint();
  45763. triggerAsyncUpdate();
  45764. }
  45765. void TreeView::handleAsyncUpdate()
  45766. {
  45767. if (needsRecalculating)
  45768. {
  45769. needsRecalculating = false;
  45770. const ScopedLock sl (nodeAlterationLock);
  45771. if (rootItem != 0)
  45772. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45773. viewport->updateComponents();
  45774. if (rootItem != 0)
  45775. {
  45776. viewport->getViewedComponent()
  45777. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45778. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45779. }
  45780. else
  45781. {
  45782. viewport->getViewedComponent()->setSize (0, 0);
  45783. }
  45784. }
  45785. }
  45786. class TreeView::InsertPointHighlight : public Component
  45787. {
  45788. public:
  45789. InsertPointHighlight()
  45790. : lastItem (0)
  45791. {
  45792. setSize (100, 12);
  45793. setAlwaysOnTop (true);
  45794. setInterceptsMouseClicks (false, false);
  45795. }
  45796. ~InsertPointHighlight() {}
  45797. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45798. {
  45799. lastItem = item;
  45800. lastIndex = insertIndex;
  45801. const int offset = getHeight() / 2;
  45802. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45803. }
  45804. void paint (Graphics& g)
  45805. {
  45806. Path p;
  45807. const float h = (float) getHeight();
  45808. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45809. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45810. p.lineTo ((float) getWidth(), h / 2.0f);
  45811. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45812. g.strokePath (p, PathStrokeType (2.0f));
  45813. }
  45814. TreeViewItem* lastItem;
  45815. int lastIndex;
  45816. private:
  45817. InsertPointHighlight (const InsertPointHighlight&);
  45818. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45819. };
  45820. class TreeView::TargetGroupHighlight : public Component
  45821. {
  45822. public:
  45823. TargetGroupHighlight()
  45824. {
  45825. setAlwaysOnTop (true);
  45826. setInterceptsMouseClicks (false, false);
  45827. }
  45828. ~TargetGroupHighlight() {}
  45829. void setTargetPosition (TreeViewItem* const item) throw()
  45830. {
  45831. Rectangle<int> r (item->getItemPosition (true));
  45832. r.setHeight (item->getItemHeight());
  45833. setBounds (r);
  45834. }
  45835. void paint (Graphics& g)
  45836. {
  45837. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45838. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45839. }
  45840. private:
  45841. TargetGroupHighlight (const TargetGroupHighlight&);
  45842. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45843. };
  45844. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45845. {
  45846. beginDragAutoRepeat (100);
  45847. if (dragInsertPointHighlight == 0)
  45848. {
  45849. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45850. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45851. }
  45852. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45853. dragTargetGroupHighlight->setTargetPosition (item);
  45854. }
  45855. void TreeView::hideDragHighlight() throw()
  45856. {
  45857. dragInsertPointHighlight = 0;
  45858. dragTargetGroupHighlight = 0;
  45859. }
  45860. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45861. const StringArray& files, const String& sourceDescription,
  45862. Component* sourceComponent) const throw()
  45863. {
  45864. insertIndex = 0;
  45865. TreeViewItem* item = getItemAt (y);
  45866. if (item == 0)
  45867. return 0;
  45868. Rectangle<int> itemPos (item->getItemPosition (true));
  45869. insertIndex = item->getIndexInParent();
  45870. const int oldY = y;
  45871. y = itemPos.getY();
  45872. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45873. {
  45874. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45875. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45876. {
  45877. // Check if we're trying to drag into an empty group item..
  45878. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45879. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45880. {
  45881. insertIndex = 0;
  45882. x = itemPos.getX() + getIndentSize();
  45883. y = itemPos.getBottom();
  45884. return item;
  45885. }
  45886. }
  45887. }
  45888. if (oldY > itemPos.getCentreY())
  45889. {
  45890. y += item->getItemHeight();
  45891. while (item->isLastOfSiblings() && item->parentItem != 0
  45892. && item->parentItem->parentItem != 0)
  45893. {
  45894. if (x > itemPos.getX())
  45895. break;
  45896. item = item->parentItem;
  45897. itemPos = item->getItemPosition (true);
  45898. insertIndex = item->getIndexInParent();
  45899. }
  45900. ++insertIndex;
  45901. }
  45902. x = itemPos.getX();
  45903. return item->parentItem;
  45904. }
  45905. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45906. {
  45907. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45908. int insertIndex;
  45909. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45910. if (item != 0)
  45911. {
  45912. if (scrolled || dragInsertPointHighlight == 0
  45913. || dragInsertPointHighlight->lastItem != item
  45914. || dragInsertPointHighlight->lastIndex != insertIndex)
  45915. {
  45916. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45917. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45918. showDragHighlight (item, insertIndex, x, y);
  45919. else
  45920. hideDragHighlight();
  45921. }
  45922. }
  45923. else
  45924. {
  45925. hideDragHighlight();
  45926. }
  45927. }
  45928. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45929. {
  45930. hideDragHighlight();
  45931. int insertIndex;
  45932. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45933. if (item != 0)
  45934. {
  45935. if (files.size() > 0)
  45936. {
  45937. if (item->isInterestedInFileDrag (files))
  45938. item->filesDropped (files, insertIndex);
  45939. }
  45940. else
  45941. {
  45942. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45943. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45944. }
  45945. }
  45946. }
  45947. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45948. {
  45949. return true;
  45950. }
  45951. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45952. {
  45953. fileDragMove (files, x, y);
  45954. }
  45955. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45956. {
  45957. handleDrag (files, String::empty, 0, x, y);
  45958. }
  45959. void TreeView::fileDragExit (const StringArray&)
  45960. {
  45961. hideDragHighlight();
  45962. }
  45963. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45964. {
  45965. handleDrop (files, String::empty, 0, x, y);
  45966. }
  45967. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45968. {
  45969. return true;
  45970. }
  45971. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45972. {
  45973. itemDragMove (sourceDescription, sourceComponent, x, y);
  45974. }
  45975. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45976. {
  45977. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45978. }
  45979. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45980. {
  45981. hideDragHighlight();
  45982. }
  45983. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45984. {
  45985. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45986. }
  45987. enum TreeViewOpenness
  45988. {
  45989. opennessDefault = 0,
  45990. opennessClosed = 1,
  45991. opennessOpen = 2
  45992. };
  45993. TreeViewItem::TreeViewItem()
  45994. : ownerView (0),
  45995. parentItem (0),
  45996. y (0),
  45997. itemHeight (0),
  45998. totalHeight (0),
  45999. selected (false),
  46000. redrawNeeded (true),
  46001. drawLinesInside (true),
  46002. drawsInLeftMargin (false),
  46003. openness (opennessDefault)
  46004. {
  46005. static int nextUID = 0;
  46006. uid = nextUID++;
  46007. }
  46008. TreeViewItem::~TreeViewItem()
  46009. {
  46010. }
  46011. const String TreeViewItem::getUniqueName() const
  46012. {
  46013. return String::empty;
  46014. }
  46015. void TreeViewItem::itemOpennessChanged (bool)
  46016. {
  46017. }
  46018. int TreeViewItem::getNumSubItems() const throw()
  46019. {
  46020. return subItems.size();
  46021. }
  46022. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46023. {
  46024. return subItems [index];
  46025. }
  46026. void TreeViewItem::clearSubItems()
  46027. {
  46028. if (subItems.size() > 0)
  46029. {
  46030. if (ownerView != 0)
  46031. {
  46032. const ScopedLock sl (ownerView->nodeAlterationLock);
  46033. subItems.clear();
  46034. treeHasChanged();
  46035. }
  46036. else
  46037. {
  46038. subItems.clear();
  46039. }
  46040. }
  46041. }
  46042. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46043. {
  46044. if (newItem != 0)
  46045. {
  46046. newItem->parentItem = this;
  46047. newItem->setOwnerView (ownerView);
  46048. newItem->y = 0;
  46049. newItem->itemHeight = newItem->getItemHeight();
  46050. newItem->totalHeight = 0;
  46051. newItem->itemWidth = newItem->getItemWidth();
  46052. newItem->totalWidth = 0;
  46053. if (ownerView != 0)
  46054. {
  46055. const ScopedLock sl (ownerView->nodeAlterationLock);
  46056. subItems.insert (insertPosition, newItem);
  46057. treeHasChanged();
  46058. if (newItem->isOpen())
  46059. newItem->itemOpennessChanged (true);
  46060. }
  46061. else
  46062. {
  46063. subItems.insert (insertPosition, newItem);
  46064. if (newItem->isOpen())
  46065. newItem->itemOpennessChanged (true);
  46066. }
  46067. }
  46068. }
  46069. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46070. {
  46071. if (ownerView != 0)
  46072. {
  46073. const ScopedLock sl (ownerView->nodeAlterationLock);
  46074. if (((unsigned int) index) < (unsigned int) subItems.size())
  46075. {
  46076. subItems.remove (index, deleteItem);
  46077. treeHasChanged();
  46078. }
  46079. }
  46080. else
  46081. {
  46082. subItems.remove (index, deleteItem);
  46083. }
  46084. }
  46085. bool TreeViewItem::isOpen() const throw()
  46086. {
  46087. if (openness == opennessDefault)
  46088. return ownerView != 0 && ownerView->defaultOpenness;
  46089. else
  46090. return openness == opennessOpen;
  46091. }
  46092. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46093. {
  46094. if (isOpen() != shouldBeOpen)
  46095. {
  46096. openness = shouldBeOpen ? opennessOpen
  46097. : opennessClosed;
  46098. treeHasChanged();
  46099. itemOpennessChanged (isOpen());
  46100. }
  46101. }
  46102. bool TreeViewItem::isSelected() const throw()
  46103. {
  46104. return selected;
  46105. }
  46106. void TreeViewItem::deselectAllRecursively()
  46107. {
  46108. setSelected (false, false);
  46109. for (int i = 0; i < subItems.size(); ++i)
  46110. subItems.getUnchecked(i)->deselectAllRecursively();
  46111. }
  46112. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46113. const bool deselectOtherItemsFirst)
  46114. {
  46115. if (shouldBeSelected && ! canBeSelected())
  46116. return;
  46117. if (deselectOtherItemsFirst)
  46118. getTopLevelItem()->deselectAllRecursively();
  46119. if (shouldBeSelected != selected)
  46120. {
  46121. selected = shouldBeSelected;
  46122. if (ownerView != 0)
  46123. ownerView->repaint();
  46124. itemSelectionChanged (shouldBeSelected);
  46125. }
  46126. }
  46127. void TreeViewItem::paintItem (Graphics&, int, int)
  46128. {
  46129. }
  46130. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46131. {
  46132. ownerView->getLookAndFeel()
  46133. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46134. }
  46135. void TreeViewItem::itemClicked (const MouseEvent&)
  46136. {
  46137. }
  46138. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46139. {
  46140. if (mightContainSubItems())
  46141. setOpen (! isOpen());
  46142. }
  46143. void TreeViewItem::itemSelectionChanged (bool)
  46144. {
  46145. }
  46146. const String TreeViewItem::getTooltip()
  46147. {
  46148. return String::empty;
  46149. }
  46150. const String TreeViewItem::getDragSourceDescription()
  46151. {
  46152. return String::empty;
  46153. }
  46154. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46155. {
  46156. return false;
  46157. }
  46158. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46159. {
  46160. }
  46161. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46162. {
  46163. return false;
  46164. }
  46165. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46166. {
  46167. }
  46168. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46169. {
  46170. const int indentX = getIndentX();
  46171. int width = itemWidth;
  46172. if (ownerView != 0 && width < 0)
  46173. width = ownerView->viewport->getViewWidth() - indentX;
  46174. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46175. if (relativeToTreeViewTopLeft)
  46176. r -= ownerView->viewport->getViewPosition();
  46177. return r;
  46178. }
  46179. void TreeViewItem::treeHasChanged() const throw()
  46180. {
  46181. if (ownerView != 0)
  46182. ownerView->itemsChanged();
  46183. }
  46184. void TreeViewItem::repaintItem() const
  46185. {
  46186. if (ownerView != 0 && areAllParentsOpen())
  46187. {
  46188. Rectangle<int> r (getItemPosition (true));
  46189. r.setLeft (0);
  46190. ownerView->viewport->repaint (r);
  46191. }
  46192. }
  46193. bool TreeViewItem::areAllParentsOpen() const throw()
  46194. {
  46195. return parentItem == 0
  46196. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46197. }
  46198. void TreeViewItem::updatePositions (int newY)
  46199. {
  46200. y = newY;
  46201. itemHeight = getItemHeight();
  46202. totalHeight = itemHeight;
  46203. itemWidth = getItemWidth();
  46204. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46205. if (isOpen())
  46206. {
  46207. newY += totalHeight;
  46208. for (int i = 0; i < subItems.size(); ++i)
  46209. {
  46210. TreeViewItem* const ti = subItems.getUnchecked(i);
  46211. ti->updatePositions (newY);
  46212. newY += ti->totalHeight;
  46213. totalHeight += ti->totalHeight;
  46214. totalWidth = jmax (totalWidth, ti->totalWidth);
  46215. }
  46216. }
  46217. }
  46218. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46219. {
  46220. TreeViewItem* result = this;
  46221. TreeViewItem* item = this;
  46222. while (item->parentItem != 0)
  46223. {
  46224. item = item->parentItem;
  46225. if (! item->isOpen())
  46226. result = item;
  46227. }
  46228. return result;
  46229. }
  46230. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46231. {
  46232. ownerView = newOwner;
  46233. for (int i = subItems.size(); --i >= 0;)
  46234. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46235. }
  46236. int TreeViewItem::getIndentX() const throw()
  46237. {
  46238. const int indentWidth = ownerView->getIndentSize();
  46239. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46240. if (! ownerView->openCloseButtonsVisible)
  46241. x -= indentWidth;
  46242. TreeViewItem* p = parentItem;
  46243. while (p != 0)
  46244. {
  46245. x += indentWidth;
  46246. p = p->parentItem;
  46247. }
  46248. return x;
  46249. }
  46250. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46251. {
  46252. drawsInLeftMargin = canDrawInLeftMargin;
  46253. }
  46254. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46255. {
  46256. jassert (ownerView != 0);
  46257. if (ownerView == 0)
  46258. return;
  46259. const int indent = getIndentX();
  46260. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46261. {
  46262. g.saveState();
  46263. g.setOrigin (indent, 0);
  46264. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46265. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46266. paintItem (g, itemW, itemHeight);
  46267. g.restoreState();
  46268. }
  46269. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46270. const float halfH = itemHeight * 0.5f;
  46271. int depth = 0;
  46272. TreeViewItem* p = parentItem;
  46273. while (p != 0)
  46274. {
  46275. ++depth;
  46276. p = p->parentItem;
  46277. }
  46278. if (! ownerView->rootItemVisible)
  46279. --depth;
  46280. const int indentWidth = ownerView->getIndentSize();
  46281. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46282. {
  46283. float x = (depth + 0.5f) * indentWidth;
  46284. if (depth >= 0)
  46285. {
  46286. if (parentItem != 0 && parentItem->drawLinesInside)
  46287. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46288. if ((parentItem != 0 && parentItem->drawLinesInside)
  46289. || (parentItem == 0 && drawLinesInside))
  46290. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46291. }
  46292. p = parentItem;
  46293. int d = depth;
  46294. while (p != 0 && --d >= 0)
  46295. {
  46296. x -= (float) indentWidth;
  46297. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46298. && ! p->isLastOfSiblings())
  46299. {
  46300. g.drawLine (x, 0, x, (float) itemHeight);
  46301. }
  46302. p = p->parentItem;
  46303. }
  46304. if (mightContainSubItems())
  46305. {
  46306. g.saveState();
  46307. g.setOrigin (depth * indentWidth, 0);
  46308. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46309. paintOpenCloseButton (g, indentWidth, itemHeight,
  46310. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46311. ->isMouseOverButton (this));
  46312. g.restoreState();
  46313. }
  46314. }
  46315. if (isOpen())
  46316. {
  46317. const Rectangle<int> clip (g.getClipBounds());
  46318. for (int i = 0; i < subItems.size(); ++i)
  46319. {
  46320. TreeViewItem* const ti = subItems.getUnchecked(i);
  46321. const int relY = ti->y - y;
  46322. if (relY >= clip.getBottom())
  46323. break;
  46324. if (relY + ti->totalHeight >= clip.getY())
  46325. {
  46326. g.saveState();
  46327. g.setOrigin (0, relY);
  46328. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46329. ti->paintRecursively (g, width);
  46330. g.restoreState();
  46331. }
  46332. }
  46333. }
  46334. }
  46335. bool TreeViewItem::isLastOfSiblings() const throw()
  46336. {
  46337. return parentItem == 0
  46338. || parentItem->subItems.getLast() == this;
  46339. }
  46340. int TreeViewItem::getIndexInParent() const throw()
  46341. {
  46342. if (parentItem == 0)
  46343. return 0;
  46344. return parentItem->subItems.indexOf (this);
  46345. }
  46346. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46347. {
  46348. return (parentItem == 0) ? this
  46349. : parentItem->getTopLevelItem();
  46350. }
  46351. int TreeViewItem::getNumRows() const throw()
  46352. {
  46353. int num = 1;
  46354. if (isOpen())
  46355. {
  46356. for (int i = subItems.size(); --i >= 0;)
  46357. num += subItems.getUnchecked(i)->getNumRows();
  46358. }
  46359. return num;
  46360. }
  46361. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46362. {
  46363. if (index == 0)
  46364. return this;
  46365. if (index > 0 && isOpen())
  46366. {
  46367. --index;
  46368. for (int i = 0; i < subItems.size(); ++i)
  46369. {
  46370. TreeViewItem* const item = subItems.getUnchecked(i);
  46371. if (index == 0)
  46372. return item;
  46373. const int numRows = item->getNumRows();
  46374. if (numRows > index)
  46375. return item->getItemOnRow (index);
  46376. index -= numRows;
  46377. }
  46378. }
  46379. return 0;
  46380. }
  46381. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46382. {
  46383. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46384. {
  46385. const int h = itemHeight;
  46386. if (targetY < h)
  46387. return this;
  46388. if (isOpen())
  46389. {
  46390. targetY -= h;
  46391. for (int i = 0; i < subItems.size(); ++i)
  46392. {
  46393. TreeViewItem* const ti = subItems.getUnchecked(i);
  46394. if (targetY < ti->totalHeight)
  46395. return ti->findItemRecursively (targetY);
  46396. targetY -= ti->totalHeight;
  46397. }
  46398. }
  46399. }
  46400. return 0;
  46401. }
  46402. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46403. {
  46404. int total = 0;
  46405. if (isSelected())
  46406. ++total;
  46407. for (int i = subItems.size(); --i >= 0;)
  46408. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46409. return total;
  46410. }
  46411. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46412. {
  46413. if (isSelected())
  46414. {
  46415. if (index == 0)
  46416. return this;
  46417. --index;
  46418. }
  46419. if (index >= 0)
  46420. {
  46421. for (int i = 0; i < subItems.size(); ++i)
  46422. {
  46423. TreeViewItem* const item = subItems.getUnchecked(i);
  46424. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46425. if (found != 0)
  46426. return found;
  46427. index -= item->countSelectedItemsRecursively();
  46428. }
  46429. }
  46430. return 0;
  46431. }
  46432. int TreeViewItem::getRowNumberInTree() const throw()
  46433. {
  46434. if (parentItem != 0 && ownerView != 0)
  46435. {
  46436. int n = 1 + parentItem->getRowNumberInTree();
  46437. int ourIndex = parentItem->subItems.indexOf (this);
  46438. jassert (ourIndex >= 0);
  46439. while (--ourIndex >= 0)
  46440. n += parentItem->subItems [ourIndex]->getNumRows();
  46441. if (parentItem->parentItem == 0
  46442. && ! ownerView->rootItemVisible)
  46443. --n;
  46444. return n;
  46445. }
  46446. else
  46447. {
  46448. return 0;
  46449. }
  46450. }
  46451. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46452. {
  46453. drawLinesInside = drawLines;
  46454. }
  46455. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46456. {
  46457. if (recurse && isOpen() && subItems.size() > 0)
  46458. return subItems [0];
  46459. if (parentItem != 0)
  46460. {
  46461. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46462. if (nextIndex >= parentItem->subItems.size())
  46463. return parentItem->getNextVisibleItem (false);
  46464. return parentItem->subItems [nextIndex];
  46465. }
  46466. return 0;
  46467. }
  46468. const String TreeViewItem::getItemIdentifierString() const
  46469. {
  46470. String s;
  46471. if (parentItem != 0)
  46472. s = parentItem->getItemIdentifierString();
  46473. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46474. }
  46475. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46476. {
  46477. const String thisId (getUniqueName());
  46478. if (thisId == identifierString)
  46479. return this;
  46480. if (identifierString.startsWith (thisId + "/"))
  46481. {
  46482. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46483. bool wasOpen = isOpen();
  46484. setOpen (true);
  46485. for (int i = subItems.size(); --i >= 0;)
  46486. {
  46487. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46488. if (item != 0)
  46489. return item;
  46490. }
  46491. setOpen (wasOpen);
  46492. }
  46493. return 0;
  46494. }
  46495. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46496. {
  46497. if (e.hasTagName ("CLOSED"))
  46498. {
  46499. setOpen (false);
  46500. }
  46501. else if (e.hasTagName ("OPEN"))
  46502. {
  46503. setOpen (true);
  46504. forEachXmlChildElement (e, n)
  46505. {
  46506. const String id (n->getStringAttribute ("id"));
  46507. for (int i = 0; i < subItems.size(); ++i)
  46508. {
  46509. TreeViewItem* const ti = subItems.getUnchecked(i);
  46510. if (ti->getUniqueName() == id)
  46511. {
  46512. ti->restoreOpennessState (*n);
  46513. break;
  46514. }
  46515. }
  46516. }
  46517. }
  46518. }
  46519. XmlElement* TreeViewItem::getOpennessState() const throw()
  46520. {
  46521. const String name (getUniqueName());
  46522. if (name.isNotEmpty())
  46523. {
  46524. XmlElement* e;
  46525. if (isOpen())
  46526. {
  46527. e = new XmlElement ("OPEN");
  46528. for (int i = 0; i < subItems.size(); ++i)
  46529. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46530. }
  46531. else
  46532. {
  46533. e = new XmlElement ("CLOSED");
  46534. }
  46535. e->setAttribute ("id", name);
  46536. return e;
  46537. }
  46538. else
  46539. {
  46540. // trying to save the openness for an element that has no name - this won't
  46541. // work because it needs the names to identify what to open.
  46542. jassertfalse;
  46543. }
  46544. return 0;
  46545. }
  46546. END_JUCE_NAMESPACE
  46547. /*** End of inlined file: juce_TreeView.cpp ***/
  46548. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46549. BEGIN_JUCE_NAMESPACE
  46550. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46551. : fileList (listToShow)
  46552. {
  46553. }
  46554. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46555. {
  46556. }
  46557. FileBrowserListener::~FileBrowserListener()
  46558. {
  46559. }
  46560. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46561. {
  46562. listeners.add (listener);
  46563. }
  46564. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46565. {
  46566. listeners.remove (listener);
  46567. }
  46568. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46569. {
  46570. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46571. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46572. }
  46573. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46574. {
  46575. if (fileList.getDirectory().exists())
  46576. {
  46577. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46578. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46579. }
  46580. }
  46581. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46582. {
  46583. if (fileList.getDirectory().exists())
  46584. {
  46585. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46586. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46587. }
  46588. }
  46589. END_JUCE_NAMESPACE
  46590. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46591. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46592. BEGIN_JUCE_NAMESPACE
  46593. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46594. TimeSliceThread& thread_)
  46595. : fileFilter (fileFilter_),
  46596. thread (thread_),
  46597. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46598. fileFindHandle (0),
  46599. shouldStop (true)
  46600. {
  46601. }
  46602. DirectoryContentsList::~DirectoryContentsList()
  46603. {
  46604. clear();
  46605. }
  46606. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46607. {
  46608. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46609. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46610. }
  46611. bool DirectoryContentsList::ignoresHiddenFiles() const
  46612. {
  46613. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46614. }
  46615. const File& DirectoryContentsList::getDirectory() const
  46616. {
  46617. return root;
  46618. }
  46619. void DirectoryContentsList::setDirectory (const File& directory,
  46620. const bool includeDirectories,
  46621. const bool includeFiles)
  46622. {
  46623. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46624. if (directory != root)
  46625. {
  46626. clear();
  46627. root = directory;
  46628. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46629. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46630. }
  46631. int newFlags = fileTypeFlags;
  46632. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46633. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46634. setTypeFlags (newFlags);
  46635. }
  46636. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46637. {
  46638. if (fileTypeFlags != newFlags)
  46639. {
  46640. fileTypeFlags = newFlags;
  46641. refresh();
  46642. }
  46643. }
  46644. void DirectoryContentsList::clear()
  46645. {
  46646. shouldStop = true;
  46647. thread.removeTimeSliceClient (this);
  46648. fileFindHandle = 0;
  46649. if (files.size() > 0)
  46650. {
  46651. files.clear();
  46652. changed();
  46653. }
  46654. }
  46655. void DirectoryContentsList::refresh()
  46656. {
  46657. clear();
  46658. if (root.isDirectory())
  46659. {
  46660. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46661. shouldStop = false;
  46662. thread.addTimeSliceClient (this);
  46663. }
  46664. }
  46665. int DirectoryContentsList::getNumFiles() const
  46666. {
  46667. return files.size();
  46668. }
  46669. bool DirectoryContentsList::getFileInfo (const int index,
  46670. FileInfo& result) const
  46671. {
  46672. const ScopedLock sl (fileListLock);
  46673. const FileInfo* const info = files [index];
  46674. if (info != 0)
  46675. {
  46676. result = *info;
  46677. return true;
  46678. }
  46679. return false;
  46680. }
  46681. const File DirectoryContentsList::getFile (const int index) const
  46682. {
  46683. const ScopedLock sl (fileListLock);
  46684. const FileInfo* const info = files [index];
  46685. if (info != 0)
  46686. return root.getChildFile (info->filename);
  46687. return File::nonexistent;
  46688. }
  46689. bool DirectoryContentsList::isStillLoading() const
  46690. {
  46691. return fileFindHandle != 0;
  46692. }
  46693. void DirectoryContentsList::changed()
  46694. {
  46695. sendChangeMessage (this);
  46696. }
  46697. bool DirectoryContentsList::useTimeSlice()
  46698. {
  46699. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46700. bool hasChanged = false;
  46701. for (int i = 100; --i >= 0;)
  46702. {
  46703. if (! checkNextFile (hasChanged))
  46704. {
  46705. if (hasChanged)
  46706. changed();
  46707. return false;
  46708. }
  46709. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46710. break;
  46711. }
  46712. if (hasChanged)
  46713. changed();
  46714. return true;
  46715. }
  46716. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46717. {
  46718. if (fileFindHandle != 0)
  46719. {
  46720. bool fileFoundIsDir, isHidden, isReadOnly;
  46721. int64 fileSize;
  46722. Time modTime, creationTime;
  46723. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46724. &modTime, &creationTime, &isReadOnly))
  46725. {
  46726. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46727. fileSize, modTime, creationTime, isReadOnly))
  46728. {
  46729. hasChanged = true;
  46730. }
  46731. return true;
  46732. }
  46733. else
  46734. {
  46735. fileFindHandle = 0;
  46736. }
  46737. }
  46738. return false;
  46739. }
  46740. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46741. const DirectoryContentsList::FileInfo* const second)
  46742. {
  46743. #if JUCE_WINDOWS
  46744. if (first->isDirectory != second->isDirectory)
  46745. return first->isDirectory ? -1 : 1;
  46746. #endif
  46747. return first->filename.compareIgnoreCase (second->filename);
  46748. }
  46749. bool DirectoryContentsList::addFile (const File& file,
  46750. const bool isDir,
  46751. const int64 fileSize,
  46752. const Time& modTime,
  46753. const Time& creationTime,
  46754. const bool isReadOnly)
  46755. {
  46756. if (fileFilter == 0
  46757. || ((! isDir) && fileFilter->isFileSuitable (file))
  46758. || (isDir && fileFilter->isDirectorySuitable (file)))
  46759. {
  46760. ScopedPointer <FileInfo> info (new FileInfo());
  46761. info->filename = file.getFileName();
  46762. info->fileSize = fileSize;
  46763. info->modificationTime = modTime;
  46764. info->creationTime = creationTime;
  46765. info->isDirectory = isDir;
  46766. info->isReadOnly = isReadOnly;
  46767. const ScopedLock sl (fileListLock);
  46768. for (int i = files.size(); --i >= 0;)
  46769. if (files.getUnchecked(i)->filename == info->filename)
  46770. return false;
  46771. files.addSorted (*this, info.release());
  46772. return true;
  46773. }
  46774. return false;
  46775. }
  46776. END_JUCE_NAMESPACE
  46777. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46778. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46779. BEGIN_JUCE_NAMESPACE
  46780. FileBrowserComponent::FileBrowserComponent (int flags_,
  46781. const File& initialFileOrDirectory,
  46782. const FileFilter* fileFilter_,
  46783. FilePreviewComponent* previewComp_)
  46784. : FileFilter (String::empty),
  46785. fileFilter (fileFilter_),
  46786. flags (flags_),
  46787. previewComp (previewComp_),
  46788. thread ("Juce FileBrowser")
  46789. {
  46790. // You need to specify one or other of the open/save flags..
  46791. jassert ((flags & (saveMode | openMode)) != 0);
  46792. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46793. // You need to specify at least one of these flags..
  46794. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46795. String filename;
  46796. if (initialFileOrDirectory == File::nonexistent)
  46797. {
  46798. currentRoot = File::getCurrentWorkingDirectory();
  46799. }
  46800. else if (initialFileOrDirectory.isDirectory())
  46801. {
  46802. currentRoot = initialFileOrDirectory;
  46803. }
  46804. else
  46805. {
  46806. chosenFiles.add (initialFileOrDirectory);
  46807. currentRoot = initialFileOrDirectory.getParentDirectory();
  46808. filename = initialFileOrDirectory.getFileName();
  46809. }
  46810. fileList = new DirectoryContentsList (this, thread);
  46811. if ((flags & useTreeView) != 0)
  46812. {
  46813. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46814. if ((flags & canSelectMultipleItems) != 0)
  46815. tree->setMultiSelectEnabled (true);
  46816. addAndMakeVisible (tree);
  46817. fileListComponent = tree;
  46818. }
  46819. else
  46820. {
  46821. FileListComponent* const list = new FileListComponent (*fileList);
  46822. list->setOutlineThickness (1);
  46823. if ((flags & canSelectMultipleItems) != 0)
  46824. list->setMultipleSelectionEnabled (true);
  46825. addAndMakeVisible (list);
  46826. fileListComponent = list;
  46827. }
  46828. fileListComponent->addListener (this);
  46829. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46830. currentPathBox->setEditableText (true);
  46831. StringArray rootNames, rootPaths;
  46832. const BigInteger separators (getRoots (rootNames, rootPaths));
  46833. for (int i = 0; i < rootNames.size(); ++i)
  46834. {
  46835. if (separators [i])
  46836. currentPathBox->addSeparator();
  46837. currentPathBox->addItem (rootNames[i], i + 1);
  46838. }
  46839. currentPathBox->addSeparator();
  46840. currentPathBox->addListener (this);
  46841. addAndMakeVisible (filenameBox = new TextEditor());
  46842. filenameBox->setMultiLine (false);
  46843. filenameBox->setSelectAllWhenFocused (true);
  46844. filenameBox->setText (filename, false);
  46845. filenameBox->addListener (this);
  46846. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46847. Label* label = new Label ("f", TRANS("file:"));
  46848. addAndMakeVisible (label);
  46849. label->attachToComponent (filenameBox, true);
  46850. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46851. goUpButton->addButtonListener (this);
  46852. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46853. if (previewComp != 0)
  46854. addAndMakeVisible (previewComp);
  46855. setRoot (currentRoot);
  46856. thread.startThread (4);
  46857. }
  46858. FileBrowserComponent::~FileBrowserComponent()
  46859. {
  46860. if (previewComp != 0)
  46861. removeChildComponent (previewComp);
  46862. deleteAllChildren();
  46863. fileList = 0;
  46864. thread.stopThread (10000);
  46865. }
  46866. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46867. {
  46868. listeners.add (newListener);
  46869. }
  46870. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46871. {
  46872. listeners.remove (listener);
  46873. }
  46874. bool FileBrowserComponent::isSaveMode() const throw()
  46875. {
  46876. return (flags & saveMode) != 0;
  46877. }
  46878. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46879. {
  46880. if (chosenFiles.size() == 0 && currentFileIsValid())
  46881. return 1;
  46882. return chosenFiles.size();
  46883. }
  46884. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46885. {
  46886. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46887. return currentRoot;
  46888. if (! filenameBox->isReadOnly())
  46889. return currentRoot.getChildFile (filenameBox->getText());
  46890. return chosenFiles[index];
  46891. }
  46892. bool FileBrowserComponent::currentFileIsValid() const
  46893. {
  46894. if (isSaveMode())
  46895. return ! getSelectedFile (0).isDirectory();
  46896. else
  46897. return getSelectedFile (0).exists();
  46898. }
  46899. const File FileBrowserComponent::getHighlightedFile() const throw()
  46900. {
  46901. return fileListComponent->getSelectedFile (0);
  46902. }
  46903. void FileBrowserComponent::deselectAllFiles()
  46904. {
  46905. fileListComponent->deselectAllFiles();
  46906. }
  46907. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46908. {
  46909. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  46910. : false;
  46911. }
  46912. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46913. {
  46914. return true;
  46915. }
  46916. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46917. {
  46918. if (f.isDirectory())
  46919. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46920. return (flags & canSelectFiles) != 0 && f.exists()
  46921. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46922. }
  46923. const File FileBrowserComponent::getRoot() const
  46924. {
  46925. return currentRoot;
  46926. }
  46927. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46928. {
  46929. if (currentRoot != newRootDirectory)
  46930. {
  46931. fileListComponent->scrollToTop();
  46932. String path (newRootDirectory.getFullPathName());
  46933. if (path.isEmpty())
  46934. path = File::separatorString;
  46935. StringArray rootNames, rootPaths;
  46936. getRoots (rootNames, rootPaths);
  46937. if (! rootPaths.contains (path, true))
  46938. {
  46939. bool alreadyListed = false;
  46940. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46941. {
  46942. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46943. {
  46944. alreadyListed = true;
  46945. break;
  46946. }
  46947. }
  46948. if (! alreadyListed)
  46949. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46950. }
  46951. }
  46952. currentRoot = newRootDirectory;
  46953. fileList->setDirectory (currentRoot, true, true);
  46954. String currentRootName (currentRoot.getFullPathName());
  46955. if (currentRootName.isEmpty())
  46956. currentRootName = File::separatorString;
  46957. currentPathBox->setText (currentRootName, true);
  46958. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46959. && currentRoot.getParentDirectory() != currentRoot);
  46960. }
  46961. void FileBrowserComponent::goUp()
  46962. {
  46963. setRoot (getRoot().getParentDirectory());
  46964. }
  46965. void FileBrowserComponent::refresh()
  46966. {
  46967. fileList->refresh();
  46968. }
  46969. const String FileBrowserComponent::getActionVerb() const
  46970. {
  46971. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46972. }
  46973. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46974. {
  46975. return previewComp;
  46976. }
  46977. void FileBrowserComponent::resized()
  46978. {
  46979. getLookAndFeel()
  46980. .layoutFileBrowserComponent (*this, fileListComponent,
  46981. previewComp, currentPathBox,
  46982. filenameBox, goUpButton);
  46983. }
  46984. void FileBrowserComponent::sendListenerChangeMessage()
  46985. {
  46986. Component::BailOutChecker checker (this);
  46987. if (previewComp != 0)
  46988. previewComp->selectedFileChanged (getSelectedFile (0));
  46989. // You shouldn't delete the browser when the file gets changed!
  46990. jassert (! checker.shouldBailOut());
  46991. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46992. }
  46993. void FileBrowserComponent::selectionChanged()
  46994. {
  46995. StringArray newFilenames;
  46996. bool resetChosenFiles = true;
  46997. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46998. {
  46999. const File f (fileListComponent->getSelectedFile (i));
  47000. if (isFileOrDirSuitable (f))
  47001. {
  47002. if (resetChosenFiles)
  47003. {
  47004. chosenFiles.clear();
  47005. resetChosenFiles = false;
  47006. }
  47007. chosenFiles.add (f);
  47008. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47009. }
  47010. }
  47011. if (newFilenames.size() > 0)
  47012. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  47013. sendListenerChangeMessage();
  47014. }
  47015. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47016. {
  47017. Component::BailOutChecker checker (this);
  47018. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47019. }
  47020. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47021. {
  47022. if (f.isDirectory())
  47023. {
  47024. setRoot (f);
  47025. if ((flags & canSelectDirectories) != 0)
  47026. filenameBox->setText (String::empty);
  47027. }
  47028. else
  47029. {
  47030. Component::BailOutChecker checker (this);
  47031. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47032. }
  47033. }
  47034. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47035. {
  47036. (void) key;
  47037. #if JUCE_LINUX || JUCE_WINDOWS
  47038. if (key.getModifiers().isCommandDown()
  47039. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47040. {
  47041. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47042. fileList->refresh();
  47043. return true;
  47044. }
  47045. #endif
  47046. return false;
  47047. }
  47048. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47049. {
  47050. sendListenerChangeMessage();
  47051. }
  47052. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47053. {
  47054. if (filenameBox->getText().containsChar (File::separator))
  47055. {
  47056. const File f (currentRoot.getChildFile (filenameBox->getText()));
  47057. if (f.isDirectory())
  47058. {
  47059. setRoot (f);
  47060. chosenFiles.clear();
  47061. filenameBox->setText (String::empty);
  47062. }
  47063. else
  47064. {
  47065. setRoot (f.getParentDirectory());
  47066. chosenFiles.clear();
  47067. chosenFiles.add (f);
  47068. filenameBox->setText (f.getFileName());
  47069. }
  47070. }
  47071. else
  47072. {
  47073. fileDoubleClicked (getSelectedFile (0));
  47074. }
  47075. }
  47076. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47077. {
  47078. }
  47079. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47080. {
  47081. if (! isSaveMode())
  47082. selectionChanged();
  47083. }
  47084. void FileBrowserComponent::buttonClicked (Button*)
  47085. {
  47086. goUp();
  47087. }
  47088. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47089. {
  47090. const String newText (currentPathBox->getText().trim().unquoted());
  47091. if (newText.isNotEmpty())
  47092. {
  47093. const int index = currentPathBox->getSelectedId() - 1;
  47094. StringArray rootNames, rootPaths;
  47095. getRoots (rootNames, rootPaths);
  47096. if (rootPaths [index].isNotEmpty())
  47097. {
  47098. setRoot (File (rootPaths [index]));
  47099. }
  47100. else
  47101. {
  47102. File f (newText);
  47103. for (;;)
  47104. {
  47105. if (f.isDirectory())
  47106. {
  47107. setRoot (f);
  47108. break;
  47109. }
  47110. if (f.getParentDirectory() == f)
  47111. break;
  47112. f = f.getParentDirectory();
  47113. }
  47114. }
  47115. }
  47116. }
  47117. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47118. {
  47119. BigInteger separators;
  47120. #if JUCE_WINDOWS
  47121. Array<File> roots;
  47122. File::findFileSystemRoots (roots);
  47123. rootPaths.clear();
  47124. for (int i = 0; i < roots.size(); ++i)
  47125. {
  47126. const File& drive = roots.getReference(i);
  47127. String name (drive.getFullPathName());
  47128. rootPaths.add (name);
  47129. if (drive.isOnHardDisk())
  47130. {
  47131. String volume (drive.getVolumeLabel());
  47132. if (volume.isEmpty())
  47133. volume = TRANS("Hard Drive");
  47134. name << " [" << drive.getVolumeLabel() << ']';
  47135. }
  47136. else if (drive.isOnCDRomDrive())
  47137. {
  47138. name << TRANS(" [CD/DVD drive]");
  47139. }
  47140. rootNames.add (name);
  47141. }
  47142. separators.setBit (rootPaths.size());
  47143. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47144. rootNames.add ("Documents");
  47145. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47146. rootNames.add ("Desktop");
  47147. #endif
  47148. #if JUCE_MAC
  47149. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47150. rootNames.add ("Home folder");
  47151. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47152. rootNames.add ("Documents");
  47153. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47154. rootNames.add ("Desktop");
  47155. separators.setBit (rootPaths.size());
  47156. Array <File> volumes;
  47157. File vol ("/Volumes");
  47158. vol.findChildFiles (volumes, File::findDirectories, false);
  47159. for (int i = 0; i < volumes.size(); ++i)
  47160. {
  47161. const File& volume = volumes.getReference(i);
  47162. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47163. {
  47164. rootPaths.add (volume.getFullPathName());
  47165. rootNames.add (volume.getFileName());
  47166. }
  47167. }
  47168. #endif
  47169. #if JUCE_LINUX
  47170. rootPaths.add ("/");
  47171. rootNames.add ("/");
  47172. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47173. rootNames.add ("Home folder");
  47174. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47175. rootNames.add ("Desktop");
  47176. #endif
  47177. return separators;
  47178. }
  47179. END_JUCE_NAMESPACE
  47180. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47181. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47182. BEGIN_JUCE_NAMESPACE
  47183. FileChooser::FileChooser (const String& chooserBoxTitle,
  47184. const File& currentFileOrDirectory,
  47185. const String& fileFilters,
  47186. const bool useNativeDialogBox_)
  47187. : title (chooserBoxTitle),
  47188. filters (fileFilters),
  47189. startingFile (currentFileOrDirectory),
  47190. useNativeDialogBox (useNativeDialogBox_)
  47191. {
  47192. #if JUCE_LINUX
  47193. useNativeDialogBox = false;
  47194. #endif
  47195. if (! fileFilters.containsNonWhitespaceChars())
  47196. filters = "*";
  47197. }
  47198. FileChooser::~FileChooser()
  47199. {
  47200. }
  47201. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47202. {
  47203. return showDialog (false, true, false, false, false, previewComponent);
  47204. }
  47205. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47206. {
  47207. return showDialog (false, true, false, false, true, previewComponent);
  47208. }
  47209. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47210. {
  47211. return showDialog (true, true, false, false, true, previewComponent);
  47212. }
  47213. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47214. {
  47215. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47216. }
  47217. bool FileChooser::browseForDirectory()
  47218. {
  47219. return showDialog (true, false, false, false, false, 0);
  47220. }
  47221. const File FileChooser::getResult() const
  47222. {
  47223. // if you've used a multiple-file select, you should use the getResults() method
  47224. // to retrieve all the files that were chosen.
  47225. jassert (results.size() <= 1);
  47226. return results.getFirst();
  47227. }
  47228. const Array<File>& FileChooser::getResults() const
  47229. {
  47230. return results;
  47231. }
  47232. bool FileChooser::showDialog (const bool selectsDirectories,
  47233. const bool selectsFiles,
  47234. const bool isSave,
  47235. const bool warnAboutOverwritingExistingFiles,
  47236. const bool selectMultipleFiles,
  47237. FilePreviewComponent* const previewComponent)
  47238. {
  47239. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47240. results.clear();
  47241. // the preview component needs to be the right size before you pass it in here..
  47242. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47243. && previewComponent->getHeight() > 10));
  47244. #if JUCE_WINDOWS
  47245. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47246. #elif JUCE_MAC
  47247. if (useNativeDialogBox && (previewComponent == 0))
  47248. #else
  47249. if (false)
  47250. #endif
  47251. {
  47252. showPlatformDialog (results, title, startingFile, filters,
  47253. selectsDirectories, selectsFiles, isSave,
  47254. warnAboutOverwritingExistingFiles,
  47255. selectMultipleFiles,
  47256. previewComponent);
  47257. }
  47258. else
  47259. {
  47260. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47261. selectsDirectories ? "*" : String::empty,
  47262. String::empty);
  47263. int flags = isSave ? FileBrowserComponent::saveMode
  47264. : FileBrowserComponent::openMode;
  47265. if (selectsFiles)
  47266. flags |= FileBrowserComponent::canSelectFiles;
  47267. if (selectsDirectories)
  47268. {
  47269. flags |= FileBrowserComponent::canSelectDirectories;
  47270. if (! isSave)
  47271. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47272. }
  47273. if (selectMultipleFiles)
  47274. flags |= FileBrowserComponent::canSelectMultipleItems;
  47275. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47276. FileChooserDialogBox box (title, String::empty,
  47277. browserComponent,
  47278. warnAboutOverwritingExistingFiles,
  47279. browserComponent.findColour (AlertWindow::backgroundColourId));
  47280. if (box.show())
  47281. {
  47282. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47283. results.add (browserComponent.getSelectedFile (i));
  47284. }
  47285. }
  47286. if (previouslyFocused != 0)
  47287. previouslyFocused->grabKeyboardFocus();
  47288. return results.size() > 0;
  47289. }
  47290. FilePreviewComponent::FilePreviewComponent()
  47291. {
  47292. }
  47293. FilePreviewComponent::~FilePreviewComponent()
  47294. {
  47295. }
  47296. END_JUCE_NAMESPACE
  47297. /*** End of inlined file: juce_FileChooser.cpp ***/
  47298. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47299. BEGIN_JUCE_NAMESPACE
  47300. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47301. const String& instructions,
  47302. FileBrowserComponent& chooserComponent,
  47303. const bool warnAboutOverwritingExistingFiles_,
  47304. const Colour& backgroundColour)
  47305. : ResizableWindow (name, backgroundColour, true),
  47306. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47307. {
  47308. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47309. setResizable (true, true);
  47310. setResizeLimits (300, 300, 1200, 1000);
  47311. content->okButton.addButtonListener (this);
  47312. content->cancelButton.addButtonListener (this);
  47313. content->chooserComponent.addListener (this);
  47314. }
  47315. FileChooserDialogBox::~FileChooserDialogBox()
  47316. {
  47317. content->chooserComponent.removeListener (this);
  47318. }
  47319. bool FileChooserDialogBox::show (int w, int h)
  47320. {
  47321. return showAt (-1, -1, w, h);
  47322. }
  47323. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47324. {
  47325. if (w <= 0)
  47326. {
  47327. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47328. if (previewComp != 0)
  47329. w = 400 + previewComp->getWidth();
  47330. else
  47331. w = 600;
  47332. }
  47333. if (h <= 0)
  47334. h = 500;
  47335. if (x < 0 || y < 0)
  47336. centreWithSize (w, h);
  47337. else
  47338. setBounds (x, y, w, h);
  47339. const bool ok = (runModalLoop() != 0);
  47340. setVisible (false);
  47341. return ok;
  47342. }
  47343. void FileChooserDialogBox::buttonClicked (Button* button)
  47344. {
  47345. if (button == &(content->okButton))
  47346. {
  47347. if (warnAboutOverwritingExistingFiles
  47348. && content->chooserComponent.isSaveMode()
  47349. && content->chooserComponent.getSelectedFile(0).exists())
  47350. {
  47351. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47352. TRANS("File already exists"),
  47353. TRANS("There's already a file called:")
  47354. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47355. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47356. TRANS("overwrite"),
  47357. TRANS("cancel")))
  47358. {
  47359. return;
  47360. }
  47361. }
  47362. exitModalState (1);
  47363. }
  47364. else if (button == &(content->cancelButton))
  47365. {
  47366. closeButtonPressed();
  47367. }
  47368. }
  47369. void FileChooserDialogBox::closeButtonPressed()
  47370. {
  47371. setVisible (false);
  47372. }
  47373. void FileChooserDialogBox::selectionChanged()
  47374. {
  47375. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47376. }
  47377. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47378. {
  47379. }
  47380. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47381. {
  47382. selectionChanged();
  47383. content->okButton.triggerClick();
  47384. }
  47385. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47386. : Component (name), instructions (instructions_),
  47387. chooserComponent (chooserComponent_),
  47388. okButton (chooserComponent_.getActionVerb()),
  47389. cancelButton (TRANS ("Cancel"))
  47390. {
  47391. addAndMakeVisible (&chooserComponent);
  47392. addAndMakeVisible (&okButton);
  47393. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47394. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47395. addAndMakeVisible (&cancelButton);
  47396. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47397. setInterceptsMouseClicks (false, true);
  47398. }
  47399. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47400. {
  47401. }
  47402. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47403. {
  47404. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47405. text.draw (g);
  47406. }
  47407. void FileChooserDialogBox::ContentComponent::resized()
  47408. {
  47409. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47410. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47411. const int y = roundToInt (bb.getBottom()) + 10;
  47412. const int buttonHeight = 26;
  47413. const int buttonY = getHeight() - buttonHeight - 8;
  47414. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47415. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47416. proportionOfWidth (0.2f), buttonHeight);
  47417. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47418. proportionOfWidth (0.2f), buttonHeight);
  47419. }
  47420. END_JUCE_NAMESPACE
  47421. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47422. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47423. BEGIN_JUCE_NAMESPACE
  47424. FileFilter::FileFilter (const String& filterDescription)
  47425. : description (filterDescription)
  47426. {
  47427. }
  47428. FileFilter::~FileFilter()
  47429. {
  47430. }
  47431. const String& FileFilter::getDescription() const throw()
  47432. {
  47433. return description;
  47434. }
  47435. END_JUCE_NAMESPACE
  47436. /*** End of inlined file: juce_FileFilter.cpp ***/
  47437. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47438. BEGIN_JUCE_NAMESPACE
  47439. const Image juce_createIconForFile (const File& file);
  47440. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47441. : ListBox (String::empty, 0),
  47442. DirectoryContentsDisplayComponent (listToShow)
  47443. {
  47444. setModel (this);
  47445. fileList.addChangeListener (this);
  47446. }
  47447. FileListComponent::~FileListComponent()
  47448. {
  47449. fileList.removeChangeListener (this);
  47450. }
  47451. int FileListComponent::getNumSelectedFiles() const
  47452. {
  47453. return getNumSelectedRows();
  47454. }
  47455. const File FileListComponent::getSelectedFile (int index) const
  47456. {
  47457. return fileList.getFile (getSelectedRow (index));
  47458. }
  47459. void FileListComponent::deselectAllFiles()
  47460. {
  47461. deselectAllRows();
  47462. }
  47463. void FileListComponent::scrollToTop()
  47464. {
  47465. getVerticalScrollBar()->setCurrentRangeStart (0);
  47466. }
  47467. void FileListComponent::changeListenerCallback (void*)
  47468. {
  47469. updateContent();
  47470. if (lastDirectory != fileList.getDirectory())
  47471. {
  47472. lastDirectory = fileList.getDirectory();
  47473. deselectAllRows();
  47474. }
  47475. }
  47476. class FileListItemComponent : public Component,
  47477. public TimeSliceClient,
  47478. public AsyncUpdater
  47479. {
  47480. public:
  47481. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47482. : owner (owner_), thread (thread_),
  47483. highlighted (false), index (0), icon (0)
  47484. {
  47485. }
  47486. ~FileListItemComponent()
  47487. {
  47488. thread.removeTimeSliceClient (this);
  47489. clearIcon();
  47490. }
  47491. void paint (Graphics& g)
  47492. {
  47493. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47494. file.getFileName(),
  47495. &icon,
  47496. fileSize, modTime,
  47497. isDirectory, highlighted,
  47498. index);
  47499. }
  47500. void mouseDown (const MouseEvent& e)
  47501. {
  47502. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47503. owner.sendMouseClickMessage (file, e);
  47504. }
  47505. void mouseDoubleClick (const MouseEvent&)
  47506. {
  47507. owner.sendDoubleClickMessage (file);
  47508. }
  47509. void update (const File& root,
  47510. const DirectoryContentsList::FileInfo* const fileInfo,
  47511. const int index_,
  47512. const bool highlighted_)
  47513. {
  47514. thread.removeTimeSliceClient (this);
  47515. if (highlighted_ != highlighted
  47516. || index_ != index)
  47517. {
  47518. index = index_;
  47519. highlighted = highlighted_;
  47520. repaint();
  47521. }
  47522. File newFile;
  47523. String newFileSize;
  47524. String newModTime;
  47525. if (fileInfo != 0)
  47526. {
  47527. newFile = root.getChildFile (fileInfo->filename);
  47528. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47529. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47530. }
  47531. if (newFile != file
  47532. || fileSize != newFileSize
  47533. || modTime != newModTime)
  47534. {
  47535. file = newFile;
  47536. fileSize = newFileSize;
  47537. modTime = newModTime;
  47538. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47539. repaint();
  47540. clearIcon();
  47541. }
  47542. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47543. {
  47544. updateIcon (true);
  47545. if (! icon.isValid())
  47546. thread.addTimeSliceClient (this);
  47547. }
  47548. }
  47549. bool useTimeSlice()
  47550. {
  47551. updateIcon (false);
  47552. return false;
  47553. }
  47554. void handleAsyncUpdate()
  47555. {
  47556. repaint();
  47557. }
  47558. juce_UseDebuggingNewOperator
  47559. private:
  47560. FileListComponent& owner;
  47561. TimeSliceThread& thread;
  47562. bool highlighted;
  47563. int index;
  47564. File file;
  47565. String fileSize;
  47566. String modTime;
  47567. Image icon;
  47568. bool isDirectory;
  47569. void clearIcon()
  47570. {
  47571. icon = Image::null;
  47572. }
  47573. void updateIcon (const bool onlyUpdateIfCached)
  47574. {
  47575. if (icon.isNull())
  47576. {
  47577. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47578. Image im (ImageCache::getFromHashCode (hashCode));
  47579. if (im.isNull() && ! onlyUpdateIfCached)
  47580. {
  47581. im = juce_createIconForFile (file);
  47582. if (im.isValid())
  47583. ImageCache::addImageToCache (im, hashCode);
  47584. }
  47585. if (im.isValid())
  47586. {
  47587. icon = im;
  47588. triggerAsyncUpdate();
  47589. }
  47590. }
  47591. }
  47592. };
  47593. int FileListComponent::getNumRows()
  47594. {
  47595. return fileList.getNumFiles();
  47596. }
  47597. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47598. {
  47599. }
  47600. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47601. {
  47602. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47603. if (comp == 0)
  47604. {
  47605. delete existingComponentToUpdate;
  47606. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47607. }
  47608. DirectoryContentsList::FileInfo fileInfo;
  47609. if (fileList.getFileInfo (row, fileInfo))
  47610. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47611. else
  47612. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47613. return comp;
  47614. }
  47615. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47616. {
  47617. sendSelectionChangeMessage();
  47618. }
  47619. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47620. {
  47621. }
  47622. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47623. {
  47624. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47625. }
  47626. END_JUCE_NAMESPACE
  47627. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47628. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47629. BEGIN_JUCE_NAMESPACE
  47630. FilenameComponent::FilenameComponent (const String& name,
  47631. const File& currentFile,
  47632. const bool canEditFilename,
  47633. const bool isDirectory,
  47634. const bool isForSaving,
  47635. const String& fileBrowserWildcard,
  47636. const String& enforcedSuffix_,
  47637. const String& textWhenNothingSelected)
  47638. : Component (name),
  47639. maxRecentFiles (30),
  47640. isDir (isDirectory),
  47641. isSaving (isForSaving),
  47642. isFileDragOver (false),
  47643. wildcard (fileBrowserWildcard),
  47644. enforcedSuffix (enforcedSuffix_)
  47645. {
  47646. addAndMakeVisible (&filenameBox);
  47647. filenameBox.setEditableText (canEditFilename);
  47648. filenameBox.addListener (this);
  47649. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47650. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47651. setBrowseButtonText ("...");
  47652. setCurrentFile (currentFile, true);
  47653. }
  47654. FilenameComponent::~FilenameComponent()
  47655. {
  47656. }
  47657. void FilenameComponent::paintOverChildren (Graphics& g)
  47658. {
  47659. if (isFileDragOver)
  47660. {
  47661. g.setColour (Colours::red.withAlpha (0.2f));
  47662. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47663. }
  47664. }
  47665. void FilenameComponent::resized()
  47666. {
  47667. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47668. }
  47669. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47670. {
  47671. browseButtonText = newBrowseButtonText;
  47672. lookAndFeelChanged();
  47673. }
  47674. void FilenameComponent::lookAndFeelChanged()
  47675. {
  47676. browseButton = 0;
  47677. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47678. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47679. resized();
  47680. browseButton->addButtonListener (this);
  47681. }
  47682. void FilenameComponent::setTooltip (const String& newTooltip)
  47683. {
  47684. SettableTooltipClient::setTooltip (newTooltip);
  47685. filenameBox.setTooltip (newTooltip);
  47686. }
  47687. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47688. {
  47689. defaultBrowseFile = newDefaultDirectory;
  47690. }
  47691. void FilenameComponent::buttonClicked (Button*)
  47692. {
  47693. FileChooser fc (TRANS("Choose a new file"),
  47694. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47695. : getCurrentFile(),
  47696. wildcard);
  47697. if (isDir ? fc.browseForDirectory()
  47698. : (isSaving ? fc.browseForFileToSave (false)
  47699. : fc.browseForFileToOpen()))
  47700. {
  47701. setCurrentFile (fc.getResult(), true);
  47702. }
  47703. }
  47704. void FilenameComponent::comboBoxChanged (ComboBox*)
  47705. {
  47706. setCurrentFile (getCurrentFile(), true);
  47707. }
  47708. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47709. {
  47710. return true;
  47711. }
  47712. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47713. {
  47714. isFileDragOver = false;
  47715. repaint();
  47716. const File f (filenames[0]);
  47717. if (f.exists() && (f.isDirectory() == isDir))
  47718. setCurrentFile (f, true);
  47719. }
  47720. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47721. {
  47722. isFileDragOver = true;
  47723. repaint();
  47724. }
  47725. void FilenameComponent::fileDragExit (const StringArray&)
  47726. {
  47727. isFileDragOver = false;
  47728. repaint();
  47729. }
  47730. const File FilenameComponent::getCurrentFile() const
  47731. {
  47732. File f (filenameBox.getText());
  47733. if (enforcedSuffix.isNotEmpty())
  47734. f = f.withFileExtension (enforcedSuffix);
  47735. return f;
  47736. }
  47737. void FilenameComponent::setCurrentFile (File newFile,
  47738. const bool addToRecentlyUsedList,
  47739. const bool sendChangeNotification)
  47740. {
  47741. if (enforcedSuffix.isNotEmpty())
  47742. newFile = newFile.withFileExtension (enforcedSuffix);
  47743. if (newFile.getFullPathName() != lastFilename)
  47744. {
  47745. lastFilename = newFile.getFullPathName();
  47746. if (addToRecentlyUsedList)
  47747. addRecentlyUsedFile (newFile);
  47748. filenameBox.setText (lastFilename, true);
  47749. if (sendChangeNotification)
  47750. triggerAsyncUpdate();
  47751. }
  47752. }
  47753. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47754. {
  47755. filenameBox.setEditableText (shouldBeEditable);
  47756. }
  47757. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47758. {
  47759. StringArray names;
  47760. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47761. names.add (filenameBox.getItemText (i));
  47762. return names;
  47763. }
  47764. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47765. {
  47766. if (filenames != getRecentlyUsedFilenames())
  47767. {
  47768. filenameBox.clear();
  47769. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47770. filenameBox.addItem (filenames[i], i + 1);
  47771. }
  47772. }
  47773. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47774. {
  47775. maxRecentFiles = jmax (1, newMaximum);
  47776. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47777. }
  47778. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47779. {
  47780. StringArray files (getRecentlyUsedFilenames());
  47781. if (file.getFullPathName().isNotEmpty())
  47782. {
  47783. files.removeString (file.getFullPathName(), true);
  47784. files.insert (0, file.getFullPathName());
  47785. setRecentlyUsedFilenames (files);
  47786. }
  47787. }
  47788. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47789. {
  47790. listeners.add (listener);
  47791. }
  47792. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47793. {
  47794. listeners.remove (listener);
  47795. }
  47796. void FilenameComponent::handleAsyncUpdate()
  47797. {
  47798. Component::BailOutChecker checker (this);
  47799. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47800. }
  47801. END_JUCE_NAMESPACE
  47802. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47803. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47804. BEGIN_JUCE_NAMESPACE
  47805. FileSearchPathListComponent::FileSearchPathListComponent()
  47806. {
  47807. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47808. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47809. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47810. listBox->setOutlineThickness (1);
  47811. addAndMakeVisible (addButton = new TextButton ("+"));
  47812. addButton->addButtonListener (this);
  47813. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47814. addAndMakeVisible (removeButton = new TextButton ("-"));
  47815. removeButton->addButtonListener (this);
  47816. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47817. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47818. changeButton->addButtonListener (this);
  47819. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47820. upButton->addButtonListener (this);
  47821. {
  47822. Path arrowPath;
  47823. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47824. DrawablePath arrowImage;
  47825. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47826. arrowImage.setPath (arrowPath);
  47827. upButton->setImages (&arrowImage);
  47828. }
  47829. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47830. downButton->addButtonListener (this);
  47831. {
  47832. Path arrowPath;
  47833. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47834. DrawablePath arrowImage;
  47835. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47836. arrowImage.setPath (arrowPath);
  47837. downButton->setImages (&arrowImage);
  47838. }
  47839. updateButtons();
  47840. }
  47841. FileSearchPathListComponent::~FileSearchPathListComponent()
  47842. {
  47843. deleteAllChildren();
  47844. }
  47845. void FileSearchPathListComponent::updateButtons()
  47846. {
  47847. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47848. removeButton->setEnabled (anythingSelected);
  47849. changeButton->setEnabled (anythingSelected);
  47850. upButton->setEnabled (anythingSelected);
  47851. downButton->setEnabled (anythingSelected);
  47852. }
  47853. void FileSearchPathListComponent::changed()
  47854. {
  47855. listBox->updateContent();
  47856. listBox->repaint();
  47857. updateButtons();
  47858. }
  47859. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47860. {
  47861. if (newPath.toString() != path.toString())
  47862. {
  47863. path = newPath;
  47864. changed();
  47865. }
  47866. }
  47867. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47868. {
  47869. defaultBrowseTarget = newDefaultDirectory;
  47870. }
  47871. int FileSearchPathListComponent::getNumRows()
  47872. {
  47873. return path.getNumPaths();
  47874. }
  47875. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47876. {
  47877. if (rowIsSelected)
  47878. g.fillAll (findColour (TextEditor::highlightColourId));
  47879. g.setColour (findColour (ListBox::textColourId));
  47880. Font f (height * 0.7f);
  47881. f.setHorizontalScale (0.9f);
  47882. g.setFont (f);
  47883. g.drawText (path [rowNumber].getFullPathName(),
  47884. 4, 0, width - 6, height,
  47885. Justification::centredLeft, true);
  47886. }
  47887. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47888. {
  47889. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47890. {
  47891. path.remove (row);
  47892. changed();
  47893. }
  47894. }
  47895. void FileSearchPathListComponent::returnKeyPressed (int row)
  47896. {
  47897. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47898. if (chooser.browseForDirectory())
  47899. {
  47900. path.remove (row);
  47901. path.add (chooser.getResult(), row);
  47902. changed();
  47903. }
  47904. }
  47905. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47906. {
  47907. returnKeyPressed (row);
  47908. }
  47909. void FileSearchPathListComponent::selectedRowsChanged (int)
  47910. {
  47911. updateButtons();
  47912. }
  47913. void FileSearchPathListComponent::paint (Graphics& g)
  47914. {
  47915. g.fillAll (findColour (backgroundColourId));
  47916. }
  47917. void FileSearchPathListComponent::resized()
  47918. {
  47919. const int buttonH = 22;
  47920. const int buttonY = getHeight() - buttonH - 4;
  47921. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47922. addButton->setBounds (2, buttonY, buttonH, buttonH);
  47923. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  47924. changeButton->changeWidthToFitText (buttonH);
  47925. downButton->setSize (buttonH * 2, buttonH);
  47926. upButton->setSize (buttonH * 2, buttonH);
  47927. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  47928. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47929. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47930. }
  47931. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47932. {
  47933. return true;
  47934. }
  47935. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47936. {
  47937. for (int i = filenames.size(); --i >= 0;)
  47938. {
  47939. const File f (filenames[i]);
  47940. if (f.isDirectory())
  47941. {
  47942. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47943. path.add (f, row);
  47944. changed();
  47945. }
  47946. }
  47947. }
  47948. void FileSearchPathListComponent::buttonClicked (Button* button)
  47949. {
  47950. const int currentRow = listBox->getSelectedRow();
  47951. if (button == removeButton)
  47952. {
  47953. deleteKeyPressed (currentRow);
  47954. }
  47955. else if (button == addButton)
  47956. {
  47957. File start (defaultBrowseTarget);
  47958. if (start == File::nonexistent)
  47959. start = path [0];
  47960. if (start == File::nonexistent)
  47961. start = File::getCurrentWorkingDirectory();
  47962. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47963. if (chooser.browseForDirectory())
  47964. {
  47965. path.add (chooser.getResult(), currentRow);
  47966. }
  47967. }
  47968. else if (button == changeButton)
  47969. {
  47970. returnKeyPressed (currentRow);
  47971. }
  47972. else if (button == upButton)
  47973. {
  47974. if (currentRow > 0 && currentRow < path.getNumPaths())
  47975. {
  47976. const File f (path[currentRow]);
  47977. path.remove (currentRow);
  47978. path.add (f, currentRow - 1);
  47979. listBox->selectRow (currentRow - 1);
  47980. }
  47981. }
  47982. else if (button == downButton)
  47983. {
  47984. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47985. {
  47986. const File f (path[currentRow]);
  47987. path.remove (currentRow);
  47988. path.add (f, currentRow + 1);
  47989. listBox->selectRow (currentRow + 1);
  47990. }
  47991. }
  47992. changed();
  47993. }
  47994. END_JUCE_NAMESPACE
  47995. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47996. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47997. BEGIN_JUCE_NAMESPACE
  47998. const Image juce_createIconForFile (const File& file);
  47999. class FileListTreeItem : public TreeViewItem,
  48000. public TimeSliceClient,
  48001. public AsyncUpdater,
  48002. public ChangeListener
  48003. {
  48004. public:
  48005. FileListTreeItem (FileTreeComponent& owner_,
  48006. DirectoryContentsList* const parentContentsList_,
  48007. const int indexInContentsList_,
  48008. const File& file_,
  48009. TimeSliceThread& thread_)
  48010. : file (file_),
  48011. owner (owner_),
  48012. parentContentsList (parentContentsList_),
  48013. indexInContentsList (indexInContentsList_),
  48014. subContentsList (0),
  48015. canDeleteSubContentsList (false),
  48016. thread (thread_),
  48017. icon (0)
  48018. {
  48019. DirectoryContentsList::FileInfo fileInfo;
  48020. if (parentContentsList_ != 0
  48021. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48022. {
  48023. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48024. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48025. isDirectory = fileInfo.isDirectory;
  48026. }
  48027. else
  48028. {
  48029. isDirectory = true;
  48030. }
  48031. }
  48032. ~FileListTreeItem()
  48033. {
  48034. thread.removeTimeSliceClient (this);
  48035. clearSubItems();
  48036. if (canDeleteSubContentsList)
  48037. delete subContentsList;
  48038. }
  48039. bool mightContainSubItems() { return isDirectory; }
  48040. const String getUniqueName() const { return file.getFullPathName(); }
  48041. int getItemHeight() const { return 22; }
  48042. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48043. void itemOpennessChanged (bool isNowOpen)
  48044. {
  48045. if (isNowOpen)
  48046. {
  48047. clearSubItems();
  48048. isDirectory = file.isDirectory();
  48049. if (isDirectory)
  48050. {
  48051. if (subContentsList == 0)
  48052. {
  48053. jassert (parentContentsList != 0);
  48054. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48055. l->setDirectory (file, true, true);
  48056. setSubContentsList (l);
  48057. canDeleteSubContentsList = true;
  48058. }
  48059. changeListenerCallback (0);
  48060. }
  48061. }
  48062. }
  48063. void setSubContentsList (DirectoryContentsList* newList)
  48064. {
  48065. jassert (subContentsList == 0);
  48066. subContentsList = newList;
  48067. newList->addChangeListener (this);
  48068. }
  48069. void changeListenerCallback (void*)
  48070. {
  48071. clearSubItems();
  48072. if (isOpen() && subContentsList != 0)
  48073. {
  48074. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48075. {
  48076. FileListTreeItem* const item
  48077. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48078. addSubItem (item);
  48079. }
  48080. }
  48081. }
  48082. void paintItem (Graphics& g, int width, int height)
  48083. {
  48084. if (file != File::nonexistent)
  48085. {
  48086. updateIcon (true);
  48087. if (icon.isNull())
  48088. thread.addTimeSliceClient (this);
  48089. }
  48090. owner.getLookAndFeel()
  48091. .drawFileBrowserRow (g, width, height,
  48092. file.getFileName(),
  48093. &icon, fileSize, modTime,
  48094. isDirectory, isSelected(),
  48095. indexInContentsList);
  48096. }
  48097. void itemClicked (const MouseEvent& e)
  48098. {
  48099. owner.sendMouseClickMessage (file, e);
  48100. }
  48101. void itemDoubleClicked (const MouseEvent& e)
  48102. {
  48103. TreeViewItem::itemDoubleClicked (e);
  48104. owner.sendDoubleClickMessage (file);
  48105. }
  48106. void itemSelectionChanged (bool)
  48107. {
  48108. owner.sendSelectionChangeMessage();
  48109. }
  48110. bool useTimeSlice()
  48111. {
  48112. updateIcon (false);
  48113. thread.removeTimeSliceClient (this);
  48114. return false;
  48115. }
  48116. void handleAsyncUpdate()
  48117. {
  48118. owner.repaint();
  48119. }
  48120. const File file;
  48121. juce_UseDebuggingNewOperator
  48122. private:
  48123. FileTreeComponent& owner;
  48124. DirectoryContentsList* parentContentsList;
  48125. int indexInContentsList;
  48126. DirectoryContentsList* subContentsList;
  48127. bool isDirectory, canDeleteSubContentsList;
  48128. TimeSliceThread& thread;
  48129. Image icon;
  48130. String fileSize;
  48131. String modTime;
  48132. void updateIcon (const bool onlyUpdateIfCached)
  48133. {
  48134. if (icon.isNull())
  48135. {
  48136. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48137. Image im (ImageCache::getFromHashCode (hashCode));
  48138. if (im.isNull() && ! onlyUpdateIfCached)
  48139. {
  48140. im = juce_createIconForFile (file);
  48141. if (im.isValid())
  48142. ImageCache::addImageToCache (im, hashCode);
  48143. }
  48144. if (im.isValid())
  48145. {
  48146. icon = im;
  48147. triggerAsyncUpdate();
  48148. }
  48149. }
  48150. }
  48151. };
  48152. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48153. : DirectoryContentsDisplayComponent (listToShow)
  48154. {
  48155. FileListTreeItem* const root
  48156. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48157. listToShow.getTimeSliceThread());
  48158. root->setSubContentsList (&listToShow);
  48159. setRootItemVisible (false);
  48160. setRootItem (root);
  48161. }
  48162. FileTreeComponent::~FileTreeComponent()
  48163. {
  48164. deleteRootItem();
  48165. }
  48166. const File FileTreeComponent::getSelectedFile (const int index) const
  48167. {
  48168. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48169. return item != 0 ? item->file
  48170. : File::nonexistent;
  48171. }
  48172. void FileTreeComponent::deselectAllFiles()
  48173. {
  48174. clearSelectedItems();
  48175. }
  48176. void FileTreeComponent::scrollToTop()
  48177. {
  48178. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48179. }
  48180. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48181. {
  48182. dragAndDropDescription = description;
  48183. }
  48184. END_JUCE_NAMESPACE
  48185. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48186. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48187. BEGIN_JUCE_NAMESPACE
  48188. ImagePreviewComponent::ImagePreviewComponent()
  48189. {
  48190. }
  48191. ImagePreviewComponent::~ImagePreviewComponent()
  48192. {
  48193. }
  48194. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48195. {
  48196. const int availableW = proportionOfWidth (0.97f);
  48197. const int availableH = getHeight() - 13 * 4;
  48198. const double scale = jmin (1.0,
  48199. availableW / (double) w,
  48200. availableH / (double) h);
  48201. w = roundToInt (scale * w);
  48202. h = roundToInt (scale * h);
  48203. }
  48204. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48205. {
  48206. if (fileToLoad != file)
  48207. {
  48208. fileToLoad = file;
  48209. startTimer (100);
  48210. }
  48211. }
  48212. void ImagePreviewComponent::timerCallback()
  48213. {
  48214. stopTimer();
  48215. currentThumbnail = Image::null;
  48216. currentDetails = String::empty;
  48217. repaint();
  48218. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48219. if (in != 0)
  48220. {
  48221. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48222. if (format != 0)
  48223. {
  48224. currentThumbnail = format->decodeImage (*in);
  48225. if (currentThumbnail.isValid())
  48226. {
  48227. int w = currentThumbnail.getWidth();
  48228. int h = currentThumbnail.getHeight();
  48229. currentDetails
  48230. << fileToLoad.getFileName() << "\n"
  48231. << format->getFormatName() << "\n"
  48232. << w << " x " << h << " pixels\n"
  48233. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48234. getThumbSize (w, h);
  48235. currentThumbnail = currentThumbnail.rescaled (w, h);
  48236. }
  48237. }
  48238. }
  48239. }
  48240. void ImagePreviewComponent::paint (Graphics& g)
  48241. {
  48242. if (currentThumbnail.isValid())
  48243. {
  48244. g.setFont (13.0f);
  48245. int w = currentThumbnail.getWidth();
  48246. int h = currentThumbnail.getHeight();
  48247. getThumbSize (w, h);
  48248. const int numLines = 4;
  48249. const int totalH = 13 * numLines + h + 4;
  48250. const int y = (getHeight() - totalH) / 2;
  48251. g.drawImageWithin (currentThumbnail,
  48252. (getWidth() - w) / 2, y, w, h,
  48253. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48254. false);
  48255. g.drawFittedText (currentDetails,
  48256. 0, y + h + 4, getWidth(), 100,
  48257. Justification::centredTop, numLines);
  48258. }
  48259. }
  48260. END_JUCE_NAMESPACE
  48261. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48262. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48263. BEGIN_JUCE_NAMESPACE
  48264. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48265. const String& directoryWildcardPatterns,
  48266. const String& description_)
  48267. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48268. : (description_ + " (" + fileWildcardPatterns + ")"))
  48269. {
  48270. parse (fileWildcardPatterns, fileWildcards);
  48271. parse (directoryWildcardPatterns, directoryWildcards);
  48272. }
  48273. WildcardFileFilter::~WildcardFileFilter()
  48274. {
  48275. }
  48276. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48277. {
  48278. return match (file, fileWildcards);
  48279. }
  48280. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48281. {
  48282. return match (file, directoryWildcards);
  48283. }
  48284. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48285. {
  48286. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48287. result.trim();
  48288. result.removeEmptyStrings();
  48289. // special case for *.*, because people use it to mean "any file", but it
  48290. // would actually ignore files with no extension.
  48291. for (int i = result.size(); --i >= 0;)
  48292. if (result[i] == "*.*")
  48293. result.set (i, "*");
  48294. }
  48295. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48296. {
  48297. const String filename (file.getFileName());
  48298. for (int i = wildcards.size(); --i >= 0;)
  48299. if (filename.matchesWildcard (wildcards[i], true))
  48300. return true;
  48301. return false;
  48302. }
  48303. END_JUCE_NAMESPACE
  48304. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48305. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48306. BEGIN_JUCE_NAMESPACE
  48307. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48308. {
  48309. }
  48310. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48311. {
  48312. }
  48313. namespace KeyboardFocusHelpers
  48314. {
  48315. // This will sort a set of components, so that they are ordered in terms of
  48316. // left-to-right and then top-to-bottom.
  48317. class ScreenPositionComparator
  48318. {
  48319. public:
  48320. ScreenPositionComparator() {}
  48321. static int compareElements (const Component* const first, const Component* const second)
  48322. {
  48323. int explicitOrder1 = first->getExplicitFocusOrder();
  48324. if (explicitOrder1 <= 0)
  48325. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48326. int explicitOrder2 = second->getExplicitFocusOrder();
  48327. if (explicitOrder2 <= 0)
  48328. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48329. if (explicitOrder1 != explicitOrder2)
  48330. return explicitOrder1 - explicitOrder2;
  48331. const int diff = first->getY() - second->getY();
  48332. return (diff == 0) ? first->getX() - second->getX()
  48333. : diff;
  48334. }
  48335. };
  48336. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48337. {
  48338. if (parent->getNumChildComponents() > 0)
  48339. {
  48340. Array <Component*> localComps;
  48341. ScreenPositionComparator comparator;
  48342. int i;
  48343. for (i = parent->getNumChildComponents(); --i >= 0;)
  48344. {
  48345. Component* const c = parent->getChildComponent (i);
  48346. if (c->isVisible() && c->isEnabled())
  48347. localComps.addSorted (comparator, c);
  48348. }
  48349. for (i = 0; i < localComps.size(); ++i)
  48350. {
  48351. Component* const c = localComps.getUnchecked (i);
  48352. if (c->getWantsKeyboardFocus())
  48353. comps.add (c);
  48354. if (! c->isFocusContainer())
  48355. findAllFocusableComponents (c, comps);
  48356. }
  48357. }
  48358. }
  48359. }
  48360. static Component* getIncrementedComponent (Component* const current, const int delta)
  48361. {
  48362. Component* focusContainer = current->getParentComponent();
  48363. if (focusContainer != 0)
  48364. {
  48365. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48366. focusContainer = focusContainer->getParentComponent();
  48367. if (focusContainer != 0)
  48368. {
  48369. Array <Component*> comps;
  48370. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48371. if (comps.size() > 0)
  48372. {
  48373. const int index = comps.indexOf (current);
  48374. return comps [(index + comps.size() + delta) % comps.size()];
  48375. }
  48376. }
  48377. }
  48378. return 0;
  48379. }
  48380. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48381. {
  48382. return getIncrementedComponent (current, 1);
  48383. }
  48384. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48385. {
  48386. return getIncrementedComponent (current, -1);
  48387. }
  48388. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48389. {
  48390. Array <Component*> comps;
  48391. if (parentComponent != 0)
  48392. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48393. return comps.getFirst();
  48394. }
  48395. END_JUCE_NAMESPACE
  48396. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48397. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48398. BEGIN_JUCE_NAMESPACE
  48399. bool KeyListener::keyStateChanged (const bool, Component*)
  48400. {
  48401. return false;
  48402. }
  48403. END_JUCE_NAMESPACE
  48404. /*** End of inlined file: juce_KeyListener.cpp ***/
  48405. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48406. BEGIN_JUCE_NAMESPACE
  48407. // N.B. these two includes are put here deliberately to avoid problems with
  48408. // old GCCs failing on long include paths
  48409. const int maxKeys = 3;
  48410. class KeyMappingChangeButton : public Button
  48411. {
  48412. public:
  48413. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  48414. const CommandID commandID_,
  48415. const String& keyName,
  48416. const int keyNum_)
  48417. : Button (keyName),
  48418. owner (owner_),
  48419. commandID (commandID_),
  48420. keyNum (keyNum_)
  48421. {
  48422. setWantsKeyboardFocus (false);
  48423. setTriggeredOnMouseDown (keyNum >= 0);
  48424. if (keyNum_ < 0)
  48425. setTooltip (TRANS("adds a new key-mapping"));
  48426. else
  48427. setTooltip (TRANS("click to change this key-mapping"));
  48428. }
  48429. ~KeyMappingChangeButton()
  48430. {
  48431. }
  48432. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48433. {
  48434. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48435. keyNum >= 0 ? getName() : String::empty);
  48436. }
  48437. void clicked()
  48438. {
  48439. if (keyNum >= 0)
  48440. {
  48441. // existing key clicked..
  48442. PopupMenu m;
  48443. m.addItem (1, TRANS("change this key-mapping"));
  48444. m.addSeparator();
  48445. m.addItem (2, TRANS("remove this key-mapping"));
  48446. const int res = m.show();
  48447. if (res == 1)
  48448. {
  48449. owner->assignNewKey (commandID, keyNum);
  48450. }
  48451. else if (res == 2)
  48452. {
  48453. owner->getMappings()->removeKeyPress (commandID, keyNum);
  48454. }
  48455. }
  48456. else
  48457. {
  48458. // + button pressed..
  48459. owner->assignNewKey (commandID, -1);
  48460. }
  48461. }
  48462. void fitToContent (const int h) throw()
  48463. {
  48464. if (keyNum < 0)
  48465. {
  48466. setSize (h, h);
  48467. }
  48468. else
  48469. {
  48470. Font f (h * 0.6f);
  48471. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48472. }
  48473. }
  48474. juce_UseDebuggingNewOperator
  48475. private:
  48476. KeyMappingEditorComponent* const owner;
  48477. const CommandID commandID;
  48478. const int keyNum;
  48479. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48480. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48481. };
  48482. class KeyMappingItemComponent : public Component
  48483. {
  48484. public:
  48485. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  48486. const CommandID commandID_)
  48487. : owner (owner_),
  48488. commandID (commandID_)
  48489. {
  48490. setInterceptsMouseClicks (false, true);
  48491. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  48492. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  48493. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  48494. {
  48495. KeyMappingChangeButton* const kb
  48496. = new KeyMappingChangeButton (owner_, commandID,
  48497. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48498. kb->setEnabled (! isReadOnly);
  48499. addAndMakeVisible (kb);
  48500. }
  48501. KeyMappingChangeButton* const kb
  48502. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  48503. addChildComponent (kb);
  48504. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  48505. }
  48506. ~KeyMappingItemComponent()
  48507. {
  48508. deleteAllChildren();
  48509. }
  48510. void paint (Graphics& g)
  48511. {
  48512. g.setFont (getHeight() * 0.7f);
  48513. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48514. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48515. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48516. Justification::centredLeft, true);
  48517. }
  48518. void resized()
  48519. {
  48520. int x = getWidth() - 4;
  48521. for (int i = getNumChildComponents(); --i >= 0;)
  48522. {
  48523. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48524. kb->fitToContent (getHeight() - 2);
  48525. kb->setTopRightPosition (x, 1);
  48526. x -= kb->getWidth() + 5;
  48527. }
  48528. }
  48529. juce_UseDebuggingNewOperator
  48530. private:
  48531. KeyMappingEditorComponent* const owner;
  48532. const CommandID commandID;
  48533. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48534. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48535. };
  48536. class KeyMappingTreeViewItem : public TreeViewItem
  48537. {
  48538. public:
  48539. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  48540. const CommandID commandID_)
  48541. : owner (owner_),
  48542. commandID (commandID_)
  48543. {
  48544. }
  48545. ~KeyMappingTreeViewItem()
  48546. {
  48547. }
  48548. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48549. bool mightContainSubItems() { return false; }
  48550. int getItemHeight() const { return 20; }
  48551. Component* createItemComponent()
  48552. {
  48553. return new KeyMappingItemComponent (owner, commandID);
  48554. }
  48555. juce_UseDebuggingNewOperator
  48556. private:
  48557. KeyMappingEditorComponent* const owner;
  48558. const CommandID commandID;
  48559. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48560. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48561. };
  48562. class KeyCategoryTreeViewItem : public TreeViewItem
  48563. {
  48564. public:
  48565. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  48566. const String& name)
  48567. : owner (owner_),
  48568. categoryName (name)
  48569. {
  48570. }
  48571. ~KeyCategoryTreeViewItem()
  48572. {
  48573. }
  48574. const String getUniqueName() const { return categoryName + "_cat"; }
  48575. bool mightContainSubItems() { return true; }
  48576. int getItemHeight() const { return 28; }
  48577. void paintItem (Graphics& g, int width, int height)
  48578. {
  48579. g.setFont (height * 0.6f, Font::bold);
  48580. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  48581. g.drawText (categoryName,
  48582. 2, 0, width - 2, height,
  48583. Justification::centredLeft, true);
  48584. }
  48585. void itemOpennessChanged (bool isNowOpen)
  48586. {
  48587. if (isNowOpen)
  48588. {
  48589. if (getNumSubItems() == 0)
  48590. {
  48591. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48592. for (int i = 0; i < commands.size(); ++i)
  48593. {
  48594. if (owner->shouldCommandBeIncluded (commands[i]))
  48595. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48596. }
  48597. }
  48598. }
  48599. else
  48600. {
  48601. clearSubItems();
  48602. }
  48603. }
  48604. juce_UseDebuggingNewOperator
  48605. private:
  48606. KeyMappingEditorComponent* owner;
  48607. String categoryName;
  48608. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48609. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48610. };
  48611. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48612. const bool showResetToDefaultButton)
  48613. : mappings (mappingManager)
  48614. {
  48615. jassert (mappingManager != 0); // can't be null!
  48616. mappingManager->addChangeListener (this);
  48617. setLinesDrawnForSubItems (false);
  48618. resetButton = 0;
  48619. if (showResetToDefaultButton)
  48620. {
  48621. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  48622. resetButton->addButtonListener (this);
  48623. }
  48624. addAndMakeVisible (tree = new TreeView());
  48625. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48626. tree->setRootItemVisible (false);
  48627. tree->setDefaultOpenness (true);
  48628. tree->setRootItem (this);
  48629. }
  48630. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48631. {
  48632. mappings->removeChangeListener (this);
  48633. deleteAllChildren();
  48634. }
  48635. bool KeyMappingEditorComponent::mightContainSubItems()
  48636. {
  48637. return true;
  48638. }
  48639. const String KeyMappingEditorComponent::getUniqueName() const
  48640. {
  48641. return "keys";
  48642. }
  48643. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48644. const Colour& textColour)
  48645. {
  48646. setColour (backgroundColourId, mainBackground);
  48647. setColour (textColourId, textColour);
  48648. tree->setColour (TreeView::backgroundColourId, mainBackground);
  48649. }
  48650. void KeyMappingEditorComponent::parentHierarchyChanged()
  48651. {
  48652. changeListenerCallback (0);
  48653. }
  48654. void KeyMappingEditorComponent::resized()
  48655. {
  48656. int h = getHeight();
  48657. if (resetButton != 0)
  48658. {
  48659. const int buttonHeight = 20;
  48660. h -= buttonHeight + 8;
  48661. int x = getWidth() - 8;
  48662. resetButton->changeWidthToFitText (buttonHeight);
  48663. resetButton->setTopRightPosition (x, h + 6);
  48664. }
  48665. tree->setBounds (0, 0, getWidth(), h);
  48666. }
  48667. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48668. {
  48669. if (button == resetButton)
  48670. {
  48671. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48672. TRANS("Reset to defaults"),
  48673. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48674. TRANS("Reset")))
  48675. {
  48676. mappings->resetToDefaultMappings();
  48677. }
  48678. }
  48679. }
  48680. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48681. {
  48682. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  48683. clearSubItems();
  48684. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48685. for (int i = 0; i < categories.size(); ++i)
  48686. {
  48687. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48688. int count = 0;
  48689. for (int j = 0; j < commands.size(); ++j)
  48690. if (shouldCommandBeIncluded (commands[j]))
  48691. ++count;
  48692. if (count > 0)
  48693. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  48694. }
  48695. if (oldOpenness != 0)
  48696. tree->restoreOpennessState (*oldOpenness);
  48697. }
  48698. class KeyEntryWindow : public AlertWindow
  48699. {
  48700. public:
  48701. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  48702. : AlertWindow (TRANS("New key-mapping"),
  48703. TRANS("Please press a key combination now..."),
  48704. AlertWindow::NoIcon),
  48705. owner (owner_)
  48706. {
  48707. addButton (TRANS("ok"), 1);
  48708. addButton (TRANS("cancel"), 0);
  48709. // (avoid return + escape keys getting processed by the buttons..)
  48710. for (int i = getNumChildComponents(); --i >= 0;)
  48711. getChildComponent (i)->setWantsKeyboardFocus (false);
  48712. setWantsKeyboardFocus (true);
  48713. grabKeyboardFocus();
  48714. }
  48715. ~KeyEntryWindow()
  48716. {
  48717. }
  48718. bool keyPressed (const KeyPress& key)
  48719. {
  48720. lastPress = key;
  48721. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48722. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48723. if (previousCommand != 0)
  48724. {
  48725. message << "\n\n"
  48726. << TRANS("(Currently assigned to \"")
  48727. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48728. << "\")";
  48729. }
  48730. setMessage (message);
  48731. return true;
  48732. }
  48733. bool keyStateChanged (bool)
  48734. {
  48735. return true;
  48736. }
  48737. KeyPress lastPress;
  48738. juce_UseDebuggingNewOperator
  48739. private:
  48740. KeyMappingEditorComponent* owner;
  48741. KeyEntryWindow (const KeyEntryWindow&);
  48742. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48743. };
  48744. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48745. {
  48746. KeyEntryWindow entryWindow (this);
  48747. if (entryWindow.runModalLoop() != 0)
  48748. {
  48749. entryWindow.setVisible (false);
  48750. if (entryWindow.lastPress.isValid())
  48751. {
  48752. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48753. if (previousCommand != 0)
  48754. {
  48755. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48756. TRANS("Change key-mapping"),
  48757. TRANS("This key is already assigned to the command \"")
  48758. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48759. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48760. TRANS("re-assign"),
  48761. TRANS("cancel")))
  48762. {
  48763. return;
  48764. }
  48765. }
  48766. mappings->removeKeyPress (entryWindow.lastPress);
  48767. if (index >= 0)
  48768. mappings->removeKeyPress (commandID, index);
  48769. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48770. }
  48771. }
  48772. }
  48773. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48774. {
  48775. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48776. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48777. }
  48778. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48779. {
  48780. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48781. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48782. }
  48783. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48784. {
  48785. return key.getTextDescription();
  48786. }
  48787. END_JUCE_NAMESPACE
  48788. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48789. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48790. BEGIN_JUCE_NAMESPACE
  48791. KeyPress::KeyPress() throw()
  48792. : keyCode (0),
  48793. mods (0),
  48794. textCharacter (0)
  48795. {
  48796. }
  48797. KeyPress::KeyPress (const int keyCode_,
  48798. const ModifierKeys& mods_,
  48799. const juce_wchar textCharacter_) throw()
  48800. : keyCode (keyCode_),
  48801. mods (mods_),
  48802. textCharacter (textCharacter_)
  48803. {
  48804. }
  48805. KeyPress::KeyPress (const int keyCode_) throw()
  48806. : keyCode (keyCode_),
  48807. textCharacter (0)
  48808. {
  48809. }
  48810. KeyPress::KeyPress (const KeyPress& other) throw()
  48811. : keyCode (other.keyCode),
  48812. mods (other.mods),
  48813. textCharacter (other.textCharacter)
  48814. {
  48815. }
  48816. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48817. {
  48818. keyCode = other.keyCode;
  48819. mods = other.mods;
  48820. textCharacter = other.textCharacter;
  48821. return *this;
  48822. }
  48823. bool KeyPress::operator== (const KeyPress& other) const throw()
  48824. {
  48825. return mods.getRawFlags() == other.mods.getRawFlags()
  48826. && (textCharacter == other.textCharacter
  48827. || textCharacter == 0
  48828. || other.textCharacter == 0)
  48829. && (keyCode == other.keyCode
  48830. || (keyCode < 256
  48831. && other.keyCode < 256
  48832. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48833. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48834. }
  48835. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48836. {
  48837. return ! operator== (other);
  48838. }
  48839. bool KeyPress::isCurrentlyDown() const
  48840. {
  48841. return isKeyCurrentlyDown (keyCode)
  48842. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48843. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48844. }
  48845. namespace KeyPressHelpers
  48846. {
  48847. struct KeyNameAndCode
  48848. {
  48849. const char* name;
  48850. int code;
  48851. };
  48852. static const KeyNameAndCode translations[] =
  48853. {
  48854. { "spacebar", KeyPress::spaceKey },
  48855. { "return", KeyPress::returnKey },
  48856. { "escape", KeyPress::escapeKey },
  48857. { "backspace", KeyPress::backspaceKey },
  48858. { "cursor left", KeyPress::leftKey },
  48859. { "cursor right", KeyPress::rightKey },
  48860. { "cursor up", KeyPress::upKey },
  48861. { "cursor down", KeyPress::downKey },
  48862. { "page up", KeyPress::pageUpKey },
  48863. { "page down", KeyPress::pageDownKey },
  48864. { "home", KeyPress::homeKey },
  48865. { "end", KeyPress::endKey },
  48866. { "delete", KeyPress::deleteKey },
  48867. { "insert", KeyPress::insertKey },
  48868. { "tab", KeyPress::tabKey },
  48869. { "play", KeyPress::playKey },
  48870. { "stop", KeyPress::stopKey },
  48871. { "fast forward", KeyPress::fastForwardKey },
  48872. { "rewind", KeyPress::rewindKey }
  48873. };
  48874. static const String numberPadPrefix() { return "numpad "; }
  48875. }
  48876. const KeyPress KeyPress::createFromDescription (const String& desc)
  48877. {
  48878. int modifiers = 0;
  48879. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48880. || desc.containsWholeWordIgnoreCase ("control")
  48881. || desc.containsWholeWordIgnoreCase ("ctl"))
  48882. modifiers |= ModifierKeys::ctrlModifier;
  48883. if (desc.containsWholeWordIgnoreCase ("shift")
  48884. || desc.containsWholeWordIgnoreCase ("shft"))
  48885. modifiers |= ModifierKeys::shiftModifier;
  48886. if (desc.containsWholeWordIgnoreCase ("alt")
  48887. || desc.containsWholeWordIgnoreCase ("option"))
  48888. modifiers |= ModifierKeys::altModifier;
  48889. if (desc.containsWholeWordIgnoreCase ("command")
  48890. || desc.containsWholeWordIgnoreCase ("cmd"))
  48891. modifiers |= ModifierKeys::commandModifier;
  48892. int key = 0;
  48893. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48894. {
  48895. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48896. {
  48897. key = KeyPressHelpers::translations[i].code;
  48898. break;
  48899. }
  48900. }
  48901. if (key == 0)
  48902. {
  48903. // see if it's a numpad key..
  48904. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48905. {
  48906. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48907. if (lastChar >= '0' && lastChar <= '9')
  48908. key = numberPad0 + lastChar - '0';
  48909. else if (lastChar == '+')
  48910. key = numberPadAdd;
  48911. else if (lastChar == '-')
  48912. key = numberPadSubtract;
  48913. else if (lastChar == '*')
  48914. key = numberPadMultiply;
  48915. else if (lastChar == '/')
  48916. key = numberPadDivide;
  48917. else if (lastChar == '.')
  48918. key = numberPadDecimalPoint;
  48919. else if (lastChar == '=')
  48920. key = numberPadEquals;
  48921. else if (desc.endsWith ("separator"))
  48922. key = numberPadSeparator;
  48923. else if (desc.endsWith ("delete"))
  48924. key = numberPadDelete;
  48925. }
  48926. if (key == 0)
  48927. {
  48928. // see if it's a function key..
  48929. for (int i = 1; i <= 12; ++i)
  48930. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48931. key = F1Key + i - 1;
  48932. if (key == 0)
  48933. {
  48934. // give up and use the hex code..
  48935. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48936. .toLowerCase()
  48937. .retainCharacters ("0123456789abcdef")
  48938. .getHexValue32();
  48939. if (hexCode > 0)
  48940. key = hexCode;
  48941. else
  48942. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48943. }
  48944. }
  48945. }
  48946. return KeyPress (key, ModifierKeys (modifiers), 0);
  48947. }
  48948. const String KeyPress::getTextDescription() const
  48949. {
  48950. String desc;
  48951. if (keyCode > 0)
  48952. {
  48953. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48954. // want to store it as being a slash, not shift+whatever.
  48955. if (textCharacter == '/')
  48956. return "/";
  48957. if (mods.isCtrlDown())
  48958. desc << "ctrl + ";
  48959. if (mods.isShiftDown())
  48960. desc << "shift + ";
  48961. #if JUCE_MAC
  48962. // only do this on the mac, because on Windows ctrl and command are the same,
  48963. // and this would get confusing
  48964. if (mods.isCommandDown())
  48965. desc << "command + ";
  48966. if (mods.isAltDown())
  48967. desc << "option + ";
  48968. #else
  48969. if (mods.isAltDown())
  48970. desc << "alt + ";
  48971. #endif
  48972. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48973. if (keyCode == KeyPressHelpers::translations[i].code)
  48974. return desc + KeyPressHelpers::translations[i].name;
  48975. if (keyCode >= F1Key && keyCode <= F16Key)
  48976. desc << 'F' << (1 + keyCode - F1Key);
  48977. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48978. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48979. else if (keyCode >= 33 && keyCode < 176)
  48980. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48981. else if (keyCode == numberPadAdd)
  48982. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48983. else if (keyCode == numberPadSubtract)
  48984. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48985. else if (keyCode == numberPadMultiply)
  48986. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48987. else if (keyCode == numberPadDivide)
  48988. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48989. else if (keyCode == numberPadSeparator)
  48990. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48991. else if (keyCode == numberPadDecimalPoint)
  48992. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48993. else if (keyCode == numberPadDelete)
  48994. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48995. else
  48996. desc << '#' << String::toHexString (keyCode);
  48997. }
  48998. return desc;
  48999. }
  49000. END_JUCE_NAMESPACE
  49001. /*** End of inlined file: juce_KeyPress.cpp ***/
  49002. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49003. BEGIN_JUCE_NAMESPACE
  49004. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49005. : commandManager (commandManager_)
  49006. {
  49007. // A manager is needed to get the descriptions of commands, and will be called when
  49008. // a command is invoked. So you can't leave this null..
  49009. jassert (commandManager_ != 0);
  49010. Desktop::getInstance().addFocusChangeListener (this);
  49011. }
  49012. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49013. : commandManager (other.commandManager)
  49014. {
  49015. Desktop::getInstance().addFocusChangeListener (this);
  49016. }
  49017. KeyPressMappingSet::~KeyPressMappingSet()
  49018. {
  49019. Desktop::getInstance().removeFocusChangeListener (this);
  49020. }
  49021. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49022. {
  49023. for (int i = 0; i < mappings.size(); ++i)
  49024. if (mappings.getUnchecked(i)->commandID == commandID)
  49025. return mappings.getUnchecked (i)->keypresses;
  49026. return Array <KeyPress> ();
  49027. }
  49028. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49029. const KeyPress& newKeyPress,
  49030. int insertIndex)
  49031. {
  49032. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49033. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49034. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49035. && ! newKeyPress.getModifiers().isShiftDown()));
  49036. if (findCommandForKeyPress (newKeyPress) != commandID)
  49037. {
  49038. removeKeyPress (newKeyPress);
  49039. if (newKeyPress.isValid())
  49040. {
  49041. for (int i = mappings.size(); --i >= 0;)
  49042. {
  49043. if (mappings.getUnchecked(i)->commandID == commandID)
  49044. {
  49045. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49046. sendChangeMessage (this);
  49047. return;
  49048. }
  49049. }
  49050. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49051. if (ci != 0)
  49052. {
  49053. CommandMapping* const cm = new CommandMapping();
  49054. cm->commandID = commandID;
  49055. cm->keypresses.add (newKeyPress);
  49056. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49057. mappings.add (cm);
  49058. sendChangeMessage (this);
  49059. }
  49060. }
  49061. }
  49062. }
  49063. void KeyPressMappingSet::resetToDefaultMappings()
  49064. {
  49065. mappings.clear();
  49066. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49067. {
  49068. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49069. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49070. {
  49071. addKeyPress (ci->commandID,
  49072. ci->defaultKeypresses.getReference (j));
  49073. }
  49074. }
  49075. sendChangeMessage (this);
  49076. }
  49077. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49078. {
  49079. clearAllKeyPresses (commandID);
  49080. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49081. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49082. {
  49083. addKeyPress (ci->commandID,
  49084. ci->defaultKeypresses.getReference (j));
  49085. }
  49086. }
  49087. void KeyPressMappingSet::clearAllKeyPresses()
  49088. {
  49089. if (mappings.size() > 0)
  49090. {
  49091. sendChangeMessage (this);
  49092. mappings.clear();
  49093. }
  49094. }
  49095. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49096. {
  49097. for (int i = mappings.size(); --i >= 0;)
  49098. {
  49099. if (mappings.getUnchecked(i)->commandID == commandID)
  49100. {
  49101. mappings.remove (i);
  49102. sendChangeMessage (this);
  49103. }
  49104. }
  49105. }
  49106. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49107. {
  49108. if (keypress.isValid())
  49109. {
  49110. for (int i = mappings.size(); --i >= 0;)
  49111. {
  49112. CommandMapping* const cm = mappings.getUnchecked(i);
  49113. for (int j = cm->keypresses.size(); --j >= 0;)
  49114. {
  49115. if (keypress == cm->keypresses [j])
  49116. {
  49117. cm->keypresses.remove (j);
  49118. sendChangeMessage (this);
  49119. }
  49120. }
  49121. }
  49122. }
  49123. }
  49124. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49125. {
  49126. for (int i = mappings.size(); --i >= 0;)
  49127. {
  49128. if (mappings.getUnchecked(i)->commandID == commandID)
  49129. {
  49130. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49131. sendChangeMessage (this);
  49132. break;
  49133. }
  49134. }
  49135. }
  49136. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49137. {
  49138. for (int i = 0; i < mappings.size(); ++i)
  49139. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49140. return mappings.getUnchecked(i)->commandID;
  49141. return 0;
  49142. }
  49143. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49144. {
  49145. for (int i = mappings.size(); --i >= 0;)
  49146. if (mappings.getUnchecked(i)->commandID == commandID)
  49147. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49148. return false;
  49149. }
  49150. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49151. const KeyPress& key,
  49152. const bool isKeyDown,
  49153. const int millisecsSinceKeyPressed,
  49154. Component* const originatingComponent) const
  49155. {
  49156. ApplicationCommandTarget::InvocationInfo info (commandID);
  49157. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49158. info.isKeyDown = isKeyDown;
  49159. info.keyPress = key;
  49160. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49161. info.originatingComponent = originatingComponent;
  49162. commandManager->invoke (info, false);
  49163. }
  49164. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49165. {
  49166. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49167. {
  49168. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49169. {
  49170. // if the XML was created as a set of differences from the default mappings,
  49171. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49172. resetToDefaultMappings();
  49173. }
  49174. else
  49175. {
  49176. // if the XML was created calling createXml (false), then we need to clear all
  49177. // the keys and treat the xml as describing the entire set of mappings.
  49178. clearAllKeyPresses();
  49179. }
  49180. forEachXmlChildElement (xmlVersion, map)
  49181. {
  49182. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49183. if (commandId != 0)
  49184. {
  49185. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49186. if (map->hasTagName ("MAPPING"))
  49187. {
  49188. addKeyPress (commandId, key);
  49189. }
  49190. else if (map->hasTagName ("UNMAPPING"))
  49191. {
  49192. if (containsMapping (commandId, key))
  49193. removeKeyPress (key);
  49194. }
  49195. }
  49196. }
  49197. return true;
  49198. }
  49199. return false;
  49200. }
  49201. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49202. {
  49203. ScopedPointer <KeyPressMappingSet> defaultSet;
  49204. if (saveDifferencesFromDefaultSet)
  49205. {
  49206. defaultSet = new KeyPressMappingSet (commandManager);
  49207. defaultSet->resetToDefaultMappings();
  49208. }
  49209. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49210. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49211. int i;
  49212. for (i = 0; i < mappings.size(); ++i)
  49213. {
  49214. const CommandMapping* const cm = mappings.getUnchecked(i);
  49215. for (int j = 0; j < cm->keypresses.size(); ++j)
  49216. {
  49217. if (defaultSet == 0
  49218. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49219. {
  49220. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49221. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49222. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49223. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49224. }
  49225. }
  49226. }
  49227. if (defaultSet != 0)
  49228. {
  49229. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49230. {
  49231. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49232. for (int j = 0; j < cm->keypresses.size(); ++j)
  49233. {
  49234. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49235. {
  49236. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49237. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49238. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49239. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49240. }
  49241. }
  49242. }
  49243. }
  49244. return doc;
  49245. }
  49246. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49247. Component* originatingComponent)
  49248. {
  49249. bool used = false;
  49250. const CommandID commandID = findCommandForKeyPress (key);
  49251. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49252. if (ci != 0
  49253. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49254. {
  49255. ApplicationCommandInfo info (0);
  49256. if (commandManager->getTargetForCommand (commandID, info) != 0
  49257. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49258. {
  49259. invokeCommand (commandID, key, true, 0, originatingComponent);
  49260. used = true;
  49261. }
  49262. else
  49263. {
  49264. if (originatingComponent != 0)
  49265. originatingComponent->getLookAndFeel().playAlertSound();
  49266. }
  49267. }
  49268. return used;
  49269. }
  49270. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49271. {
  49272. bool used = false;
  49273. const uint32 now = Time::getMillisecondCounter();
  49274. for (int i = mappings.size(); --i >= 0;)
  49275. {
  49276. CommandMapping* const cm = mappings.getUnchecked(i);
  49277. if (cm->wantsKeyUpDownCallbacks)
  49278. {
  49279. for (int j = cm->keypresses.size(); --j >= 0;)
  49280. {
  49281. const KeyPress key (cm->keypresses.getReference (j));
  49282. const bool isDown = key.isCurrentlyDown();
  49283. int keyPressEntryIndex = 0;
  49284. bool wasDown = false;
  49285. for (int k = keysDown.size(); --k >= 0;)
  49286. {
  49287. if (key == keysDown.getUnchecked(k)->key)
  49288. {
  49289. keyPressEntryIndex = k;
  49290. wasDown = true;
  49291. used = true;
  49292. break;
  49293. }
  49294. }
  49295. if (isDown != wasDown)
  49296. {
  49297. int millisecs = 0;
  49298. if (isDown)
  49299. {
  49300. KeyPressTime* const k = new KeyPressTime();
  49301. k->key = key;
  49302. k->timeWhenPressed = now;
  49303. keysDown.add (k);
  49304. }
  49305. else
  49306. {
  49307. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49308. if (now > pressTime)
  49309. millisecs = now - pressTime;
  49310. keysDown.remove (keyPressEntryIndex);
  49311. }
  49312. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49313. used = true;
  49314. }
  49315. }
  49316. }
  49317. }
  49318. return used;
  49319. }
  49320. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49321. {
  49322. if (focusedComponent != 0)
  49323. focusedComponent->keyStateChanged (false);
  49324. }
  49325. END_JUCE_NAMESPACE
  49326. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49327. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49328. BEGIN_JUCE_NAMESPACE
  49329. ModifierKeys::ModifierKeys (const int flags_) throw()
  49330. : flags (flags_)
  49331. {
  49332. }
  49333. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49334. : flags (other.flags)
  49335. {
  49336. }
  49337. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49338. {
  49339. flags = other.flags;
  49340. return *this;
  49341. }
  49342. ModifierKeys ModifierKeys::currentModifiers;
  49343. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49344. {
  49345. return currentModifiers;
  49346. }
  49347. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49348. {
  49349. int num = 0;
  49350. if (isLeftButtonDown()) ++num;
  49351. if (isRightButtonDown()) ++num;
  49352. if (isMiddleButtonDown()) ++num;
  49353. return num;
  49354. }
  49355. END_JUCE_NAMESPACE
  49356. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49357. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49358. BEGIN_JUCE_NAMESPACE
  49359. class ComponentAnimator::AnimationTask
  49360. {
  49361. public:
  49362. AnimationTask (Component* const comp)
  49363. : component (comp)
  49364. {
  49365. }
  49366. Component::SafePointer<Component> component;
  49367. Rectangle<int> destination;
  49368. int msElapsed, msTotal;
  49369. double startSpeed, midSpeed, endSpeed, lastProgress;
  49370. double left, top, right, bottom;
  49371. bool useTimeslice (const int elapsed)
  49372. {
  49373. if (component == 0)
  49374. return false;
  49375. msElapsed += elapsed;
  49376. double newProgress = msElapsed / (double) msTotal;
  49377. if (newProgress >= 0 && newProgress < 1.0)
  49378. {
  49379. newProgress = timeToDistance (newProgress);
  49380. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49381. jassert (newProgress >= lastProgress);
  49382. lastProgress = newProgress;
  49383. left += (destination.getX() - left) * delta;
  49384. top += (destination.getY() - top) * delta;
  49385. right += (destination.getRight() - right) * delta;
  49386. bottom += (destination.getBottom() - bottom) * delta;
  49387. if (delta < 1.0)
  49388. {
  49389. const Rectangle<int> newBounds (roundToInt (left),
  49390. roundToInt (top),
  49391. roundToInt (right - left),
  49392. roundToInt (bottom - top));
  49393. if (newBounds != destination)
  49394. {
  49395. component->setBounds (newBounds);
  49396. return true;
  49397. }
  49398. }
  49399. }
  49400. component->setBounds (destination);
  49401. return false;
  49402. }
  49403. void moveToFinalDestination()
  49404. {
  49405. if (component != 0)
  49406. component->setBounds (destination);
  49407. }
  49408. private:
  49409. inline double timeToDistance (const double time) const
  49410. {
  49411. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49412. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49413. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49414. }
  49415. };
  49416. ComponentAnimator::ComponentAnimator()
  49417. : lastTime (0)
  49418. {
  49419. }
  49420. ComponentAnimator::~ComponentAnimator()
  49421. {
  49422. cancelAllAnimations (false);
  49423. jassert (tasks.size() == 0);
  49424. }
  49425. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49426. {
  49427. for (int i = tasks.size(); --i >= 0;)
  49428. if (component == tasks.getUnchecked(i)->component.getComponent())
  49429. return tasks.getUnchecked(i);
  49430. return 0;
  49431. }
  49432. void ComponentAnimator::animateComponent (Component* const component,
  49433. const Rectangle<int>& finalPosition,
  49434. const int millisecondsToSpendMoving,
  49435. const double startSpeed,
  49436. const double endSpeed)
  49437. {
  49438. if (component != 0)
  49439. {
  49440. AnimationTask* at = findTaskFor (component);
  49441. if (at == 0)
  49442. {
  49443. at = new AnimationTask (component);
  49444. tasks.add (at);
  49445. sendChangeMessage (this);
  49446. }
  49447. at->msElapsed = 0;
  49448. at->lastProgress = 0;
  49449. at->msTotal = jmax (1, millisecondsToSpendMoving);
  49450. at->destination = finalPosition;
  49451. // the speeds must be 0 or greater!
  49452. jassert (startSpeed >= 0 && endSpeed >= 0)
  49453. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  49454. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  49455. at->midSpeed = invTotalDistance;
  49456. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  49457. at->left = component->getX();
  49458. at->top = component->getY();
  49459. at->right = component->getRight();
  49460. at->bottom = component->getBottom();
  49461. if (! isTimerRunning())
  49462. {
  49463. lastTime = Time::getMillisecondCounter();
  49464. startTimer (1000 / 50);
  49465. }
  49466. }
  49467. }
  49468. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49469. {
  49470. for (int i = tasks.size(); --i >= 0;)
  49471. {
  49472. AnimationTask* const at = tasks.getUnchecked(i);
  49473. if (moveComponentsToTheirFinalPositions)
  49474. at->moveToFinalDestination();
  49475. delete at;
  49476. tasks.remove (i);
  49477. sendChangeMessage (this);
  49478. }
  49479. }
  49480. void ComponentAnimator::cancelAnimation (Component* const component,
  49481. const bool moveComponentToItsFinalPosition)
  49482. {
  49483. AnimationTask* const at = findTaskFor (component);
  49484. if (at != 0)
  49485. {
  49486. if (moveComponentToItsFinalPosition)
  49487. at->moveToFinalDestination();
  49488. tasks.removeValue (at);
  49489. delete at;
  49490. sendChangeMessage (this);
  49491. }
  49492. }
  49493. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49494. {
  49495. AnimationTask* const at = findTaskFor (component);
  49496. if (at != 0)
  49497. return at->destination;
  49498. else if (component != 0)
  49499. return component->getBounds();
  49500. return Rectangle<int>();
  49501. }
  49502. bool ComponentAnimator::isAnimating (Component* component) const
  49503. {
  49504. return findTaskFor (component) != 0;
  49505. }
  49506. void ComponentAnimator::timerCallback()
  49507. {
  49508. const uint32 timeNow = Time::getMillisecondCounter();
  49509. if (lastTime == 0 || lastTime == timeNow)
  49510. lastTime = timeNow;
  49511. const int elapsed = timeNow - lastTime;
  49512. for (int i = tasks.size(); --i >= 0;)
  49513. {
  49514. AnimationTask* const at = tasks.getUnchecked(i);
  49515. if (! at->useTimeslice (elapsed))
  49516. {
  49517. tasks.remove (i);
  49518. delete at;
  49519. sendChangeMessage (this);
  49520. }
  49521. }
  49522. lastTime = timeNow;
  49523. if (tasks.size() == 0)
  49524. stopTimer();
  49525. }
  49526. END_JUCE_NAMESPACE
  49527. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49528. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49529. BEGIN_JUCE_NAMESPACE
  49530. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49531. : minW (0),
  49532. maxW (0x3fffffff),
  49533. minH (0),
  49534. maxH (0x3fffffff),
  49535. minOffTop (0),
  49536. minOffLeft (0),
  49537. minOffBottom (0),
  49538. minOffRight (0),
  49539. aspectRatio (0.0)
  49540. {
  49541. }
  49542. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49543. {
  49544. }
  49545. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49546. {
  49547. minW = minimumWidth;
  49548. }
  49549. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49550. {
  49551. maxW = maximumWidth;
  49552. }
  49553. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49554. {
  49555. minH = minimumHeight;
  49556. }
  49557. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49558. {
  49559. maxH = maximumHeight;
  49560. }
  49561. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49562. {
  49563. jassert (maxW >= minimumWidth);
  49564. jassert (maxH >= minimumHeight);
  49565. jassert (minimumWidth > 0 && minimumHeight > 0);
  49566. minW = minimumWidth;
  49567. minH = minimumHeight;
  49568. if (minW > maxW)
  49569. maxW = minW;
  49570. if (minH > maxH)
  49571. maxH = minH;
  49572. }
  49573. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49574. {
  49575. jassert (maximumWidth >= minW);
  49576. jassert (maximumHeight >= minH);
  49577. jassert (maximumWidth > 0 && maximumHeight > 0);
  49578. maxW = jmax (minW, maximumWidth);
  49579. maxH = jmax (minH, maximumHeight);
  49580. }
  49581. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49582. const int minimumHeight,
  49583. const int maximumWidth,
  49584. const int maximumHeight) throw()
  49585. {
  49586. jassert (maximumWidth >= minimumWidth);
  49587. jassert (maximumHeight >= minimumHeight);
  49588. jassert (maximumWidth > 0 && maximumHeight > 0);
  49589. jassert (minimumWidth > 0 && minimumHeight > 0);
  49590. minW = jmax (0, minimumWidth);
  49591. minH = jmax (0, minimumHeight);
  49592. maxW = jmax (minW, maximumWidth);
  49593. maxH = jmax (minH, maximumHeight);
  49594. }
  49595. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49596. const int minimumWhenOffTheLeft,
  49597. const int minimumWhenOffTheBottom,
  49598. const int minimumWhenOffTheRight) throw()
  49599. {
  49600. minOffTop = minimumWhenOffTheTop;
  49601. minOffLeft = minimumWhenOffTheLeft;
  49602. minOffBottom = minimumWhenOffTheBottom;
  49603. minOffRight = minimumWhenOffTheRight;
  49604. }
  49605. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49606. {
  49607. aspectRatio = jmax (0.0, widthOverHeight);
  49608. }
  49609. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49610. {
  49611. return aspectRatio;
  49612. }
  49613. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49614. const Rectangle<int>& targetBounds,
  49615. const bool isStretchingTop,
  49616. const bool isStretchingLeft,
  49617. const bool isStretchingBottom,
  49618. const bool isStretchingRight)
  49619. {
  49620. jassert (component != 0);
  49621. Rectangle<int> limits, bounds (targetBounds);
  49622. BorderSize border;
  49623. Component* const parent = component->getParentComponent();
  49624. if (parent == 0)
  49625. {
  49626. ComponentPeer* peer = component->getPeer();
  49627. if (peer != 0)
  49628. border = peer->getFrameSize();
  49629. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49630. }
  49631. else
  49632. {
  49633. limits.setSize (parent->getWidth(), parent->getHeight());
  49634. }
  49635. border.addTo (bounds);
  49636. checkBounds (bounds,
  49637. border.addedTo (component->getBounds()), limits,
  49638. isStretchingTop, isStretchingLeft,
  49639. isStretchingBottom, isStretchingRight);
  49640. border.subtractFrom (bounds);
  49641. applyBoundsToComponent (component, bounds);
  49642. }
  49643. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49644. {
  49645. setBoundsForComponent (component, component->getBounds(),
  49646. false, false, false, false);
  49647. }
  49648. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49649. const Rectangle<int>& bounds)
  49650. {
  49651. component->setBounds (bounds);
  49652. }
  49653. void ComponentBoundsConstrainer::resizeStart()
  49654. {
  49655. }
  49656. void ComponentBoundsConstrainer::resizeEnd()
  49657. {
  49658. }
  49659. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49660. const Rectangle<int>& old,
  49661. const Rectangle<int>& limits,
  49662. const bool isStretchingTop,
  49663. const bool isStretchingLeft,
  49664. const bool isStretchingBottom,
  49665. const bool isStretchingRight)
  49666. {
  49667. int x = bounds.getX();
  49668. int y = bounds.getY();
  49669. int w = bounds.getWidth();
  49670. int h = bounds.getHeight();
  49671. // constrain the size if it's being stretched..
  49672. if (isStretchingLeft)
  49673. {
  49674. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  49675. w = old.getRight() - x;
  49676. }
  49677. if (isStretchingRight)
  49678. {
  49679. w = jlimit (minW, maxW, w);
  49680. }
  49681. if (isStretchingTop)
  49682. {
  49683. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  49684. h = old.getBottom() - y;
  49685. }
  49686. if (isStretchingBottom)
  49687. {
  49688. h = jlimit (minH, maxH, h);
  49689. }
  49690. // constrain the aspect ratio if one has been specified..
  49691. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49692. {
  49693. bool adjustWidth;
  49694. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49695. {
  49696. adjustWidth = true;
  49697. }
  49698. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49699. {
  49700. adjustWidth = false;
  49701. }
  49702. else
  49703. {
  49704. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49705. const double newRatio = std::abs (w / (double) h);
  49706. adjustWidth = (oldRatio > newRatio);
  49707. }
  49708. if (adjustWidth)
  49709. {
  49710. w = roundToInt (h * aspectRatio);
  49711. if (w > maxW || w < minW)
  49712. {
  49713. w = jlimit (minW, maxW, w);
  49714. h = roundToInt (w / aspectRatio);
  49715. }
  49716. }
  49717. else
  49718. {
  49719. h = roundToInt (w / aspectRatio);
  49720. if (h > maxH || h < minH)
  49721. {
  49722. h = jlimit (minH, maxH, h);
  49723. w = roundToInt (h * aspectRatio);
  49724. }
  49725. }
  49726. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49727. {
  49728. x = old.getX() + (old.getWidth() - w) / 2;
  49729. }
  49730. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49731. {
  49732. y = old.getY() + (old.getHeight() - h) / 2;
  49733. }
  49734. else
  49735. {
  49736. if (isStretchingLeft)
  49737. x = old.getRight() - w;
  49738. if (isStretchingTop)
  49739. y = old.getBottom() - h;
  49740. }
  49741. }
  49742. // ...and constrain the position if limits have been set for that.
  49743. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49744. {
  49745. if (minOffTop > 0)
  49746. {
  49747. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49748. if (y < limit)
  49749. {
  49750. if (isStretchingTop)
  49751. h -= (limit - y);
  49752. y = limit;
  49753. }
  49754. }
  49755. if (minOffLeft > 0)
  49756. {
  49757. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49758. if (x < limit)
  49759. {
  49760. if (isStretchingLeft)
  49761. w -= (limit - x);
  49762. x = limit;
  49763. }
  49764. }
  49765. if (minOffBottom > 0)
  49766. {
  49767. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49768. if (y > limit)
  49769. {
  49770. if (isStretchingBottom)
  49771. h += (limit - y);
  49772. else
  49773. y = limit;
  49774. }
  49775. }
  49776. if (minOffRight > 0)
  49777. {
  49778. const int limit = limits.getRight() - jmin (minOffRight, w);
  49779. if (x > limit)
  49780. {
  49781. if (isStretchingRight)
  49782. w += (limit - x);
  49783. else
  49784. x = limit;
  49785. }
  49786. }
  49787. }
  49788. jassert (w >= 0 && h >= 0);
  49789. bounds = Rectangle<int> (x, y, w, h);
  49790. }
  49791. END_JUCE_NAMESPACE
  49792. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49793. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49794. BEGIN_JUCE_NAMESPACE
  49795. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49796. : component (component_),
  49797. lastPeer (0),
  49798. reentrant (false)
  49799. {
  49800. jassert (component != 0); // can't use this with a null pointer..
  49801. component->addComponentListener (this);
  49802. registerWithParentComps();
  49803. }
  49804. ComponentMovementWatcher::~ComponentMovementWatcher()
  49805. {
  49806. component->removeComponentListener (this);
  49807. unregister();
  49808. }
  49809. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49810. {
  49811. // agh! don't delete the target component without deleting this object first!
  49812. jassert (component != 0);
  49813. if (! reentrant)
  49814. {
  49815. reentrant = true;
  49816. ComponentPeer* const peer = component->getPeer();
  49817. if (peer != lastPeer)
  49818. {
  49819. componentPeerChanged();
  49820. if (component == 0)
  49821. return;
  49822. lastPeer = peer;
  49823. }
  49824. unregister();
  49825. registerWithParentComps();
  49826. reentrant = false;
  49827. componentMovedOrResized (*component, true, true);
  49828. }
  49829. }
  49830. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49831. {
  49832. // agh! don't delete the target component without deleting this object first!
  49833. jassert (component != 0);
  49834. if (wasMoved)
  49835. {
  49836. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49837. wasMoved = lastBounds.getPosition() != pos;
  49838. lastBounds.setPosition (pos);
  49839. }
  49840. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49841. lastBounds.setSize (component->getWidth(), component->getHeight());
  49842. if (wasMoved || wasResized)
  49843. componentMovedOrResized (wasMoved, wasResized);
  49844. }
  49845. void ComponentMovementWatcher::registerWithParentComps()
  49846. {
  49847. Component* p = component->getParentComponent();
  49848. while (p != 0)
  49849. {
  49850. p->addComponentListener (this);
  49851. registeredParentComps.add (p);
  49852. p = p->getParentComponent();
  49853. }
  49854. }
  49855. void ComponentMovementWatcher::unregister()
  49856. {
  49857. for (int i = registeredParentComps.size(); --i >= 0;)
  49858. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49859. registeredParentComps.clear();
  49860. }
  49861. END_JUCE_NAMESPACE
  49862. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49863. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49864. BEGIN_JUCE_NAMESPACE
  49865. GroupComponent::GroupComponent (const String& componentName,
  49866. const String& labelText)
  49867. : Component (componentName),
  49868. text (labelText),
  49869. justification (Justification::left)
  49870. {
  49871. setInterceptsMouseClicks (false, true);
  49872. }
  49873. GroupComponent::~GroupComponent()
  49874. {
  49875. }
  49876. void GroupComponent::setText (const String& newText)
  49877. {
  49878. if (text != newText)
  49879. {
  49880. text = newText;
  49881. repaint();
  49882. }
  49883. }
  49884. const String GroupComponent::getText() const
  49885. {
  49886. return text;
  49887. }
  49888. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49889. {
  49890. if (justification != newJustification)
  49891. {
  49892. justification = newJustification;
  49893. repaint();
  49894. }
  49895. }
  49896. void GroupComponent::paint (Graphics& g)
  49897. {
  49898. getLookAndFeel()
  49899. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49900. text, justification,
  49901. *this);
  49902. }
  49903. void GroupComponent::enablementChanged()
  49904. {
  49905. repaint();
  49906. }
  49907. void GroupComponent::colourChanged()
  49908. {
  49909. repaint();
  49910. }
  49911. END_JUCE_NAMESPACE
  49912. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49913. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49914. BEGIN_JUCE_NAMESPACE
  49915. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49916. : DocumentWindow (String::empty, backgroundColour,
  49917. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49918. {
  49919. }
  49920. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49921. {
  49922. }
  49923. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49924. {
  49925. MultiDocumentPanel* const owner = getOwner();
  49926. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49927. if (owner != 0)
  49928. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49929. }
  49930. void MultiDocumentPanelWindow::closeButtonPressed()
  49931. {
  49932. MultiDocumentPanel* const owner = getOwner();
  49933. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49934. if (owner != 0)
  49935. owner->closeDocument (getContentComponent(), true);
  49936. }
  49937. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49938. {
  49939. DocumentWindow::activeWindowStatusChanged();
  49940. updateOrder();
  49941. }
  49942. void MultiDocumentPanelWindow::broughtToFront()
  49943. {
  49944. DocumentWindow::broughtToFront();
  49945. updateOrder();
  49946. }
  49947. void MultiDocumentPanelWindow::updateOrder()
  49948. {
  49949. MultiDocumentPanel* const owner = getOwner();
  49950. if (owner != 0)
  49951. owner->updateOrder();
  49952. }
  49953. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49954. {
  49955. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49956. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49957. }
  49958. class MDITabbedComponentInternal : public TabbedComponent
  49959. {
  49960. public:
  49961. MDITabbedComponentInternal()
  49962. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49963. {
  49964. }
  49965. ~MDITabbedComponentInternal()
  49966. {
  49967. }
  49968. void currentTabChanged (int, const String&)
  49969. {
  49970. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49971. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49972. if (owner != 0)
  49973. owner->updateOrder();
  49974. }
  49975. };
  49976. MultiDocumentPanel::MultiDocumentPanel()
  49977. : mode (MaximisedWindowsWithTabs),
  49978. backgroundColour (Colours::lightblue),
  49979. maximumNumDocuments (0),
  49980. numDocsBeforeTabsUsed (0)
  49981. {
  49982. setOpaque (true);
  49983. }
  49984. MultiDocumentPanel::~MultiDocumentPanel()
  49985. {
  49986. closeAllDocuments (false);
  49987. }
  49988. static bool shouldDeleteComp (Component* const c)
  49989. {
  49990. return c->getProperties() ["mdiDocumentDelete_"];
  49991. }
  49992. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49993. {
  49994. while (components.size() > 0)
  49995. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49996. return false;
  49997. return true;
  49998. }
  49999. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50000. {
  50001. return new MultiDocumentPanelWindow (backgroundColour);
  50002. }
  50003. void MultiDocumentPanel::addWindow (Component* component)
  50004. {
  50005. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50006. dw->setResizable (true, false);
  50007. dw->setContentComponent (component, false, true);
  50008. dw->setName (component->getName());
  50009. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50010. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50011. int x = 4;
  50012. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50013. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50014. x += 16;
  50015. dw->setTopLeftPosition (x, x);
  50016. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50017. if (pos.toString().isNotEmpty())
  50018. dw->restoreWindowStateFromString (pos.toString());
  50019. addAndMakeVisible (dw);
  50020. dw->toFront (true);
  50021. }
  50022. bool MultiDocumentPanel::addDocument (Component* const component,
  50023. const Colour& docColour,
  50024. const bool deleteWhenRemoved)
  50025. {
  50026. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50027. // with a frame-within-a-frame! Just pass in the bare content component.
  50028. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50029. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50030. return false;
  50031. components.add (component);
  50032. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50033. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50034. component->addComponentListener (this);
  50035. if (mode == FloatingWindows)
  50036. {
  50037. if (isFullscreenWhenOneDocument())
  50038. {
  50039. if (components.size() == 1)
  50040. {
  50041. addAndMakeVisible (component);
  50042. }
  50043. else
  50044. {
  50045. if (components.size() == 2)
  50046. addWindow (components.getFirst());
  50047. addWindow (component);
  50048. }
  50049. }
  50050. else
  50051. {
  50052. addWindow (component);
  50053. }
  50054. }
  50055. else
  50056. {
  50057. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50058. {
  50059. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50060. Array <Component*> temp (components);
  50061. for (int i = 0; i < temp.size(); ++i)
  50062. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50063. resized();
  50064. }
  50065. else
  50066. {
  50067. if (tabComponent != 0)
  50068. tabComponent->addTab (component->getName(), docColour, component, false);
  50069. else
  50070. addAndMakeVisible (component);
  50071. }
  50072. setActiveDocument (component);
  50073. }
  50074. resized();
  50075. activeDocumentChanged();
  50076. return true;
  50077. }
  50078. bool MultiDocumentPanel::closeDocument (Component* component,
  50079. const bool checkItsOkToCloseFirst)
  50080. {
  50081. if (components.contains (component))
  50082. {
  50083. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50084. return false;
  50085. component->removeComponentListener (this);
  50086. const bool shouldDelete = shouldDeleteComp (component);
  50087. component->getProperties().remove ("mdiDocumentDelete_");
  50088. component->getProperties().remove ("mdiDocumentBkg_");
  50089. if (mode == FloatingWindows)
  50090. {
  50091. for (int i = getNumChildComponents(); --i >= 0;)
  50092. {
  50093. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50094. if (dw != 0 && dw->getContentComponent() == component)
  50095. {
  50096. dw->setContentComponent (0, false);
  50097. delete dw;
  50098. break;
  50099. }
  50100. }
  50101. if (shouldDelete)
  50102. delete component;
  50103. components.removeValue (component);
  50104. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50105. {
  50106. for (int i = getNumChildComponents(); --i >= 0;)
  50107. {
  50108. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50109. if (dw != 0)
  50110. {
  50111. dw->setContentComponent (0, false);
  50112. delete dw;
  50113. }
  50114. }
  50115. addAndMakeVisible (components.getFirst());
  50116. }
  50117. }
  50118. else
  50119. {
  50120. jassert (components.indexOf (component) >= 0);
  50121. if (tabComponent != 0)
  50122. {
  50123. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50124. if (tabComponent->getTabContentComponent (i) == component)
  50125. tabComponent->removeTab (i);
  50126. }
  50127. else
  50128. {
  50129. removeChildComponent (component);
  50130. }
  50131. if (shouldDelete)
  50132. delete component;
  50133. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50134. tabComponent = 0;
  50135. components.removeValue (component);
  50136. if (components.size() > 0 && tabComponent == 0)
  50137. addAndMakeVisible (components.getFirst());
  50138. }
  50139. resized();
  50140. activeDocumentChanged();
  50141. }
  50142. else
  50143. {
  50144. jassertfalse;
  50145. }
  50146. return true;
  50147. }
  50148. int MultiDocumentPanel::getNumDocuments() const throw()
  50149. {
  50150. return components.size();
  50151. }
  50152. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50153. {
  50154. return components [index];
  50155. }
  50156. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50157. {
  50158. if (mode == FloatingWindows)
  50159. {
  50160. for (int i = getNumChildComponents(); --i >= 0;)
  50161. {
  50162. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50163. if (dw != 0 && dw->isActiveWindow())
  50164. return dw->getContentComponent();
  50165. }
  50166. }
  50167. return components.getLast();
  50168. }
  50169. void MultiDocumentPanel::setActiveDocument (Component* component)
  50170. {
  50171. if (mode == FloatingWindows)
  50172. {
  50173. component = getContainerComp (component);
  50174. if (component != 0)
  50175. component->toFront (true);
  50176. }
  50177. else if (tabComponent != 0)
  50178. {
  50179. jassert (components.indexOf (component) >= 0);
  50180. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50181. {
  50182. if (tabComponent->getTabContentComponent (i) == component)
  50183. {
  50184. tabComponent->setCurrentTabIndex (i);
  50185. break;
  50186. }
  50187. }
  50188. }
  50189. else
  50190. {
  50191. component->grabKeyboardFocus();
  50192. }
  50193. }
  50194. void MultiDocumentPanel::activeDocumentChanged()
  50195. {
  50196. }
  50197. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50198. {
  50199. maximumNumDocuments = newNumber;
  50200. }
  50201. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50202. {
  50203. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50204. }
  50205. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50206. {
  50207. return numDocsBeforeTabsUsed != 0;
  50208. }
  50209. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50210. {
  50211. if (mode != newLayoutMode)
  50212. {
  50213. mode = newLayoutMode;
  50214. if (mode == FloatingWindows)
  50215. {
  50216. tabComponent = 0;
  50217. }
  50218. else
  50219. {
  50220. for (int i = getNumChildComponents(); --i >= 0;)
  50221. {
  50222. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50223. if (dw != 0)
  50224. {
  50225. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50226. dw->setContentComponent (0, false);
  50227. delete dw;
  50228. }
  50229. }
  50230. }
  50231. resized();
  50232. const Array <Component*> tempComps (components);
  50233. components.clear();
  50234. for (int i = 0; i < tempComps.size(); ++i)
  50235. {
  50236. Component* const c = tempComps.getUnchecked(i);
  50237. addDocument (c,
  50238. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50239. shouldDeleteComp (c));
  50240. }
  50241. }
  50242. }
  50243. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50244. {
  50245. if (backgroundColour != newBackgroundColour)
  50246. {
  50247. backgroundColour = newBackgroundColour;
  50248. setOpaque (newBackgroundColour.isOpaque());
  50249. repaint();
  50250. }
  50251. }
  50252. void MultiDocumentPanel::paint (Graphics& g)
  50253. {
  50254. g.fillAll (backgroundColour);
  50255. }
  50256. void MultiDocumentPanel::resized()
  50257. {
  50258. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50259. {
  50260. for (int i = getNumChildComponents(); --i >= 0;)
  50261. getChildComponent (i)->setBounds (getLocalBounds());
  50262. }
  50263. setWantsKeyboardFocus (components.size() == 0);
  50264. }
  50265. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50266. {
  50267. if (mode == FloatingWindows)
  50268. {
  50269. for (int i = 0; i < getNumChildComponents(); ++i)
  50270. {
  50271. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50272. if (dw != 0 && dw->getContentComponent() == c)
  50273. {
  50274. c = dw;
  50275. break;
  50276. }
  50277. }
  50278. }
  50279. return c;
  50280. }
  50281. void MultiDocumentPanel::componentNameChanged (Component&)
  50282. {
  50283. if (mode == FloatingWindows)
  50284. {
  50285. for (int i = 0; i < getNumChildComponents(); ++i)
  50286. {
  50287. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50288. if (dw != 0)
  50289. dw->setName (dw->getContentComponent()->getName());
  50290. }
  50291. }
  50292. else if (tabComponent != 0)
  50293. {
  50294. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50295. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50296. }
  50297. }
  50298. void MultiDocumentPanel::updateOrder()
  50299. {
  50300. const Array <Component*> oldList (components);
  50301. if (mode == FloatingWindows)
  50302. {
  50303. components.clear();
  50304. for (int i = 0; i < getNumChildComponents(); ++i)
  50305. {
  50306. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50307. if (dw != 0)
  50308. components.add (dw->getContentComponent());
  50309. }
  50310. }
  50311. else
  50312. {
  50313. if (tabComponent != 0)
  50314. {
  50315. Component* const current = tabComponent->getCurrentContentComponent();
  50316. if (current != 0)
  50317. {
  50318. components.removeValue (current);
  50319. components.add (current);
  50320. }
  50321. }
  50322. }
  50323. if (components != oldList)
  50324. activeDocumentChanged();
  50325. }
  50326. END_JUCE_NAMESPACE
  50327. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50328. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50329. BEGIN_JUCE_NAMESPACE
  50330. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50331. : zone (zoneFlags)
  50332. {
  50333. }
  50334. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50335. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50336. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50337. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50338. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50339. const BorderSize& border,
  50340. const Point<int>& position)
  50341. {
  50342. int z = 0;
  50343. if (totalSize.contains (position)
  50344. && ! border.subtractedFrom (totalSize).contains (position))
  50345. {
  50346. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50347. if (position.getX() < jmax (border.getLeft(), minW))
  50348. z |= left;
  50349. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50350. z |= right;
  50351. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50352. if (position.getY() < jmax (border.getTop(), minH))
  50353. z |= top;
  50354. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50355. z |= bottom;
  50356. }
  50357. return Zone (z);
  50358. }
  50359. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50360. {
  50361. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50362. switch (zone)
  50363. {
  50364. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50365. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50366. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50367. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50368. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50369. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50370. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50371. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50372. default: break;
  50373. }
  50374. return mc;
  50375. }
  50376. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50377. {
  50378. if (isDraggingWholeObject())
  50379. return b + offset;
  50380. if (isDraggingLeftEdge())
  50381. b.setLeft (b.getX() + offset.getX());
  50382. if (isDraggingRightEdge())
  50383. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50384. if (isDraggingTopEdge())
  50385. b.setTop (b.getY() + offset.getY());
  50386. if (isDraggingBottomEdge())
  50387. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50388. return b;
  50389. }
  50390. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50391. {
  50392. if (isDraggingWholeObject())
  50393. return b + offset;
  50394. if (isDraggingLeftEdge())
  50395. b.setLeft (b.getX() + offset.getX());
  50396. if (isDraggingRightEdge())
  50397. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50398. if (isDraggingTopEdge())
  50399. b.setTop (b.getY() + offset.getY());
  50400. if (isDraggingBottomEdge())
  50401. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50402. return b;
  50403. }
  50404. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50405. ComponentBoundsConstrainer* const constrainer_)
  50406. : component (componentToResize),
  50407. constrainer (constrainer_),
  50408. borderSize (5),
  50409. mouseZone (0)
  50410. {
  50411. }
  50412. ResizableBorderComponent::~ResizableBorderComponent()
  50413. {
  50414. }
  50415. void ResizableBorderComponent::paint (Graphics& g)
  50416. {
  50417. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50418. }
  50419. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50420. {
  50421. updateMouseZone (e);
  50422. }
  50423. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50424. {
  50425. updateMouseZone (e);
  50426. }
  50427. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50428. {
  50429. if (component == 0)
  50430. {
  50431. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50432. return;
  50433. }
  50434. updateMouseZone (e);
  50435. originalBounds = component->getBounds();
  50436. if (constrainer != 0)
  50437. constrainer->resizeStart();
  50438. }
  50439. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50440. {
  50441. if (component == 0)
  50442. {
  50443. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50444. return;
  50445. }
  50446. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50447. if (constrainer != 0)
  50448. constrainer->setBoundsForComponent (component, bounds,
  50449. mouseZone.isDraggingTopEdge(),
  50450. mouseZone.isDraggingLeftEdge(),
  50451. mouseZone.isDraggingBottomEdge(),
  50452. mouseZone.isDraggingRightEdge());
  50453. else
  50454. component->setBounds (bounds);
  50455. }
  50456. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50457. {
  50458. if (constrainer != 0)
  50459. constrainer->resizeEnd();
  50460. }
  50461. bool ResizableBorderComponent::hitTest (int x, int y)
  50462. {
  50463. return x < borderSize.getLeft()
  50464. || x >= getWidth() - borderSize.getRight()
  50465. || y < borderSize.getTop()
  50466. || y >= getHeight() - borderSize.getBottom();
  50467. }
  50468. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50469. {
  50470. if (borderSize != newBorderSize)
  50471. {
  50472. borderSize = newBorderSize;
  50473. repaint();
  50474. }
  50475. }
  50476. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50477. {
  50478. return borderSize;
  50479. }
  50480. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50481. {
  50482. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50483. if (mouseZone != newZone)
  50484. {
  50485. mouseZone = newZone;
  50486. setMouseCursor (newZone.getMouseCursor());
  50487. }
  50488. }
  50489. END_JUCE_NAMESPACE
  50490. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50491. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50492. BEGIN_JUCE_NAMESPACE
  50493. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50494. ComponentBoundsConstrainer* const constrainer_)
  50495. : component (componentToResize),
  50496. constrainer (constrainer_)
  50497. {
  50498. setRepaintsOnMouseActivity (true);
  50499. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50500. }
  50501. ResizableCornerComponent::~ResizableCornerComponent()
  50502. {
  50503. }
  50504. void ResizableCornerComponent::paint (Graphics& g)
  50505. {
  50506. getLookAndFeel()
  50507. .drawCornerResizer (g, getWidth(), getHeight(),
  50508. isMouseOverOrDragging(),
  50509. isMouseButtonDown());
  50510. }
  50511. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50512. {
  50513. if (component == 0)
  50514. {
  50515. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50516. return;
  50517. }
  50518. originalBounds = component->getBounds();
  50519. if (constrainer != 0)
  50520. constrainer->resizeStart();
  50521. }
  50522. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50523. {
  50524. if (component == 0)
  50525. {
  50526. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50527. return;
  50528. }
  50529. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50530. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50531. if (constrainer != 0)
  50532. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50533. else
  50534. component->setBounds (r);
  50535. }
  50536. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50537. {
  50538. if (constrainer != 0)
  50539. constrainer->resizeStart();
  50540. }
  50541. bool ResizableCornerComponent::hitTest (int x, int y)
  50542. {
  50543. if (getWidth() <= 0)
  50544. return false;
  50545. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50546. return y >= yAtX - getHeight() / 4;
  50547. }
  50548. END_JUCE_NAMESPACE
  50549. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50550. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50551. BEGIN_JUCE_NAMESPACE
  50552. class ScrollBar::ScrollbarButton : public Button
  50553. {
  50554. public:
  50555. int direction;
  50556. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50557. : Button (String::empty),
  50558. direction (direction_),
  50559. owner (owner_)
  50560. {
  50561. setWantsKeyboardFocus (false);
  50562. }
  50563. ~ScrollbarButton()
  50564. {
  50565. }
  50566. void paintButton (Graphics& g, bool over, bool down)
  50567. {
  50568. getLookAndFeel()
  50569. .drawScrollbarButton (g, owner,
  50570. getWidth(), getHeight(),
  50571. direction,
  50572. owner.isVertical(),
  50573. over, down);
  50574. }
  50575. void clicked()
  50576. {
  50577. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50578. }
  50579. juce_UseDebuggingNewOperator
  50580. private:
  50581. ScrollBar& owner;
  50582. ScrollbarButton (const ScrollbarButton&);
  50583. ScrollbarButton& operator= (const ScrollbarButton&);
  50584. };
  50585. ScrollBar::ScrollBar (const bool vertical_,
  50586. const bool buttonsAreVisible)
  50587. : totalRange (0.0, 1.0),
  50588. visibleRange (0.0, 0.1),
  50589. singleStepSize (0.1),
  50590. thumbAreaStart (0),
  50591. thumbAreaSize (0),
  50592. thumbStart (0),
  50593. thumbSize (0),
  50594. initialDelayInMillisecs (100),
  50595. repeatDelayInMillisecs (50),
  50596. minimumDelayInMillisecs (10),
  50597. vertical (vertical_),
  50598. isDraggingThumb (false),
  50599. autohides (true)
  50600. {
  50601. setButtonVisibility (buttonsAreVisible);
  50602. setRepaintsOnMouseActivity (true);
  50603. setFocusContainer (true);
  50604. }
  50605. ScrollBar::~ScrollBar()
  50606. {
  50607. upButton = 0;
  50608. downButton = 0;
  50609. }
  50610. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50611. {
  50612. if (totalRange != newRangeLimit)
  50613. {
  50614. totalRange = newRangeLimit;
  50615. setCurrentRange (visibleRange);
  50616. updateThumbPosition();
  50617. }
  50618. }
  50619. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50620. {
  50621. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50622. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50623. }
  50624. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50625. {
  50626. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50627. if (visibleRange != constrainedRange)
  50628. {
  50629. visibleRange = constrainedRange;
  50630. updateThumbPosition();
  50631. triggerAsyncUpdate();
  50632. }
  50633. }
  50634. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50635. {
  50636. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50637. }
  50638. void ScrollBar::setCurrentRangeStart (const double newStart)
  50639. {
  50640. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50641. }
  50642. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50643. {
  50644. singleStepSize = newSingleStepSize;
  50645. }
  50646. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50647. {
  50648. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50649. }
  50650. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50651. {
  50652. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50653. }
  50654. void ScrollBar::scrollToTop()
  50655. {
  50656. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50657. }
  50658. void ScrollBar::scrollToBottom()
  50659. {
  50660. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50661. }
  50662. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50663. const int repeatDelayInMillisecs_,
  50664. const int minimumDelayInMillisecs_)
  50665. {
  50666. initialDelayInMillisecs = initialDelayInMillisecs_;
  50667. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50668. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50669. if (upButton != 0)
  50670. {
  50671. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50672. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50673. }
  50674. }
  50675. void ScrollBar::addListener (Listener* const listener)
  50676. {
  50677. listeners.add (listener);
  50678. }
  50679. void ScrollBar::removeListener (Listener* const listener)
  50680. {
  50681. listeners.remove (listener);
  50682. }
  50683. void ScrollBar::handleAsyncUpdate()
  50684. {
  50685. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50686. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50687. }
  50688. void ScrollBar::updateThumbPosition()
  50689. {
  50690. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50691. : thumbAreaSize);
  50692. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50693. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50694. if (newThumbSize > thumbAreaSize)
  50695. newThumbSize = thumbAreaSize;
  50696. int newThumbStart = thumbAreaStart;
  50697. if (totalRange.getLength() > visibleRange.getLength())
  50698. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50699. / (totalRange.getLength() - visibleRange.getLength()));
  50700. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50701. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50702. {
  50703. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50704. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50705. if (vertical)
  50706. repaint (0, repaintStart, getWidth(), repaintSize);
  50707. else
  50708. repaint (repaintStart, 0, repaintSize, getHeight());
  50709. thumbStart = newThumbStart;
  50710. thumbSize = newThumbSize;
  50711. }
  50712. }
  50713. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50714. {
  50715. if (vertical != shouldBeVertical)
  50716. {
  50717. vertical = shouldBeVertical;
  50718. if (upButton != 0)
  50719. {
  50720. upButton->direction = vertical ? 0 : 3;
  50721. downButton->direction = vertical ? 2 : 1;
  50722. }
  50723. updateThumbPosition();
  50724. }
  50725. }
  50726. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50727. {
  50728. upButton = 0;
  50729. downButton = 0;
  50730. if (buttonsAreVisible)
  50731. {
  50732. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50733. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50734. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50735. }
  50736. updateThumbPosition();
  50737. }
  50738. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50739. {
  50740. autohides = shouldHideWhenFullRange;
  50741. updateThumbPosition();
  50742. }
  50743. bool ScrollBar::autoHides() const throw()
  50744. {
  50745. return autohides;
  50746. }
  50747. void ScrollBar::paint (Graphics& g)
  50748. {
  50749. if (thumbAreaSize > 0)
  50750. {
  50751. LookAndFeel& lf = getLookAndFeel();
  50752. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50753. ? thumbSize : 0;
  50754. if (vertical)
  50755. {
  50756. lf.drawScrollbar (g, *this,
  50757. 0, thumbAreaStart,
  50758. getWidth(), thumbAreaSize,
  50759. vertical,
  50760. thumbStart, thumb,
  50761. isMouseOver(), isMouseButtonDown());
  50762. }
  50763. else
  50764. {
  50765. lf.drawScrollbar (g, *this,
  50766. thumbAreaStart, 0,
  50767. thumbAreaSize, getHeight(),
  50768. vertical,
  50769. thumbStart, thumb,
  50770. isMouseOver(), isMouseButtonDown());
  50771. }
  50772. }
  50773. }
  50774. void ScrollBar::lookAndFeelChanged()
  50775. {
  50776. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50777. }
  50778. void ScrollBar::resized()
  50779. {
  50780. const int length = ((vertical) ? getHeight() : getWidth());
  50781. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50782. : 0;
  50783. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50784. {
  50785. thumbAreaStart = length >> 1;
  50786. thumbAreaSize = 0;
  50787. }
  50788. else
  50789. {
  50790. thumbAreaStart = buttonSize;
  50791. thumbAreaSize = length - (buttonSize << 1);
  50792. }
  50793. if (upButton != 0)
  50794. {
  50795. if (vertical)
  50796. {
  50797. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50798. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50799. }
  50800. else
  50801. {
  50802. upButton->setBounds (0, 0, buttonSize, getHeight());
  50803. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50804. }
  50805. }
  50806. updateThumbPosition();
  50807. }
  50808. void ScrollBar::mouseDown (const MouseEvent& e)
  50809. {
  50810. isDraggingThumb = false;
  50811. lastMousePos = vertical ? e.y : e.x;
  50812. dragStartMousePos = lastMousePos;
  50813. dragStartRange = visibleRange.getStart();
  50814. if (dragStartMousePos < thumbStart)
  50815. {
  50816. moveScrollbarInPages (-1);
  50817. startTimer (400);
  50818. }
  50819. else if (dragStartMousePos >= thumbStart + thumbSize)
  50820. {
  50821. moveScrollbarInPages (1);
  50822. startTimer (400);
  50823. }
  50824. else
  50825. {
  50826. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50827. && (thumbAreaSize > thumbSize);
  50828. }
  50829. }
  50830. void ScrollBar::mouseDrag (const MouseEvent& e)
  50831. {
  50832. if (isDraggingThumb)
  50833. {
  50834. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50835. setCurrentRangeStart (dragStartRange
  50836. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50837. / (thumbAreaSize - thumbSize));
  50838. }
  50839. else
  50840. {
  50841. lastMousePos = (vertical) ? e.y : e.x;
  50842. }
  50843. }
  50844. void ScrollBar::mouseUp (const MouseEvent&)
  50845. {
  50846. isDraggingThumb = false;
  50847. stopTimer();
  50848. repaint();
  50849. }
  50850. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50851. float wheelIncrementX,
  50852. float wheelIncrementY)
  50853. {
  50854. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50855. if (increment < 0)
  50856. increment = jmin (increment * 10.0f, -1.0f);
  50857. else if (increment > 0)
  50858. increment = jmax (increment * 10.0f, 1.0f);
  50859. setCurrentRange (visibleRange - singleStepSize * increment);
  50860. }
  50861. void ScrollBar::timerCallback()
  50862. {
  50863. if (isMouseButtonDown())
  50864. {
  50865. startTimer (40);
  50866. if (lastMousePos < thumbStart)
  50867. setCurrentRange (visibleRange - visibleRange.getLength());
  50868. else if (lastMousePos > thumbStart + thumbSize)
  50869. setCurrentRangeStart (visibleRange.getEnd());
  50870. }
  50871. else
  50872. {
  50873. stopTimer();
  50874. }
  50875. }
  50876. bool ScrollBar::keyPressed (const KeyPress& key)
  50877. {
  50878. if (! isVisible())
  50879. return false;
  50880. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50881. moveScrollbarInSteps (-1);
  50882. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50883. moveScrollbarInSteps (1);
  50884. else if (key.isKeyCode (KeyPress::pageUpKey))
  50885. moveScrollbarInPages (-1);
  50886. else if (key.isKeyCode (KeyPress::pageDownKey))
  50887. moveScrollbarInPages (1);
  50888. else if (key.isKeyCode (KeyPress::homeKey))
  50889. scrollToTop();
  50890. else if (key.isKeyCode (KeyPress::endKey))
  50891. scrollToBottom();
  50892. else
  50893. return false;
  50894. return true;
  50895. }
  50896. END_JUCE_NAMESPACE
  50897. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50898. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50899. BEGIN_JUCE_NAMESPACE
  50900. StretchableLayoutManager::StretchableLayoutManager()
  50901. : totalSize (0)
  50902. {
  50903. }
  50904. StretchableLayoutManager::~StretchableLayoutManager()
  50905. {
  50906. }
  50907. void StretchableLayoutManager::clearAllItems()
  50908. {
  50909. items.clear();
  50910. totalSize = 0;
  50911. }
  50912. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50913. const double minimumSize,
  50914. const double maximumSize,
  50915. const double preferredSize)
  50916. {
  50917. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50918. if (layout == 0)
  50919. {
  50920. layout = new ItemLayoutProperties();
  50921. layout->itemIndex = itemIndex;
  50922. int i;
  50923. for (i = 0; i < items.size(); ++i)
  50924. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50925. break;
  50926. items.insert (i, layout);
  50927. }
  50928. layout->minSize = minimumSize;
  50929. layout->maxSize = maximumSize;
  50930. layout->preferredSize = preferredSize;
  50931. layout->currentSize = 0;
  50932. }
  50933. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50934. double& minimumSize,
  50935. double& maximumSize,
  50936. double& preferredSize) const
  50937. {
  50938. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50939. if (layout != 0)
  50940. {
  50941. minimumSize = layout->minSize;
  50942. maximumSize = layout->maxSize;
  50943. preferredSize = layout->preferredSize;
  50944. return true;
  50945. }
  50946. return false;
  50947. }
  50948. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50949. {
  50950. totalSize = newTotalSize;
  50951. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50952. }
  50953. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50954. {
  50955. int pos = 0;
  50956. for (int i = 0; i < itemIndex; ++i)
  50957. {
  50958. const ItemLayoutProperties* const layout = getInfoFor (i);
  50959. if (layout != 0)
  50960. pos += layout->currentSize;
  50961. }
  50962. return pos;
  50963. }
  50964. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50965. {
  50966. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50967. if (layout != 0)
  50968. return layout->currentSize;
  50969. return 0;
  50970. }
  50971. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50972. {
  50973. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50974. if (layout != 0)
  50975. return -layout->currentSize / (double) totalSize;
  50976. return 0;
  50977. }
  50978. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50979. int newPosition)
  50980. {
  50981. for (int i = items.size(); --i >= 0;)
  50982. {
  50983. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50984. if (layout->itemIndex == itemIndex)
  50985. {
  50986. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50987. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50988. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50989. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50990. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50991. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50992. endPos += layout->currentSize;
  50993. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50994. updatePrefSizesToMatchCurrentPositions();
  50995. break;
  50996. }
  50997. }
  50998. }
  50999. void StretchableLayoutManager::layOutComponents (Component** const components,
  51000. int numComponents,
  51001. int x, int y, int w, int h,
  51002. const bool vertically,
  51003. const bool resizeOtherDimension)
  51004. {
  51005. setTotalSize (vertically ? h : w);
  51006. int pos = vertically ? y : x;
  51007. for (int i = 0; i < numComponents; ++i)
  51008. {
  51009. const ItemLayoutProperties* const layout = getInfoFor (i);
  51010. if (layout != 0)
  51011. {
  51012. Component* const c = components[i];
  51013. if (c != 0)
  51014. {
  51015. if (i == numComponents - 1)
  51016. {
  51017. // if it's the last item, crop it to exactly fit the available space..
  51018. if (resizeOtherDimension)
  51019. {
  51020. if (vertically)
  51021. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51022. else
  51023. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51024. }
  51025. else
  51026. {
  51027. if (vertically)
  51028. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51029. else
  51030. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51031. }
  51032. }
  51033. else
  51034. {
  51035. if (resizeOtherDimension)
  51036. {
  51037. if (vertically)
  51038. c->setBounds (x, pos, w, layout->currentSize);
  51039. else
  51040. c->setBounds (pos, y, layout->currentSize, h);
  51041. }
  51042. else
  51043. {
  51044. if (vertically)
  51045. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51046. else
  51047. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51048. }
  51049. }
  51050. }
  51051. pos += layout->currentSize;
  51052. }
  51053. }
  51054. }
  51055. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51056. {
  51057. for (int i = items.size(); --i >= 0;)
  51058. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51059. return items.getUnchecked(i);
  51060. return 0;
  51061. }
  51062. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51063. const int endIndex,
  51064. const int availableSpace,
  51065. int startPos)
  51066. {
  51067. // calculate the total sizes
  51068. int i;
  51069. double totalIdealSize = 0.0;
  51070. int totalMinimums = 0;
  51071. for (i = startIndex; i < endIndex; ++i)
  51072. {
  51073. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51074. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51075. totalMinimums += layout->currentSize;
  51076. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51077. }
  51078. if (totalIdealSize <= 0)
  51079. totalIdealSize = 1.0;
  51080. // now calc the best sizes..
  51081. int extraSpace = availableSpace - totalMinimums;
  51082. while (extraSpace > 0)
  51083. {
  51084. int numWantingMoreSpace = 0;
  51085. int numHavingTakenExtraSpace = 0;
  51086. // first figure out how many comps want a slice of the extra space..
  51087. for (i = startIndex; i < endIndex; ++i)
  51088. {
  51089. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51090. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51091. const int bestSize = jlimit (layout->currentSize,
  51092. jmax (layout->currentSize,
  51093. sizeToRealSize (layout->maxSize, totalSize)),
  51094. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51095. if (bestSize > layout->currentSize)
  51096. ++numWantingMoreSpace;
  51097. }
  51098. // ..share out the extra space..
  51099. for (i = startIndex; i < endIndex; ++i)
  51100. {
  51101. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51102. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51103. int bestSize = jlimit (layout->currentSize,
  51104. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51105. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51106. const int extraWanted = bestSize - layout->currentSize;
  51107. if (extraWanted > 0)
  51108. {
  51109. const int extraAllowed = jmin (extraWanted,
  51110. extraSpace / jmax (1, numWantingMoreSpace));
  51111. if (extraAllowed > 0)
  51112. {
  51113. ++numHavingTakenExtraSpace;
  51114. --numWantingMoreSpace;
  51115. layout->currentSize += extraAllowed;
  51116. extraSpace -= extraAllowed;
  51117. }
  51118. }
  51119. }
  51120. if (numHavingTakenExtraSpace <= 0)
  51121. break;
  51122. }
  51123. // ..and calculate the end position
  51124. for (i = startIndex; i < endIndex; ++i)
  51125. {
  51126. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51127. startPos += layout->currentSize;
  51128. }
  51129. return startPos;
  51130. }
  51131. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51132. const int endIndex) const
  51133. {
  51134. int totalMinimums = 0;
  51135. for (int i = startIndex; i < endIndex; ++i)
  51136. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51137. return totalMinimums;
  51138. }
  51139. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51140. {
  51141. int totalMaximums = 0;
  51142. for (int i = startIndex; i < endIndex; ++i)
  51143. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51144. return totalMaximums;
  51145. }
  51146. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51147. {
  51148. for (int i = 0; i < items.size(); ++i)
  51149. {
  51150. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51151. layout->preferredSize
  51152. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51153. : getItemCurrentAbsoluteSize (i);
  51154. }
  51155. }
  51156. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51157. {
  51158. if (size < 0)
  51159. size *= -totalSpace;
  51160. return roundToInt (size);
  51161. }
  51162. END_JUCE_NAMESPACE
  51163. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51164. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51165. BEGIN_JUCE_NAMESPACE
  51166. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51167. const int itemIndex_,
  51168. const bool isVertical_)
  51169. : layout (layout_),
  51170. itemIndex (itemIndex_),
  51171. isVertical (isVertical_)
  51172. {
  51173. setRepaintsOnMouseActivity (true);
  51174. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51175. : MouseCursor::UpDownResizeCursor));
  51176. }
  51177. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51178. {
  51179. }
  51180. void StretchableLayoutResizerBar::paint (Graphics& g)
  51181. {
  51182. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51183. getWidth(), getHeight(),
  51184. isVertical,
  51185. isMouseOver(),
  51186. isMouseButtonDown());
  51187. }
  51188. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51189. {
  51190. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51191. }
  51192. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51193. {
  51194. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51195. : e.getDistanceFromDragStartY());
  51196. layout->setItemPosition (itemIndex, desiredPos);
  51197. hasBeenMoved();
  51198. }
  51199. void StretchableLayoutResizerBar::hasBeenMoved()
  51200. {
  51201. if (getParentComponent() != 0)
  51202. getParentComponent()->resized();
  51203. }
  51204. END_JUCE_NAMESPACE
  51205. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51206. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51207. BEGIN_JUCE_NAMESPACE
  51208. StretchableObjectResizer::StretchableObjectResizer()
  51209. {
  51210. }
  51211. StretchableObjectResizer::~StretchableObjectResizer()
  51212. {
  51213. }
  51214. void StretchableObjectResizer::addItem (const double size,
  51215. const double minSize, const double maxSize,
  51216. const int order)
  51217. {
  51218. // the order must be >= 0 but less than the maximum integer value.
  51219. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51220. Item* const item = new Item();
  51221. item->size = size;
  51222. item->minSize = minSize;
  51223. item->maxSize = maxSize;
  51224. item->order = order;
  51225. items.add (item);
  51226. }
  51227. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51228. {
  51229. const Item* const it = items [index];
  51230. return it != 0 ? it->size : 0;
  51231. }
  51232. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51233. {
  51234. int order = 0;
  51235. for (;;)
  51236. {
  51237. double currentSize = 0;
  51238. double minSize = 0;
  51239. double maxSize = 0;
  51240. int nextHighestOrder = std::numeric_limits<int>::max();
  51241. for (int i = 0; i < items.size(); ++i)
  51242. {
  51243. const Item* const it = items.getUnchecked(i);
  51244. currentSize += it->size;
  51245. if (it->order <= order)
  51246. {
  51247. minSize += it->minSize;
  51248. maxSize += it->maxSize;
  51249. }
  51250. else
  51251. {
  51252. minSize += it->size;
  51253. maxSize += it->size;
  51254. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51255. }
  51256. }
  51257. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51258. if (thisIterationTarget >= currentSize)
  51259. {
  51260. const double availableExtraSpace = maxSize - currentSize;
  51261. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51262. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51263. for (int i = 0; i < items.size(); ++i)
  51264. {
  51265. Item* const it = items.getUnchecked(i);
  51266. if (it->order <= order)
  51267. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51268. }
  51269. }
  51270. else
  51271. {
  51272. const double amountOfSlack = currentSize - minSize;
  51273. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51274. const double scale = targetAmountOfSlack / amountOfSlack;
  51275. for (int i = 0; i < items.size(); ++i)
  51276. {
  51277. Item* const it = items.getUnchecked(i);
  51278. if (it->order <= order)
  51279. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51280. }
  51281. }
  51282. if (nextHighestOrder < std::numeric_limits<int>::max())
  51283. order = nextHighestOrder;
  51284. else
  51285. break;
  51286. }
  51287. }
  51288. END_JUCE_NAMESPACE
  51289. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51290. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51291. BEGIN_JUCE_NAMESPACE
  51292. TabBarButton::TabBarButton (const String& name,
  51293. TabbedButtonBar* const owner_,
  51294. const int index)
  51295. : Button (name),
  51296. owner (owner_),
  51297. tabIndex (index),
  51298. overlapPixels (0)
  51299. {
  51300. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51301. setComponentEffect (&shadow);
  51302. setWantsKeyboardFocus (false);
  51303. }
  51304. TabBarButton::~TabBarButton()
  51305. {
  51306. }
  51307. void TabBarButton::paintButton (Graphics& g,
  51308. bool isMouseOverButton,
  51309. bool isButtonDown)
  51310. {
  51311. int x, y, w, h;
  51312. getActiveArea (x, y, w, h);
  51313. g.setOrigin (x, y);
  51314. getLookAndFeel()
  51315. .drawTabButton (g, w, h,
  51316. owner->getTabBackgroundColour (tabIndex),
  51317. tabIndex, getButtonText(), *this,
  51318. owner->getOrientation(),
  51319. isMouseOverButton, isButtonDown,
  51320. getToggleState());
  51321. }
  51322. void TabBarButton::clicked (const ModifierKeys& mods)
  51323. {
  51324. if (mods.isPopupMenu())
  51325. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51326. else
  51327. owner->setCurrentTabIndex (tabIndex);
  51328. }
  51329. bool TabBarButton::hitTest (int mx, int my)
  51330. {
  51331. int x, y, w, h;
  51332. getActiveArea (x, y, w, h);
  51333. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51334. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51335. {
  51336. if (((unsigned int) mx) < (unsigned int) getWidth()
  51337. && my >= y + overlapPixels
  51338. && my < y + h - overlapPixels)
  51339. return true;
  51340. }
  51341. else
  51342. {
  51343. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51344. && ((unsigned int) my) < (unsigned int) getHeight())
  51345. return true;
  51346. }
  51347. Path p;
  51348. getLookAndFeel()
  51349. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51350. owner->getOrientation(),
  51351. false, false, getToggleState());
  51352. return p.contains ((float) (mx - x),
  51353. (float) (my - y));
  51354. }
  51355. int TabBarButton::getBestTabLength (const int depth)
  51356. {
  51357. return jlimit (depth * 2,
  51358. depth * 7,
  51359. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51360. }
  51361. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51362. {
  51363. x = 0;
  51364. y = 0;
  51365. int r = getWidth();
  51366. int b = getHeight();
  51367. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51368. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51369. r -= spaceAroundImage;
  51370. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51371. x += spaceAroundImage;
  51372. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51373. y += spaceAroundImage;
  51374. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51375. b -= spaceAroundImage;
  51376. w = r - x;
  51377. h = b - y;
  51378. }
  51379. class TabAreaBehindFrontButtonComponent : public Component
  51380. {
  51381. public:
  51382. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51383. : owner (owner_)
  51384. {
  51385. setInterceptsMouseClicks (false, false);
  51386. }
  51387. ~TabAreaBehindFrontButtonComponent()
  51388. {
  51389. }
  51390. void paint (Graphics& g)
  51391. {
  51392. getLookAndFeel()
  51393. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51394. *owner, owner->getOrientation());
  51395. }
  51396. void enablementChanged()
  51397. {
  51398. repaint();
  51399. }
  51400. private:
  51401. TabbedButtonBar* const owner;
  51402. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51403. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51404. };
  51405. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51406. : orientation (orientation_),
  51407. currentTabIndex (-1)
  51408. {
  51409. setInterceptsMouseClicks (false, true);
  51410. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51411. setFocusContainer (true);
  51412. }
  51413. TabbedButtonBar::~TabbedButtonBar()
  51414. {
  51415. extraTabsButton = 0;
  51416. deleteAllChildren();
  51417. }
  51418. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51419. {
  51420. orientation = newOrientation;
  51421. for (int i = getNumChildComponents(); --i >= 0;)
  51422. getChildComponent (i)->resized();
  51423. resized();
  51424. }
  51425. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51426. {
  51427. return new TabBarButton (name, this, index);
  51428. }
  51429. void TabbedButtonBar::clearTabs()
  51430. {
  51431. tabs.clear();
  51432. tabColours.clear();
  51433. currentTabIndex = -1;
  51434. extraTabsButton = 0;
  51435. removeChildComponent (behindFrontTab);
  51436. deleteAllChildren();
  51437. addChildComponent (behindFrontTab);
  51438. setCurrentTabIndex (-1);
  51439. }
  51440. void TabbedButtonBar::addTab (const String& tabName,
  51441. const Colour& tabBackgroundColour,
  51442. int insertIndex)
  51443. {
  51444. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51445. if (tabName.isNotEmpty())
  51446. {
  51447. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51448. insertIndex = tabs.size();
  51449. for (int i = tabs.size(); --i >= insertIndex;)
  51450. {
  51451. TabBarButton* const tb = getTabButton (i);
  51452. if (tb != 0)
  51453. tb->tabIndex++;
  51454. }
  51455. tabs.insert (insertIndex, tabName);
  51456. tabColours.insert (insertIndex, tabBackgroundColour);
  51457. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51458. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51459. addAndMakeVisible (tb, insertIndex);
  51460. resized();
  51461. if (currentTabIndex < 0)
  51462. setCurrentTabIndex (0);
  51463. }
  51464. }
  51465. void TabbedButtonBar::setTabName (const int tabIndex,
  51466. const String& newName)
  51467. {
  51468. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51469. && tabs[tabIndex] != newName)
  51470. {
  51471. tabs.set (tabIndex, newName);
  51472. TabBarButton* const tb = getTabButton (tabIndex);
  51473. if (tb != 0)
  51474. tb->setButtonText (newName);
  51475. resized();
  51476. }
  51477. }
  51478. void TabbedButtonBar::removeTab (const int tabIndex)
  51479. {
  51480. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51481. {
  51482. const int oldTabIndex = currentTabIndex;
  51483. if (currentTabIndex == tabIndex)
  51484. currentTabIndex = -1;
  51485. tabs.remove (tabIndex);
  51486. tabColours.remove (tabIndex);
  51487. delete getTabButton (tabIndex);
  51488. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51489. {
  51490. TabBarButton* const tb = getTabButton (i);
  51491. if (tb != 0)
  51492. tb->tabIndex--;
  51493. }
  51494. resized();
  51495. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51496. }
  51497. }
  51498. void TabbedButtonBar::moveTab (const int currentIndex,
  51499. const int newIndex)
  51500. {
  51501. tabs.move (currentIndex, newIndex);
  51502. tabColours.move (currentIndex, newIndex);
  51503. resized();
  51504. }
  51505. int TabbedButtonBar::getNumTabs() const
  51506. {
  51507. return tabs.size();
  51508. }
  51509. const StringArray TabbedButtonBar::getTabNames() const
  51510. {
  51511. return tabs;
  51512. }
  51513. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51514. {
  51515. if (currentTabIndex != newIndex)
  51516. {
  51517. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51518. newIndex = -1;
  51519. currentTabIndex = newIndex;
  51520. for (int i = 0; i < getNumChildComponents(); ++i)
  51521. {
  51522. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51523. if (tb != 0)
  51524. tb->setToggleState (tb->tabIndex == newIndex, false);
  51525. }
  51526. resized();
  51527. if (sendChangeMessage_)
  51528. sendChangeMessage (this);
  51529. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51530. }
  51531. }
  51532. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51533. {
  51534. for (int i = getNumChildComponents(); --i >= 0;)
  51535. {
  51536. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51537. if (tb != 0 && tb->tabIndex == index)
  51538. return tb;
  51539. }
  51540. return 0;
  51541. }
  51542. void TabbedButtonBar::lookAndFeelChanged()
  51543. {
  51544. extraTabsButton = 0;
  51545. resized();
  51546. }
  51547. void TabbedButtonBar::resized()
  51548. {
  51549. const double minimumScale = 0.7;
  51550. int depth = getWidth();
  51551. int length = getHeight();
  51552. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51553. swapVariables (depth, length);
  51554. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51555. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51556. int i, totalLength = overlap;
  51557. int numVisibleButtons = tabs.size();
  51558. for (i = 0; i < getNumChildComponents(); ++i)
  51559. {
  51560. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51561. if (tb != 0)
  51562. {
  51563. totalLength += tb->getBestTabLength (depth) - overlap;
  51564. tb->overlapPixels = overlap / 2;
  51565. }
  51566. }
  51567. double scale = 1.0;
  51568. if (totalLength > length)
  51569. scale = jmax (minimumScale, length / (double) totalLength);
  51570. const bool isTooBig = totalLength * scale > length;
  51571. int tabsButtonPos = 0;
  51572. if (isTooBig)
  51573. {
  51574. if (extraTabsButton == 0)
  51575. {
  51576. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51577. extraTabsButton->addButtonListener (this);
  51578. extraTabsButton->setAlwaysOnTop (true);
  51579. extraTabsButton->setTriggeredOnMouseDown (true);
  51580. }
  51581. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51582. extraTabsButton->setSize (buttonSize, buttonSize);
  51583. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51584. {
  51585. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51586. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51587. }
  51588. else
  51589. {
  51590. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51591. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51592. }
  51593. totalLength = 0;
  51594. for (i = 0; i < tabs.size(); ++i)
  51595. {
  51596. TabBarButton* const tb = getTabButton (i);
  51597. if (tb != 0)
  51598. {
  51599. const int newLength = totalLength + tb->getBestTabLength (depth);
  51600. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51601. {
  51602. totalLength += overlap;
  51603. break;
  51604. }
  51605. numVisibleButtons = i + 1;
  51606. totalLength = newLength - overlap;
  51607. }
  51608. }
  51609. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51610. }
  51611. else
  51612. {
  51613. extraTabsButton = 0;
  51614. }
  51615. int pos = 0;
  51616. TabBarButton* frontTab = 0;
  51617. for (i = 0; i < tabs.size(); ++i)
  51618. {
  51619. TabBarButton* const tb = getTabButton (i);
  51620. if (tb != 0)
  51621. {
  51622. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51623. if (i < numVisibleButtons)
  51624. {
  51625. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51626. tb->setBounds (pos, 0, bestLength, getHeight());
  51627. else
  51628. tb->setBounds (0, pos, getWidth(), bestLength);
  51629. tb->toBack();
  51630. if (tb->tabIndex == currentTabIndex)
  51631. frontTab = tb;
  51632. tb->setVisible (true);
  51633. }
  51634. else
  51635. {
  51636. tb->setVisible (false);
  51637. }
  51638. pos += bestLength - overlap;
  51639. }
  51640. }
  51641. behindFrontTab->setBounds (getLocalBounds());
  51642. if (frontTab != 0)
  51643. {
  51644. frontTab->toFront (false);
  51645. behindFrontTab->toBehind (frontTab);
  51646. }
  51647. }
  51648. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51649. {
  51650. return tabColours [tabIndex];
  51651. }
  51652. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51653. {
  51654. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51655. && tabColours [tabIndex] != newColour)
  51656. {
  51657. tabColours.set (tabIndex, newColour);
  51658. repaint();
  51659. }
  51660. }
  51661. void TabbedButtonBar::buttonClicked (Button* button)
  51662. {
  51663. if (button == extraTabsButton)
  51664. {
  51665. PopupMenu m;
  51666. for (int i = 0; i < tabs.size(); ++i)
  51667. {
  51668. TabBarButton* const tb = getTabButton (i);
  51669. if (tb != 0 && ! tb->isVisible())
  51670. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51671. }
  51672. const int res = m.showAt (extraTabsButton);
  51673. if (res != 0)
  51674. setCurrentTabIndex (res - 1);
  51675. }
  51676. }
  51677. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51678. {
  51679. }
  51680. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51681. {
  51682. }
  51683. END_JUCE_NAMESPACE
  51684. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51685. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51686. BEGIN_JUCE_NAMESPACE
  51687. class TabCompButtonBar : public TabbedButtonBar
  51688. {
  51689. public:
  51690. TabCompButtonBar (TabbedComponent* const owner_,
  51691. const TabbedButtonBar::Orientation orientation_)
  51692. : TabbedButtonBar (orientation_),
  51693. owner (owner_)
  51694. {
  51695. }
  51696. ~TabCompButtonBar()
  51697. {
  51698. }
  51699. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51700. {
  51701. owner->changeCallback (newCurrentTabIndex, newTabName);
  51702. }
  51703. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51704. {
  51705. owner->popupMenuClickOnTab (tabIndex, tabName);
  51706. }
  51707. const Colour getTabBackgroundColour (const int tabIndex)
  51708. {
  51709. return owner->tabs->getTabBackgroundColour (tabIndex);
  51710. }
  51711. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51712. {
  51713. return owner->createTabButton (tabName, tabIndex);
  51714. }
  51715. juce_UseDebuggingNewOperator
  51716. private:
  51717. TabbedComponent* const owner;
  51718. TabCompButtonBar (const TabCompButtonBar&);
  51719. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51720. };
  51721. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51722. : panelComponent (0),
  51723. tabDepth (30),
  51724. outlineThickness (1),
  51725. edgeIndent (0)
  51726. {
  51727. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51728. }
  51729. TabbedComponent::~TabbedComponent()
  51730. {
  51731. clearTabs();
  51732. delete tabs;
  51733. }
  51734. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51735. {
  51736. tabs->setOrientation (orientation);
  51737. resized();
  51738. }
  51739. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51740. {
  51741. return tabs->getOrientation();
  51742. }
  51743. void TabbedComponent::setTabBarDepth (const int newDepth)
  51744. {
  51745. if (tabDepth != newDepth)
  51746. {
  51747. tabDepth = newDepth;
  51748. resized();
  51749. }
  51750. }
  51751. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51752. {
  51753. return new TabBarButton (tabName, tabs, tabIndex);
  51754. }
  51755. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51756. void TabbedComponent::clearTabs()
  51757. {
  51758. if (panelComponent != 0)
  51759. {
  51760. panelComponent->setVisible (false);
  51761. removeChildComponent (panelComponent);
  51762. panelComponent = 0;
  51763. }
  51764. tabs->clearTabs();
  51765. for (int i = contentComponents.size(); --i >= 0;)
  51766. {
  51767. Component* const c = contentComponents.getUnchecked(i);
  51768. // be careful not to delete these components until they've been removed from the tab component
  51769. jassert (c == 0 || c->isValidComponent());
  51770. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51771. delete c;
  51772. }
  51773. contentComponents.clear();
  51774. }
  51775. void TabbedComponent::addTab (const String& tabName,
  51776. const Colour& tabBackgroundColour,
  51777. Component* const contentComponent,
  51778. const bool deleteComponentWhenNotNeeded,
  51779. const int insertIndex)
  51780. {
  51781. contentComponents.insert (insertIndex, contentComponent);
  51782. if (contentComponent != 0)
  51783. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51784. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51785. }
  51786. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51787. {
  51788. tabs->setTabName (tabIndex, newName);
  51789. }
  51790. void TabbedComponent::removeTab (const int tabIndex)
  51791. {
  51792. Component* const c = contentComponents [tabIndex];
  51793. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51794. {
  51795. if (c == panelComponent)
  51796. panelComponent = 0;
  51797. delete c;
  51798. }
  51799. contentComponents.remove (tabIndex);
  51800. tabs->removeTab (tabIndex);
  51801. }
  51802. int TabbedComponent::getNumTabs() const
  51803. {
  51804. return tabs->getNumTabs();
  51805. }
  51806. const StringArray TabbedComponent::getTabNames() const
  51807. {
  51808. return tabs->getTabNames();
  51809. }
  51810. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51811. {
  51812. return contentComponents [tabIndex];
  51813. }
  51814. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51815. {
  51816. return tabs->getTabBackgroundColour (tabIndex);
  51817. }
  51818. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51819. {
  51820. tabs->setTabBackgroundColour (tabIndex, newColour);
  51821. if (getCurrentTabIndex() == tabIndex)
  51822. repaint();
  51823. }
  51824. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51825. {
  51826. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51827. }
  51828. int TabbedComponent::getCurrentTabIndex() const
  51829. {
  51830. return tabs->getCurrentTabIndex();
  51831. }
  51832. const String& TabbedComponent::getCurrentTabName() const
  51833. {
  51834. return tabs->getCurrentTabName();
  51835. }
  51836. void TabbedComponent::setOutline (int thickness)
  51837. {
  51838. outlineThickness = thickness;
  51839. repaint();
  51840. }
  51841. void TabbedComponent::setIndent (const int indentThickness)
  51842. {
  51843. edgeIndent = indentThickness;
  51844. }
  51845. void TabbedComponent::paint (Graphics& g)
  51846. {
  51847. g.fillAll (findColour (backgroundColourId));
  51848. const TabbedButtonBar::Orientation o = getOrientation();
  51849. int x = 0;
  51850. int y = 0;
  51851. int r = getWidth();
  51852. int b = getHeight();
  51853. if (o == TabbedButtonBar::TabsAtTop)
  51854. y += tabDepth;
  51855. else if (o == TabbedButtonBar::TabsAtBottom)
  51856. b -= tabDepth;
  51857. else if (o == TabbedButtonBar::TabsAtLeft)
  51858. x += tabDepth;
  51859. else if (o == TabbedButtonBar::TabsAtRight)
  51860. r -= tabDepth;
  51861. g.reduceClipRegion (x, y, r - x, b - y);
  51862. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51863. if (outlineThickness > 0)
  51864. {
  51865. if (o == TabbedButtonBar::TabsAtTop)
  51866. --y;
  51867. else if (o == TabbedButtonBar::TabsAtBottom)
  51868. ++b;
  51869. else if (o == TabbedButtonBar::TabsAtLeft)
  51870. --x;
  51871. else if (o == TabbedButtonBar::TabsAtRight)
  51872. ++r;
  51873. g.setColour (findColour (outlineColourId));
  51874. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51875. }
  51876. }
  51877. void TabbedComponent::resized()
  51878. {
  51879. const TabbedButtonBar::Orientation o = getOrientation();
  51880. const int indent = edgeIndent + outlineThickness;
  51881. BorderSize indents (indent);
  51882. if (o == TabbedButtonBar::TabsAtTop)
  51883. {
  51884. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51885. indents.setTop (tabDepth + edgeIndent);
  51886. }
  51887. else if (o == TabbedButtonBar::TabsAtBottom)
  51888. {
  51889. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51890. indents.setBottom (tabDepth + edgeIndent);
  51891. }
  51892. else if (o == TabbedButtonBar::TabsAtLeft)
  51893. {
  51894. tabs->setBounds (0, 0, tabDepth, getHeight());
  51895. indents.setLeft (tabDepth + edgeIndent);
  51896. }
  51897. else if (o == TabbedButtonBar::TabsAtRight)
  51898. {
  51899. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51900. indents.setRight (tabDepth + edgeIndent);
  51901. }
  51902. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51903. for (int i = contentComponents.size(); --i >= 0;)
  51904. if (contentComponents.getUnchecked (i) != 0)
  51905. contentComponents.getUnchecked (i)->setBounds (bounds);
  51906. }
  51907. void TabbedComponent::lookAndFeelChanged()
  51908. {
  51909. for (int i = contentComponents.size(); --i >= 0;)
  51910. if (contentComponents.getUnchecked (i) != 0)
  51911. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51912. }
  51913. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51914. const String& newTabName)
  51915. {
  51916. if (panelComponent != 0)
  51917. {
  51918. panelComponent->setVisible (false);
  51919. removeChildComponent (panelComponent);
  51920. panelComponent = 0;
  51921. }
  51922. if (getCurrentTabIndex() >= 0)
  51923. {
  51924. panelComponent = contentComponents [getCurrentTabIndex()];
  51925. if (panelComponent != 0)
  51926. {
  51927. // do these ops as two stages instead of addAndMakeVisible() so that the
  51928. // component has always got a parent when it gets the visibilityChanged() callback
  51929. addChildComponent (panelComponent);
  51930. panelComponent->setVisible (true);
  51931. panelComponent->toFront (true);
  51932. }
  51933. repaint();
  51934. }
  51935. resized();
  51936. currentTabChanged (newCurrentTabIndex, newTabName);
  51937. }
  51938. void TabbedComponent::currentTabChanged (const int, const String&)
  51939. {
  51940. }
  51941. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51942. {
  51943. }
  51944. END_JUCE_NAMESPACE
  51945. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51946. /*** Start of inlined file: juce_Viewport.cpp ***/
  51947. BEGIN_JUCE_NAMESPACE
  51948. Viewport::Viewport (const String& componentName)
  51949. : Component (componentName),
  51950. scrollBarThickness (0),
  51951. singleStepX (16),
  51952. singleStepY (16),
  51953. showHScrollbar (true),
  51954. showVScrollbar (true),
  51955. verticalScrollBar (true),
  51956. horizontalScrollBar (false)
  51957. {
  51958. // content holder is used to clip the contents so they don't overlap the scrollbars
  51959. addAndMakeVisible (&contentHolder);
  51960. contentHolder.setInterceptsMouseClicks (false, true);
  51961. addChildComponent (&verticalScrollBar);
  51962. addChildComponent (&horizontalScrollBar);
  51963. verticalScrollBar.addListener (this);
  51964. horizontalScrollBar.addListener (this);
  51965. setInterceptsMouseClicks (false, true);
  51966. setWantsKeyboardFocus (true);
  51967. }
  51968. Viewport::~Viewport()
  51969. {
  51970. contentHolder.deleteAllChildren();
  51971. }
  51972. void Viewport::visibleAreaChanged (int, int, int, int)
  51973. {
  51974. }
  51975. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51976. {
  51977. if (contentComp.getComponent() != newViewedComponent)
  51978. {
  51979. {
  51980. ScopedPointer<Component> oldCompDeleter (contentComp);
  51981. contentComp = 0;
  51982. }
  51983. contentComp = newViewedComponent;
  51984. if (contentComp != 0)
  51985. {
  51986. contentComp->setTopLeftPosition (0, 0);
  51987. contentHolder.addAndMakeVisible (contentComp);
  51988. contentComp->addComponentListener (this);
  51989. }
  51990. updateVisibleArea();
  51991. }
  51992. }
  51993. int Viewport::getMaximumVisibleWidth() const
  51994. {
  51995. return contentHolder.getWidth();
  51996. }
  51997. int Viewport::getMaximumVisibleHeight() const
  51998. {
  51999. return contentHolder.getHeight();
  52000. }
  52001. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52002. {
  52003. if (contentComp != 0)
  52004. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52005. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52006. }
  52007. void Viewport::setViewPosition (const Point<int>& newPosition)
  52008. {
  52009. setViewPosition (newPosition.getX(), newPosition.getY());
  52010. }
  52011. void Viewport::setViewPositionProportionately (const double x, const double y)
  52012. {
  52013. if (contentComp != 0)
  52014. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52015. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52016. }
  52017. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52018. {
  52019. if (contentComp != 0)
  52020. {
  52021. int dx = 0, dy = 0;
  52022. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52023. {
  52024. if (mouseX < activeBorderThickness)
  52025. dx = activeBorderThickness - mouseX;
  52026. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52027. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52028. if (dx < 0)
  52029. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52030. else
  52031. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52032. }
  52033. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52034. {
  52035. if (mouseY < activeBorderThickness)
  52036. dy = activeBorderThickness - mouseY;
  52037. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52038. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52039. if (dy < 0)
  52040. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52041. else
  52042. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52043. }
  52044. if (dx != 0 || dy != 0)
  52045. {
  52046. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52047. contentComp->getY() + dy);
  52048. return true;
  52049. }
  52050. }
  52051. return false;
  52052. }
  52053. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52054. {
  52055. updateVisibleArea();
  52056. }
  52057. void Viewport::resized()
  52058. {
  52059. updateVisibleArea();
  52060. }
  52061. void Viewport::updateVisibleArea()
  52062. {
  52063. const int scrollbarWidth = getScrollBarThickness();
  52064. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52065. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52066. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52067. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52068. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52069. Rectangle<int> contentArea (getLocalBounds());
  52070. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52071. {
  52072. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52073. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52074. if (vBarVisible)
  52075. contentArea.setWidth (getWidth() - scrollbarWidth);
  52076. if (hBarVisible)
  52077. contentArea.setHeight (getHeight() - scrollbarWidth);
  52078. if (! contentArea.contains (contentComp->getBounds()))
  52079. {
  52080. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52081. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52082. }
  52083. }
  52084. if (vBarVisible)
  52085. contentArea.setWidth (getWidth() - scrollbarWidth);
  52086. if (hBarVisible)
  52087. contentArea.setHeight (getHeight() - scrollbarWidth);
  52088. contentHolder.setBounds (contentArea);
  52089. Rectangle<int> contentBounds;
  52090. if (contentComp != 0)
  52091. contentBounds = contentComp->getBounds();
  52092. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52093. if (hBarVisible)
  52094. {
  52095. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52096. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52097. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52098. horizontalScrollBar.setSingleStepSize (singleStepX);
  52099. horizontalScrollBar.cancelPendingUpdate();
  52100. }
  52101. if (vBarVisible)
  52102. {
  52103. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52104. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52105. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52106. verticalScrollBar.setSingleStepSize (singleStepY);
  52107. verticalScrollBar.cancelPendingUpdate();
  52108. }
  52109. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52110. horizontalScrollBar.setVisible (hBarVisible);
  52111. verticalScrollBar.setVisible (vBarVisible);
  52112. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52113. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52114. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52115. if (lastVisibleArea != visibleArea)
  52116. {
  52117. lastVisibleArea = visibleArea;
  52118. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52119. }
  52120. horizontalScrollBar.handleUpdateNowIfNeeded();
  52121. verticalScrollBar.handleUpdateNowIfNeeded();
  52122. }
  52123. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52124. {
  52125. if (singleStepX != stepX || singleStepY != stepY)
  52126. {
  52127. singleStepX = stepX;
  52128. singleStepY = stepY;
  52129. updateVisibleArea();
  52130. }
  52131. }
  52132. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52133. const bool showHorizontalScrollbarIfNeeded)
  52134. {
  52135. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52136. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52137. {
  52138. showVScrollbar = showVerticalScrollbarIfNeeded;
  52139. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52140. updateVisibleArea();
  52141. }
  52142. }
  52143. void Viewport::setScrollBarThickness (const int thickness)
  52144. {
  52145. if (scrollBarThickness != thickness)
  52146. {
  52147. scrollBarThickness = thickness;
  52148. updateVisibleArea();
  52149. }
  52150. }
  52151. int Viewport::getScrollBarThickness() const
  52152. {
  52153. return scrollBarThickness > 0 ? scrollBarThickness
  52154. : getLookAndFeel().getDefaultScrollbarWidth();
  52155. }
  52156. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52157. {
  52158. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52159. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52160. }
  52161. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52162. {
  52163. const int newRangeStartInt = roundToInt (newRangeStart);
  52164. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52165. {
  52166. setViewPosition (newRangeStartInt, getViewPositionY());
  52167. }
  52168. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52169. {
  52170. setViewPosition (getViewPositionX(), newRangeStartInt);
  52171. }
  52172. }
  52173. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52174. {
  52175. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52176. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52177. }
  52178. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52179. {
  52180. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52181. {
  52182. const bool hasVertBar = verticalScrollBar.isVisible();
  52183. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52184. if (hasHorzBar || hasVertBar)
  52185. {
  52186. if (wheelIncrementX != 0)
  52187. {
  52188. wheelIncrementX *= 14.0f * singleStepX;
  52189. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52190. : jmax (wheelIncrementX, 1.0f);
  52191. }
  52192. if (wheelIncrementY != 0)
  52193. {
  52194. wheelIncrementY *= 14.0f * singleStepY;
  52195. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52196. : jmax (wheelIncrementY, 1.0f);
  52197. }
  52198. Point<int> pos (getViewPosition());
  52199. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52200. {
  52201. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52202. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52203. }
  52204. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52205. {
  52206. if (wheelIncrementX == 0 && ! hasVertBar)
  52207. wheelIncrementX = wheelIncrementY;
  52208. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52209. }
  52210. else if (hasVertBar && wheelIncrementY != 0)
  52211. {
  52212. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52213. }
  52214. if (pos != getViewPosition())
  52215. {
  52216. setViewPosition (pos);
  52217. return true;
  52218. }
  52219. }
  52220. }
  52221. return false;
  52222. }
  52223. bool Viewport::keyPressed (const KeyPress& key)
  52224. {
  52225. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52226. || key.isKeyCode (KeyPress::downKey)
  52227. || key.isKeyCode (KeyPress::pageUpKey)
  52228. || key.isKeyCode (KeyPress::pageDownKey)
  52229. || key.isKeyCode (KeyPress::homeKey)
  52230. || key.isKeyCode (KeyPress::endKey);
  52231. if (verticalScrollBar.isVisible() && isUpDownKey)
  52232. return verticalScrollBar.keyPressed (key);
  52233. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52234. || key.isKeyCode (KeyPress::rightKey);
  52235. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52236. return horizontalScrollBar.keyPressed (key);
  52237. return false;
  52238. }
  52239. END_JUCE_NAMESPACE
  52240. /*** End of inlined file: juce_Viewport.cpp ***/
  52241. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52242. BEGIN_JUCE_NAMESPACE
  52243. static const Colour createBaseColour (const Colour& buttonColour,
  52244. const bool hasKeyboardFocus,
  52245. const bool isMouseOverButton,
  52246. const bool isButtonDown) throw()
  52247. {
  52248. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52249. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52250. if (isButtonDown)
  52251. return baseColour.contrasting (0.2f);
  52252. else if (isMouseOverButton)
  52253. return baseColour.contrasting (0.1f);
  52254. return baseColour;
  52255. }
  52256. LookAndFeel::LookAndFeel()
  52257. {
  52258. /* if this fails it means you're trying to create a LookAndFeel object before
  52259. the static Colours have been initialised. That ain't gonna work. It probably
  52260. means that you're using a static LookAndFeel object and that your compiler has
  52261. decided to intialise it before the Colours class.
  52262. */
  52263. jassert (Colours::white == Colour (0xffffffff));
  52264. // set up the standard set of colours..
  52265. const int textButtonColour = 0xffbbbbff;
  52266. const int textHighlightColour = 0x401111ee;
  52267. const int standardOutlineColour = 0xb2808080;
  52268. static const int standardColours[] =
  52269. {
  52270. TextButton::buttonColourId, textButtonColour,
  52271. TextButton::buttonOnColourId, 0xff4444ff,
  52272. TextButton::textColourOnId, 0xff000000,
  52273. TextButton::textColourOffId, 0xff000000,
  52274. ComboBox::buttonColourId, 0xffbbbbff,
  52275. ComboBox::outlineColourId, standardOutlineColour,
  52276. ToggleButton::textColourId, 0xff000000,
  52277. TextEditor::backgroundColourId, 0xffffffff,
  52278. TextEditor::textColourId, 0xff000000,
  52279. TextEditor::highlightColourId, textHighlightColour,
  52280. TextEditor::highlightedTextColourId, 0xff000000,
  52281. TextEditor::caretColourId, 0xff000000,
  52282. TextEditor::outlineColourId, 0x00000000,
  52283. TextEditor::focusedOutlineColourId, textButtonColour,
  52284. TextEditor::shadowColourId, 0x38000000,
  52285. Label::backgroundColourId, 0x00000000,
  52286. Label::textColourId, 0xff000000,
  52287. Label::outlineColourId, 0x00000000,
  52288. ScrollBar::backgroundColourId, 0x00000000,
  52289. ScrollBar::thumbColourId, 0xffffffff,
  52290. ScrollBar::trackColourId, 0xffffffff,
  52291. TreeView::linesColourId, 0x4c000000,
  52292. TreeView::backgroundColourId, 0x00000000,
  52293. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52294. PopupMenu::backgroundColourId, 0xffffffff,
  52295. PopupMenu::textColourId, 0xff000000,
  52296. PopupMenu::headerTextColourId, 0xff000000,
  52297. PopupMenu::highlightedTextColourId, 0xffffffff,
  52298. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52299. ComboBox::textColourId, 0xff000000,
  52300. ComboBox::backgroundColourId, 0xffffffff,
  52301. ComboBox::arrowColourId, 0x99000000,
  52302. ListBox::backgroundColourId, 0xffffffff,
  52303. ListBox::outlineColourId, standardOutlineColour,
  52304. ListBox::textColourId, 0xff000000,
  52305. Slider::backgroundColourId, 0x00000000,
  52306. Slider::thumbColourId, textButtonColour,
  52307. Slider::trackColourId, 0x7fffffff,
  52308. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52309. Slider::rotarySliderOutlineColourId, 0x66000000,
  52310. Slider::textBoxTextColourId, 0xff000000,
  52311. Slider::textBoxBackgroundColourId, 0xffffffff,
  52312. Slider::textBoxHighlightColourId, textHighlightColour,
  52313. Slider::textBoxOutlineColourId, standardOutlineColour,
  52314. ResizableWindow::backgroundColourId, 0xff777777,
  52315. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52316. AlertWindow::backgroundColourId, 0xffededed,
  52317. AlertWindow::textColourId, 0xff000000,
  52318. AlertWindow::outlineColourId, 0xff666666,
  52319. ProgressBar::backgroundColourId, 0xffeeeeee,
  52320. ProgressBar::foregroundColourId, 0xffaaaaee,
  52321. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52322. TooltipWindow::textColourId, 0xff000000,
  52323. TooltipWindow::outlineColourId, 0x4c000000,
  52324. TabbedComponent::backgroundColourId, 0x00000000,
  52325. TabbedComponent::outlineColourId, 0xff777777,
  52326. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52327. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52328. Toolbar::backgroundColourId, 0xfff6f8f9,
  52329. Toolbar::separatorColourId, 0x4c000000,
  52330. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52331. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52332. Toolbar::labelTextColourId, 0xff000000,
  52333. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52334. HyperlinkButton::textColourId, 0xcc1111ee,
  52335. GroupComponent::outlineColourId, 0x66000000,
  52336. GroupComponent::textColourId, 0xff000000,
  52337. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52338. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52339. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52340. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52341. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52342. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52343. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52344. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52345. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52346. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52347. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52348. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52349. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52350. CodeEditorComponent::caretColourId, 0xff000000,
  52351. CodeEditorComponent::highlightColourId, textHighlightColour,
  52352. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52353. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52354. ColourSelector::labelTextColourId, 0xff000000,
  52355. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52356. KeyMappingEditorComponent::textColourId, 0xff000000,
  52357. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52358. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52359. };
  52360. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52361. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52362. static String defaultSansName, defaultSerifName, defaultFixedName;
  52363. if (defaultSansName.isEmpty())
  52364. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52365. defaultSans = defaultSansName;
  52366. defaultSerif = defaultSerifName;
  52367. defaultFixed = defaultFixedName;
  52368. }
  52369. LookAndFeel::~LookAndFeel()
  52370. {
  52371. }
  52372. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52373. {
  52374. const int index = colourIds.indexOf (colourId);
  52375. if (index >= 0)
  52376. return colours [index];
  52377. jassertfalse;
  52378. return Colours::black;
  52379. }
  52380. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52381. {
  52382. const int index = colourIds.indexOf (colourId);
  52383. if (index >= 0)
  52384. {
  52385. colours.set (index, colour);
  52386. }
  52387. else
  52388. {
  52389. colourIds.add (colourId);
  52390. colours.add (colour);
  52391. }
  52392. }
  52393. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52394. {
  52395. return colourIds.contains (colourId);
  52396. }
  52397. static LookAndFeel* defaultLF = 0;
  52398. static LookAndFeel* currentDefaultLF = 0;
  52399. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52400. {
  52401. // if this happens, your app hasn't initialised itself properly.. if you're
  52402. // trying to hack your own main() function, have a look at
  52403. // JUCEApplication::initialiseForGUI()
  52404. jassert (currentDefaultLF != 0);
  52405. return *currentDefaultLF;
  52406. }
  52407. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52408. {
  52409. if (newDefaultLookAndFeel == 0)
  52410. {
  52411. if (defaultLF == 0)
  52412. defaultLF = new LookAndFeel();
  52413. newDefaultLookAndFeel = defaultLF;
  52414. }
  52415. currentDefaultLF = newDefaultLookAndFeel;
  52416. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52417. {
  52418. Component* const c = Desktop::getInstance().getComponent (i);
  52419. if (c != 0)
  52420. c->sendLookAndFeelChange();
  52421. }
  52422. }
  52423. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52424. {
  52425. if (currentDefaultLF == defaultLF)
  52426. currentDefaultLF = 0;
  52427. deleteAndZero (defaultLF);
  52428. }
  52429. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52430. {
  52431. String faceName (font.getTypefaceName());
  52432. if (faceName == Font::getDefaultSansSerifFontName())
  52433. faceName = defaultSans;
  52434. else if (faceName == Font::getDefaultSerifFontName())
  52435. faceName = defaultSerif;
  52436. else if (faceName == Font::getDefaultMonospacedFontName())
  52437. faceName = defaultFixed;
  52438. Font f (font);
  52439. f.setTypefaceName (faceName);
  52440. return Typeface::createSystemTypefaceFor (f);
  52441. }
  52442. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52443. {
  52444. defaultSans = newName;
  52445. }
  52446. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52447. {
  52448. return component.getMouseCursor();
  52449. }
  52450. void LookAndFeel::drawButtonBackground (Graphics& g,
  52451. Button& button,
  52452. const Colour& backgroundColour,
  52453. bool isMouseOverButton,
  52454. bool isButtonDown)
  52455. {
  52456. const int width = button.getWidth();
  52457. const int height = button.getHeight();
  52458. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52459. const float halfThickness = outlineThickness * 0.5f;
  52460. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52461. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52462. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52463. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52464. const Colour baseColour (createBaseColour (backgroundColour,
  52465. button.hasKeyboardFocus (true),
  52466. isMouseOverButton, isButtonDown)
  52467. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52468. drawGlassLozenge (g,
  52469. indentL,
  52470. indentT,
  52471. width - indentL - indentR,
  52472. height - indentT - indentB,
  52473. baseColour, outlineThickness, -1.0f,
  52474. button.isConnectedOnLeft(),
  52475. button.isConnectedOnRight(),
  52476. button.isConnectedOnTop(),
  52477. button.isConnectedOnBottom());
  52478. }
  52479. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52480. {
  52481. return button.getFont();
  52482. }
  52483. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52484. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52485. {
  52486. Font font (getFontForTextButton (button));
  52487. g.setFont (font);
  52488. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52489. : TextButton::textColourOffId)
  52490. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52491. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52492. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52493. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52494. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52495. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52496. g.drawFittedText (button.getButtonText(),
  52497. leftIndent,
  52498. yIndent,
  52499. button.getWidth() - leftIndent - rightIndent,
  52500. button.getHeight() - yIndent * 2,
  52501. Justification::centred, 2);
  52502. }
  52503. void LookAndFeel::drawTickBox (Graphics& g,
  52504. Component& component,
  52505. float x, float y, float w, float h,
  52506. const bool ticked,
  52507. const bool isEnabled,
  52508. const bool isMouseOverButton,
  52509. const bool isButtonDown)
  52510. {
  52511. const float boxSize = w * 0.7f;
  52512. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52513. createBaseColour (component.findColour (TextButton::buttonColourId)
  52514. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52515. true,
  52516. isMouseOverButton,
  52517. isButtonDown),
  52518. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52519. if (ticked)
  52520. {
  52521. Path tick;
  52522. tick.startNewSubPath (1.5f, 3.0f);
  52523. tick.lineTo (3.0f, 6.0f);
  52524. tick.lineTo (6.0f, 0.0f);
  52525. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52526. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52527. .translated (x, y));
  52528. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52529. }
  52530. }
  52531. void LookAndFeel::drawToggleButton (Graphics& g,
  52532. ToggleButton& button,
  52533. bool isMouseOverButton,
  52534. bool isButtonDown)
  52535. {
  52536. if (button.hasKeyboardFocus (true))
  52537. {
  52538. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52539. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52540. }
  52541. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52542. const float tickWidth = fontSize * 1.1f;
  52543. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52544. tickWidth, tickWidth,
  52545. button.getToggleState(),
  52546. button.isEnabled(),
  52547. isMouseOverButton,
  52548. isButtonDown);
  52549. g.setColour (button.findColour (ToggleButton::textColourId));
  52550. g.setFont (fontSize);
  52551. if (! button.isEnabled())
  52552. g.setOpacity (0.5f);
  52553. const int textX = (int) tickWidth + 5;
  52554. g.drawFittedText (button.getButtonText(),
  52555. textX, 0,
  52556. button.getWidth() - textX - 2, button.getHeight(),
  52557. Justification::centredLeft, 10);
  52558. }
  52559. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52560. {
  52561. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52562. const int tickWidth = jmin (24, button.getHeight());
  52563. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52564. button.getHeight());
  52565. }
  52566. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52567. const String& message,
  52568. const String& button1,
  52569. const String& button2,
  52570. const String& button3,
  52571. AlertWindow::AlertIconType iconType,
  52572. int numButtons,
  52573. Component* associatedComponent)
  52574. {
  52575. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52576. if (numButtons == 1)
  52577. {
  52578. aw->addButton (button1, 0,
  52579. KeyPress (KeyPress::escapeKey, 0, 0),
  52580. KeyPress (KeyPress::returnKey, 0, 0));
  52581. }
  52582. else
  52583. {
  52584. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52585. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52586. if (button1ShortCut == button2ShortCut)
  52587. button2ShortCut = KeyPress();
  52588. if (numButtons == 2)
  52589. {
  52590. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52591. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52592. }
  52593. else if (numButtons == 3)
  52594. {
  52595. aw->addButton (button1, 1, button1ShortCut);
  52596. aw->addButton (button2, 2, button2ShortCut);
  52597. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52598. }
  52599. }
  52600. return aw;
  52601. }
  52602. void LookAndFeel::drawAlertBox (Graphics& g,
  52603. AlertWindow& alert,
  52604. const Rectangle<int>& textArea,
  52605. TextLayout& textLayout)
  52606. {
  52607. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52608. int iconSpaceUsed = 0;
  52609. Justification alignment (Justification::horizontallyCentred);
  52610. const int iconWidth = 80;
  52611. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52612. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52613. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52614. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52615. iconSize, iconSize);
  52616. if (alert.getAlertType() != AlertWindow::NoIcon)
  52617. {
  52618. Path icon;
  52619. uint32 colour;
  52620. char character;
  52621. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52622. {
  52623. colour = 0x55ff5555;
  52624. character = '!';
  52625. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52626. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52627. (float) iconRect.getX(), (float) iconRect.getBottom());
  52628. icon = icon.createPathWithRoundedCorners (5.0f);
  52629. }
  52630. else
  52631. {
  52632. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52633. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52634. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52635. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52636. }
  52637. GlyphArrangement ga;
  52638. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52639. String::charToString (character),
  52640. (float) iconRect.getX(), (float) iconRect.getY(),
  52641. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52642. Justification::centred, false);
  52643. ga.createPath (icon);
  52644. icon.setUsingNonZeroWinding (false);
  52645. g.setColour (Colour (colour));
  52646. g.fillPath (icon);
  52647. iconSpaceUsed = iconWidth;
  52648. alignment = Justification::left;
  52649. }
  52650. g.setColour (alert.findColour (AlertWindow::textColourId));
  52651. textLayout.drawWithin (g,
  52652. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52653. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52654. alignment.getFlags() | Justification::top);
  52655. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52656. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52657. }
  52658. int LookAndFeel::getAlertBoxWindowFlags()
  52659. {
  52660. return ComponentPeer::windowAppearsOnTaskbar
  52661. | ComponentPeer::windowHasDropShadow;
  52662. }
  52663. int LookAndFeel::getAlertWindowButtonHeight()
  52664. {
  52665. return 28;
  52666. }
  52667. const Font LookAndFeel::getAlertWindowFont()
  52668. {
  52669. return Font (12.0f);
  52670. }
  52671. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52672. int width, int height,
  52673. double progress, const String& textToShow)
  52674. {
  52675. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52676. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52677. g.fillAll (background);
  52678. if (progress >= 0.0f && progress < 1.0f)
  52679. {
  52680. drawGlassLozenge (g, 1.0f, 1.0f,
  52681. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52682. (float) (height - 2),
  52683. foreground,
  52684. 0.5f, 0.0f,
  52685. true, true, true, true);
  52686. }
  52687. else
  52688. {
  52689. // spinning bar..
  52690. g.setColour (foreground);
  52691. const int stripeWidth = height * 2;
  52692. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52693. Path p;
  52694. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52695. p.addQuadrilateral (x, 0.0f,
  52696. x + stripeWidth * 0.5f, 0.0f,
  52697. x, (float) height,
  52698. x - stripeWidth * 0.5f, (float) height);
  52699. Image im (Image::ARGB, width, height, true);
  52700. {
  52701. Graphics g2 (im);
  52702. drawGlassLozenge (g2, 1.0f, 1.0f,
  52703. (float) (width - 2),
  52704. (float) (height - 2),
  52705. foreground,
  52706. 0.5f, 0.0f,
  52707. true, true, true, true);
  52708. }
  52709. g.setTiledImageFill (im, 0, 0, 0.85f);
  52710. g.fillPath (p);
  52711. }
  52712. if (textToShow.isNotEmpty())
  52713. {
  52714. g.setColour (Colour::contrasting (background, foreground));
  52715. g.setFont (height * 0.6f);
  52716. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52717. }
  52718. }
  52719. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52720. {
  52721. const float radius = jmin (w, h) * 0.4f;
  52722. const float thickness = radius * 0.15f;
  52723. Path p;
  52724. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52725. radius * 0.6f, thickness,
  52726. thickness * 0.5f);
  52727. const float cx = x + w * 0.5f;
  52728. const float cy = y + h * 0.5f;
  52729. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52730. for (int i = 0; i < 12; ++i)
  52731. {
  52732. const int n = (i + 12 - animationIndex) % 12;
  52733. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52734. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52735. .translated (cx, cy));
  52736. }
  52737. }
  52738. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52739. ScrollBar& scrollbar,
  52740. int width, int height,
  52741. int buttonDirection,
  52742. bool /*isScrollbarVertical*/,
  52743. bool /*isMouseOverButton*/,
  52744. bool isButtonDown)
  52745. {
  52746. Path p;
  52747. if (buttonDirection == 0)
  52748. p.addTriangle (width * 0.5f, height * 0.2f,
  52749. width * 0.1f, height * 0.7f,
  52750. width * 0.9f, height * 0.7f);
  52751. else if (buttonDirection == 1)
  52752. p.addTriangle (width * 0.8f, height * 0.5f,
  52753. width * 0.3f, height * 0.1f,
  52754. width * 0.3f, height * 0.9f);
  52755. else if (buttonDirection == 2)
  52756. p.addTriangle (width * 0.5f, height * 0.8f,
  52757. width * 0.1f, height * 0.3f,
  52758. width * 0.9f, height * 0.3f);
  52759. else if (buttonDirection == 3)
  52760. p.addTriangle (width * 0.2f, height * 0.5f,
  52761. width * 0.7f, height * 0.1f,
  52762. width * 0.7f, height * 0.9f);
  52763. if (isButtonDown)
  52764. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52765. else
  52766. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52767. g.fillPath (p);
  52768. g.setColour (Colour (0x80000000));
  52769. g.strokePath (p, PathStrokeType (0.5f));
  52770. }
  52771. void LookAndFeel::drawScrollbar (Graphics& g,
  52772. ScrollBar& scrollbar,
  52773. int x, int y,
  52774. int width, int height,
  52775. bool isScrollbarVertical,
  52776. int thumbStartPosition,
  52777. int thumbSize,
  52778. bool /*isMouseOver*/,
  52779. bool /*isMouseDown*/)
  52780. {
  52781. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52782. Path slotPath, thumbPath;
  52783. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52784. const float slotIndentx2 = slotIndent * 2.0f;
  52785. const float thumbIndent = slotIndent + 1.0f;
  52786. const float thumbIndentx2 = thumbIndent * 2.0f;
  52787. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52788. if (isScrollbarVertical)
  52789. {
  52790. slotPath.addRoundedRectangle (x + slotIndent,
  52791. y + slotIndent,
  52792. width - slotIndentx2,
  52793. height - slotIndentx2,
  52794. (width - slotIndentx2) * 0.5f);
  52795. if (thumbSize > 0)
  52796. thumbPath.addRoundedRectangle (x + thumbIndent,
  52797. thumbStartPosition + thumbIndent,
  52798. width - thumbIndentx2,
  52799. thumbSize - thumbIndentx2,
  52800. (width - thumbIndentx2) * 0.5f);
  52801. gx1 = (float) x;
  52802. gx2 = x + width * 0.7f;
  52803. }
  52804. else
  52805. {
  52806. slotPath.addRoundedRectangle (x + slotIndent,
  52807. y + slotIndent,
  52808. width - slotIndentx2,
  52809. height - slotIndentx2,
  52810. (height - slotIndentx2) * 0.5f);
  52811. if (thumbSize > 0)
  52812. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52813. y + thumbIndent,
  52814. thumbSize - thumbIndentx2,
  52815. height - thumbIndentx2,
  52816. (height - thumbIndentx2) * 0.5f);
  52817. gy1 = (float) y;
  52818. gy2 = y + height * 0.7f;
  52819. }
  52820. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52821. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52822. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52823. g.fillPath (slotPath);
  52824. if (isScrollbarVertical)
  52825. {
  52826. gx1 = x + width * 0.6f;
  52827. gx2 = (float) x + width;
  52828. }
  52829. else
  52830. {
  52831. gy1 = y + height * 0.6f;
  52832. gy2 = (float) y + height;
  52833. }
  52834. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52835. Colour (0x19000000), gx2, gy2, false));
  52836. g.fillPath (slotPath);
  52837. g.setColour (thumbColour);
  52838. g.fillPath (thumbPath);
  52839. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52840. Colours::transparentBlack, gx2, gy2, false));
  52841. g.saveState();
  52842. if (isScrollbarVertical)
  52843. g.reduceClipRegion (x + width / 2, y, width, height);
  52844. else
  52845. g.reduceClipRegion (x, y + height / 2, width, height);
  52846. g.fillPath (thumbPath);
  52847. g.restoreState();
  52848. g.setColour (Colour (0x4c000000));
  52849. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52850. }
  52851. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52852. {
  52853. return 0;
  52854. }
  52855. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52856. {
  52857. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52858. }
  52859. int LookAndFeel::getDefaultScrollbarWidth()
  52860. {
  52861. return 18;
  52862. }
  52863. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52864. {
  52865. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52866. : scrollbar.getHeight());
  52867. }
  52868. const Path LookAndFeel::getTickShape (const float height)
  52869. {
  52870. static const unsigned char tickShapeData[] =
  52871. {
  52872. 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,
  52873. 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,
  52874. 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,
  52875. 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,
  52876. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52877. };
  52878. Path p;
  52879. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52880. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52881. return p;
  52882. }
  52883. const Path LookAndFeel::getCrossShape (const float height)
  52884. {
  52885. static const unsigned char crossShapeData[] =
  52886. {
  52887. 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,
  52888. 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,
  52889. 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,
  52890. 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,
  52891. 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,
  52892. 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,
  52893. 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
  52894. };
  52895. Path p;
  52896. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52897. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52898. return p;
  52899. }
  52900. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52901. {
  52902. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52903. x += (w - boxSize) >> 1;
  52904. y += (h - boxSize) >> 1;
  52905. w = boxSize;
  52906. h = boxSize;
  52907. g.setColour (Colour (0xe5ffffff));
  52908. g.fillRect (x, y, w, h);
  52909. g.setColour (Colour (0x80000000));
  52910. g.drawRect (x, y, w, h);
  52911. const float size = boxSize / 2 + 1.0f;
  52912. const float centre = (float) (boxSize / 2);
  52913. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52914. if (isPlus)
  52915. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52916. }
  52917. void LookAndFeel::drawBubble (Graphics& g,
  52918. float tipX, float tipY,
  52919. float boxX, float boxY,
  52920. float boxW, float boxH)
  52921. {
  52922. int side = 0;
  52923. if (tipX < boxX)
  52924. side = 1;
  52925. else if (tipX > boxX + boxW)
  52926. side = 3;
  52927. else if (tipY > boxY + boxH)
  52928. side = 2;
  52929. const float indent = 2.0f;
  52930. Path p;
  52931. p.addBubble (boxX + indent,
  52932. boxY + indent,
  52933. boxW - indent * 2.0f,
  52934. boxH - indent * 2.0f,
  52935. 5.0f,
  52936. tipX, tipY,
  52937. side,
  52938. 0.5f,
  52939. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52940. //xxx need to take comp as param for colour
  52941. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52942. g.fillPath (p);
  52943. //xxx as above
  52944. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52945. g.strokePath (p, PathStrokeType (1.33f));
  52946. }
  52947. const Font LookAndFeel::getPopupMenuFont()
  52948. {
  52949. return Font (17.0f);
  52950. }
  52951. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52952. const bool isSeparator,
  52953. int standardMenuItemHeight,
  52954. int& idealWidth,
  52955. int& idealHeight)
  52956. {
  52957. if (isSeparator)
  52958. {
  52959. idealWidth = 50;
  52960. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52961. }
  52962. else
  52963. {
  52964. Font font (getPopupMenuFont());
  52965. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52966. font.setHeight (standardMenuItemHeight / 1.3f);
  52967. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52968. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52969. }
  52970. }
  52971. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52972. {
  52973. const Colour background (findColour (PopupMenu::backgroundColourId));
  52974. g.fillAll (background);
  52975. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52976. for (int i = 0; i < height; i += 3)
  52977. g.fillRect (0, i, width, 1);
  52978. #if ! JUCE_MAC
  52979. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52980. g.drawRect (0, 0, width, height);
  52981. #endif
  52982. }
  52983. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52984. int width, int height,
  52985. bool isScrollUpArrow)
  52986. {
  52987. const Colour background (findColour (PopupMenu::backgroundColourId));
  52988. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52989. background.withAlpha (0.0f),
  52990. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52991. false));
  52992. g.fillRect (1, 1, width - 2, height - 2);
  52993. const float hw = width * 0.5f;
  52994. const float arrowW = height * 0.3f;
  52995. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52996. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52997. Path p;
  52998. p.addTriangle (hw - arrowW, y1,
  52999. hw + arrowW, y1,
  53000. hw, y2);
  53001. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53002. g.fillPath (p);
  53003. }
  53004. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53005. int width, int height,
  53006. const bool isSeparator,
  53007. const bool isActive,
  53008. const bool isHighlighted,
  53009. const bool isTicked,
  53010. const bool hasSubMenu,
  53011. const String& text,
  53012. const String& shortcutKeyText,
  53013. Image* image,
  53014. const Colour* const textColourToUse)
  53015. {
  53016. const float halfH = height * 0.5f;
  53017. if (isSeparator)
  53018. {
  53019. const float separatorIndent = 5.5f;
  53020. g.setColour (Colour (0x33000000));
  53021. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53022. g.setColour (Colour (0x66ffffff));
  53023. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53024. }
  53025. else
  53026. {
  53027. Colour textColour (findColour (PopupMenu::textColourId));
  53028. if (textColourToUse != 0)
  53029. textColour = *textColourToUse;
  53030. if (isHighlighted)
  53031. {
  53032. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53033. g.fillRect (1, 1, width - 2, height - 2);
  53034. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53035. }
  53036. else
  53037. {
  53038. g.setColour (textColour);
  53039. }
  53040. if (! isActive)
  53041. g.setOpacity (0.3f);
  53042. Font font (getPopupMenuFont());
  53043. if (font.getHeight() > height / 1.3f)
  53044. font.setHeight (height / 1.3f);
  53045. g.setFont (font);
  53046. const int leftBorder = (height * 5) / 4;
  53047. const int rightBorder = 4;
  53048. if (image != 0)
  53049. {
  53050. g.drawImageWithin (*image,
  53051. 2, 1, leftBorder - 4, height - 2,
  53052. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53053. }
  53054. else if (isTicked)
  53055. {
  53056. const Path tick (getTickShape (1.0f));
  53057. const float th = font.getAscent();
  53058. const float ty = halfH - th * 0.5f;
  53059. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53060. th, true));
  53061. }
  53062. g.drawFittedText (text,
  53063. leftBorder, 0,
  53064. width - (leftBorder + rightBorder), height,
  53065. Justification::centredLeft, 1);
  53066. if (shortcutKeyText.isNotEmpty())
  53067. {
  53068. Font f2 (font);
  53069. f2.setHeight (f2.getHeight() * 0.75f);
  53070. f2.setHorizontalScale (0.95f);
  53071. g.setFont (f2);
  53072. g.drawText (shortcutKeyText,
  53073. leftBorder,
  53074. 0,
  53075. width - (leftBorder + rightBorder + 4),
  53076. height,
  53077. Justification::centredRight,
  53078. true);
  53079. }
  53080. if (hasSubMenu)
  53081. {
  53082. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53083. const float x = width - height * 0.6f;
  53084. Path p;
  53085. p.addTriangle (x, halfH - arrowH * 0.5f,
  53086. x, halfH + arrowH * 0.5f,
  53087. x + arrowH * 0.6f, halfH);
  53088. g.fillPath (p);
  53089. }
  53090. }
  53091. }
  53092. int LookAndFeel::getMenuWindowFlags()
  53093. {
  53094. return ComponentPeer::windowHasDropShadow;
  53095. }
  53096. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53097. bool, MenuBarComponent& menuBar)
  53098. {
  53099. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53100. if (menuBar.isEnabled())
  53101. {
  53102. drawShinyButtonShape (g,
  53103. -4.0f, 0.0f,
  53104. width + 8.0f, (float) height,
  53105. 0.0f,
  53106. baseColour,
  53107. 0.4f,
  53108. true, true, true, true);
  53109. }
  53110. else
  53111. {
  53112. g.fillAll (baseColour);
  53113. }
  53114. }
  53115. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53116. {
  53117. return Font (menuBar.getHeight() * 0.7f);
  53118. }
  53119. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53120. {
  53121. return getMenuBarFont (menuBar, itemIndex, itemText)
  53122. .getStringWidth (itemText) + menuBar.getHeight();
  53123. }
  53124. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53125. int width, int height,
  53126. int itemIndex,
  53127. const String& itemText,
  53128. bool isMouseOverItem,
  53129. bool isMenuOpen,
  53130. bool /*isMouseOverBar*/,
  53131. MenuBarComponent& menuBar)
  53132. {
  53133. if (! menuBar.isEnabled())
  53134. {
  53135. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53136. .withMultipliedAlpha (0.5f));
  53137. }
  53138. else if (isMenuOpen || isMouseOverItem)
  53139. {
  53140. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53141. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53142. }
  53143. else
  53144. {
  53145. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53146. }
  53147. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53148. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53149. }
  53150. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53151. TextEditor& textEditor)
  53152. {
  53153. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53154. }
  53155. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53156. {
  53157. if (textEditor.isEnabled())
  53158. {
  53159. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53160. {
  53161. const int border = 2;
  53162. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53163. g.drawRect (0, 0, width, height, border);
  53164. g.setOpacity (1.0f);
  53165. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53166. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53167. }
  53168. else
  53169. {
  53170. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53171. g.drawRect (0, 0, width, height);
  53172. g.setOpacity (1.0f);
  53173. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53174. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53175. }
  53176. }
  53177. }
  53178. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53179. const bool isButtonDown,
  53180. int buttonX, int buttonY,
  53181. int buttonW, int buttonH,
  53182. ComboBox& box)
  53183. {
  53184. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53185. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53186. {
  53187. g.setColour (box.findColour (TextButton::buttonColourId));
  53188. g.drawRect (0, 0, width, height, 2);
  53189. }
  53190. else
  53191. {
  53192. g.setColour (box.findColour (ComboBox::outlineColourId));
  53193. g.drawRect (0, 0, width, height);
  53194. }
  53195. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53196. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  53197. box.hasKeyboardFocus (true),
  53198. false, isButtonDown)
  53199. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53200. drawGlassLozenge (g,
  53201. buttonX + outlineThickness, buttonY + outlineThickness,
  53202. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53203. baseColour, outlineThickness, -1.0f,
  53204. true, true, true, true);
  53205. if (box.isEnabled())
  53206. {
  53207. const float arrowX = 0.3f;
  53208. const float arrowH = 0.2f;
  53209. Path p;
  53210. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53211. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53212. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53213. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53214. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53215. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53216. g.setColour (box.findColour (ComboBox::arrowColourId));
  53217. g.fillPath (p);
  53218. }
  53219. }
  53220. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53221. {
  53222. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53223. }
  53224. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53225. {
  53226. return new Label (String::empty, String::empty);
  53227. }
  53228. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53229. {
  53230. label.setBounds (1, 1,
  53231. box.getWidth() + 3 - box.getHeight(),
  53232. box.getHeight() - 2);
  53233. label.setFont (getComboBoxFont (box));
  53234. }
  53235. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53236. {
  53237. g.fillAll (label.findColour (Label::backgroundColourId));
  53238. if (! label.isBeingEdited())
  53239. {
  53240. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53241. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53242. g.setFont (label.getFont());
  53243. g.drawFittedText (label.getText(),
  53244. label.getHorizontalBorderSize(),
  53245. label.getVerticalBorderSize(),
  53246. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53247. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53248. label.getJustificationType(),
  53249. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53250. label.getMinimumHorizontalScale());
  53251. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53252. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53253. }
  53254. else if (label.isEnabled())
  53255. {
  53256. g.setColour (label.findColour (Label::outlineColourId));
  53257. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53258. }
  53259. }
  53260. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53261. int x, int y,
  53262. int width, int height,
  53263. float /*sliderPos*/,
  53264. float /*minSliderPos*/,
  53265. float /*maxSliderPos*/,
  53266. const Slider::SliderStyle /*style*/,
  53267. Slider& slider)
  53268. {
  53269. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53270. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53271. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53272. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53273. Path indent;
  53274. if (slider.isHorizontal())
  53275. {
  53276. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53277. const float ih = sliderRadius;
  53278. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53279. gradCol2, 0.0f, iy + ih, false));
  53280. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53281. width + sliderRadius, ih,
  53282. 5.0f);
  53283. g.fillPath (indent);
  53284. }
  53285. else
  53286. {
  53287. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53288. const float iw = sliderRadius;
  53289. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53290. gradCol2, ix + iw, 0.0f, false));
  53291. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53292. iw, height + sliderRadius,
  53293. 5.0f);
  53294. g.fillPath (indent);
  53295. }
  53296. g.setColour (Colour (0x4c000000));
  53297. g.strokePath (indent, PathStrokeType (0.5f));
  53298. }
  53299. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53300. int x, int y,
  53301. int width, int height,
  53302. float sliderPos,
  53303. float minSliderPos,
  53304. float maxSliderPos,
  53305. const Slider::SliderStyle style,
  53306. Slider& slider)
  53307. {
  53308. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53309. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  53310. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53311. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53312. slider.isMouseButtonDown() && slider.isEnabled()));
  53313. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53314. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53315. {
  53316. float kx, ky;
  53317. if (style == Slider::LinearVertical)
  53318. {
  53319. kx = x + width * 0.5f;
  53320. ky = sliderPos;
  53321. }
  53322. else
  53323. {
  53324. kx = sliderPos;
  53325. ky = y + height * 0.5f;
  53326. }
  53327. drawGlassSphere (g,
  53328. kx - sliderRadius,
  53329. ky - sliderRadius,
  53330. sliderRadius * 2.0f,
  53331. knobColour, outlineThickness);
  53332. }
  53333. else
  53334. {
  53335. if (style == Slider::ThreeValueVertical)
  53336. {
  53337. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53338. sliderPos - sliderRadius,
  53339. sliderRadius * 2.0f,
  53340. knobColour, outlineThickness);
  53341. }
  53342. else if (style == Slider::ThreeValueHorizontal)
  53343. {
  53344. drawGlassSphere (g,sliderPos - sliderRadius,
  53345. y + height * 0.5f - sliderRadius,
  53346. sliderRadius * 2.0f,
  53347. knobColour, outlineThickness);
  53348. }
  53349. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53350. {
  53351. const float sr = jmin (sliderRadius, width * 0.4f);
  53352. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53353. minSliderPos - sliderRadius,
  53354. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53355. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53356. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53357. }
  53358. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53359. {
  53360. const float sr = jmin (sliderRadius, height * 0.4f);
  53361. drawGlassPointer (g, minSliderPos - sr,
  53362. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53363. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53364. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53365. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53366. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53367. }
  53368. }
  53369. }
  53370. void LookAndFeel::drawLinearSlider (Graphics& g,
  53371. int x, int y,
  53372. int width, int height,
  53373. float sliderPos,
  53374. float minSliderPos,
  53375. float maxSliderPos,
  53376. const Slider::SliderStyle style,
  53377. Slider& slider)
  53378. {
  53379. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53380. if (style == Slider::LinearBar)
  53381. {
  53382. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53383. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  53384. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53385. false,
  53386. isMouseOver,
  53387. isMouseOver || slider.isMouseButtonDown()));
  53388. drawShinyButtonShape (g,
  53389. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53390. baseColour,
  53391. slider.isEnabled() ? 0.9f : 0.3f,
  53392. true, true, true, true);
  53393. }
  53394. else
  53395. {
  53396. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53397. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53398. }
  53399. }
  53400. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53401. {
  53402. return jmin (7,
  53403. slider.getHeight() / 2,
  53404. slider.getWidth() / 2) + 2;
  53405. }
  53406. void LookAndFeel::drawRotarySlider (Graphics& g,
  53407. int x, int y,
  53408. int width, int height,
  53409. float sliderPos,
  53410. const float rotaryStartAngle,
  53411. const float rotaryEndAngle,
  53412. Slider& slider)
  53413. {
  53414. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53415. const float centreX = x + width * 0.5f;
  53416. const float centreY = y + height * 0.5f;
  53417. const float rx = centreX - radius;
  53418. const float ry = centreY - radius;
  53419. const float rw = radius * 2.0f;
  53420. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53421. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53422. if (radius > 12.0f)
  53423. {
  53424. if (slider.isEnabled())
  53425. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53426. else
  53427. g.setColour (Colour (0x80808080));
  53428. const float thickness = 0.7f;
  53429. {
  53430. Path filledArc;
  53431. filledArc.addPieSegment (rx, ry, rw, rw,
  53432. rotaryStartAngle,
  53433. angle,
  53434. thickness);
  53435. g.fillPath (filledArc);
  53436. }
  53437. if (thickness > 0)
  53438. {
  53439. const float innerRadius = radius * 0.2f;
  53440. Path p;
  53441. p.addTriangle (-innerRadius, 0.0f,
  53442. 0.0f, -radius * thickness * 1.1f,
  53443. innerRadius, 0.0f);
  53444. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53445. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53446. }
  53447. if (slider.isEnabled())
  53448. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53449. else
  53450. g.setColour (Colour (0x80808080));
  53451. Path outlineArc;
  53452. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53453. outlineArc.closeSubPath();
  53454. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53455. }
  53456. else
  53457. {
  53458. if (slider.isEnabled())
  53459. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53460. else
  53461. g.setColour (Colour (0x80808080));
  53462. Path p;
  53463. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53464. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53465. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53466. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53467. }
  53468. }
  53469. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53470. {
  53471. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53472. }
  53473. class SliderLabelComp : public Label
  53474. {
  53475. public:
  53476. SliderLabelComp() : Label (String::empty, String::empty) {}
  53477. ~SliderLabelComp() {}
  53478. void mouseWheelMove (const MouseEvent&, float, float) {}
  53479. };
  53480. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53481. {
  53482. Label* const l = new SliderLabelComp();
  53483. l->setJustificationType (Justification::centred);
  53484. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53485. l->setColour (Label::backgroundColourId,
  53486. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53487. : slider.findColour (Slider::textBoxBackgroundColourId));
  53488. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53489. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53490. l->setColour (TextEditor::backgroundColourId,
  53491. slider.findColour (Slider::textBoxBackgroundColourId)
  53492. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53493. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53494. return l;
  53495. }
  53496. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53497. {
  53498. return 0;
  53499. }
  53500. static const TextLayout layoutTooltipText (const String& text) throw()
  53501. {
  53502. const float tooltipFontSize = 12.0f;
  53503. const int maxToolTipWidth = 400;
  53504. const Font f (tooltipFontSize, Font::bold);
  53505. TextLayout tl (text, f);
  53506. tl.layout (maxToolTipWidth, Justification::left, true);
  53507. return tl;
  53508. }
  53509. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53510. {
  53511. const TextLayout tl (layoutTooltipText (tipText));
  53512. width = tl.getWidth() + 14;
  53513. height = tl.getHeight() + 6;
  53514. }
  53515. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53516. {
  53517. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53518. const Colour textCol (findColour (TooltipWindow::textColourId));
  53519. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53520. g.setColour (findColour (TooltipWindow::outlineColourId));
  53521. g.drawRect (0, 0, width, height, 1);
  53522. #endif
  53523. const TextLayout tl (layoutTooltipText (text));
  53524. g.setColour (findColour (TooltipWindow::textColourId));
  53525. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53526. }
  53527. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53528. {
  53529. return new TextButton (text, TRANS("click to browse for a different file"));
  53530. }
  53531. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53532. ComboBox* filenameBox,
  53533. Button* browseButton)
  53534. {
  53535. browseButton->setSize (80, filenameComp.getHeight());
  53536. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53537. if (tb != 0)
  53538. tb->changeWidthToFitText();
  53539. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53540. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53541. }
  53542. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53543. int imageX, int imageY, int imageW, int imageH,
  53544. const Colour& overlayColour,
  53545. float imageOpacity,
  53546. ImageButton& button)
  53547. {
  53548. if (! button.isEnabled())
  53549. imageOpacity *= 0.3f;
  53550. if (! overlayColour.isOpaque())
  53551. {
  53552. g.setOpacity (imageOpacity);
  53553. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53554. 0, 0, image->getWidth(), image->getHeight(), false);
  53555. }
  53556. if (! overlayColour.isTransparent())
  53557. {
  53558. g.setColour (overlayColour);
  53559. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53560. 0, 0, image->getWidth(), image->getHeight(), true);
  53561. }
  53562. }
  53563. void LookAndFeel::drawCornerResizer (Graphics& g,
  53564. int w, int h,
  53565. bool /*isMouseOver*/,
  53566. bool /*isMouseDragging*/)
  53567. {
  53568. const float lineThickness = jmin (w, h) * 0.075f;
  53569. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53570. {
  53571. g.setColour (Colours::lightgrey);
  53572. g.drawLine (w * i,
  53573. h + 1.0f,
  53574. w + 1.0f,
  53575. h * i,
  53576. lineThickness);
  53577. g.setColour (Colours::darkgrey);
  53578. g.drawLine (w * i + lineThickness,
  53579. h + 1.0f,
  53580. w + 1.0f,
  53581. h * i + lineThickness,
  53582. lineThickness);
  53583. }
  53584. }
  53585. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  53586. const BorderSize& /*borders*/)
  53587. {
  53588. }
  53589. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53590. const BorderSize& /*border*/, ResizableWindow& window)
  53591. {
  53592. g.fillAll (window.getBackgroundColour());
  53593. }
  53594. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  53595. const BorderSize& border, ResizableWindow&)
  53596. {
  53597. g.setColour (Colour (0x80000000));
  53598. g.drawRect (0, 0, w, h);
  53599. g.setColour (Colour (0x19000000));
  53600. g.drawRect (border.getLeft() - 1,
  53601. border.getTop() - 1,
  53602. w + 2 - border.getLeftAndRight(),
  53603. h + 2 - border.getTopAndBottom());
  53604. }
  53605. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53606. Graphics& g, int w, int h,
  53607. int titleSpaceX, int titleSpaceW,
  53608. const Image* icon,
  53609. bool drawTitleTextOnLeft)
  53610. {
  53611. const bool isActive = window.isActiveWindow();
  53612. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53613. 0.0f, 0.0f,
  53614. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53615. 0.0f, (float) h, false));
  53616. g.fillAll();
  53617. Font font (h * 0.65f, Font::bold);
  53618. g.setFont (font);
  53619. int textW = font.getStringWidth (window.getName());
  53620. int iconW = 0;
  53621. int iconH = 0;
  53622. if (icon != 0)
  53623. {
  53624. iconH = (int) font.getHeight();
  53625. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53626. }
  53627. textW = jmin (titleSpaceW, textW + iconW);
  53628. int textX = drawTitleTextOnLeft ? titleSpaceX
  53629. : jmax (titleSpaceX, (w - textW) / 2);
  53630. if (textX + textW > titleSpaceX + titleSpaceW)
  53631. textX = titleSpaceX + titleSpaceW - textW;
  53632. if (icon != 0)
  53633. {
  53634. g.setOpacity (isActive ? 1.0f : 0.6f);
  53635. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53636. RectanglePlacement::centred, false);
  53637. textX += iconW;
  53638. textW -= iconW;
  53639. }
  53640. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53641. g.setColour (findColour (DocumentWindow::textColourId));
  53642. else
  53643. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53644. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53645. }
  53646. class GlassWindowButton : public Button
  53647. {
  53648. public:
  53649. GlassWindowButton (const String& name, const Colour& col,
  53650. const Path& normalShape_,
  53651. const Path& toggledShape_) throw()
  53652. : Button (name),
  53653. colour (col),
  53654. normalShape (normalShape_),
  53655. toggledShape (toggledShape_)
  53656. {
  53657. }
  53658. ~GlassWindowButton()
  53659. {
  53660. }
  53661. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53662. {
  53663. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53664. if (! isEnabled())
  53665. alpha *= 0.5f;
  53666. float x = 0, y = 0, diam;
  53667. if (getWidth() < getHeight())
  53668. {
  53669. diam = (float) getWidth();
  53670. y = (getHeight() - getWidth()) * 0.5f;
  53671. }
  53672. else
  53673. {
  53674. diam = (float) getHeight();
  53675. y = (getWidth() - getHeight()) * 0.5f;
  53676. }
  53677. x += diam * 0.05f;
  53678. y += diam * 0.05f;
  53679. diam *= 0.9f;
  53680. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53681. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53682. g.fillEllipse (x, y, diam, diam);
  53683. x += 2.0f;
  53684. y += 2.0f;
  53685. diam -= 4.0f;
  53686. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53687. Path& p = getToggleState() ? toggledShape : normalShape;
  53688. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53689. diam * 0.4f, diam * 0.4f, true));
  53690. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53691. g.fillPath (p, t);
  53692. }
  53693. juce_UseDebuggingNewOperator
  53694. private:
  53695. Colour colour;
  53696. Path normalShape, toggledShape;
  53697. GlassWindowButton (const GlassWindowButton&);
  53698. GlassWindowButton& operator= (const GlassWindowButton&);
  53699. };
  53700. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53701. {
  53702. Path shape;
  53703. const float crossThickness = 0.25f;
  53704. if (buttonType == DocumentWindow::closeButton)
  53705. {
  53706. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53707. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53708. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53709. }
  53710. else if (buttonType == DocumentWindow::minimiseButton)
  53711. {
  53712. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53713. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53714. }
  53715. else if (buttonType == DocumentWindow::maximiseButton)
  53716. {
  53717. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53718. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53719. Path fullscreenShape;
  53720. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53721. fullscreenShape.lineTo (0.0f, 100.0f);
  53722. fullscreenShape.lineTo (0.0f, 0.0f);
  53723. fullscreenShape.lineTo (100.0f, 0.0f);
  53724. fullscreenShape.lineTo (100.0f, 45.0f);
  53725. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53726. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53727. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53728. }
  53729. jassertfalse;
  53730. return 0;
  53731. }
  53732. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53733. int titleBarX,
  53734. int titleBarY,
  53735. int titleBarW,
  53736. int titleBarH,
  53737. Button* minimiseButton,
  53738. Button* maximiseButton,
  53739. Button* closeButton,
  53740. bool positionTitleBarButtonsOnLeft)
  53741. {
  53742. const int buttonW = titleBarH - titleBarH / 8;
  53743. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53744. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53745. if (closeButton != 0)
  53746. {
  53747. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53748. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53749. }
  53750. if (positionTitleBarButtonsOnLeft)
  53751. swapVariables (minimiseButton, maximiseButton);
  53752. if (maximiseButton != 0)
  53753. {
  53754. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53755. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53756. }
  53757. if (minimiseButton != 0)
  53758. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53759. }
  53760. int LookAndFeel::getDefaultMenuBarHeight()
  53761. {
  53762. return 24;
  53763. }
  53764. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53765. {
  53766. return new DropShadower (0.4f, 1, 5, 10);
  53767. }
  53768. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53769. int w, int h,
  53770. bool /*isVerticalBar*/,
  53771. bool isMouseOver,
  53772. bool isMouseDragging)
  53773. {
  53774. float alpha = 0.5f;
  53775. if (isMouseOver || isMouseDragging)
  53776. {
  53777. g.fillAll (Colour (0x190000ff));
  53778. alpha = 1.0f;
  53779. }
  53780. const float cx = w * 0.5f;
  53781. const float cy = h * 0.5f;
  53782. const float cr = jmin (w, h) * 0.4f;
  53783. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53784. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53785. true));
  53786. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53787. }
  53788. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53789. const String& text,
  53790. const Justification& position,
  53791. GroupComponent& group)
  53792. {
  53793. const float textH = 15.0f;
  53794. const float indent = 3.0f;
  53795. const float textEdgeGap = 4.0f;
  53796. float cs = 5.0f;
  53797. Font f (textH);
  53798. Path p;
  53799. float x = indent;
  53800. float y = f.getAscent() - 3.0f;
  53801. float w = jmax (0.0f, width - x * 2.0f);
  53802. float h = jmax (0.0f, height - y - indent);
  53803. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53804. const float cs2 = 2.0f * cs;
  53805. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53806. float textX = cs + textEdgeGap;
  53807. if (position.testFlags (Justification::horizontallyCentred))
  53808. textX = cs + (w - cs2 - textW) * 0.5f;
  53809. else if (position.testFlags (Justification::right))
  53810. textX = w - cs - textW - textEdgeGap;
  53811. p.startNewSubPath (x + textX + textW, y);
  53812. p.lineTo (x + w - cs, y);
  53813. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53814. p.lineTo (x + w, y + h - cs);
  53815. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53816. p.lineTo (x + cs, y + h);
  53817. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53818. p.lineTo (x, y + cs);
  53819. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53820. p.lineTo (x + textX, y);
  53821. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53822. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53823. .withMultipliedAlpha (alpha));
  53824. g.strokePath (p, PathStrokeType (2.0f));
  53825. g.setColour (group.findColour (GroupComponent::textColourId)
  53826. .withMultipliedAlpha (alpha));
  53827. g.setFont (f);
  53828. g.drawText (text,
  53829. roundToInt (x + textX), 0,
  53830. roundToInt (textW),
  53831. roundToInt (textH),
  53832. Justification::centred, true);
  53833. }
  53834. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53835. {
  53836. return 1 + tabDepth / 3;
  53837. }
  53838. int LookAndFeel::getTabButtonSpaceAroundImage()
  53839. {
  53840. return 4;
  53841. }
  53842. void LookAndFeel::createTabButtonShape (Path& p,
  53843. int width, int height,
  53844. int /*tabIndex*/,
  53845. const String& /*text*/,
  53846. Button& /*button*/,
  53847. TabbedButtonBar::Orientation orientation,
  53848. const bool /*isMouseOver*/,
  53849. const bool /*isMouseDown*/,
  53850. const bool /*isFrontTab*/)
  53851. {
  53852. const float w = (float) width;
  53853. const float h = (float) height;
  53854. float length = w;
  53855. float depth = h;
  53856. if (orientation == TabbedButtonBar::TabsAtLeft
  53857. || orientation == TabbedButtonBar::TabsAtRight)
  53858. {
  53859. swapVariables (length, depth);
  53860. }
  53861. const float indent = (float) getTabButtonOverlap ((int) depth);
  53862. const float overhang = 4.0f;
  53863. if (orientation == TabbedButtonBar::TabsAtLeft)
  53864. {
  53865. p.startNewSubPath (w, 0.0f);
  53866. p.lineTo (0.0f, indent);
  53867. p.lineTo (0.0f, h - indent);
  53868. p.lineTo (w, h);
  53869. p.lineTo (w + overhang, h + overhang);
  53870. p.lineTo (w + overhang, -overhang);
  53871. }
  53872. else if (orientation == TabbedButtonBar::TabsAtRight)
  53873. {
  53874. p.startNewSubPath (0.0f, 0.0f);
  53875. p.lineTo (w, indent);
  53876. p.lineTo (w, h - indent);
  53877. p.lineTo (0.0f, h);
  53878. p.lineTo (-overhang, h + overhang);
  53879. p.lineTo (-overhang, -overhang);
  53880. }
  53881. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53882. {
  53883. p.startNewSubPath (0.0f, 0.0f);
  53884. p.lineTo (indent, h);
  53885. p.lineTo (w - indent, h);
  53886. p.lineTo (w, 0.0f);
  53887. p.lineTo (w + overhang, -overhang);
  53888. p.lineTo (-overhang, -overhang);
  53889. }
  53890. else
  53891. {
  53892. p.startNewSubPath (0.0f, h);
  53893. p.lineTo (indent, 0.0f);
  53894. p.lineTo (w - indent, 0.0f);
  53895. p.lineTo (w, h);
  53896. p.lineTo (w + overhang, h + overhang);
  53897. p.lineTo (-overhang, h + overhang);
  53898. }
  53899. p.closeSubPath();
  53900. p = p.createPathWithRoundedCorners (3.0f);
  53901. }
  53902. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53903. const Path& path,
  53904. const Colour& preferredColour,
  53905. int /*tabIndex*/,
  53906. const String& /*text*/,
  53907. Button& button,
  53908. TabbedButtonBar::Orientation /*orientation*/,
  53909. const bool /*isMouseOver*/,
  53910. const bool /*isMouseDown*/,
  53911. const bool isFrontTab)
  53912. {
  53913. g.setColour (isFrontTab ? preferredColour
  53914. : preferredColour.withMultipliedAlpha (0.9f));
  53915. g.fillPath (path);
  53916. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53917. : TabbedButtonBar::tabOutlineColourId, false)
  53918. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53919. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53920. }
  53921. void LookAndFeel::drawTabButtonText (Graphics& g,
  53922. int x, int y, int w, int h,
  53923. const Colour& preferredBackgroundColour,
  53924. int /*tabIndex*/,
  53925. const String& text,
  53926. Button& button,
  53927. TabbedButtonBar::Orientation orientation,
  53928. const bool isMouseOver,
  53929. const bool isMouseDown,
  53930. const bool isFrontTab)
  53931. {
  53932. int length = w;
  53933. int depth = h;
  53934. if (orientation == TabbedButtonBar::TabsAtLeft
  53935. || orientation == TabbedButtonBar::TabsAtRight)
  53936. {
  53937. swapVariables (length, depth);
  53938. }
  53939. Font font (depth * 0.6f);
  53940. font.setUnderline (button.hasKeyboardFocus (false));
  53941. GlyphArrangement textLayout;
  53942. textLayout.addFittedText (font, text.trim(),
  53943. 0.0f, 0.0f, (float) length, (float) depth,
  53944. Justification::centred,
  53945. jmax (1, depth / 12));
  53946. AffineTransform transform;
  53947. if (orientation == TabbedButtonBar::TabsAtLeft)
  53948. {
  53949. transform = transform.rotated (float_Pi * -0.5f)
  53950. .translated ((float) x, (float) (y + h));
  53951. }
  53952. else if (orientation == TabbedButtonBar::TabsAtRight)
  53953. {
  53954. transform = transform.rotated (float_Pi * 0.5f)
  53955. .translated ((float) (x + w), (float) y);
  53956. }
  53957. else
  53958. {
  53959. transform = transform.translated ((float) x, (float) y);
  53960. }
  53961. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53962. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53963. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53964. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53965. else
  53966. g.setColour (preferredBackgroundColour.contrasting());
  53967. if (! (isMouseOver || isMouseDown))
  53968. g.setOpacity (0.8f);
  53969. if (! button.isEnabled())
  53970. g.setOpacity (0.3f);
  53971. textLayout.draw (g, transform);
  53972. }
  53973. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53974. const String& text,
  53975. int tabDepth,
  53976. Button&)
  53977. {
  53978. Font f (tabDepth * 0.6f);
  53979. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53980. }
  53981. void LookAndFeel::drawTabButton (Graphics& g,
  53982. int w, int h,
  53983. const Colour& preferredColour,
  53984. int tabIndex,
  53985. const String& text,
  53986. Button& button,
  53987. TabbedButtonBar::Orientation orientation,
  53988. const bool isMouseOver,
  53989. const bool isMouseDown,
  53990. const bool isFrontTab)
  53991. {
  53992. int length = w;
  53993. int depth = h;
  53994. if (orientation == TabbedButtonBar::TabsAtLeft
  53995. || orientation == TabbedButtonBar::TabsAtRight)
  53996. {
  53997. swapVariables (length, depth);
  53998. }
  53999. Path tabShape;
  54000. createTabButtonShape (tabShape, w, h,
  54001. tabIndex, text, button, orientation,
  54002. isMouseOver, isMouseDown, isFrontTab);
  54003. fillTabButtonShape (g, tabShape, preferredColour,
  54004. tabIndex, text, button, orientation,
  54005. isMouseOver, isMouseDown, isFrontTab);
  54006. const int indent = getTabButtonOverlap (depth);
  54007. int x = 0, y = 0;
  54008. if (orientation == TabbedButtonBar::TabsAtLeft
  54009. || orientation == TabbedButtonBar::TabsAtRight)
  54010. {
  54011. y += indent;
  54012. h -= indent * 2;
  54013. }
  54014. else
  54015. {
  54016. x += indent;
  54017. w -= indent * 2;
  54018. }
  54019. drawTabButtonText (g, x, y, w, h, preferredColour,
  54020. tabIndex, text, button, orientation,
  54021. isMouseOver, isMouseDown, isFrontTab);
  54022. }
  54023. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54024. int w, int h,
  54025. TabbedButtonBar& tabBar,
  54026. TabbedButtonBar::Orientation orientation)
  54027. {
  54028. const float shadowSize = 0.2f;
  54029. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54030. Rectangle<int> shadowRect;
  54031. if (orientation == TabbedButtonBar::TabsAtLeft)
  54032. {
  54033. x1 = (float) w;
  54034. x2 = w * (1.0f - shadowSize);
  54035. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54036. }
  54037. else if (orientation == TabbedButtonBar::TabsAtRight)
  54038. {
  54039. x2 = w * shadowSize;
  54040. shadowRect.setBounds (0, 0, (int) x2, h);
  54041. }
  54042. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54043. {
  54044. y2 = h * shadowSize;
  54045. shadowRect.setBounds (0, 0, w, (int) y2);
  54046. }
  54047. else
  54048. {
  54049. y1 = (float) h;
  54050. y2 = h * (1.0f - shadowSize);
  54051. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54052. }
  54053. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54054. Colours::transparentBlack, x2, y2, false));
  54055. shadowRect.expand (2, 2);
  54056. g.fillRect (shadowRect);
  54057. g.setColour (Colour (0x80000000));
  54058. if (orientation == TabbedButtonBar::TabsAtLeft)
  54059. {
  54060. g.fillRect (w - 1, 0, 1, h);
  54061. }
  54062. else if (orientation == TabbedButtonBar::TabsAtRight)
  54063. {
  54064. g.fillRect (0, 0, 1, h);
  54065. }
  54066. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54067. {
  54068. g.fillRect (0, 0, w, 1);
  54069. }
  54070. else
  54071. {
  54072. g.fillRect (0, h - 1, w, 1);
  54073. }
  54074. }
  54075. Button* LookAndFeel::createTabBarExtrasButton()
  54076. {
  54077. const float thickness = 7.0f;
  54078. const float indent = 22.0f;
  54079. Path p;
  54080. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54081. DrawablePath ellipse;
  54082. ellipse.setPath (p);
  54083. ellipse.setFill (Colour (0x99ffffff));
  54084. p.clear();
  54085. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54086. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54087. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54088. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54089. p.setUsingNonZeroWinding (false);
  54090. DrawablePath dp;
  54091. dp.setPath (p);
  54092. dp.setFill (Colour (0x59000000));
  54093. DrawableComposite normalImage;
  54094. normalImage.insertDrawable (ellipse);
  54095. normalImage.insertDrawable (dp);
  54096. dp.setFill (Colour (0xcc000000));
  54097. DrawableComposite overImage;
  54098. overImage.insertDrawable (ellipse);
  54099. overImage.insertDrawable (dp);
  54100. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54101. db->setImages (&normalImage, &overImage, 0);
  54102. return db;
  54103. }
  54104. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54105. {
  54106. g.fillAll (Colours::white);
  54107. const int w = header.getWidth();
  54108. const int h = header.getHeight();
  54109. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54110. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54111. false));
  54112. g.fillRect (0, h / 2, w, h);
  54113. g.setColour (Colour (0x33000000));
  54114. g.fillRect (0, h - 1, w, 1);
  54115. for (int i = header.getNumColumns (true); --i >= 0;)
  54116. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54117. }
  54118. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54119. int width, int height,
  54120. bool isMouseOver, bool isMouseDown,
  54121. int columnFlags)
  54122. {
  54123. if (isMouseDown)
  54124. g.fillAll (Colour (0x8899aadd));
  54125. else if (isMouseOver)
  54126. g.fillAll (Colour (0x5599aadd));
  54127. int rightOfText = width - 4;
  54128. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54129. {
  54130. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54131. const float bottom = height - top;
  54132. const float w = height * 0.5f;
  54133. const float x = rightOfText - (w * 1.25f);
  54134. rightOfText = (int) x;
  54135. Path sortArrow;
  54136. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54137. g.setColour (Colour (0x99000000));
  54138. g.fillPath (sortArrow);
  54139. }
  54140. g.setColour (Colours::black);
  54141. g.setFont (height * 0.5f, Font::bold);
  54142. const int textX = 4;
  54143. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54144. }
  54145. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54146. {
  54147. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54148. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54149. background.darker (0.1f),
  54150. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54151. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54152. false));
  54153. g.fillAll();
  54154. }
  54155. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54156. {
  54157. return createTabBarExtrasButton();
  54158. }
  54159. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54160. bool isMouseOver, bool isMouseDown,
  54161. ToolbarItemComponent& component)
  54162. {
  54163. if (isMouseDown)
  54164. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54165. else if (isMouseOver)
  54166. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54167. }
  54168. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54169. const String& text, ToolbarItemComponent& component)
  54170. {
  54171. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54172. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54173. const float fontHeight = jmin (14.0f, height * 0.85f);
  54174. g.setFont (fontHeight);
  54175. g.drawFittedText (text,
  54176. x, y, width, height,
  54177. Justification::centred,
  54178. jmax (1, height / (int) fontHeight));
  54179. }
  54180. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54181. bool isOpen, int width, int height)
  54182. {
  54183. const int buttonSize = (height * 3) / 4;
  54184. const int buttonIndent = (height - buttonSize) / 2;
  54185. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54186. const int textX = buttonIndent * 2 + buttonSize + 2;
  54187. g.setColour (Colours::black);
  54188. g.setFont (height * 0.7f, Font::bold);
  54189. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54190. }
  54191. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54192. PropertyComponent&)
  54193. {
  54194. g.setColour (Colour (0x66ffffff));
  54195. g.fillRect (0, 0, width, height - 1);
  54196. }
  54197. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54198. PropertyComponent& component)
  54199. {
  54200. g.setColour (Colours::black);
  54201. if (! component.isEnabled())
  54202. g.setOpacity (0.6f);
  54203. g.setFont (jmin (height, 24) * 0.65f);
  54204. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54205. g.drawFittedText (component.getName(),
  54206. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54207. Justification::centredLeft, 2);
  54208. }
  54209. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54210. {
  54211. return Rectangle<int> (component.getWidth() / 3, 1,
  54212. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54213. }
  54214. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54215. {
  54216. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54217. {
  54218. Graphics g2 (content);
  54219. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54220. g2.fillPath (path);
  54221. g2.setColour (Colours::white.withAlpha (0.8f));
  54222. g2.strokePath (path, PathStrokeType (2.0f));
  54223. }
  54224. DropShadowEffect shadow;
  54225. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54226. shadow.applyEffect (content, g);
  54227. }
  54228. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54229. const String& instructions,
  54230. GlyphArrangement& text,
  54231. int width)
  54232. {
  54233. text.clear();
  54234. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54235. 8.0f, 22.0f, width - 16.0f,
  54236. Justification::centred);
  54237. text.addJustifiedText (Font (14.0f), instructions,
  54238. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54239. Justification::centred);
  54240. }
  54241. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54242. const String& filename, Image* icon,
  54243. const String& fileSizeDescription,
  54244. const String& fileTimeDescription,
  54245. const bool isDirectory,
  54246. const bool isItemSelected,
  54247. const int /*itemIndex*/)
  54248. {
  54249. if (isItemSelected)
  54250. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54251. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54252. g.setFont (height * 0.7f);
  54253. Image im;
  54254. if (icon != 0)
  54255. im = *icon;
  54256. if (im.isNull())
  54257. im = isDirectory ? getDefaultFolderImage()
  54258. : getDefaultDocumentFileImage();
  54259. const int x = 32;
  54260. if (im.isValid())
  54261. {
  54262. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  54263. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54264. false);
  54265. }
  54266. if (width > 450 && ! isDirectory)
  54267. {
  54268. const int sizeX = roundToInt (width * 0.7f);
  54269. const int dateX = roundToInt (width * 0.8f);
  54270. g.drawFittedText (filename,
  54271. x, 0, sizeX - x, height,
  54272. Justification::centredLeft, 1);
  54273. g.setFont (height * 0.5f);
  54274. g.setColour (Colours::darkgrey);
  54275. if (! isDirectory)
  54276. {
  54277. g.drawFittedText (fileSizeDescription,
  54278. sizeX, 0, dateX - sizeX - 8, height,
  54279. Justification::centredRight, 1);
  54280. g.drawFittedText (fileTimeDescription,
  54281. dateX, 0, width - 8 - dateX, height,
  54282. Justification::centredRight, 1);
  54283. }
  54284. }
  54285. else
  54286. {
  54287. g.drawFittedText (filename,
  54288. x, 0, width - x, height,
  54289. Justification::centredLeft, 1);
  54290. }
  54291. }
  54292. Button* LookAndFeel::createFileBrowserGoUpButton()
  54293. {
  54294. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54295. Path arrowPath;
  54296. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54297. DrawablePath arrowImage;
  54298. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54299. arrowImage.setPath (arrowPath);
  54300. goUpButton->setImages (&arrowImage);
  54301. return goUpButton;
  54302. }
  54303. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54304. DirectoryContentsDisplayComponent* fileListComponent,
  54305. FilePreviewComponent* previewComp,
  54306. ComboBox* currentPathBox,
  54307. TextEditor* filenameBox,
  54308. Button* goUpButton)
  54309. {
  54310. const int x = 8;
  54311. int w = browserComp.getWidth() - x - x;
  54312. if (previewComp != 0)
  54313. {
  54314. const int previewWidth = w / 3;
  54315. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54316. w -= previewWidth + 4;
  54317. }
  54318. int y = 4;
  54319. const int controlsHeight = 22;
  54320. const int bottomSectionHeight = controlsHeight + 8;
  54321. const int upButtonWidth = 50;
  54322. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54323. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54324. y += controlsHeight + 4;
  54325. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54326. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54327. y = listAsComp->getBottom() + 4;
  54328. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54329. }
  54330. const Image LookAndFeel::getDefaultFolderImage()
  54331. {
  54332. 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,
  54333. 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,
  54334. 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,
  54335. 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,
  54336. 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,
  54337. 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,
  54338. 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,
  54339. 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,
  54340. 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,
  54341. 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,
  54342. 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,
  54343. 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,
  54344. 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,
  54345. 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,
  54346. 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,
  54347. 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,
  54348. 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,
  54349. 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,
  54350. 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,
  54351. 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,
  54352. 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,
  54353. 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,
  54354. 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,
  54355. 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,
  54356. 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,
  54357. 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,
  54358. 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,
  54359. 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,
  54360. 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,
  54361. 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,
  54362. 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,
  54363. 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,
  54364. 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,
  54365. 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,
  54366. 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,
  54367. 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,
  54368. 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,
  54369. 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,
  54370. 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,
  54371. 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,
  54372. 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,
  54373. 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,
  54374. 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,
  54375. 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};
  54376. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  54377. }
  54378. const Image LookAndFeel::getDefaultDocumentFileImage()
  54379. {
  54380. 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,
  54381. 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,
  54382. 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,
  54383. 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,
  54384. 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,
  54385. 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,
  54386. 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,
  54387. 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,
  54388. 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,
  54389. 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,
  54390. 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,
  54391. 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,
  54392. 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,
  54393. 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,
  54394. 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,
  54395. 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,
  54396. 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,
  54397. 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,
  54398. 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,
  54399. 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,
  54400. 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,
  54401. 174,66,96,130,0,0};
  54402. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  54403. }
  54404. void LookAndFeel::playAlertSound()
  54405. {
  54406. PlatformUtilities::beep();
  54407. }
  54408. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54409. {
  54410. g.setColour (Colours::white.withAlpha (0.7f));
  54411. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54412. g.setColour (Colours::black.withAlpha (0.2f));
  54413. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54414. const int totalBlocks = 7;
  54415. const int numBlocks = roundToInt (totalBlocks * level);
  54416. const float w = (width - 6.0f) / (float) totalBlocks;
  54417. for (int i = 0; i < totalBlocks; ++i)
  54418. {
  54419. if (i >= numBlocks)
  54420. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54421. else
  54422. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54423. : Colours::red);
  54424. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54425. }
  54426. }
  54427. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54428. {
  54429. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54430. if (keyDescription.isNotEmpty())
  54431. {
  54432. if (button.isEnabled())
  54433. {
  54434. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54435. g.fillAll (textColour.withAlpha (alpha));
  54436. g.setOpacity (0.3f);
  54437. g.drawBevel (0, 0, width, height, 2);
  54438. }
  54439. g.setColour (textColour);
  54440. g.setFont (height * 0.6f);
  54441. g.drawFittedText (keyDescription,
  54442. 3, 0, width - 6, height,
  54443. Justification::centred, 1);
  54444. }
  54445. else
  54446. {
  54447. const float thickness = 7.0f;
  54448. const float indent = 22.0f;
  54449. Path p;
  54450. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54451. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54452. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54453. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54454. p.setUsingNonZeroWinding (false);
  54455. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54456. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54457. }
  54458. if (button.hasKeyboardFocus (false))
  54459. {
  54460. g.setColour (textColour.withAlpha (0.4f));
  54461. g.drawRect (0, 0, width, height);
  54462. }
  54463. }
  54464. static void createRoundedPath (Path& p,
  54465. const float x, const float y,
  54466. const float w, const float h,
  54467. const float cs,
  54468. const bool curveTopLeft, const bool curveTopRight,
  54469. const bool curveBottomLeft, const bool curveBottomRight) throw()
  54470. {
  54471. const float cs2 = 2.0f * cs;
  54472. if (curveTopLeft)
  54473. {
  54474. p.startNewSubPath (x, y + cs);
  54475. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54476. }
  54477. else
  54478. {
  54479. p.startNewSubPath (x, y);
  54480. }
  54481. if (curveTopRight)
  54482. {
  54483. p.lineTo (x + w - cs, y);
  54484. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  54485. }
  54486. else
  54487. {
  54488. p.lineTo (x + w, y);
  54489. }
  54490. if (curveBottomRight)
  54491. {
  54492. p.lineTo (x + w, y + h - cs);
  54493. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54494. }
  54495. else
  54496. {
  54497. p.lineTo (x + w, y + h);
  54498. }
  54499. if (curveBottomLeft)
  54500. {
  54501. p.lineTo (x + cs, y + h);
  54502. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54503. }
  54504. else
  54505. {
  54506. p.lineTo (x, y + h);
  54507. }
  54508. p.closeSubPath();
  54509. }
  54510. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54511. float x, float y, float w, float h,
  54512. float maxCornerSize,
  54513. const Colour& baseColour,
  54514. const float strokeWidth,
  54515. const bool flatOnLeft,
  54516. const bool flatOnRight,
  54517. const bool flatOnTop,
  54518. const bool flatOnBottom) throw()
  54519. {
  54520. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54521. return;
  54522. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54523. Path outline;
  54524. createRoundedPath (outline, x, y, w, h, cs,
  54525. ! (flatOnLeft || flatOnTop),
  54526. ! (flatOnRight || flatOnTop),
  54527. ! (flatOnLeft || flatOnBottom),
  54528. ! (flatOnRight || flatOnBottom));
  54529. ColourGradient cg (baseColour, 0.0f, y,
  54530. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54531. false);
  54532. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54533. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54534. g.setGradientFill (cg);
  54535. g.fillPath (outline);
  54536. g.setColour (Colour (0x80000000));
  54537. g.strokePath (outline, PathStrokeType (strokeWidth));
  54538. }
  54539. void LookAndFeel::drawGlassSphere (Graphics& g,
  54540. const float x, const float y,
  54541. const float diameter,
  54542. const Colour& colour,
  54543. const float outlineThickness) throw()
  54544. {
  54545. if (diameter <= outlineThickness)
  54546. return;
  54547. Path p;
  54548. p.addEllipse (x, y, diameter, diameter);
  54549. {
  54550. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54551. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54552. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54553. g.setGradientFill (cg);
  54554. g.fillPath (p);
  54555. }
  54556. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54557. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54558. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54559. ColourGradient cg (Colours::transparentBlack,
  54560. x + diameter * 0.5f, y + diameter * 0.5f,
  54561. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54562. x, y + diameter * 0.5f, true);
  54563. cg.addColour (0.7, Colours::transparentBlack);
  54564. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54565. g.setGradientFill (cg);
  54566. g.fillPath (p);
  54567. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54568. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54569. }
  54570. void LookAndFeel::drawGlassPointer (Graphics& g,
  54571. const float x, const float y,
  54572. const float diameter,
  54573. const Colour& colour, const float outlineThickness,
  54574. const int direction) throw()
  54575. {
  54576. if (diameter <= outlineThickness)
  54577. return;
  54578. Path p;
  54579. p.startNewSubPath (x + diameter * 0.5f, y);
  54580. p.lineTo (x + diameter, y + diameter * 0.6f);
  54581. p.lineTo (x + diameter, y + diameter);
  54582. p.lineTo (x, y + diameter);
  54583. p.lineTo (x, y + diameter * 0.6f);
  54584. p.closeSubPath();
  54585. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54586. {
  54587. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54588. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54589. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54590. g.setGradientFill (cg);
  54591. g.fillPath (p);
  54592. }
  54593. ColourGradient cg (Colours::transparentBlack,
  54594. x + diameter * 0.5f, y + diameter * 0.5f,
  54595. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54596. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54597. cg.addColour (0.5, Colours::transparentBlack);
  54598. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54599. g.setGradientFill (cg);
  54600. g.fillPath (p);
  54601. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54602. g.strokePath (p, PathStrokeType (outlineThickness));
  54603. }
  54604. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54605. const float x, const float y,
  54606. const float width, const float height,
  54607. const Colour& colour,
  54608. const float outlineThickness,
  54609. const float cornerSize,
  54610. const bool flatOnLeft,
  54611. const bool flatOnRight,
  54612. const bool flatOnTop,
  54613. const bool flatOnBottom) throw()
  54614. {
  54615. if (width <= outlineThickness || height <= outlineThickness)
  54616. return;
  54617. const int intX = (int) x;
  54618. const int intY = (int) y;
  54619. const int intW = (int) width;
  54620. const int intH = (int) height;
  54621. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54622. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54623. const int intEdge = (int) edgeBlurRadius;
  54624. Path outline;
  54625. createRoundedPath (outline, x, y, width, height, cs,
  54626. ! (flatOnLeft || flatOnTop),
  54627. ! (flatOnRight || flatOnTop),
  54628. ! (flatOnLeft || flatOnBottom),
  54629. ! (flatOnRight || flatOnBottom));
  54630. {
  54631. ColourGradient cg (colour.darker (0.2f), 0, y,
  54632. colour.darker (0.2f), 0, y + height, false);
  54633. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54634. cg.addColour (0.4, colour);
  54635. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54636. g.setGradientFill (cg);
  54637. g.fillPath (outline);
  54638. }
  54639. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54640. colour.darker (0.2f), x, y + height * 0.5f, true);
  54641. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54642. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54643. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54644. {
  54645. g.saveState();
  54646. g.setGradientFill (cg);
  54647. g.reduceClipRegion (intX, intY, intEdge, intH);
  54648. g.fillPath (outline);
  54649. g.restoreState();
  54650. }
  54651. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54652. {
  54653. cg.point1.setX (x + width - edgeBlurRadius);
  54654. cg.point2.setX (x + width);
  54655. g.saveState();
  54656. g.setGradientFill (cg);
  54657. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54658. g.fillPath (outline);
  54659. g.restoreState();
  54660. }
  54661. {
  54662. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54663. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54664. Path highlight;
  54665. createRoundedPath (highlight,
  54666. x + leftIndent,
  54667. y + cs * 0.1f,
  54668. width - (leftIndent + rightIndent),
  54669. height * 0.4f, cs * 0.4f,
  54670. ! (flatOnLeft || flatOnTop),
  54671. ! (flatOnRight || flatOnTop),
  54672. ! (flatOnLeft || flatOnBottom),
  54673. ! (flatOnRight || flatOnBottom));
  54674. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54675. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54676. g.fillPath (highlight);
  54677. }
  54678. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54679. g.strokePath (outline, PathStrokeType (outlineThickness));
  54680. }
  54681. END_JUCE_NAMESPACE
  54682. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54683. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54684. BEGIN_JUCE_NAMESPACE
  54685. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54686. {
  54687. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54688. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54689. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54690. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54691. setColour (Slider::thumbColourId, Colours::white);
  54692. setColour (Slider::trackColourId, Colour (0x7f000000));
  54693. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54694. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54695. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54696. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54697. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54698. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54699. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54700. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54701. }
  54702. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54703. {
  54704. }
  54705. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54706. Button& button,
  54707. const Colour& backgroundColour,
  54708. bool isMouseOverButton,
  54709. bool isButtonDown)
  54710. {
  54711. const int width = button.getWidth();
  54712. const int height = button.getHeight();
  54713. const float indent = 2.0f;
  54714. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54715. roundToInt (height * 0.4f));
  54716. Path p;
  54717. p.addRoundedRectangle (indent, indent,
  54718. width - indent * 2.0f,
  54719. height - indent * 2.0f,
  54720. (float) cornerSize);
  54721. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54722. if (isMouseOverButton)
  54723. {
  54724. if (isButtonDown)
  54725. bc = bc.brighter();
  54726. else if (bc.getBrightness() > 0.5f)
  54727. bc = bc.darker (0.1f);
  54728. else
  54729. bc = bc.brighter (0.1f);
  54730. }
  54731. g.setColour (bc);
  54732. g.fillPath (p);
  54733. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54734. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54735. }
  54736. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54737. Component& /*component*/,
  54738. float x, float y, float w, float h,
  54739. const bool ticked,
  54740. const bool isEnabled,
  54741. const bool /*isMouseOverButton*/,
  54742. const bool isButtonDown)
  54743. {
  54744. Path box;
  54745. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54746. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54747. : Colours::lightgrey.withAlpha (0.1f));
  54748. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54749. g.fillPath (box, trans);
  54750. g.setColour (Colours::black.withAlpha (0.6f));
  54751. g.strokePath (box, PathStrokeType (0.9f), trans);
  54752. if (ticked)
  54753. {
  54754. Path tick;
  54755. tick.startNewSubPath (1.5f, 3.0f);
  54756. tick.lineTo (3.0f, 6.0f);
  54757. tick.lineTo (6.0f, 0.0f);
  54758. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54759. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54760. }
  54761. }
  54762. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54763. ToggleButton& button,
  54764. bool isMouseOverButton,
  54765. bool isButtonDown)
  54766. {
  54767. if (button.hasKeyboardFocus (true))
  54768. {
  54769. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54770. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54771. }
  54772. const int tickWidth = jmin (20, button.getHeight() - 4);
  54773. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54774. (float) tickWidth, (float) tickWidth,
  54775. button.getToggleState(),
  54776. button.isEnabled(),
  54777. isMouseOverButton,
  54778. isButtonDown);
  54779. g.setColour (button.findColour (ToggleButton::textColourId));
  54780. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54781. if (! button.isEnabled())
  54782. g.setOpacity (0.5f);
  54783. const int textX = tickWidth + 5;
  54784. g.drawFittedText (button.getButtonText(),
  54785. textX, 4,
  54786. button.getWidth() - textX - 2, button.getHeight() - 8,
  54787. Justification::centredLeft, 10);
  54788. }
  54789. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54790. int width, int height,
  54791. double progress, const String& textToShow)
  54792. {
  54793. if (progress < 0 || progress >= 1.0)
  54794. {
  54795. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54796. }
  54797. else
  54798. {
  54799. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54800. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54801. g.fillAll (background);
  54802. g.setColour (foreground);
  54803. g.fillRect (1, 1,
  54804. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54805. height - 2);
  54806. if (textToShow.isNotEmpty())
  54807. {
  54808. g.setColour (Colour::contrasting (background, foreground));
  54809. g.setFont (height * 0.6f);
  54810. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54811. }
  54812. }
  54813. }
  54814. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54815. ScrollBar& bar,
  54816. int width, int height,
  54817. int buttonDirection,
  54818. bool isScrollbarVertical,
  54819. bool isMouseOverButton,
  54820. bool isButtonDown)
  54821. {
  54822. if (isScrollbarVertical)
  54823. width -= 2;
  54824. else
  54825. height -= 2;
  54826. Path p;
  54827. if (buttonDirection == 0)
  54828. p.addTriangle (width * 0.5f, height * 0.2f,
  54829. width * 0.1f, height * 0.7f,
  54830. width * 0.9f, height * 0.7f);
  54831. else if (buttonDirection == 1)
  54832. p.addTriangle (width * 0.8f, height * 0.5f,
  54833. width * 0.3f, height * 0.1f,
  54834. width * 0.3f, height * 0.9f);
  54835. else if (buttonDirection == 2)
  54836. p.addTriangle (width * 0.5f, height * 0.8f,
  54837. width * 0.1f, height * 0.3f,
  54838. width * 0.9f, height * 0.3f);
  54839. else if (buttonDirection == 3)
  54840. p.addTriangle (width * 0.2f, height * 0.5f,
  54841. width * 0.7f, height * 0.1f,
  54842. width * 0.7f, height * 0.9f);
  54843. if (isButtonDown)
  54844. g.setColour (Colours::white);
  54845. else if (isMouseOverButton)
  54846. g.setColour (Colours::white.withAlpha (0.7f));
  54847. else
  54848. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54849. g.fillPath (p);
  54850. g.setColour (Colours::black.withAlpha (0.5f));
  54851. g.strokePath (p, PathStrokeType (0.5f));
  54852. }
  54853. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54854. ScrollBar& bar,
  54855. int x, int y,
  54856. int width, int height,
  54857. bool isScrollbarVertical,
  54858. int thumbStartPosition,
  54859. int thumbSize,
  54860. bool isMouseOver,
  54861. bool isMouseDown)
  54862. {
  54863. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54864. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54865. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54866. if (thumbSize > 0.0f)
  54867. {
  54868. Rectangle<int> thumb;
  54869. if (isScrollbarVertical)
  54870. {
  54871. width -= 2;
  54872. g.fillRect (x + roundToInt (width * 0.35f), y,
  54873. roundToInt (width * 0.3f), height);
  54874. thumb.setBounds (x + 1, thumbStartPosition,
  54875. width - 2, thumbSize);
  54876. }
  54877. else
  54878. {
  54879. height -= 2;
  54880. g.fillRect (x, y + roundToInt (height * 0.35f),
  54881. width, roundToInt (height * 0.3f));
  54882. thumb.setBounds (thumbStartPosition, y + 1,
  54883. thumbSize, height - 2);
  54884. }
  54885. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54886. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54887. g.fillRect (thumb);
  54888. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54889. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54890. if (thumbSize > 16)
  54891. {
  54892. for (int i = 3; --i >= 0;)
  54893. {
  54894. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54895. g.setColour (Colours::black.withAlpha (0.15f));
  54896. if (isScrollbarVertical)
  54897. {
  54898. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54899. g.setColour (Colours::white.withAlpha (0.15f));
  54900. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54901. }
  54902. else
  54903. {
  54904. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54905. g.setColour (Colours::white.withAlpha (0.15f));
  54906. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54907. }
  54908. }
  54909. }
  54910. }
  54911. }
  54912. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54913. {
  54914. return &scrollbarShadow;
  54915. }
  54916. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54917. {
  54918. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54919. g.setColour (Colours::black.withAlpha (0.6f));
  54920. g.drawRect (0, 0, width, height);
  54921. }
  54922. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54923. bool, MenuBarComponent& menuBar)
  54924. {
  54925. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54926. }
  54927. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54928. {
  54929. if (textEditor.isEnabled())
  54930. {
  54931. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54932. g.drawRect (0, 0, width, height);
  54933. }
  54934. }
  54935. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54936. const bool isButtonDown,
  54937. int buttonX, int buttonY,
  54938. int buttonW, int buttonH,
  54939. ComboBox& box)
  54940. {
  54941. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54942. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54943. : ComboBox::backgroundColourId));
  54944. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54945. g.setColour (box.findColour (ComboBox::outlineColourId));
  54946. g.drawRect (0, 0, width, height);
  54947. const float arrowX = 0.2f;
  54948. const float arrowH = 0.3f;
  54949. if (box.isEnabled())
  54950. {
  54951. Path p;
  54952. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54953. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54954. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54955. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54956. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54957. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54958. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54959. : ComboBox::buttonColourId));
  54960. g.fillPath (p);
  54961. }
  54962. }
  54963. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54964. {
  54965. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54966. f.setHorizontalScale (0.9f);
  54967. return f;
  54968. }
  54969. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54970. {
  54971. Path p;
  54972. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54973. g.setColour (fill);
  54974. g.fillPath (p);
  54975. g.setColour (outline);
  54976. g.strokePath (p, PathStrokeType (0.3f));
  54977. }
  54978. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54979. int x, int y,
  54980. int w, int h,
  54981. float sliderPos,
  54982. float minSliderPos,
  54983. float maxSliderPos,
  54984. const Slider::SliderStyle style,
  54985. Slider& slider)
  54986. {
  54987. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54988. if (style == Slider::LinearBar)
  54989. {
  54990. g.setColour (slider.findColour (Slider::thumbColourId));
  54991. g.fillRect (x, y, (int) sliderPos - x, h);
  54992. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54993. g.drawRect (x, y, (int) sliderPos - x, h);
  54994. }
  54995. else
  54996. {
  54997. g.setColour (slider.findColour (Slider::trackColourId)
  54998. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54999. if (slider.isHorizontal())
  55000. {
  55001. g.fillRect (x, y + roundToInt (h * 0.6f),
  55002. w, roundToInt (h * 0.2f));
  55003. }
  55004. else
  55005. {
  55006. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55007. jmin (4, roundToInt (w * 0.2f)), h);
  55008. }
  55009. float alpha = 0.35f;
  55010. if (slider.isEnabled())
  55011. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55012. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55013. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55014. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55015. {
  55016. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55017. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55018. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55019. fill, outline);
  55020. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55021. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55022. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55023. fill, outline);
  55024. }
  55025. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55026. {
  55027. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55028. minSliderPos - 7.0f, y + h * 0.9f ,
  55029. minSliderPos, y + h * 0.9f,
  55030. fill, outline);
  55031. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55032. maxSliderPos, y + h * 0.9f,
  55033. maxSliderPos + 7.0f, y + h * 0.9f,
  55034. fill, outline);
  55035. }
  55036. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55037. {
  55038. drawTriangle (g, sliderPos, y + h * 0.9f,
  55039. sliderPos - 7.0f, y + h * 0.2f,
  55040. sliderPos + 7.0f, y + h * 0.2f,
  55041. fill, outline);
  55042. }
  55043. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55044. {
  55045. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55046. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55047. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55048. fill, outline);
  55049. }
  55050. }
  55051. }
  55052. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55053. {
  55054. if (isIncrement)
  55055. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55056. else
  55057. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55058. }
  55059. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55060. {
  55061. return &scrollbarShadow;
  55062. }
  55063. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55064. {
  55065. return 8;
  55066. }
  55067. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55068. int w, int h,
  55069. bool isMouseOver,
  55070. bool isMouseDragging)
  55071. {
  55072. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55073. : Colours::darkgrey);
  55074. const float lineThickness = jmin (w, h) * 0.1f;
  55075. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55076. {
  55077. g.drawLine (w * i,
  55078. h + 1.0f,
  55079. w + 1.0f,
  55080. h * i,
  55081. lineThickness);
  55082. }
  55083. }
  55084. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55085. {
  55086. Path shape;
  55087. if (buttonType == DocumentWindow::closeButton)
  55088. {
  55089. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55090. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55091. ShapeButton* const b = new ShapeButton ("close",
  55092. Colour (0x7fff3333),
  55093. Colour (0xd7ff3333),
  55094. Colour (0xf7ff3333));
  55095. b->setShape (shape, true, true, true);
  55096. return b;
  55097. }
  55098. else if (buttonType == DocumentWindow::minimiseButton)
  55099. {
  55100. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55101. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55102. DrawablePath dp;
  55103. dp.setPath (shape);
  55104. dp.setFill (Colours::black.withAlpha (0.3f));
  55105. b->setImages (&dp);
  55106. return b;
  55107. }
  55108. else if (buttonType == DocumentWindow::maximiseButton)
  55109. {
  55110. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55111. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55112. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55113. DrawablePath dp;
  55114. dp.setPath (shape);
  55115. dp.setFill (Colours::black.withAlpha (0.3f));
  55116. b->setImages (&dp);
  55117. return b;
  55118. }
  55119. jassertfalse;
  55120. return 0;
  55121. }
  55122. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55123. int titleBarX,
  55124. int titleBarY,
  55125. int titleBarW,
  55126. int titleBarH,
  55127. Button* minimiseButton,
  55128. Button* maximiseButton,
  55129. Button* closeButton,
  55130. bool positionTitleBarButtonsOnLeft)
  55131. {
  55132. titleBarY += titleBarH / 8;
  55133. titleBarH -= titleBarH / 4;
  55134. const int buttonW = titleBarH;
  55135. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55136. : titleBarX + titleBarW - buttonW - 4;
  55137. if (closeButton != 0)
  55138. {
  55139. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55140. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55141. : -(buttonW + buttonW / 5);
  55142. }
  55143. if (positionTitleBarButtonsOnLeft)
  55144. swapVariables (minimiseButton, maximiseButton);
  55145. if (maximiseButton != 0)
  55146. {
  55147. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55148. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55149. }
  55150. if (minimiseButton != 0)
  55151. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55152. }
  55153. END_JUCE_NAMESPACE
  55154. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55155. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55156. BEGIN_JUCE_NAMESPACE
  55157. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55158. : model (0),
  55159. itemUnderMouse (-1),
  55160. currentPopupIndex (-1),
  55161. topLevelIndexClicked (0),
  55162. lastMouseX (0),
  55163. lastMouseY (0)
  55164. {
  55165. setRepaintsOnMouseActivity (true);
  55166. setWantsKeyboardFocus (false);
  55167. setMouseClickGrabsKeyboardFocus (false);
  55168. setModel (model_);
  55169. }
  55170. MenuBarComponent::~MenuBarComponent()
  55171. {
  55172. setModel (0);
  55173. Desktop::getInstance().removeGlobalMouseListener (this);
  55174. }
  55175. MenuBarModel* MenuBarComponent::getModel() const throw()
  55176. {
  55177. return model;
  55178. }
  55179. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55180. {
  55181. if (model != newModel)
  55182. {
  55183. if (model != 0)
  55184. model->removeListener (this);
  55185. model = newModel;
  55186. if (model != 0)
  55187. model->addListener (this);
  55188. repaint();
  55189. menuBarItemsChanged (0);
  55190. }
  55191. }
  55192. void MenuBarComponent::paint (Graphics& g)
  55193. {
  55194. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55195. getLookAndFeel().drawMenuBarBackground (g,
  55196. getWidth(),
  55197. getHeight(),
  55198. isMouseOverBar,
  55199. *this);
  55200. if (model != 0)
  55201. {
  55202. for (int i = 0; i < menuNames.size(); ++i)
  55203. {
  55204. g.saveState();
  55205. g.setOrigin (xPositions [i], 0);
  55206. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55207. getLookAndFeel().drawMenuBarItem (g,
  55208. xPositions[i + 1] - xPositions[i],
  55209. getHeight(),
  55210. i,
  55211. menuNames[i],
  55212. i == itemUnderMouse,
  55213. i == currentPopupIndex,
  55214. isMouseOverBar,
  55215. *this);
  55216. g.restoreState();
  55217. }
  55218. }
  55219. }
  55220. void MenuBarComponent::resized()
  55221. {
  55222. xPositions.clear();
  55223. int x = 2;
  55224. xPositions.add (x);
  55225. for (int i = 0; i < menuNames.size(); ++i)
  55226. {
  55227. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55228. xPositions.add (x);
  55229. }
  55230. }
  55231. int MenuBarComponent::getItemAt (const int x, const int y)
  55232. {
  55233. for (int i = 0; i < xPositions.size(); ++i)
  55234. if (x >= xPositions[i] && x < xPositions[i + 1])
  55235. return reallyContains (x, y, true) ? i : -1;
  55236. return -1;
  55237. }
  55238. void MenuBarComponent::repaintMenuItem (int index)
  55239. {
  55240. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55241. {
  55242. const int x1 = xPositions [index];
  55243. const int x2 = xPositions [index + 1];
  55244. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55245. }
  55246. }
  55247. void MenuBarComponent::setItemUnderMouse (const int index)
  55248. {
  55249. if (itemUnderMouse != index)
  55250. {
  55251. repaintMenuItem (itemUnderMouse);
  55252. itemUnderMouse = index;
  55253. repaintMenuItem (itemUnderMouse);
  55254. }
  55255. }
  55256. void MenuBarComponent::setOpenItem (int index)
  55257. {
  55258. if (currentPopupIndex != index)
  55259. {
  55260. repaintMenuItem (currentPopupIndex);
  55261. currentPopupIndex = index;
  55262. repaintMenuItem (currentPopupIndex);
  55263. if (index >= 0)
  55264. Desktop::getInstance().addGlobalMouseListener (this);
  55265. else
  55266. Desktop::getInstance().removeGlobalMouseListener (this);
  55267. }
  55268. }
  55269. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55270. {
  55271. setItemUnderMouse (getItemAt (x, y));
  55272. }
  55273. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55274. {
  55275. public:
  55276. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55277. : bar (bar_), topLevelIndex (topLevelIndex_)
  55278. {
  55279. }
  55280. ~AsyncCallback() {}
  55281. void modalStateFinished (int returnValue)
  55282. {
  55283. if (bar != 0)
  55284. bar->menuDismissed (topLevelIndex, returnValue);
  55285. }
  55286. private:
  55287. Component::SafePointer<MenuBarComponent> bar;
  55288. const int topLevelIndex;
  55289. AsyncCallback (const AsyncCallback&);
  55290. AsyncCallback& operator= (const AsyncCallback&);
  55291. };
  55292. void MenuBarComponent::showMenu (int index)
  55293. {
  55294. if (index != currentPopupIndex)
  55295. {
  55296. PopupMenu::dismissAllActiveMenus();
  55297. menuBarItemsChanged (0);
  55298. setOpenItem (index);
  55299. setItemUnderMouse (index);
  55300. if (index >= 0)
  55301. {
  55302. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55303. menuNames [itemUnderMouse]));
  55304. if (m.lookAndFeel == 0)
  55305. m.setLookAndFeel (&getLookAndFeel());
  55306. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55307. m.showMenu (itemPos + getScreenPosition(),
  55308. 0, itemPos.getWidth(), 0, 0, true, this,
  55309. new AsyncCallback (this, index));
  55310. }
  55311. }
  55312. }
  55313. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55314. {
  55315. topLevelIndexClicked = topLevelIndex;
  55316. postCommandMessage (itemId);
  55317. }
  55318. void MenuBarComponent::handleCommandMessage (int commandId)
  55319. {
  55320. const Point<int> mousePos (getMouseXYRelative());
  55321. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55322. if (! isCurrentlyBlockedByAnotherModalComponent())
  55323. setOpenItem (-1);
  55324. if (commandId != 0 && model != 0)
  55325. model->menuItemSelected (commandId, topLevelIndexClicked);
  55326. }
  55327. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55328. {
  55329. if (e.eventComponent == this)
  55330. updateItemUnderMouse (e.x, e.y);
  55331. }
  55332. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55333. {
  55334. if (e.eventComponent == this)
  55335. updateItemUnderMouse (e.x, e.y);
  55336. }
  55337. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55338. {
  55339. if (currentPopupIndex < 0)
  55340. {
  55341. const MouseEvent e2 (e.getEventRelativeTo (this));
  55342. updateItemUnderMouse (e2.x, e2.y);
  55343. currentPopupIndex = -2;
  55344. showMenu (itemUnderMouse);
  55345. }
  55346. }
  55347. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55348. {
  55349. const MouseEvent e2 (e.getEventRelativeTo (this));
  55350. const int item = getItemAt (e2.x, e2.y);
  55351. if (item >= 0)
  55352. showMenu (item);
  55353. }
  55354. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55355. {
  55356. const MouseEvent e2 (e.getEventRelativeTo (this));
  55357. updateItemUnderMouse (e2.x, e2.y);
  55358. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55359. {
  55360. setOpenItem (-1);
  55361. PopupMenu::dismissAllActiveMenus();
  55362. }
  55363. }
  55364. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55365. {
  55366. const MouseEvent e2 (e.getEventRelativeTo (this));
  55367. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55368. {
  55369. if (currentPopupIndex >= 0)
  55370. {
  55371. const int item = getItemAt (e2.x, e2.y);
  55372. if (item >= 0)
  55373. showMenu (item);
  55374. }
  55375. else
  55376. {
  55377. updateItemUnderMouse (e2.x, e2.y);
  55378. }
  55379. lastMouseX = e2.x;
  55380. lastMouseY = e2.y;
  55381. }
  55382. }
  55383. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55384. {
  55385. bool used = false;
  55386. const int numMenus = menuNames.size();
  55387. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55388. if (key.isKeyCode (KeyPress::leftKey))
  55389. {
  55390. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55391. used = true;
  55392. }
  55393. else if (key.isKeyCode (KeyPress::rightKey))
  55394. {
  55395. showMenu ((currentIndex + 1) % numMenus);
  55396. used = true;
  55397. }
  55398. return used;
  55399. }
  55400. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55401. {
  55402. StringArray newNames;
  55403. if (model != 0)
  55404. newNames = model->getMenuBarNames();
  55405. if (newNames != menuNames)
  55406. {
  55407. menuNames = newNames;
  55408. repaint();
  55409. resized();
  55410. }
  55411. }
  55412. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55413. const ApplicationCommandTarget::InvocationInfo& info)
  55414. {
  55415. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55416. return;
  55417. for (int i = 0; i < menuNames.size(); ++i)
  55418. {
  55419. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55420. if (menu.containsCommandItem (info.commandID))
  55421. {
  55422. setItemUnderMouse (i);
  55423. startTimer (200);
  55424. break;
  55425. }
  55426. }
  55427. }
  55428. void MenuBarComponent::timerCallback()
  55429. {
  55430. stopTimer();
  55431. const Point<int> mousePos (getMouseXYRelative());
  55432. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55433. }
  55434. END_JUCE_NAMESPACE
  55435. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55436. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55437. BEGIN_JUCE_NAMESPACE
  55438. MenuBarModel::MenuBarModel() throw()
  55439. : manager (0)
  55440. {
  55441. }
  55442. MenuBarModel::~MenuBarModel()
  55443. {
  55444. setApplicationCommandManagerToWatch (0);
  55445. }
  55446. void MenuBarModel::menuItemsChanged()
  55447. {
  55448. triggerAsyncUpdate();
  55449. }
  55450. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55451. {
  55452. if (manager != newManager)
  55453. {
  55454. if (manager != 0)
  55455. manager->removeListener (this);
  55456. manager = newManager;
  55457. if (manager != 0)
  55458. manager->addListener (this);
  55459. }
  55460. }
  55461. void MenuBarModel::addListener (Listener* const newListener) throw()
  55462. {
  55463. listeners.add (newListener);
  55464. }
  55465. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55466. {
  55467. // Trying to remove a listener that isn't on the list!
  55468. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55469. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55470. jassert (listeners.contains (listenerToRemove));
  55471. listeners.remove (listenerToRemove);
  55472. }
  55473. void MenuBarModel::handleAsyncUpdate()
  55474. {
  55475. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55476. }
  55477. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55478. {
  55479. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55480. }
  55481. void MenuBarModel::applicationCommandListChanged()
  55482. {
  55483. menuItemsChanged();
  55484. }
  55485. END_JUCE_NAMESPACE
  55486. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55487. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55488. BEGIN_JUCE_NAMESPACE
  55489. class PopupMenu::Item
  55490. {
  55491. public:
  55492. Item()
  55493. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55494. usesColour (false), customComp (0), commandManager (0)
  55495. {
  55496. }
  55497. Item (const int itemId_,
  55498. const String& text_,
  55499. const bool active_,
  55500. const bool isTicked_,
  55501. const Image& im,
  55502. const Colour& textColour_,
  55503. const bool usesColour_,
  55504. PopupMenuCustomComponent* const customComp_,
  55505. const PopupMenu* const subMenu_,
  55506. ApplicationCommandManager* const commandManager_)
  55507. : itemId (itemId_), text (text_), textColour (textColour_),
  55508. active (active_), isSeparator (false), isTicked (isTicked_),
  55509. usesColour (usesColour_), image (im), customComp (customComp_),
  55510. commandManager (commandManager_)
  55511. {
  55512. if (subMenu_ != 0)
  55513. subMenu = new PopupMenu (*subMenu_);
  55514. if (commandManager_ != 0 && itemId_ != 0)
  55515. {
  55516. String shortcutKey;
  55517. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55518. ->getKeyPressesAssignedToCommand (itemId_));
  55519. for (int i = 0; i < keyPresses.size(); ++i)
  55520. {
  55521. const String key (keyPresses.getReference(i).getTextDescription());
  55522. if (shortcutKey.isNotEmpty())
  55523. shortcutKey << ", ";
  55524. if (key.length() == 1)
  55525. shortcutKey << "shortcut: '" << key << '\'';
  55526. else
  55527. shortcutKey << key;
  55528. }
  55529. shortcutKey = shortcutKey.trim();
  55530. if (shortcutKey.isNotEmpty())
  55531. text << "<end>" << shortcutKey;
  55532. }
  55533. }
  55534. Item (const Item& other)
  55535. : itemId (other.itemId),
  55536. text (other.text),
  55537. textColour (other.textColour),
  55538. active (other.active),
  55539. isSeparator (other.isSeparator),
  55540. isTicked (other.isTicked),
  55541. usesColour (other.usesColour),
  55542. image (other.image),
  55543. customComp (other.customComp),
  55544. commandManager (other.commandManager)
  55545. {
  55546. if (other.subMenu != 0)
  55547. subMenu = new PopupMenu (*(other.subMenu));
  55548. }
  55549. ~Item()
  55550. {
  55551. customComp = 0;
  55552. }
  55553. bool canBeTriggered() const throw()
  55554. {
  55555. return active && ! (isSeparator || (subMenu != 0));
  55556. }
  55557. bool hasActiveSubMenu() const throw()
  55558. {
  55559. return active && (subMenu != 0);
  55560. }
  55561. const int itemId;
  55562. String text;
  55563. const Colour textColour;
  55564. const bool active, isSeparator, isTicked, usesColour;
  55565. Image image;
  55566. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55567. ScopedPointer <PopupMenu> subMenu;
  55568. ApplicationCommandManager* const commandManager;
  55569. juce_UseDebuggingNewOperator
  55570. private:
  55571. Item& operator= (const Item&);
  55572. };
  55573. class PopupMenu::ItemComponent : public Component
  55574. {
  55575. public:
  55576. ItemComponent (const PopupMenu::Item& itemInfo_)
  55577. : itemInfo (itemInfo_),
  55578. isHighlighted (false)
  55579. {
  55580. if (itemInfo.customComp != 0)
  55581. addAndMakeVisible (itemInfo.customComp);
  55582. }
  55583. ~ItemComponent()
  55584. {
  55585. if (itemInfo.customComp != 0)
  55586. removeChildComponent (itemInfo.customComp);
  55587. }
  55588. void getIdealSize (int& idealWidth,
  55589. int& idealHeight,
  55590. const int standardItemHeight)
  55591. {
  55592. if (itemInfo.customComp != 0)
  55593. {
  55594. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55595. }
  55596. else
  55597. {
  55598. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55599. itemInfo.isSeparator,
  55600. standardItemHeight,
  55601. idealWidth,
  55602. idealHeight);
  55603. }
  55604. }
  55605. void paint (Graphics& g)
  55606. {
  55607. if (itemInfo.customComp == 0)
  55608. {
  55609. String mainText (itemInfo.text);
  55610. String endText;
  55611. const int endIndex = mainText.indexOf ("<end>");
  55612. if (endIndex >= 0)
  55613. {
  55614. endText = mainText.substring (endIndex + 5).trim();
  55615. mainText = mainText.substring (0, endIndex);
  55616. }
  55617. getLookAndFeel()
  55618. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55619. itemInfo.isSeparator,
  55620. itemInfo.active,
  55621. isHighlighted,
  55622. itemInfo.isTicked,
  55623. itemInfo.subMenu != 0,
  55624. mainText, endText,
  55625. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55626. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55627. }
  55628. }
  55629. void resized()
  55630. {
  55631. if (getNumChildComponents() > 0)
  55632. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55633. }
  55634. void setHighlighted (bool shouldBeHighlighted)
  55635. {
  55636. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55637. if (isHighlighted != shouldBeHighlighted)
  55638. {
  55639. isHighlighted = shouldBeHighlighted;
  55640. if (itemInfo.customComp != 0)
  55641. {
  55642. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55643. itemInfo.customComp->repaint();
  55644. }
  55645. repaint();
  55646. }
  55647. }
  55648. PopupMenu::Item itemInfo;
  55649. juce_UseDebuggingNewOperator
  55650. private:
  55651. bool isHighlighted;
  55652. ItemComponent (const ItemComponent&);
  55653. ItemComponent& operator= (const ItemComponent&);
  55654. };
  55655. namespace PopupMenuSettings
  55656. {
  55657. static const int scrollZone = 24;
  55658. static const int borderSize = 2;
  55659. static const int timerInterval = 50;
  55660. static const int dismissCommandId = 0x6287345f;
  55661. }
  55662. class PopupMenu::Window : public Component,
  55663. private Timer
  55664. {
  55665. public:
  55666. Window()
  55667. : Component ("menu"),
  55668. owner (0),
  55669. currentChild (0),
  55670. activeSubMenu (0),
  55671. managerOfChosenCommand (0),
  55672. minimumWidth (0),
  55673. maximumNumColumns (7),
  55674. standardItemHeight (0),
  55675. isOver (false),
  55676. hasBeenOver (false),
  55677. isDown (false),
  55678. needsToScroll (false),
  55679. hideOnExit (false),
  55680. disableMouseMoves (false),
  55681. hasAnyJuceCompHadFocus (false),
  55682. numColumns (0),
  55683. contentHeight (0),
  55684. childYOffset (0),
  55685. timeEnteredCurrentChildComp (0),
  55686. scrollAcceleration (1.0)
  55687. {
  55688. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55689. setWantsKeyboardFocus (true);
  55690. setMouseClickGrabsKeyboardFocus (false);
  55691. setOpaque (true);
  55692. setAlwaysOnTop (true);
  55693. Desktop::getInstance().addGlobalMouseListener (this);
  55694. getActiveWindows().add (this);
  55695. }
  55696. ~Window()
  55697. {
  55698. getActiveWindows().removeValue (this);
  55699. Desktop::getInstance().removeGlobalMouseListener (this);
  55700. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55701. activeSubMenu = 0;
  55702. deleteAllChildren();
  55703. }
  55704. static Window* create (const PopupMenu& menu,
  55705. const bool dismissOnMouseUp,
  55706. Window* const owner_,
  55707. const Rectangle<int>& target,
  55708. const int minimumWidth,
  55709. const int maximumNumColumns,
  55710. const int standardItemHeight,
  55711. const bool alignToRectangle,
  55712. const int itemIdThatMustBeVisible,
  55713. ApplicationCommandManager** managerOfChosenCommand,
  55714. Component* const componentAttachedTo)
  55715. {
  55716. if (menu.items.size() > 0)
  55717. {
  55718. int totalItems = 0;
  55719. ScopedPointer <Window> mw (new Window());
  55720. mw->setLookAndFeel (menu.lookAndFeel);
  55721. mw->setWantsKeyboardFocus (false);
  55722. mw->minimumWidth = minimumWidth;
  55723. mw->maximumNumColumns = maximumNumColumns;
  55724. mw->standardItemHeight = standardItemHeight;
  55725. mw->dismissOnMouseUp = dismissOnMouseUp;
  55726. for (int i = 0; i < menu.items.size(); ++i)
  55727. {
  55728. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55729. mw->addItem (*item);
  55730. ++totalItems;
  55731. }
  55732. if (totalItems > 0)
  55733. {
  55734. mw->owner = owner_;
  55735. mw->managerOfChosenCommand = managerOfChosenCommand;
  55736. mw->componentAttachedTo = componentAttachedTo;
  55737. mw->componentAttachedToOriginal = componentAttachedTo;
  55738. mw->calculateWindowPos (target, alignToRectangle);
  55739. mw->setTopLeftPosition (mw->windowPos.getX(),
  55740. mw->windowPos.getY());
  55741. mw->updateYPositions();
  55742. if (itemIdThatMustBeVisible != 0)
  55743. {
  55744. const int y = target.getY() - mw->windowPos.getY();
  55745. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55746. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55747. }
  55748. mw->resizeToBestWindowPos();
  55749. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55750. | mw->getLookAndFeel().getMenuWindowFlags());
  55751. return mw.release();
  55752. }
  55753. }
  55754. return 0;
  55755. }
  55756. void paint (Graphics& g)
  55757. {
  55758. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55759. }
  55760. void paintOverChildren (Graphics& g)
  55761. {
  55762. if (isScrolling())
  55763. {
  55764. LookAndFeel& lf = getLookAndFeel();
  55765. if (isScrollZoneActive (false))
  55766. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55767. if (isScrollZoneActive (true))
  55768. {
  55769. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55770. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55771. }
  55772. }
  55773. }
  55774. bool isScrollZoneActive (bool bottomOne) const
  55775. {
  55776. return isScrolling()
  55777. && (bottomOne
  55778. ? childYOffset < contentHeight - windowPos.getHeight()
  55779. : childYOffset > 0);
  55780. }
  55781. void addItem (const PopupMenu::Item& item)
  55782. {
  55783. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55784. addAndMakeVisible (mic);
  55785. int itemW = 80;
  55786. int itemH = 16;
  55787. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55788. mic->setSize (itemW, jlimit (2, 600, itemH));
  55789. mic->addMouseListener (this, false);
  55790. }
  55791. // hide this and all sub-comps
  55792. void hide (const PopupMenu::Item* const item)
  55793. {
  55794. if (isVisible())
  55795. {
  55796. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55797. activeSubMenu = 0;
  55798. currentChild = 0;
  55799. exitModalState (item != 0 ? item->itemId : 0);
  55800. setVisible (false);
  55801. if (item != 0
  55802. && item->commandManager != 0
  55803. && item->itemId != 0)
  55804. {
  55805. *managerOfChosenCommand = item->commandManager;
  55806. }
  55807. }
  55808. }
  55809. void dismissMenu (const PopupMenu::Item* const item)
  55810. {
  55811. if (owner != 0)
  55812. {
  55813. owner->dismissMenu (item);
  55814. }
  55815. else
  55816. {
  55817. if (item != 0)
  55818. {
  55819. // need a copy of this on the stack as the one passed in will get deleted during this call
  55820. const PopupMenu::Item mi (*item);
  55821. hide (&mi);
  55822. }
  55823. else
  55824. {
  55825. hide (0);
  55826. }
  55827. }
  55828. }
  55829. void mouseMove (const MouseEvent&)
  55830. {
  55831. timerCallback();
  55832. }
  55833. void mouseDown (const MouseEvent&)
  55834. {
  55835. timerCallback();
  55836. }
  55837. void mouseDrag (const MouseEvent&)
  55838. {
  55839. timerCallback();
  55840. }
  55841. void mouseUp (const MouseEvent&)
  55842. {
  55843. timerCallback();
  55844. }
  55845. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55846. {
  55847. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55848. lastMouse = Point<int> (-1, -1);
  55849. }
  55850. bool keyPressed (const KeyPress& key)
  55851. {
  55852. if (key.isKeyCode (KeyPress::downKey))
  55853. {
  55854. selectNextItem (1);
  55855. }
  55856. else if (key.isKeyCode (KeyPress::upKey))
  55857. {
  55858. selectNextItem (-1);
  55859. }
  55860. else if (key.isKeyCode (KeyPress::leftKey))
  55861. {
  55862. if (owner != 0)
  55863. {
  55864. Component::SafePointer<Window> parentWindow (owner);
  55865. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55866. hide (0);
  55867. if (parentWindow != 0)
  55868. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55869. disableTimerUntilMouseMoves();
  55870. }
  55871. else if (componentAttachedTo != 0)
  55872. {
  55873. componentAttachedTo->keyPressed (key);
  55874. }
  55875. }
  55876. else if (key.isKeyCode (KeyPress::rightKey))
  55877. {
  55878. disableTimerUntilMouseMoves();
  55879. if (showSubMenuFor (currentChild))
  55880. {
  55881. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55882. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55883. activeSubMenu->selectNextItem (1);
  55884. }
  55885. else if (componentAttachedTo != 0)
  55886. {
  55887. componentAttachedTo->keyPressed (key);
  55888. }
  55889. }
  55890. else if (key.isKeyCode (KeyPress::returnKey))
  55891. {
  55892. triggerCurrentlyHighlightedItem();
  55893. }
  55894. else if (key.isKeyCode (KeyPress::escapeKey))
  55895. {
  55896. dismissMenu (0);
  55897. }
  55898. else
  55899. {
  55900. return false;
  55901. }
  55902. return true;
  55903. }
  55904. void inputAttemptWhenModal()
  55905. {
  55906. Component::SafePointer<Component> deletionChecker (this);
  55907. timerCallback();
  55908. if (deletionChecker != 0 && ! isOverAnyMenu())
  55909. {
  55910. if (componentAttachedTo != 0)
  55911. {
  55912. // we want to dismiss the menu, but if we do it synchronously, then
  55913. // the mouse-click will be allowed to pass through. That's good, except
  55914. // when the user clicks on the button that orginally popped the menu up,
  55915. // as they'll expect the menu to go away, and in fact it'll just
  55916. // come back. So only dismiss synchronously if they're not on the original
  55917. // comp that we're attached to.
  55918. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55919. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55920. {
  55921. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55922. return;
  55923. }
  55924. }
  55925. dismissMenu (0);
  55926. }
  55927. }
  55928. void handleCommandMessage (int commandId)
  55929. {
  55930. Component::handleCommandMessage (commandId);
  55931. if (commandId == PopupMenuSettings::dismissCommandId)
  55932. dismissMenu (0);
  55933. }
  55934. void timerCallback()
  55935. {
  55936. if (! isVisible())
  55937. return;
  55938. if (componentAttachedTo != componentAttachedToOriginal)
  55939. {
  55940. dismissMenu (0);
  55941. return;
  55942. }
  55943. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55944. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55945. return;
  55946. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55947. // move rather than a real timer callback
  55948. const Point<int> globalMousePos (Desktop::getMousePosition());
  55949. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55950. const uint32 now = Time::getMillisecondCounter();
  55951. if (now > timeEnteredCurrentChildComp + 100
  55952. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55953. && currentChild->isValidComponent()
  55954. && (! disableMouseMoves)
  55955. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55956. {
  55957. showSubMenuFor (currentChild);
  55958. }
  55959. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55960. {
  55961. highlightItemUnderMouse (globalMousePos, localMousePos);
  55962. }
  55963. bool overScrollArea = false;
  55964. if (isScrolling()
  55965. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55966. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55967. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55968. {
  55969. if (now > lastScroll + 20)
  55970. {
  55971. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55972. int amount = 0;
  55973. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55974. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55975. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55976. lastScroll = now;
  55977. }
  55978. overScrollArea = true;
  55979. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55980. }
  55981. else
  55982. {
  55983. scrollAcceleration = 1.0;
  55984. }
  55985. const bool wasDown = isDown;
  55986. bool isOverAny = isOverAnyMenu();
  55987. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55988. {
  55989. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55990. isOverAny = isOverAnyMenu();
  55991. }
  55992. if (hideOnExit && hasBeenOver && ! isOverAny)
  55993. {
  55994. hide (0);
  55995. }
  55996. else
  55997. {
  55998. isDown = hasBeenOver
  55999. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56000. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56001. bool anyFocused = Process::isForegroundProcess();
  56002. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56003. {
  56004. // because no component at all may have focus, our test here will
  56005. // only be triggered when something has focus and then loses it.
  56006. anyFocused = ! hasAnyJuceCompHadFocus;
  56007. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56008. {
  56009. if (ComponentPeer::getPeer (i)->isFocused())
  56010. {
  56011. anyFocused = true;
  56012. hasAnyJuceCompHadFocus = true;
  56013. break;
  56014. }
  56015. }
  56016. }
  56017. if (! anyFocused)
  56018. {
  56019. if (now > lastFocused + 10)
  56020. {
  56021. wasHiddenBecauseOfAppChange() = true;
  56022. dismissMenu (0);
  56023. return; // may have been deleted by the previous call..
  56024. }
  56025. }
  56026. else if (wasDown && now > menuCreationTime + 250
  56027. && ! (isDown || overScrollArea))
  56028. {
  56029. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56030. if (isOver)
  56031. {
  56032. triggerCurrentlyHighlightedItem();
  56033. }
  56034. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56035. {
  56036. dismissMenu (0);
  56037. }
  56038. return; // may have been deleted by the previous calls..
  56039. }
  56040. else
  56041. {
  56042. lastFocused = now;
  56043. }
  56044. }
  56045. }
  56046. static Array<Window*>& getActiveWindows()
  56047. {
  56048. static Array<Window*> activeMenuWindows;
  56049. return activeMenuWindows;
  56050. }
  56051. static bool& wasHiddenBecauseOfAppChange() throw()
  56052. {
  56053. static bool b = false;
  56054. return b;
  56055. }
  56056. juce_UseDebuggingNewOperator
  56057. private:
  56058. Window* owner;
  56059. PopupMenu::ItemComponent* currentChild;
  56060. ScopedPointer <Window> activeSubMenu;
  56061. ApplicationCommandManager** managerOfChosenCommand;
  56062. Component::SafePointer<Component> componentAttachedTo;
  56063. Component* componentAttachedToOriginal;
  56064. Rectangle<int> windowPos;
  56065. Point<int> lastMouse;
  56066. int minimumWidth, maximumNumColumns, standardItemHeight;
  56067. bool isOver, hasBeenOver, isDown, needsToScroll;
  56068. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56069. int numColumns, contentHeight, childYOffset;
  56070. Array <int> columnWidths;
  56071. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56072. double scrollAcceleration;
  56073. bool overlaps (const Rectangle<int>& r) const
  56074. {
  56075. return r.intersects (getBounds())
  56076. || (owner != 0 && owner->overlaps (r));
  56077. }
  56078. bool isOverAnyMenu() const
  56079. {
  56080. return (owner != 0) ? owner->isOverAnyMenu()
  56081. : isOverChildren();
  56082. }
  56083. bool isOverChildren() const
  56084. {
  56085. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56086. return isVisible()
  56087. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56088. }
  56089. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56090. {
  56091. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56092. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56093. if (activeSubMenu != 0)
  56094. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56095. }
  56096. bool treeContains (const Window* const window) const throw()
  56097. {
  56098. const Window* mw = this;
  56099. while (mw->owner != 0)
  56100. mw = mw->owner;
  56101. while (mw != 0)
  56102. {
  56103. if (mw == window)
  56104. return true;
  56105. mw = mw->activeSubMenu;
  56106. }
  56107. return false;
  56108. }
  56109. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56110. {
  56111. const Rectangle<int> mon (Desktop::getInstance()
  56112. .getMonitorAreaContaining (target.getCentre(),
  56113. #if JUCE_MAC
  56114. true));
  56115. #else
  56116. false)); // on windows, don't stop the menu overlapping the taskbar
  56117. #endif
  56118. int x, y, widthToUse, heightToUse;
  56119. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56120. if (alignToRectangle)
  56121. {
  56122. x = target.getX();
  56123. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56124. const int spaceOver = target.getY() - mon.getY();
  56125. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56126. y = target.getBottom();
  56127. else
  56128. y = target.getY() - heightToUse;
  56129. }
  56130. else
  56131. {
  56132. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56133. if (owner != 0)
  56134. {
  56135. if (owner->owner != 0)
  56136. {
  56137. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56138. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56139. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56140. tendTowardsRight = true;
  56141. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56142. tendTowardsRight = false;
  56143. }
  56144. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56145. {
  56146. tendTowardsRight = true;
  56147. }
  56148. }
  56149. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56150. target.getX() - mon.getX()) - 32;
  56151. if (biggestSpace < widthToUse)
  56152. {
  56153. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56154. if (numColumns > 1)
  56155. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56156. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56157. }
  56158. if (tendTowardsRight)
  56159. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56160. else
  56161. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56162. y = target.getY();
  56163. if (target.getCentreY() > mon.getCentreY())
  56164. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56165. }
  56166. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56167. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56168. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56169. // sets this flag if it's big enough to obscure any of its parent menus
  56170. hideOnExit = (owner != 0)
  56171. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56172. }
  56173. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56174. {
  56175. numColumns = 0;
  56176. contentHeight = 0;
  56177. const int maxMenuH = getParentHeight() - 24;
  56178. int totalW;
  56179. do
  56180. {
  56181. ++numColumns;
  56182. totalW = workOutBestSize (maxMenuW);
  56183. if (totalW > maxMenuW)
  56184. {
  56185. numColumns = jmax (1, numColumns - 1);
  56186. totalW = workOutBestSize (maxMenuW); // to update col widths
  56187. break;
  56188. }
  56189. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56190. {
  56191. break;
  56192. }
  56193. } while (numColumns < maximumNumColumns);
  56194. const int actualH = jmin (contentHeight, maxMenuH);
  56195. needsToScroll = contentHeight > actualH;
  56196. width = updateYPositions();
  56197. height = actualH + PopupMenuSettings::borderSize * 2;
  56198. }
  56199. int workOutBestSize (const int maxMenuW)
  56200. {
  56201. int totalW = 0;
  56202. contentHeight = 0;
  56203. int childNum = 0;
  56204. for (int col = 0; col < numColumns; ++col)
  56205. {
  56206. int i, colW = 50, colH = 0;
  56207. const int numChildren = jmin (getNumChildComponents() - childNum,
  56208. (getNumChildComponents() + numColumns - 1) / numColumns);
  56209. for (i = numChildren; --i >= 0;)
  56210. {
  56211. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56212. colH += getChildComponent (childNum + i)->getHeight();
  56213. }
  56214. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56215. columnWidths.set (col, colW);
  56216. totalW += colW;
  56217. contentHeight = jmax (contentHeight, colH);
  56218. childNum += numChildren;
  56219. }
  56220. if (totalW < minimumWidth)
  56221. {
  56222. totalW = minimumWidth;
  56223. for (int col = 0; col < numColumns; ++col)
  56224. columnWidths.set (0, totalW / numColumns);
  56225. }
  56226. return totalW;
  56227. }
  56228. void ensureItemIsVisible (const int itemId, int wantedY)
  56229. {
  56230. jassert (itemId != 0)
  56231. for (int i = getNumChildComponents(); --i >= 0;)
  56232. {
  56233. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56234. if (m != 0
  56235. && m->itemInfo.itemId == itemId
  56236. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56237. {
  56238. const int currentY = m->getY();
  56239. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56240. {
  56241. if (wantedY < 0)
  56242. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56243. jmax (PopupMenuSettings::scrollZone,
  56244. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56245. currentY);
  56246. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56247. int deltaY = wantedY - currentY;
  56248. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56249. jmin (windowPos.getHeight(), mon.getHeight()));
  56250. const int newY = jlimit (mon.getY(),
  56251. mon.getBottom() - windowPos.getHeight(),
  56252. windowPos.getY() + deltaY);
  56253. deltaY -= newY - windowPos.getY();
  56254. childYOffset -= deltaY;
  56255. windowPos.setPosition (windowPos.getX(), newY);
  56256. updateYPositions();
  56257. }
  56258. break;
  56259. }
  56260. }
  56261. }
  56262. void resizeToBestWindowPos()
  56263. {
  56264. Rectangle<int> r (windowPos);
  56265. if (childYOffset < 0)
  56266. {
  56267. r.setBounds (r.getX(), r.getY() - childYOffset,
  56268. r.getWidth(), r.getHeight() + childYOffset);
  56269. }
  56270. else if (childYOffset > 0)
  56271. {
  56272. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56273. if (spaceAtBottom > 0)
  56274. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56275. }
  56276. setBounds (r);
  56277. updateYPositions();
  56278. }
  56279. void alterChildYPos (const int delta)
  56280. {
  56281. if (isScrolling())
  56282. {
  56283. childYOffset += delta;
  56284. if (delta < 0)
  56285. {
  56286. childYOffset = jmax (childYOffset, 0);
  56287. }
  56288. else if (delta > 0)
  56289. {
  56290. childYOffset = jmin (childYOffset,
  56291. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56292. }
  56293. updateYPositions();
  56294. }
  56295. else
  56296. {
  56297. childYOffset = 0;
  56298. }
  56299. resizeToBestWindowPos();
  56300. repaint();
  56301. }
  56302. int updateYPositions()
  56303. {
  56304. int x = 0;
  56305. int childNum = 0;
  56306. for (int col = 0; col < numColumns; ++col)
  56307. {
  56308. const int numChildren = jmin (getNumChildComponents() - childNum,
  56309. (getNumChildComponents() + numColumns - 1) / numColumns);
  56310. const int colW = columnWidths [col];
  56311. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56312. for (int i = 0; i < numChildren; ++i)
  56313. {
  56314. Component* const c = getChildComponent (childNum + i);
  56315. c->setBounds (x, y, colW, c->getHeight());
  56316. y += c->getHeight();
  56317. }
  56318. x += colW;
  56319. childNum += numChildren;
  56320. }
  56321. return x;
  56322. }
  56323. bool isScrolling() const throw()
  56324. {
  56325. return childYOffset != 0 || needsToScroll;
  56326. }
  56327. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56328. {
  56329. if (currentChild->isValidComponent())
  56330. currentChild->setHighlighted (false);
  56331. currentChild = child;
  56332. if (currentChild != 0)
  56333. {
  56334. currentChild->setHighlighted (true);
  56335. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56336. }
  56337. }
  56338. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56339. {
  56340. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56341. activeSubMenu = 0;
  56342. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56343. {
  56344. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56345. dismissOnMouseUp,
  56346. this,
  56347. childComp->getScreenBounds(),
  56348. 0, maximumNumColumns,
  56349. standardItemHeight,
  56350. false, 0, managerOfChosenCommand,
  56351. componentAttachedTo);
  56352. if (activeSubMenu != 0)
  56353. {
  56354. activeSubMenu->setVisible (true);
  56355. activeSubMenu->enterModalState (false);
  56356. activeSubMenu->toFront (false);
  56357. return true;
  56358. }
  56359. }
  56360. return false;
  56361. }
  56362. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56363. {
  56364. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56365. if (isOver)
  56366. hasBeenOver = true;
  56367. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56368. {
  56369. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56370. if (disableMouseMoves && isOver)
  56371. disableMouseMoves = false;
  56372. }
  56373. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56374. return;
  56375. bool isMovingTowardsMenu = false;
  56376. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56377. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56378. {
  56379. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56380. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56381. // extends from the last mouse pos to the submenu's rectangle..
  56382. float subX = (float) activeSubMenu->getScreenX();
  56383. if (activeSubMenu->getX() > getX())
  56384. {
  56385. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56386. }
  56387. else
  56388. {
  56389. lastMouse += Point<int> (2, 0);
  56390. subX += activeSubMenu->getWidth();
  56391. }
  56392. Path areaTowardsSubMenu;
  56393. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56394. (float) lastMouse.getY(),
  56395. subX,
  56396. (float) activeSubMenu->getScreenY(),
  56397. subX,
  56398. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56399. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56400. }
  56401. lastMouse = globalMousePos;
  56402. if (! isMovingTowardsMenu)
  56403. {
  56404. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56405. if (c == this)
  56406. c = 0;
  56407. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56408. if (mic == 0 && c != 0)
  56409. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56410. if (mic != currentChild
  56411. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56412. {
  56413. if (isOver && (c != 0) && (activeSubMenu != 0))
  56414. {
  56415. activeSubMenu->hide (0);
  56416. }
  56417. if (! isOver)
  56418. mic = 0;
  56419. setCurrentlyHighlightedChild (mic);
  56420. }
  56421. }
  56422. }
  56423. void triggerCurrentlyHighlightedItem()
  56424. {
  56425. if (currentChild->isValidComponent()
  56426. && currentChild->itemInfo.canBeTriggered()
  56427. && (currentChild->itemInfo.customComp == 0
  56428. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56429. {
  56430. dismissMenu (&currentChild->itemInfo);
  56431. }
  56432. }
  56433. void selectNextItem (const int delta)
  56434. {
  56435. disableTimerUntilMouseMoves();
  56436. PopupMenu::ItemComponent* mic = 0;
  56437. bool wasLastOne = (currentChild == 0);
  56438. const int numItems = getNumChildComponents();
  56439. for (int i = 0; i < numItems + 1; ++i)
  56440. {
  56441. int index = (delta > 0) ? i : (numItems - 1 - i);
  56442. index = (index + numItems) % numItems;
  56443. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56444. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56445. && wasLastOne)
  56446. break;
  56447. if (mic == currentChild)
  56448. wasLastOne = true;
  56449. }
  56450. setCurrentlyHighlightedChild (mic);
  56451. }
  56452. void disableTimerUntilMouseMoves()
  56453. {
  56454. disableMouseMoves = true;
  56455. if (owner != 0)
  56456. owner->disableTimerUntilMouseMoves();
  56457. }
  56458. Window (const Window&);
  56459. Window& operator= (const Window&);
  56460. };
  56461. PopupMenu::PopupMenu()
  56462. : lookAndFeel (0),
  56463. separatorPending (false)
  56464. {
  56465. }
  56466. PopupMenu::PopupMenu (const PopupMenu& other)
  56467. : lookAndFeel (other.lookAndFeel),
  56468. separatorPending (false)
  56469. {
  56470. items.addCopiesOf (other.items);
  56471. }
  56472. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56473. {
  56474. if (this != &other)
  56475. {
  56476. lookAndFeel = other.lookAndFeel;
  56477. clear();
  56478. items.addCopiesOf (other.items);
  56479. }
  56480. return *this;
  56481. }
  56482. PopupMenu::~PopupMenu()
  56483. {
  56484. clear();
  56485. }
  56486. void PopupMenu::clear()
  56487. {
  56488. items.clear();
  56489. separatorPending = false;
  56490. }
  56491. void PopupMenu::addSeparatorIfPending()
  56492. {
  56493. if (separatorPending)
  56494. {
  56495. separatorPending = false;
  56496. if (items.size() > 0)
  56497. items.add (new Item());
  56498. }
  56499. }
  56500. void PopupMenu::addItem (const int itemResultId,
  56501. const String& itemText,
  56502. const bool isActive,
  56503. const bool isTicked,
  56504. const Image& iconToUse)
  56505. {
  56506. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56507. // didn't pick anything, so you shouldn't use it as the id
  56508. // for an item..
  56509. addSeparatorIfPending();
  56510. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56511. Colours::black, false, 0, 0, 0));
  56512. }
  56513. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56514. const int commandID,
  56515. const String& displayName)
  56516. {
  56517. jassert (commandManager != 0 && commandID != 0);
  56518. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56519. if (registeredInfo != 0)
  56520. {
  56521. ApplicationCommandInfo info (*registeredInfo);
  56522. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56523. addSeparatorIfPending();
  56524. items.add (new Item (commandID,
  56525. displayName.isNotEmpty() ? displayName
  56526. : info.shortName,
  56527. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56528. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56529. Image::null,
  56530. Colours::black,
  56531. false,
  56532. 0, 0,
  56533. commandManager));
  56534. }
  56535. }
  56536. void PopupMenu::addColouredItem (const int itemResultId,
  56537. const String& itemText,
  56538. const Colour& itemTextColour,
  56539. const bool isActive,
  56540. const bool isTicked,
  56541. const Image& iconToUse)
  56542. {
  56543. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56544. // didn't pick anything, so you shouldn't use it as the id
  56545. // for an item..
  56546. addSeparatorIfPending();
  56547. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56548. itemTextColour, true, 0, 0, 0));
  56549. }
  56550. void PopupMenu::addCustomItem (const int itemResultId,
  56551. PopupMenuCustomComponent* const customComponent)
  56552. {
  56553. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56554. // didn't pick anything, so you shouldn't use it as the id
  56555. // for an item..
  56556. addSeparatorIfPending();
  56557. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56558. Colours::black, false, customComponent, 0, 0));
  56559. }
  56560. class NormalComponentWrapper : public PopupMenuCustomComponent
  56561. {
  56562. public:
  56563. NormalComponentWrapper (Component* const comp,
  56564. const int w, const int h,
  56565. const bool triggerMenuItemAutomaticallyWhenClicked)
  56566. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56567. width (w),
  56568. height (h)
  56569. {
  56570. addAndMakeVisible (comp);
  56571. }
  56572. ~NormalComponentWrapper() {}
  56573. void getIdealSize (int& idealWidth, int& idealHeight)
  56574. {
  56575. idealWidth = width;
  56576. idealHeight = height;
  56577. }
  56578. void resized()
  56579. {
  56580. if (getChildComponent(0) != 0)
  56581. getChildComponent(0)->setBounds (getLocalBounds());
  56582. }
  56583. juce_UseDebuggingNewOperator
  56584. private:
  56585. const int width, height;
  56586. NormalComponentWrapper (const NormalComponentWrapper&);
  56587. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56588. };
  56589. void PopupMenu::addCustomItem (const int itemResultId,
  56590. Component* customComponent,
  56591. int idealWidth, int idealHeight,
  56592. const bool triggerMenuItemAutomaticallyWhenClicked)
  56593. {
  56594. addCustomItem (itemResultId,
  56595. new NormalComponentWrapper (customComponent,
  56596. idealWidth, idealHeight,
  56597. triggerMenuItemAutomaticallyWhenClicked));
  56598. }
  56599. void PopupMenu::addSubMenu (const String& subMenuName,
  56600. const PopupMenu& subMenu,
  56601. const bool isActive,
  56602. const Image& iconToUse,
  56603. const bool isTicked)
  56604. {
  56605. addSeparatorIfPending();
  56606. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56607. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56608. }
  56609. void PopupMenu::addSeparator()
  56610. {
  56611. separatorPending = true;
  56612. }
  56613. class HeaderItemComponent : public PopupMenuCustomComponent
  56614. {
  56615. public:
  56616. HeaderItemComponent (const String& name)
  56617. : PopupMenuCustomComponent (false)
  56618. {
  56619. setName (name);
  56620. }
  56621. ~HeaderItemComponent()
  56622. {
  56623. }
  56624. void paint (Graphics& g)
  56625. {
  56626. Font f (getLookAndFeel().getPopupMenuFont());
  56627. f.setBold (true);
  56628. g.setFont (f);
  56629. g.setColour (findColour (PopupMenu::headerTextColourId));
  56630. g.drawFittedText (getName(),
  56631. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56632. Justification::bottomLeft, 1);
  56633. }
  56634. void getIdealSize (int& idealWidth,
  56635. int& idealHeight)
  56636. {
  56637. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56638. idealHeight += idealHeight / 2;
  56639. idealWidth += idealWidth / 4;
  56640. }
  56641. juce_UseDebuggingNewOperator
  56642. };
  56643. void PopupMenu::addSectionHeader (const String& title)
  56644. {
  56645. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56646. }
  56647. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56648. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56649. {
  56650. public:
  56651. PopupMenuCompletionCallback()
  56652. : managerOfChosenCommand (0)
  56653. {
  56654. }
  56655. ~PopupMenuCompletionCallback() {}
  56656. void modalStateFinished (int result)
  56657. {
  56658. if (managerOfChosenCommand != 0 && result != 0)
  56659. {
  56660. ApplicationCommandTarget::InvocationInfo info (result);
  56661. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56662. managerOfChosenCommand->invoke (info, true);
  56663. }
  56664. }
  56665. ApplicationCommandManager* managerOfChosenCommand;
  56666. ScopedPointer<Component> component;
  56667. private:
  56668. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56669. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56670. };
  56671. int PopupMenu::showMenu (const Rectangle<int>& target,
  56672. const int itemIdThatMustBeVisible,
  56673. const int minimumWidth,
  56674. const int maximumNumColumns,
  56675. const int standardItemHeight,
  56676. const bool alignToRectangle,
  56677. Component* const componentAttachedTo,
  56678. ModalComponentManager::Callback* userCallback)
  56679. {
  56680. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56681. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56682. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56683. Window::wasHiddenBecauseOfAppChange() = false;
  56684. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56685. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56686. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56687. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56688. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56689. &callback->managerOfChosenCommand, componentAttachedTo);
  56690. if (callback->component == 0)
  56691. return 0;
  56692. callbackDeleter.release();
  56693. callback->component->enterModalState (false, userCallbackDeleter.release());
  56694. callback->component->toFront (false); // need to do this after making it modal, or it could
  56695. // be stuck behind other comps that are already modal..
  56696. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56697. if (userCallback != 0)
  56698. return 0;
  56699. const int result = callback->component->runModalLoop();
  56700. if (! Window::wasHiddenBecauseOfAppChange())
  56701. {
  56702. if (prevTopLevel != 0)
  56703. prevTopLevel->toFront (true);
  56704. if (prevFocused != 0)
  56705. prevFocused->grabKeyboardFocus();
  56706. }
  56707. return result;
  56708. }
  56709. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56710. const int minimumWidth,
  56711. const int maximumNumColumns,
  56712. const int standardItemHeight,
  56713. ModalComponentManager::Callback* callback)
  56714. {
  56715. const Point<int> mousePos (Desktop::getMousePosition());
  56716. return showAt (mousePos.getX(), mousePos.getY(),
  56717. itemIdThatMustBeVisible,
  56718. minimumWidth,
  56719. maximumNumColumns,
  56720. standardItemHeight,
  56721. callback);
  56722. }
  56723. int PopupMenu::showAt (const int screenX,
  56724. const int screenY,
  56725. const int itemIdThatMustBeVisible,
  56726. const int minimumWidth,
  56727. const int maximumNumColumns,
  56728. const int standardItemHeight,
  56729. ModalComponentManager::Callback* callback)
  56730. {
  56731. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56732. itemIdThatMustBeVisible,
  56733. minimumWidth, maximumNumColumns,
  56734. standardItemHeight,
  56735. false, 0, callback);
  56736. }
  56737. int PopupMenu::showAt (Component* componentToAttachTo,
  56738. const int itemIdThatMustBeVisible,
  56739. const int minimumWidth,
  56740. const int maximumNumColumns,
  56741. const int standardItemHeight,
  56742. ModalComponentManager::Callback* callback)
  56743. {
  56744. if (componentToAttachTo != 0)
  56745. {
  56746. return showMenu (componentToAttachTo->getScreenBounds(),
  56747. itemIdThatMustBeVisible,
  56748. minimumWidth,
  56749. maximumNumColumns,
  56750. standardItemHeight,
  56751. true, componentToAttachTo, callback);
  56752. }
  56753. else
  56754. {
  56755. return show (itemIdThatMustBeVisible,
  56756. minimumWidth,
  56757. maximumNumColumns,
  56758. standardItemHeight,
  56759. callback);
  56760. }
  56761. }
  56762. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56763. {
  56764. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56765. {
  56766. Window* const pmw = Window::getActiveWindows()[i];
  56767. if (pmw != 0)
  56768. pmw->dismissMenu (0);
  56769. }
  56770. }
  56771. int PopupMenu::getNumItems() const throw()
  56772. {
  56773. int num = 0;
  56774. for (int i = items.size(); --i >= 0;)
  56775. if (! (items.getUnchecked(i))->isSeparator)
  56776. ++num;
  56777. return num;
  56778. }
  56779. bool PopupMenu::containsCommandItem (const int commandID) const
  56780. {
  56781. for (int i = items.size(); --i >= 0;)
  56782. {
  56783. const Item* mi = items.getUnchecked (i);
  56784. if ((mi->itemId == commandID && mi->commandManager != 0)
  56785. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56786. {
  56787. return true;
  56788. }
  56789. }
  56790. return false;
  56791. }
  56792. bool PopupMenu::containsAnyActiveItems() const throw()
  56793. {
  56794. for (int i = items.size(); --i >= 0;)
  56795. {
  56796. const Item* const mi = items.getUnchecked (i);
  56797. if (mi->subMenu != 0)
  56798. {
  56799. if (mi->subMenu->containsAnyActiveItems())
  56800. return true;
  56801. }
  56802. else if (mi->active)
  56803. {
  56804. return true;
  56805. }
  56806. }
  56807. return false;
  56808. }
  56809. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56810. {
  56811. lookAndFeel = newLookAndFeel;
  56812. }
  56813. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56814. : isHighlighted (false),
  56815. isTriggeredAutomatically (isTriggeredAutomatically_)
  56816. {
  56817. }
  56818. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56819. {
  56820. }
  56821. void PopupMenuCustomComponent::triggerMenuItem()
  56822. {
  56823. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56824. if (mic != 0)
  56825. {
  56826. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56827. if (pmw != 0)
  56828. {
  56829. pmw->dismissMenu (&mic->itemInfo);
  56830. }
  56831. else
  56832. {
  56833. // something must have gone wrong with the component hierarchy if this happens..
  56834. jassertfalse;
  56835. }
  56836. }
  56837. else
  56838. {
  56839. // why isn't this component inside a menu? Not much point triggering the item if
  56840. // there's no menu.
  56841. jassertfalse;
  56842. }
  56843. }
  56844. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56845. : subMenu (0),
  56846. itemId (0),
  56847. isSeparator (false),
  56848. isTicked (false),
  56849. isEnabled (false),
  56850. isCustomComponent (false),
  56851. isSectionHeader (false),
  56852. customColour (0),
  56853. customImage (0),
  56854. menu (menu_),
  56855. index (0)
  56856. {
  56857. }
  56858. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56859. {
  56860. }
  56861. bool PopupMenu::MenuItemIterator::next()
  56862. {
  56863. if (index >= menu.items.size())
  56864. return false;
  56865. const Item* const item = menu.items.getUnchecked (index);
  56866. ++index;
  56867. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56868. subMenu = item->subMenu;
  56869. itemId = item->itemId;
  56870. isSeparator = item->isSeparator;
  56871. isTicked = item->isTicked;
  56872. isEnabled = item->active;
  56873. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56874. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56875. customColour = item->usesColour ? &(item->textColour) : 0;
  56876. customImage = item->image;
  56877. commandManager = item->commandManager;
  56878. return true;
  56879. }
  56880. END_JUCE_NAMESPACE
  56881. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56882. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56883. BEGIN_JUCE_NAMESPACE
  56884. ComponentDragger::ComponentDragger()
  56885. : constrainer (0)
  56886. {
  56887. }
  56888. ComponentDragger::~ComponentDragger()
  56889. {
  56890. }
  56891. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56892. ComponentBoundsConstrainer* const constrainer_)
  56893. {
  56894. jassert (componentToDrag->isValidComponent());
  56895. if (componentToDrag != 0)
  56896. {
  56897. constrainer = constrainer_;
  56898. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56899. }
  56900. }
  56901. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56902. {
  56903. jassert (componentToDrag->isValidComponent());
  56904. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56905. if (componentToDrag != 0)
  56906. {
  56907. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56908. const Component* const parentComp = componentToDrag->getParentComponent();
  56909. if (parentComp != 0)
  56910. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56911. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56912. if (constrainer != 0)
  56913. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56914. else
  56915. componentToDrag->setBounds (bounds);
  56916. }
  56917. }
  56918. END_JUCE_NAMESPACE
  56919. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56920. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56921. BEGIN_JUCE_NAMESPACE
  56922. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56923. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56924. class DragImageComponent : public Component,
  56925. public Timer
  56926. {
  56927. public:
  56928. DragImageComponent (const Image& im,
  56929. const String& desc,
  56930. Component* const sourceComponent,
  56931. Component* const mouseDragSource_,
  56932. DragAndDropContainer* const o,
  56933. const Point<int>& imageOffset_)
  56934. : image (im),
  56935. source (sourceComponent),
  56936. mouseDragSource (mouseDragSource_),
  56937. owner (o),
  56938. dragDesc (desc),
  56939. imageOffset (imageOffset_),
  56940. hasCheckedForExternalDrag (false),
  56941. drawImage (true)
  56942. {
  56943. setSize (im.getWidth(), im.getHeight());
  56944. if (mouseDragSource == 0)
  56945. mouseDragSource = source;
  56946. mouseDragSource->addMouseListener (this, false);
  56947. startTimer (200);
  56948. setInterceptsMouseClicks (false, false);
  56949. setAlwaysOnTop (true);
  56950. }
  56951. ~DragImageComponent()
  56952. {
  56953. if (owner->dragImageComponent == this)
  56954. owner->dragImageComponent.release();
  56955. if (mouseDragSource != 0)
  56956. {
  56957. mouseDragSource->removeMouseListener (this);
  56958. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56959. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56960. }
  56961. }
  56962. void paint (Graphics& g)
  56963. {
  56964. if (isOpaque())
  56965. g.fillAll (Colours::white);
  56966. if (drawImage)
  56967. {
  56968. g.setOpacity (1.0f);
  56969. g.drawImageAt (image, 0, 0);
  56970. }
  56971. }
  56972. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56973. {
  56974. Component* hit = getParentComponent();
  56975. if (hit == 0)
  56976. {
  56977. hit = Desktop::getInstance().findComponentAt (screenPos);
  56978. }
  56979. else
  56980. {
  56981. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56982. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56983. }
  56984. // (note: use a local copy of the dragDesc member in case the callback runs
  56985. // a modal loop and deletes this object before the method completes)
  56986. const String dragDescLocal (dragDesc);
  56987. while (hit != 0)
  56988. {
  56989. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56990. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56991. {
  56992. relativePos = hit->globalPositionToRelative (screenPos);
  56993. return ddt;
  56994. }
  56995. hit = hit->getParentComponent();
  56996. }
  56997. return 0;
  56998. }
  56999. void mouseUp (const MouseEvent& e)
  57000. {
  57001. if (e.originalComponent != this)
  57002. {
  57003. if (mouseDragSource != 0)
  57004. mouseDragSource->removeMouseListener (this);
  57005. bool dropAccepted = false;
  57006. DragAndDropTarget* ddt = 0;
  57007. Point<int> relPos;
  57008. if (isVisible())
  57009. {
  57010. setVisible (false);
  57011. ddt = findTarget (e.getScreenPosition(), relPos);
  57012. // fade this component and remove it - it'll be deleted later by the timer callback
  57013. dropAccepted = ddt != 0;
  57014. setVisible (true);
  57015. if (dropAccepted || source == 0)
  57016. {
  57017. fadeOutComponent (120);
  57018. }
  57019. else
  57020. {
  57021. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  57022. source->getHeight() / 2)));
  57023. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  57024. getHeight() / 2)));
  57025. fadeOutComponent (120,
  57026. target.getX() - ourCentre.getX(),
  57027. target.getY() - ourCentre.getY());
  57028. }
  57029. }
  57030. if (getParentComponent() != 0)
  57031. getParentComponent()->removeChildComponent (this);
  57032. if (dropAccepted && ddt != 0)
  57033. {
  57034. // (note: use a local copy of the dragDesc member in case the callback runs
  57035. // a modal loop and deletes this object before the method completes)
  57036. const String dragDescLocal (dragDesc);
  57037. currentlyOverComp = 0;
  57038. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57039. }
  57040. // careful - this object could now be deleted..
  57041. }
  57042. }
  57043. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57044. {
  57045. // (note: use a local copy of the dragDesc member in case the callback runs
  57046. // a modal loop and deletes this object before it returns)
  57047. const String dragDescLocal (dragDesc);
  57048. Point<int> newPos (screenPos + imageOffset);
  57049. if (getParentComponent() != 0)
  57050. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57051. //if (newX != getX() || newY != getY())
  57052. {
  57053. setTopLeftPosition (newPos.getX(), newPos.getY());
  57054. Point<int> relPos;
  57055. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57056. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57057. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57058. if (ddtComp != currentlyOverComp)
  57059. {
  57060. if (currentlyOverComp != 0 && source != 0
  57061. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57062. {
  57063. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57064. }
  57065. currentlyOverComp = ddtComp;
  57066. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57067. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57068. }
  57069. DragAndDropTarget* target = getCurrentlyOver();
  57070. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57071. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57072. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57073. {
  57074. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57075. {
  57076. hasCheckedForExternalDrag = true;
  57077. StringArray files;
  57078. bool canMoveFiles = false;
  57079. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57080. && files.size() > 0)
  57081. {
  57082. Component::SafePointer<Component> cdw (this);
  57083. setVisible (false);
  57084. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57085. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57086. if (cdw != 0)
  57087. delete this;
  57088. return;
  57089. }
  57090. }
  57091. }
  57092. }
  57093. }
  57094. void mouseDrag (const MouseEvent& e)
  57095. {
  57096. if (e.originalComponent != this)
  57097. updateLocation (true, e.getScreenPosition());
  57098. }
  57099. void timerCallback()
  57100. {
  57101. if (source == 0)
  57102. {
  57103. delete this;
  57104. }
  57105. else if (! isMouseButtonDownAnywhere())
  57106. {
  57107. if (mouseDragSource != 0)
  57108. mouseDragSource->removeMouseListener (this);
  57109. delete this;
  57110. }
  57111. }
  57112. private:
  57113. Image image;
  57114. Component::SafePointer<Component> source;
  57115. Component::SafePointer<Component> mouseDragSource;
  57116. DragAndDropContainer* const owner;
  57117. Component::SafePointer<Component> currentlyOverComp;
  57118. DragAndDropTarget* getCurrentlyOver()
  57119. {
  57120. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57121. }
  57122. String dragDesc;
  57123. const Point<int> imageOffset;
  57124. bool hasCheckedForExternalDrag, drawImage;
  57125. DragImageComponent (const DragImageComponent&);
  57126. DragImageComponent& operator= (const DragImageComponent&);
  57127. };
  57128. DragAndDropContainer::DragAndDropContainer()
  57129. {
  57130. }
  57131. DragAndDropContainer::~DragAndDropContainer()
  57132. {
  57133. dragImageComponent = 0;
  57134. }
  57135. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57136. Component* sourceComponent,
  57137. const Image& dragImage_,
  57138. const bool allowDraggingToExternalWindows,
  57139. const Point<int>* imageOffsetFromMouse)
  57140. {
  57141. Image dragImage (dragImage_);
  57142. if (dragImageComponent == 0)
  57143. {
  57144. Component* const thisComp = dynamic_cast <Component*> (this);
  57145. if (thisComp == 0)
  57146. {
  57147. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57148. return;
  57149. }
  57150. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57151. if (draggingSource == 0 || ! draggingSource->isDragging())
  57152. {
  57153. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57154. return;
  57155. }
  57156. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57157. Point<int> imageOffset;
  57158. if (dragImage.isNull())
  57159. {
  57160. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57161. .convertedToFormat (Image::ARGB);
  57162. dragImage.multiplyAllAlphas (0.6f);
  57163. const int lo = 150;
  57164. const int hi = 400;
  57165. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57166. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57167. for (int y = dragImage.getHeight(); --y >= 0;)
  57168. {
  57169. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57170. for (int x = dragImage.getWidth(); --x >= 0;)
  57171. {
  57172. const int dx = x - clipped.getX();
  57173. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57174. if (distance > lo)
  57175. {
  57176. const float alpha = (distance > hi) ? 0
  57177. : (hi - distance) / (float) (hi - lo)
  57178. + Random::getSystemRandom().nextFloat() * 0.008f;
  57179. dragImage.multiplyAlphaAt (x, y, alpha);
  57180. }
  57181. }
  57182. }
  57183. imageOffset = -clipped;
  57184. }
  57185. else
  57186. {
  57187. if (imageOffsetFromMouse == 0)
  57188. imageOffset = -dragImage.getBounds().getCentre();
  57189. else
  57190. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57191. }
  57192. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57193. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57194. currentDragDesc = sourceDescription;
  57195. if (allowDraggingToExternalWindows)
  57196. {
  57197. if (! Desktop::canUseSemiTransparentWindows())
  57198. dragImageComponent->setOpaque (true);
  57199. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57200. | ComponentPeer::windowIsTemporary
  57201. | ComponentPeer::windowIgnoresKeyPresses);
  57202. }
  57203. else
  57204. thisComp->addChildComponent (dragImageComponent);
  57205. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57206. dragImageComponent->setVisible (true);
  57207. }
  57208. }
  57209. bool DragAndDropContainer::isDragAndDropActive() const
  57210. {
  57211. return dragImageComponent != 0;
  57212. }
  57213. const String DragAndDropContainer::getCurrentDragDescription() const
  57214. {
  57215. return (dragImageComponent != 0) ? currentDragDesc
  57216. : String::empty;
  57217. }
  57218. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57219. {
  57220. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57221. }
  57222. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57223. {
  57224. return false;
  57225. }
  57226. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57227. {
  57228. }
  57229. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57230. {
  57231. }
  57232. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57233. {
  57234. }
  57235. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57236. {
  57237. return true;
  57238. }
  57239. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57240. {
  57241. }
  57242. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57243. {
  57244. }
  57245. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57246. {
  57247. }
  57248. END_JUCE_NAMESPACE
  57249. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57250. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57251. BEGIN_JUCE_NAMESPACE
  57252. class MouseCursor::SharedCursorHandle
  57253. {
  57254. public:
  57255. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57256. : handle (createStandardMouseCursor (type)),
  57257. refCount (1),
  57258. standardType (type),
  57259. isStandard (true)
  57260. {
  57261. }
  57262. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57263. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57264. refCount (1),
  57265. standardType (MouseCursor::NormalCursor),
  57266. isStandard (false)
  57267. {
  57268. }
  57269. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57270. {
  57271. const ScopedLock sl (getLock());
  57272. for (int i = 0; i < getCursors().size(); ++i)
  57273. {
  57274. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57275. if (sc->standardType == type)
  57276. return sc->retain();
  57277. }
  57278. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57279. getCursors().add (sc);
  57280. return sc;
  57281. }
  57282. SharedCursorHandle* retain() throw()
  57283. {
  57284. ++refCount;
  57285. return this;
  57286. }
  57287. void release()
  57288. {
  57289. if (--refCount == 0)
  57290. {
  57291. if (isStandard)
  57292. {
  57293. const ScopedLock sl (getLock());
  57294. getCursors().removeValue (this);
  57295. }
  57296. delete this;
  57297. }
  57298. }
  57299. void* getHandle() const throw() { return handle; }
  57300. juce_UseDebuggingNewOperator
  57301. private:
  57302. void* const handle;
  57303. Atomic <int> refCount;
  57304. const MouseCursor::StandardCursorType standardType;
  57305. const bool isStandard;
  57306. static CriticalSection& getLock()
  57307. {
  57308. static CriticalSection lock;
  57309. return lock;
  57310. }
  57311. static Array <SharedCursorHandle*>& getCursors()
  57312. {
  57313. static Array <SharedCursorHandle*> cursors;
  57314. return cursors;
  57315. }
  57316. ~SharedCursorHandle()
  57317. {
  57318. deleteMouseCursor (handle, isStandard);
  57319. }
  57320. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57321. };
  57322. MouseCursor::MouseCursor()
  57323. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57324. {
  57325. jassert (cursorHandle != 0);
  57326. }
  57327. MouseCursor::MouseCursor (const StandardCursorType type)
  57328. : cursorHandle (SharedCursorHandle::createStandard (type))
  57329. {
  57330. jassert (cursorHandle != 0);
  57331. }
  57332. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57333. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57334. {
  57335. }
  57336. MouseCursor::MouseCursor (const MouseCursor& other)
  57337. : cursorHandle (other.cursorHandle->retain())
  57338. {
  57339. }
  57340. MouseCursor::~MouseCursor()
  57341. {
  57342. cursorHandle->release();
  57343. }
  57344. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57345. {
  57346. other.cursorHandle->retain();
  57347. cursorHandle->release();
  57348. cursorHandle = other.cursorHandle;
  57349. return *this;
  57350. }
  57351. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57352. {
  57353. return getHandle() == other.getHandle();
  57354. }
  57355. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57356. {
  57357. return getHandle() != other.getHandle();
  57358. }
  57359. void* MouseCursor::getHandle() const throw()
  57360. {
  57361. return cursorHandle->getHandle();
  57362. }
  57363. void MouseCursor::showWaitCursor()
  57364. {
  57365. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57366. }
  57367. void MouseCursor::hideWaitCursor()
  57368. {
  57369. Desktop::getInstance().getMainMouseSource().revealCursor();
  57370. }
  57371. END_JUCE_NAMESPACE
  57372. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57373. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57374. BEGIN_JUCE_NAMESPACE
  57375. MouseEvent::MouseEvent (MouseInputSource& source_,
  57376. const Point<int>& position,
  57377. const ModifierKeys& mods_,
  57378. Component* const eventComponent_,
  57379. Component* const originator,
  57380. const Time& eventTime_,
  57381. const Point<int> mouseDownPos_,
  57382. const Time& mouseDownTime_,
  57383. const int numberOfClicks_,
  57384. const bool mouseWasDragged) throw()
  57385. : x (position.getX()),
  57386. y (position.getY()),
  57387. mods (mods_),
  57388. eventComponent (eventComponent_),
  57389. originalComponent (originator),
  57390. eventTime (eventTime_),
  57391. source (source_),
  57392. mouseDownPos (mouseDownPos_),
  57393. mouseDownTime (mouseDownTime_),
  57394. numberOfClicks (numberOfClicks_),
  57395. wasMovedSinceMouseDown (mouseWasDragged)
  57396. {
  57397. }
  57398. MouseEvent::~MouseEvent() throw()
  57399. {
  57400. }
  57401. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57402. {
  57403. if (otherComponent == 0)
  57404. {
  57405. jassertfalse;
  57406. return *this;
  57407. }
  57408. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57409. mods, otherComponent, originalComponent, eventTime,
  57410. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57411. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57412. }
  57413. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57414. {
  57415. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57416. eventTime, mouseDownPos, mouseDownTime,
  57417. numberOfClicks, wasMovedSinceMouseDown);
  57418. }
  57419. bool MouseEvent::mouseWasClicked() const throw()
  57420. {
  57421. return ! wasMovedSinceMouseDown;
  57422. }
  57423. int MouseEvent::getMouseDownX() const throw()
  57424. {
  57425. return mouseDownPos.getX();
  57426. }
  57427. int MouseEvent::getMouseDownY() const throw()
  57428. {
  57429. return mouseDownPos.getY();
  57430. }
  57431. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57432. {
  57433. return mouseDownPos;
  57434. }
  57435. int MouseEvent::getDistanceFromDragStartX() const throw()
  57436. {
  57437. return x - mouseDownPos.getX();
  57438. }
  57439. int MouseEvent::getDistanceFromDragStartY() const throw()
  57440. {
  57441. return y - mouseDownPos.getY();
  57442. }
  57443. int MouseEvent::getDistanceFromDragStart() const throw()
  57444. {
  57445. return mouseDownPos.getDistanceFrom (getPosition());
  57446. }
  57447. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57448. {
  57449. return getPosition() - mouseDownPos;
  57450. }
  57451. int MouseEvent::getLengthOfMousePress() const throw()
  57452. {
  57453. if (mouseDownTime.toMilliseconds() > 0)
  57454. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57455. return 0;
  57456. }
  57457. const Point<int> MouseEvent::getPosition() const throw()
  57458. {
  57459. return Point<int> (x, y);
  57460. }
  57461. int MouseEvent::getScreenX() const
  57462. {
  57463. return getScreenPosition().getX();
  57464. }
  57465. int MouseEvent::getScreenY() const
  57466. {
  57467. return getScreenPosition().getY();
  57468. }
  57469. const Point<int> MouseEvent::getScreenPosition() const
  57470. {
  57471. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57472. }
  57473. int MouseEvent::getMouseDownScreenX() const
  57474. {
  57475. return getMouseDownScreenPosition().getX();
  57476. }
  57477. int MouseEvent::getMouseDownScreenY() const
  57478. {
  57479. return getMouseDownScreenPosition().getY();
  57480. }
  57481. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57482. {
  57483. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57484. }
  57485. int MouseEvent::doubleClickTimeOutMs = 400;
  57486. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57487. {
  57488. doubleClickTimeOutMs = newTime;
  57489. }
  57490. int MouseEvent::getDoubleClickTimeout() throw()
  57491. {
  57492. return doubleClickTimeOutMs;
  57493. }
  57494. END_JUCE_NAMESPACE
  57495. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57496. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57497. BEGIN_JUCE_NAMESPACE
  57498. class MouseInputSourceInternal : public AsyncUpdater
  57499. {
  57500. public:
  57501. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57502. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  57503. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57504. mouseEventCounter (0)
  57505. {
  57506. zerostruct (mouseDowns);
  57507. }
  57508. ~MouseInputSourceInternal()
  57509. {
  57510. }
  57511. bool isDragging() const throw()
  57512. {
  57513. return buttonState.isAnyMouseButtonDown();
  57514. }
  57515. Component* getComponentUnderMouse() const
  57516. {
  57517. return static_cast <Component*> (componentUnderMouse);
  57518. }
  57519. const ModifierKeys getCurrentModifiers() const
  57520. {
  57521. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57522. }
  57523. ComponentPeer* getPeer()
  57524. {
  57525. if (! ComponentPeer::isValidPeer (lastPeer))
  57526. lastPeer = 0;
  57527. return lastPeer;
  57528. }
  57529. Component* findComponentAt (const Point<int>& screenPos)
  57530. {
  57531. ComponentPeer* const peer = getPeer();
  57532. if (peer != 0)
  57533. {
  57534. Component* const comp = peer->getComponent();
  57535. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57536. // (the contains() call is needed to test for overlapping desktop windows)
  57537. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57538. return comp->getComponentAt (relativePos);
  57539. }
  57540. return 0;
  57541. }
  57542. const Point<int> getScreenPosition() const throw()
  57543. {
  57544. return lastScreenPos + unboundedMouseOffset;
  57545. }
  57546. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57547. {
  57548. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57549. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57550. }
  57551. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57552. {
  57553. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57554. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57555. }
  57556. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57557. {
  57558. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57559. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57560. }
  57561. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57562. {
  57563. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57564. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57565. }
  57566. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57567. {
  57568. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57569. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57570. }
  57571. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57572. {
  57573. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57574. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57575. }
  57576. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57577. {
  57578. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57579. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57580. }
  57581. // (returns true if the button change caused a modal event loop)
  57582. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57583. {
  57584. if (buttonState == newButtonState)
  57585. return false;
  57586. setScreenPos (screenPos, time, false);
  57587. // (ignore secondary clicks when there's already a button down)
  57588. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57589. {
  57590. buttonState = newButtonState;
  57591. return false;
  57592. }
  57593. const int lastCounter = mouseEventCounter;
  57594. if (buttonState.isAnyMouseButtonDown())
  57595. {
  57596. Component* const current = getComponentUnderMouse();
  57597. if (current != 0)
  57598. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57599. enableUnboundedMouseMovement (false, false);
  57600. }
  57601. buttonState = newButtonState;
  57602. if (buttonState.isAnyMouseButtonDown())
  57603. {
  57604. Desktop::getInstance().incrementMouseClickCounter();
  57605. Component* const current = getComponentUnderMouse();
  57606. if (current != 0)
  57607. {
  57608. registerMouseDown (screenPos, time, current);
  57609. sendMouseDown (current, screenPos, time);
  57610. }
  57611. }
  57612. return lastCounter != mouseEventCounter;
  57613. }
  57614. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57615. {
  57616. Component* current = getComponentUnderMouse();
  57617. if (newComponent != current)
  57618. {
  57619. Component::SafePointer<Component> safeNewComp (newComponent);
  57620. const ModifierKeys originalButtonState (buttonState);
  57621. if (current != 0)
  57622. {
  57623. setButtons (screenPos, time, ModifierKeys());
  57624. sendMouseExit (current, screenPos, time);
  57625. buttonState = originalButtonState;
  57626. }
  57627. componentUnderMouse = safeNewComp;
  57628. current = getComponentUnderMouse();
  57629. if (current != 0)
  57630. sendMouseEnter (current, screenPos, time);
  57631. revealCursor (false);
  57632. setButtons (screenPos, time, originalButtonState);
  57633. }
  57634. }
  57635. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57636. {
  57637. ModifierKeys::updateCurrentModifiers();
  57638. if (newPeer != lastPeer)
  57639. {
  57640. setComponentUnderMouse (0, screenPos, time);
  57641. lastPeer = newPeer;
  57642. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57643. }
  57644. }
  57645. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57646. {
  57647. if (! isDragging())
  57648. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57649. if (newScreenPos != lastScreenPos || forceUpdate)
  57650. {
  57651. cancelPendingUpdate();
  57652. lastScreenPos = newScreenPos;
  57653. Component* const current = getComponentUnderMouse();
  57654. if (current != 0)
  57655. {
  57656. if (isDragging())
  57657. {
  57658. registerMouseDrag (newScreenPos);
  57659. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57660. if (isUnboundedMouseModeOn)
  57661. handleUnboundedDrag (current);
  57662. }
  57663. else
  57664. {
  57665. sendMouseMove (current, newScreenPos, time);
  57666. }
  57667. }
  57668. revealCursor (false);
  57669. }
  57670. }
  57671. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57672. {
  57673. jassert (newPeer != 0);
  57674. lastTime = time;
  57675. ++mouseEventCounter;
  57676. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57677. if (isDragging() && newMods.isAnyMouseButtonDown())
  57678. {
  57679. setScreenPos (screenPos, time, false);
  57680. }
  57681. else
  57682. {
  57683. setPeer (newPeer, screenPos, time);
  57684. ComponentPeer* peer = getPeer();
  57685. if (peer != 0)
  57686. {
  57687. if (setButtons (screenPos, time, newMods))
  57688. return; // some modal events have been dispatched, so the current event is now out-of-date
  57689. peer = getPeer();
  57690. if (peer != 0)
  57691. setScreenPos (screenPos, time, false);
  57692. }
  57693. }
  57694. }
  57695. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57696. {
  57697. jassert (peer != 0);
  57698. lastTime = time;
  57699. ++mouseEventCounter;
  57700. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57701. setPeer (peer, screenPos, time);
  57702. setScreenPos (screenPos, time, false);
  57703. triggerFakeMove();
  57704. if (! isDragging())
  57705. {
  57706. Component* current = getComponentUnderMouse();
  57707. if (current != 0)
  57708. sendMouseWheel (current, screenPos, time, x, y);
  57709. }
  57710. }
  57711. const Time getLastMouseDownTime() const throw()
  57712. {
  57713. return Time (mouseDowns[0].time);
  57714. }
  57715. const Point<int> getLastMouseDownPosition() const throw()
  57716. {
  57717. return mouseDowns[0].position;
  57718. }
  57719. int getNumberOfMultipleClicks() const throw()
  57720. {
  57721. int numClicks = 0;
  57722. if (mouseDowns[0].time != 0)
  57723. {
  57724. if (! mouseMovedSignificantlySincePressed)
  57725. ++numClicks;
  57726. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57727. {
  57728. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57729. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57730. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57731. {
  57732. ++numClicks;
  57733. }
  57734. else
  57735. {
  57736. break;
  57737. }
  57738. }
  57739. }
  57740. return numClicks;
  57741. }
  57742. bool hasMouseMovedSignificantlySincePressed() const throw()
  57743. {
  57744. return mouseMovedSignificantlySincePressed
  57745. || lastTime > mouseDowns[0].time + 300;
  57746. }
  57747. void triggerFakeMove()
  57748. {
  57749. triggerAsyncUpdate();
  57750. }
  57751. void handleAsyncUpdate()
  57752. {
  57753. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57754. }
  57755. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57756. {
  57757. enable = enable && isDragging();
  57758. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57759. if (enable != isUnboundedMouseModeOn)
  57760. {
  57761. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57762. {
  57763. // when released, return the mouse to within the component's bounds
  57764. Component* current = getComponentUnderMouse();
  57765. if (current != 0)
  57766. Desktop::setMousePosition (current->getScreenBounds()
  57767. .getConstrainedPoint (lastScreenPos));
  57768. }
  57769. isUnboundedMouseModeOn = enable;
  57770. unboundedMouseOffset = Point<int>();
  57771. revealCursor (true);
  57772. }
  57773. }
  57774. void handleUnboundedDrag (Component* current)
  57775. {
  57776. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57777. if (! screenArea.contains (lastScreenPos))
  57778. {
  57779. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57780. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57781. Desktop::setMousePosition (componentCentre);
  57782. }
  57783. else if (isCursorVisibleUntilOffscreen
  57784. && (! unboundedMouseOffset.isOrigin())
  57785. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57786. {
  57787. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57788. unboundedMouseOffset = Point<int>();
  57789. }
  57790. }
  57791. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57792. {
  57793. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57794. {
  57795. cursor = MouseCursor::NoCursor;
  57796. forcedUpdate = true;
  57797. }
  57798. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57799. {
  57800. currentCursorHandle = cursor.getHandle();
  57801. cursor.showInWindow (getPeer());
  57802. }
  57803. }
  57804. void hideCursor()
  57805. {
  57806. showMouseCursor (MouseCursor::NoCursor, true);
  57807. }
  57808. void revealCursor (bool forcedUpdate)
  57809. {
  57810. MouseCursor mc (MouseCursor::NormalCursor);
  57811. Component* current = getComponentUnderMouse();
  57812. if (current != 0)
  57813. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57814. showMouseCursor (mc, forcedUpdate);
  57815. }
  57816. int index;
  57817. bool isMouseDevice;
  57818. Point<int> lastScreenPos;
  57819. ModifierKeys buttonState;
  57820. private:
  57821. MouseInputSource& source;
  57822. Component::SafePointer<Component> componentUnderMouse;
  57823. ComponentPeer* lastPeer;
  57824. Point<int> unboundedMouseOffset;
  57825. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57826. void* currentCursorHandle;
  57827. int mouseEventCounter;
  57828. struct RecentMouseDown
  57829. {
  57830. Point<int> position;
  57831. int64 time;
  57832. Component* component;
  57833. };
  57834. RecentMouseDown mouseDowns[4];
  57835. bool mouseMovedSignificantlySincePressed;
  57836. int64 lastTime;
  57837. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57838. {
  57839. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57840. mouseDowns[i] = mouseDowns[i - 1];
  57841. mouseDowns[0].position = screenPos;
  57842. mouseDowns[0].time = time;
  57843. mouseDowns[0].component = component;
  57844. mouseMovedSignificantlySincePressed = false;
  57845. }
  57846. void registerMouseDrag (const Point<int>& screenPos) throw()
  57847. {
  57848. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57849. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57850. }
  57851. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57852. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57853. };
  57854. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57855. {
  57856. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57857. }
  57858. MouseInputSource::~MouseInputSource()
  57859. {
  57860. }
  57861. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57862. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57863. bool MouseInputSource::canHover() const { return isMouse(); }
  57864. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57865. int MouseInputSource::getIndex() const { return pimpl->index; }
  57866. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57867. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57868. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57869. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57870. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57871. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57872. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57873. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57874. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57875. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57876. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57877. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57878. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57879. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57880. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57881. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57882. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57883. {
  57884. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57885. }
  57886. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57887. {
  57888. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57889. }
  57890. END_JUCE_NAMESPACE
  57891. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57892. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57893. BEGIN_JUCE_NAMESPACE
  57894. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57895. : source (0),
  57896. hoverTimeMillisecs (hoverTimeMillisecs_),
  57897. hasJustHovered (false)
  57898. {
  57899. internalTimer.owner = this;
  57900. }
  57901. MouseHoverDetector::~MouseHoverDetector()
  57902. {
  57903. setHoverComponent (0);
  57904. }
  57905. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57906. {
  57907. hoverTimeMillisecs = newTimeInMillisecs;
  57908. }
  57909. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57910. {
  57911. if (source != newSourceComponent)
  57912. {
  57913. internalTimer.stopTimer();
  57914. hasJustHovered = false;
  57915. if (source != 0)
  57916. {
  57917. // ! you need to delete the hover detector before deleting its component
  57918. jassert (source->isValidComponent());
  57919. source->removeMouseListener (&internalTimer);
  57920. }
  57921. source = newSourceComponent;
  57922. if (newSourceComponent != 0)
  57923. newSourceComponent->addMouseListener (&internalTimer, false);
  57924. }
  57925. }
  57926. void MouseHoverDetector::hoverTimerCallback()
  57927. {
  57928. internalTimer.stopTimer();
  57929. if (source != 0)
  57930. {
  57931. const Point<int> pos (source->getMouseXYRelative());
  57932. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57933. {
  57934. hasJustHovered = true;
  57935. mouseHovered (pos.getX(), pos.getY());
  57936. }
  57937. }
  57938. }
  57939. void MouseHoverDetector::checkJustHoveredCallback()
  57940. {
  57941. if (hasJustHovered)
  57942. {
  57943. hasJustHovered = false;
  57944. mouseMovedAfterHover();
  57945. }
  57946. }
  57947. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57948. {
  57949. owner->hoverTimerCallback();
  57950. }
  57951. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57952. {
  57953. stopTimer();
  57954. owner->checkJustHoveredCallback();
  57955. }
  57956. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57957. {
  57958. stopTimer();
  57959. owner->checkJustHoveredCallback();
  57960. }
  57961. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57962. {
  57963. stopTimer();
  57964. owner->checkJustHoveredCallback();
  57965. }
  57966. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57967. {
  57968. stopTimer();
  57969. owner->checkJustHoveredCallback();
  57970. }
  57971. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57972. {
  57973. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57974. {
  57975. lastX = e.x;
  57976. lastY = e.y;
  57977. if (owner->source != 0)
  57978. startTimer (owner->hoverTimeMillisecs);
  57979. owner->checkJustHoveredCallback();
  57980. }
  57981. }
  57982. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57983. {
  57984. stopTimer();
  57985. owner->checkJustHoveredCallback();
  57986. }
  57987. END_JUCE_NAMESPACE
  57988. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57989. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57990. BEGIN_JUCE_NAMESPACE
  57991. void MouseListener::mouseEnter (const MouseEvent&)
  57992. {
  57993. }
  57994. void MouseListener::mouseExit (const MouseEvent&)
  57995. {
  57996. }
  57997. void MouseListener::mouseDown (const MouseEvent&)
  57998. {
  57999. }
  58000. void MouseListener::mouseUp (const MouseEvent&)
  58001. {
  58002. }
  58003. void MouseListener::mouseDrag (const MouseEvent&)
  58004. {
  58005. }
  58006. void MouseListener::mouseMove (const MouseEvent&)
  58007. {
  58008. }
  58009. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58010. {
  58011. }
  58012. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58013. {
  58014. }
  58015. END_JUCE_NAMESPACE
  58016. /*** End of inlined file: juce_MouseListener.cpp ***/
  58017. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58018. BEGIN_JUCE_NAMESPACE
  58019. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58020. const String& buttonTextWhenTrue,
  58021. const String& buttonTextWhenFalse)
  58022. : PropertyComponent (name),
  58023. onText (buttonTextWhenTrue),
  58024. offText (buttonTextWhenFalse)
  58025. {
  58026. addAndMakeVisible (&button);
  58027. button.setClickingTogglesState (false);
  58028. button.addButtonListener (this);
  58029. }
  58030. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58031. const String& name,
  58032. const String& buttonText)
  58033. : PropertyComponent (name),
  58034. onText (buttonText),
  58035. offText (buttonText)
  58036. {
  58037. addAndMakeVisible (&button);
  58038. button.setClickingTogglesState (false);
  58039. button.setButtonText (buttonText);
  58040. button.getToggleStateValue().referTo (valueToControl);
  58041. button.setClickingTogglesState (true);
  58042. }
  58043. BooleanPropertyComponent::~BooleanPropertyComponent()
  58044. {
  58045. }
  58046. void BooleanPropertyComponent::setState (const bool newState)
  58047. {
  58048. button.setToggleState (newState, true);
  58049. }
  58050. bool BooleanPropertyComponent::getState() const
  58051. {
  58052. return button.getToggleState();
  58053. }
  58054. void BooleanPropertyComponent::paint (Graphics& g)
  58055. {
  58056. PropertyComponent::paint (g);
  58057. g.setColour (Colours::white);
  58058. g.fillRect (button.getBounds());
  58059. g.setColour (findColour (ComboBox::outlineColourId));
  58060. g.drawRect (button.getBounds());
  58061. }
  58062. void BooleanPropertyComponent::refresh()
  58063. {
  58064. button.setToggleState (getState(), false);
  58065. button.setButtonText (button.getToggleState() ? onText : offText);
  58066. }
  58067. void BooleanPropertyComponent::buttonClicked (Button*)
  58068. {
  58069. setState (! getState());
  58070. }
  58071. END_JUCE_NAMESPACE
  58072. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58073. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58074. BEGIN_JUCE_NAMESPACE
  58075. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58076. const bool triggerOnMouseDown)
  58077. : PropertyComponent (name)
  58078. {
  58079. addAndMakeVisible (&button);
  58080. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58081. button.addButtonListener (this);
  58082. }
  58083. ButtonPropertyComponent::~ButtonPropertyComponent()
  58084. {
  58085. }
  58086. void ButtonPropertyComponent::refresh()
  58087. {
  58088. button.setButtonText (getButtonText());
  58089. }
  58090. void ButtonPropertyComponent::buttonClicked (Button*)
  58091. {
  58092. buttonClicked();
  58093. }
  58094. END_JUCE_NAMESPACE
  58095. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58096. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58097. BEGIN_JUCE_NAMESPACE
  58098. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58099. public Value::Listener
  58100. {
  58101. public:
  58102. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58103. : sourceValue (sourceValue_),
  58104. mappings (mappings_)
  58105. {
  58106. sourceValue.addListener (this);
  58107. }
  58108. ~RemapperValueSource() {}
  58109. const var getValue() const
  58110. {
  58111. return mappings.indexOf (sourceValue.getValue()) + 1;
  58112. }
  58113. void setValue (const var& newValue)
  58114. {
  58115. const var remappedVal (mappings [(int) newValue - 1]);
  58116. if (remappedVal != sourceValue)
  58117. sourceValue = remappedVal;
  58118. }
  58119. void valueChanged (Value&)
  58120. {
  58121. sendChangeMessage (true);
  58122. }
  58123. juce_UseDebuggingNewOperator
  58124. protected:
  58125. Value sourceValue;
  58126. Array<var> mappings;
  58127. RemapperValueSource (const RemapperValueSource&);
  58128. const RemapperValueSource& operator= (const RemapperValueSource&);
  58129. };
  58130. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58131. : PropertyComponent (name),
  58132. isCustomClass (true)
  58133. {
  58134. }
  58135. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58136. const String& name,
  58137. const StringArray& choices_,
  58138. const Array <var>& correspondingValues)
  58139. : PropertyComponent (name),
  58140. choices (choices_),
  58141. isCustomClass (false)
  58142. {
  58143. // The array of corresponding values must contain one value for each of the items in
  58144. // the choices array!
  58145. jassert (correspondingValues.size() == choices.size());
  58146. createComboBox();
  58147. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58148. }
  58149. ChoicePropertyComponent::~ChoicePropertyComponent()
  58150. {
  58151. }
  58152. void ChoicePropertyComponent::createComboBox()
  58153. {
  58154. addAndMakeVisible (&comboBox);
  58155. for (int i = 0; i < choices.size(); ++i)
  58156. {
  58157. if (choices[i].isNotEmpty())
  58158. comboBox.addItem (choices[i], i + 1);
  58159. else
  58160. comboBox.addSeparator();
  58161. }
  58162. comboBox.setEditableText (false);
  58163. }
  58164. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58165. {
  58166. jassertfalse; // you need to override this method in your subclass!
  58167. }
  58168. int ChoicePropertyComponent::getIndex() const
  58169. {
  58170. jassertfalse; // you need to override this method in your subclass!
  58171. return -1;
  58172. }
  58173. const StringArray& ChoicePropertyComponent::getChoices() const
  58174. {
  58175. return choices;
  58176. }
  58177. void ChoicePropertyComponent::refresh()
  58178. {
  58179. if (isCustomClass)
  58180. {
  58181. if (! comboBox.isVisible())
  58182. {
  58183. createComboBox();
  58184. comboBox.addListener (this);
  58185. }
  58186. comboBox.setSelectedId (getIndex() + 1, true);
  58187. }
  58188. }
  58189. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58190. {
  58191. if (isCustomClass)
  58192. {
  58193. const int newIndex = comboBox.getSelectedId() - 1;
  58194. if (newIndex != getIndex())
  58195. setIndex (newIndex);
  58196. }
  58197. }
  58198. END_JUCE_NAMESPACE
  58199. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58200. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58201. BEGIN_JUCE_NAMESPACE
  58202. PropertyComponent::PropertyComponent (const String& name,
  58203. const int preferredHeight_)
  58204. : Component (name),
  58205. preferredHeight (preferredHeight_)
  58206. {
  58207. jassert (name.isNotEmpty());
  58208. }
  58209. PropertyComponent::~PropertyComponent()
  58210. {
  58211. }
  58212. void PropertyComponent::paint (Graphics& g)
  58213. {
  58214. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58215. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58216. }
  58217. void PropertyComponent::resized()
  58218. {
  58219. if (getNumChildComponents() > 0)
  58220. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58221. }
  58222. void PropertyComponent::enablementChanged()
  58223. {
  58224. repaint();
  58225. }
  58226. END_JUCE_NAMESPACE
  58227. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58228. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58229. BEGIN_JUCE_NAMESPACE
  58230. class PropertyPanel::PropertyHolderComponent : public Component
  58231. {
  58232. public:
  58233. PropertyHolderComponent()
  58234. {
  58235. }
  58236. ~PropertyHolderComponent()
  58237. {
  58238. deleteAllChildren();
  58239. }
  58240. void paint (Graphics&)
  58241. {
  58242. }
  58243. void updateLayout (int width);
  58244. void refreshAll() const;
  58245. private:
  58246. PropertyHolderComponent (const PropertyHolderComponent&);
  58247. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58248. };
  58249. class PropertySectionComponent : public Component
  58250. {
  58251. public:
  58252. PropertySectionComponent (const String& sectionTitle,
  58253. const Array <PropertyComponent*>& newProperties,
  58254. const bool open)
  58255. : Component (sectionTitle),
  58256. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58257. isOpen_ (open)
  58258. {
  58259. for (int i = newProperties.size(); --i >= 0;)
  58260. {
  58261. addAndMakeVisible (newProperties.getUnchecked(i));
  58262. newProperties.getUnchecked(i)->refresh();
  58263. }
  58264. }
  58265. ~PropertySectionComponent()
  58266. {
  58267. deleteAllChildren();
  58268. }
  58269. void paint (Graphics& g)
  58270. {
  58271. if (titleHeight > 0)
  58272. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58273. }
  58274. void resized()
  58275. {
  58276. int y = titleHeight;
  58277. for (int i = getNumChildComponents(); --i >= 0;)
  58278. {
  58279. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58280. if (pec != 0)
  58281. {
  58282. const int prefH = pec->getPreferredHeight();
  58283. pec->setBounds (1, y, getWidth() - 2, prefH);
  58284. y += prefH;
  58285. }
  58286. }
  58287. }
  58288. int getPreferredHeight() const
  58289. {
  58290. int y = titleHeight;
  58291. if (isOpen())
  58292. {
  58293. for (int i = 0; i < getNumChildComponents(); ++i)
  58294. {
  58295. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58296. if (pec != 0)
  58297. y += pec->getPreferredHeight();
  58298. }
  58299. }
  58300. return y;
  58301. }
  58302. void setOpen (const bool open)
  58303. {
  58304. if (isOpen_ != open)
  58305. {
  58306. isOpen_ = open;
  58307. for (int i = 0; i < getNumChildComponents(); ++i)
  58308. {
  58309. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58310. if (pec != 0)
  58311. pec->setVisible (open);
  58312. }
  58313. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58314. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58315. if (pp != 0)
  58316. pp->resized();
  58317. }
  58318. }
  58319. bool isOpen() const
  58320. {
  58321. return isOpen_;
  58322. }
  58323. void refreshAll() const
  58324. {
  58325. for (int i = 0; i < getNumChildComponents(); ++i)
  58326. {
  58327. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58328. if (pec != 0)
  58329. pec->refresh();
  58330. }
  58331. }
  58332. void mouseDown (const MouseEvent&)
  58333. {
  58334. }
  58335. void mouseUp (const MouseEvent& e)
  58336. {
  58337. if (e.getMouseDownX() < titleHeight
  58338. && e.x < titleHeight
  58339. && e.y < titleHeight
  58340. && e.getNumberOfClicks() != 2)
  58341. {
  58342. setOpen (! isOpen());
  58343. }
  58344. }
  58345. void mouseDoubleClick (const MouseEvent& e)
  58346. {
  58347. if (e.y < titleHeight)
  58348. setOpen (! isOpen());
  58349. }
  58350. private:
  58351. int titleHeight;
  58352. bool isOpen_;
  58353. PropertySectionComponent (const PropertySectionComponent&);
  58354. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58355. };
  58356. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58357. {
  58358. int y = 0;
  58359. for (int i = getNumChildComponents(); --i >= 0;)
  58360. {
  58361. PropertySectionComponent* const section
  58362. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58363. if (section != 0)
  58364. {
  58365. const int prefH = section->getPreferredHeight();
  58366. section->setBounds (0, y, width, prefH);
  58367. y += prefH;
  58368. }
  58369. }
  58370. setSize (width, y);
  58371. repaint();
  58372. }
  58373. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58374. {
  58375. for (int i = getNumChildComponents(); --i >= 0;)
  58376. {
  58377. PropertySectionComponent* const section
  58378. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58379. if (section != 0)
  58380. section->refreshAll();
  58381. }
  58382. }
  58383. PropertyPanel::PropertyPanel()
  58384. {
  58385. messageWhenEmpty = TRANS("(nothing selected)");
  58386. addAndMakeVisible (&viewport);
  58387. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58388. viewport.setFocusContainer (true);
  58389. }
  58390. PropertyPanel::~PropertyPanel()
  58391. {
  58392. clear();
  58393. }
  58394. void PropertyPanel::paint (Graphics& g)
  58395. {
  58396. if (propertyHolderComponent->getNumChildComponents() == 0)
  58397. {
  58398. g.setColour (Colours::black.withAlpha (0.5f));
  58399. g.setFont (14.0f);
  58400. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58401. Justification::centred, true);
  58402. }
  58403. }
  58404. void PropertyPanel::resized()
  58405. {
  58406. viewport.setBounds (getLocalBounds());
  58407. updatePropHolderLayout();
  58408. }
  58409. void PropertyPanel::clear()
  58410. {
  58411. if (propertyHolderComponent->getNumChildComponents() > 0)
  58412. {
  58413. propertyHolderComponent->deleteAllChildren();
  58414. repaint();
  58415. }
  58416. }
  58417. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58418. {
  58419. if (propertyHolderComponent->getNumChildComponents() == 0)
  58420. repaint();
  58421. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58422. newProperties,
  58423. true), 0);
  58424. updatePropHolderLayout();
  58425. }
  58426. void PropertyPanel::addSection (const String& sectionTitle,
  58427. const Array <PropertyComponent*>& newProperties,
  58428. const bool shouldBeOpen)
  58429. {
  58430. jassert (sectionTitle.isNotEmpty());
  58431. if (propertyHolderComponent->getNumChildComponents() == 0)
  58432. repaint();
  58433. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58434. newProperties,
  58435. shouldBeOpen), 0);
  58436. updatePropHolderLayout();
  58437. }
  58438. void PropertyPanel::updatePropHolderLayout() const
  58439. {
  58440. const int maxWidth = viewport.getMaximumVisibleWidth();
  58441. propertyHolderComponent->updateLayout (maxWidth);
  58442. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58443. if (maxWidth != newMaxWidth)
  58444. {
  58445. // need to do this twice because of scrollbars changing the size, etc.
  58446. propertyHolderComponent->updateLayout (newMaxWidth);
  58447. }
  58448. }
  58449. void PropertyPanel::refreshAll() const
  58450. {
  58451. propertyHolderComponent->refreshAll();
  58452. }
  58453. const StringArray PropertyPanel::getSectionNames() const
  58454. {
  58455. StringArray s;
  58456. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58457. {
  58458. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58459. if (section != 0 && section->getName().isNotEmpty())
  58460. s.add (section->getName());
  58461. }
  58462. return s;
  58463. }
  58464. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58465. {
  58466. int index = 0;
  58467. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58468. {
  58469. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58470. if (section != 0 && section->getName().isNotEmpty())
  58471. {
  58472. if (index == sectionIndex)
  58473. return section->isOpen();
  58474. ++index;
  58475. }
  58476. }
  58477. return false;
  58478. }
  58479. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58480. {
  58481. int index = 0;
  58482. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58483. {
  58484. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58485. if (section != 0 && section->getName().isNotEmpty())
  58486. {
  58487. if (index == sectionIndex)
  58488. {
  58489. section->setOpen (shouldBeOpen);
  58490. break;
  58491. }
  58492. ++index;
  58493. }
  58494. }
  58495. }
  58496. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58497. {
  58498. int index = 0;
  58499. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58500. {
  58501. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58502. if (section != 0 && section->getName().isNotEmpty())
  58503. {
  58504. if (index == sectionIndex)
  58505. {
  58506. section->setEnabled (shouldBeEnabled);
  58507. break;
  58508. }
  58509. ++index;
  58510. }
  58511. }
  58512. }
  58513. XmlElement* PropertyPanel::getOpennessState() const
  58514. {
  58515. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58516. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58517. const StringArray sections (getSectionNames());
  58518. for (int i = 0; i < sections.size(); ++i)
  58519. {
  58520. if (sections[i].isNotEmpty())
  58521. {
  58522. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58523. e->setAttribute ("name", sections[i]);
  58524. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58525. }
  58526. }
  58527. return xml;
  58528. }
  58529. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58530. {
  58531. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58532. {
  58533. const StringArray sections (getSectionNames());
  58534. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58535. {
  58536. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58537. e->getBoolAttribute ("open"));
  58538. }
  58539. viewport.setViewPosition (viewport.getViewPositionX(),
  58540. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58541. }
  58542. }
  58543. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58544. {
  58545. if (messageWhenEmpty != newMessage)
  58546. {
  58547. messageWhenEmpty = newMessage;
  58548. repaint();
  58549. }
  58550. }
  58551. const String& PropertyPanel::getMessageWhenEmpty() const
  58552. {
  58553. return messageWhenEmpty;
  58554. }
  58555. END_JUCE_NAMESPACE
  58556. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58557. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58558. BEGIN_JUCE_NAMESPACE
  58559. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58560. const double rangeMin,
  58561. const double rangeMax,
  58562. const double interval,
  58563. const double skewFactor)
  58564. : PropertyComponent (name)
  58565. {
  58566. addAndMakeVisible (&slider);
  58567. slider.setRange (rangeMin, rangeMax, interval);
  58568. slider.setSkewFactor (skewFactor);
  58569. slider.setSliderStyle (Slider::LinearBar);
  58570. slider.addListener (this);
  58571. }
  58572. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58573. const String& name,
  58574. const double rangeMin,
  58575. const double rangeMax,
  58576. const double interval,
  58577. const double skewFactor)
  58578. : PropertyComponent (name)
  58579. {
  58580. addAndMakeVisible (&slider);
  58581. slider.setRange (rangeMin, rangeMax, interval);
  58582. slider.setSkewFactor (skewFactor);
  58583. slider.setSliderStyle (Slider::LinearBar);
  58584. slider.getValueObject().referTo (valueToControl);
  58585. }
  58586. SliderPropertyComponent::~SliderPropertyComponent()
  58587. {
  58588. }
  58589. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58590. {
  58591. }
  58592. double SliderPropertyComponent::getValue() const
  58593. {
  58594. return slider.getValue();
  58595. }
  58596. void SliderPropertyComponent::refresh()
  58597. {
  58598. slider.setValue (getValue(), false);
  58599. }
  58600. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58601. {
  58602. if (getValue() != slider.getValue())
  58603. setValue (slider.getValue());
  58604. }
  58605. END_JUCE_NAMESPACE
  58606. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58607. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58608. BEGIN_JUCE_NAMESPACE
  58609. class TextPropLabel : public Label
  58610. {
  58611. TextPropertyComponent& owner;
  58612. int maxChars;
  58613. bool isMultiline;
  58614. public:
  58615. TextPropLabel (TextPropertyComponent& owner_,
  58616. const int maxChars_, const bool isMultiline_)
  58617. : Label (String::empty, String::empty),
  58618. owner (owner_),
  58619. maxChars (maxChars_),
  58620. isMultiline (isMultiline_)
  58621. {
  58622. setEditable (true, true, false);
  58623. setColour (backgroundColourId, Colours::white);
  58624. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58625. }
  58626. ~TextPropLabel()
  58627. {
  58628. }
  58629. TextEditor* createEditorComponent()
  58630. {
  58631. TextEditor* const textEditor = Label::createEditorComponent();
  58632. textEditor->setInputRestrictions (maxChars);
  58633. if (isMultiline)
  58634. {
  58635. textEditor->setMultiLine (true, true);
  58636. textEditor->setReturnKeyStartsNewLine (true);
  58637. }
  58638. return textEditor;
  58639. }
  58640. void textWasEdited()
  58641. {
  58642. owner.textWasEdited();
  58643. }
  58644. };
  58645. TextPropertyComponent::TextPropertyComponent (const String& name,
  58646. const int maxNumChars,
  58647. const bool isMultiLine)
  58648. : PropertyComponent (name)
  58649. {
  58650. createEditor (maxNumChars, isMultiLine);
  58651. }
  58652. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58653. const String& name,
  58654. const int maxNumChars,
  58655. const bool isMultiLine)
  58656. : PropertyComponent (name)
  58657. {
  58658. createEditor (maxNumChars, isMultiLine);
  58659. textEditor->getTextValue().referTo (valueToControl);
  58660. }
  58661. TextPropertyComponent::~TextPropertyComponent()
  58662. {
  58663. deleteAllChildren();
  58664. }
  58665. void TextPropertyComponent::setText (const String& newText)
  58666. {
  58667. textEditor->setText (newText, true);
  58668. }
  58669. const String TextPropertyComponent::getText() const
  58670. {
  58671. return textEditor->getText();
  58672. }
  58673. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58674. {
  58675. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58676. if (isMultiLine)
  58677. {
  58678. textEditor->setJustificationType (Justification::topLeft);
  58679. preferredHeight = 120;
  58680. }
  58681. }
  58682. void TextPropertyComponent::refresh()
  58683. {
  58684. textEditor->setText (getText(), false);
  58685. }
  58686. void TextPropertyComponent::textWasEdited()
  58687. {
  58688. const String newText (textEditor->getText());
  58689. if (getText() != newText)
  58690. setText (newText);
  58691. }
  58692. END_JUCE_NAMESPACE
  58693. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58694. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58695. BEGIN_JUCE_NAMESPACE
  58696. class SimpleDeviceManagerInputLevelMeter : public Component,
  58697. public Timer
  58698. {
  58699. public:
  58700. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58701. : manager (manager_),
  58702. level (0)
  58703. {
  58704. startTimer (50);
  58705. manager->enableInputLevelMeasurement (true);
  58706. }
  58707. ~SimpleDeviceManagerInputLevelMeter()
  58708. {
  58709. manager->enableInputLevelMeasurement (false);
  58710. }
  58711. void timerCallback()
  58712. {
  58713. const float newLevel = (float) manager->getCurrentInputLevel();
  58714. if (std::abs (level - newLevel) > 0.005f)
  58715. {
  58716. level = newLevel;
  58717. repaint();
  58718. }
  58719. }
  58720. void paint (Graphics& g)
  58721. {
  58722. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58723. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58724. }
  58725. private:
  58726. AudioDeviceManager* const manager;
  58727. float level;
  58728. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58729. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58730. };
  58731. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58732. public ListBoxModel
  58733. {
  58734. public:
  58735. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58736. const String& noItemsMessage_,
  58737. const int minNumber_,
  58738. const int maxNumber_)
  58739. : ListBox (String::empty, 0),
  58740. deviceManager (deviceManager_),
  58741. noItemsMessage (noItemsMessage_),
  58742. minNumber (minNumber_),
  58743. maxNumber (maxNumber_)
  58744. {
  58745. items = MidiInput::getDevices();
  58746. setModel (this);
  58747. setOutlineThickness (1);
  58748. }
  58749. ~MidiInputSelectorComponentListBox()
  58750. {
  58751. }
  58752. int getNumRows()
  58753. {
  58754. return items.size();
  58755. }
  58756. void paintListBoxItem (int row,
  58757. Graphics& g,
  58758. int width, int height,
  58759. bool rowIsSelected)
  58760. {
  58761. if (((unsigned int) row) < (unsigned int) items.size())
  58762. {
  58763. if (rowIsSelected)
  58764. g.fillAll (findColour (TextEditor::highlightColourId)
  58765. .withMultipliedAlpha (0.3f));
  58766. const String item (items [row]);
  58767. bool enabled = deviceManager.isMidiInputEnabled (item);
  58768. const int x = getTickX();
  58769. const float tickW = height * 0.75f;
  58770. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58771. enabled, true, true, false);
  58772. g.setFont (height * 0.6f);
  58773. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58774. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58775. }
  58776. }
  58777. void listBoxItemClicked (int row, const MouseEvent& e)
  58778. {
  58779. selectRow (row);
  58780. if (e.x < getTickX())
  58781. flipEnablement (row);
  58782. }
  58783. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58784. {
  58785. flipEnablement (row);
  58786. }
  58787. void returnKeyPressed (int row)
  58788. {
  58789. flipEnablement (row);
  58790. }
  58791. void paint (Graphics& g)
  58792. {
  58793. ListBox::paint (g);
  58794. if (items.size() == 0)
  58795. {
  58796. g.setColour (Colours::grey);
  58797. g.setFont (13.0f);
  58798. g.drawText (noItemsMessage,
  58799. 0, 0, getWidth(), getHeight() / 2,
  58800. Justification::centred, true);
  58801. }
  58802. }
  58803. int getBestHeight (const int preferredHeight)
  58804. {
  58805. const int extra = getOutlineThickness() * 2;
  58806. return jmax (getRowHeight() * 2 + extra,
  58807. jmin (getRowHeight() * getNumRows() + extra,
  58808. preferredHeight));
  58809. }
  58810. juce_UseDebuggingNewOperator
  58811. private:
  58812. AudioDeviceManager& deviceManager;
  58813. const String noItemsMessage;
  58814. StringArray items;
  58815. int minNumber, maxNumber;
  58816. void flipEnablement (const int row)
  58817. {
  58818. if (((unsigned int) row) < (unsigned int) items.size())
  58819. {
  58820. const String item (items [row]);
  58821. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58822. }
  58823. }
  58824. int getTickX() const
  58825. {
  58826. return getRowHeight() + 5;
  58827. }
  58828. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58829. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58830. };
  58831. class AudioDeviceSettingsPanel : public Component,
  58832. public ChangeListener,
  58833. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58834. public ButtonListener
  58835. {
  58836. public:
  58837. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58838. AudioIODeviceType::DeviceSetupDetails& setup_,
  58839. const bool hideAdvancedOptionsWithButton)
  58840. : type (type_),
  58841. setup (setup_)
  58842. {
  58843. if (hideAdvancedOptionsWithButton)
  58844. {
  58845. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58846. showAdvancedSettingsButton->addButtonListener (this);
  58847. }
  58848. type->scanForDevices();
  58849. setup.manager->addChangeListener (this);
  58850. changeListenerCallback (0);
  58851. }
  58852. ~AudioDeviceSettingsPanel()
  58853. {
  58854. setup.manager->removeChangeListener (this);
  58855. }
  58856. void resized()
  58857. {
  58858. const int lx = proportionOfWidth (0.35f);
  58859. const int w = proportionOfWidth (0.4f);
  58860. const int h = 24;
  58861. const int space = 6;
  58862. const int dh = h + space;
  58863. int y = 0;
  58864. if (outputDeviceDropDown != 0)
  58865. {
  58866. outputDeviceDropDown->setBounds (lx, y, w, h);
  58867. if (testButton != 0)
  58868. testButton->setBounds (proportionOfWidth (0.77f),
  58869. outputDeviceDropDown->getY(),
  58870. proportionOfWidth (0.18f),
  58871. h);
  58872. y += dh;
  58873. }
  58874. if (inputDeviceDropDown != 0)
  58875. {
  58876. inputDeviceDropDown->setBounds (lx, y, w, h);
  58877. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58878. inputDeviceDropDown->getY(),
  58879. proportionOfWidth (0.18f),
  58880. h);
  58881. y += dh;
  58882. }
  58883. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58884. if (outputChanList != 0)
  58885. {
  58886. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58887. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58888. y += bh + space;
  58889. }
  58890. if (inputChanList != 0)
  58891. {
  58892. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58893. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58894. y += bh + space;
  58895. }
  58896. y += space * 2;
  58897. if (showAdvancedSettingsButton != 0)
  58898. {
  58899. showAdvancedSettingsButton->changeWidthToFitText (h);
  58900. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58901. }
  58902. if (sampleRateDropDown != 0)
  58903. {
  58904. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58905. || ! showAdvancedSettingsButton->isVisible());
  58906. sampleRateDropDown->setBounds (lx, y, w, h);
  58907. y += dh;
  58908. }
  58909. if (bufferSizeDropDown != 0)
  58910. {
  58911. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58912. || ! showAdvancedSettingsButton->isVisible());
  58913. bufferSizeDropDown->setBounds (lx, y, w, h);
  58914. y += dh;
  58915. }
  58916. if (showUIButton != 0)
  58917. {
  58918. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58919. || ! showAdvancedSettingsButton->isVisible());
  58920. showUIButton->changeWidthToFitText (h);
  58921. showUIButton->setTopLeftPosition (lx, y);
  58922. }
  58923. }
  58924. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58925. {
  58926. if (comboBoxThatHasChanged == 0)
  58927. return;
  58928. AudioDeviceManager::AudioDeviceSetup config;
  58929. setup.manager->getAudioDeviceSetup (config);
  58930. String error;
  58931. if (comboBoxThatHasChanged == outputDeviceDropDown
  58932. || comboBoxThatHasChanged == inputDeviceDropDown)
  58933. {
  58934. if (outputDeviceDropDown != 0)
  58935. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58936. : outputDeviceDropDown->getText();
  58937. if (inputDeviceDropDown != 0)
  58938. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58939. : inputDeviceDropDown->getText();
  58940. if (! type->hasSeparateInputsAndOutputs())
  58941. config.inputDeviceName = config.outputDeviceName;
  58942. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58943. config.useDefaultInputChannels = true;
  58944. else
  58945. config.useDefaultOutputChannels = true;
  58946. error = setup.manager->setAudioDeviceSetup (config, true);
  58947. showCorrectDeviceName (inputDeviceDropDown, true);
  58948. showCorrectDeviceName (outputDeviceDropDown, false);
  58949. updateControlPanelButton();
  58950. resized();
  58951. }
  58952. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58953. {
  58954. if (sampleRateDropDown->getSelectedId() > 0)
  58955. {
  58956. config.sampleRate = sampleRateDropDown->getSelectedId();
  58957. error = setup.manager->setAudioDeviceSetup (config, true);
  58958. }
  58959. }
  58960. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58961. {
  58962. if (bufferSizeDropDown->getSelectedId() > 0)
  58963. {
  58964. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58965. error = setup.manager->setAudioDeviceSetup (config, true);
  58966. }
  58967. }
  58968. if (error.isNotEmpty())
  58969. {
  58970. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58971. "Error when trying to open audio device!",
  58972. error);
  58973. }
  58974. }
  58975. void buttonClicked (Button* button)
  58976. {
  58977. if (button == showAdvancedSettingsButton)
  58978. {
  58979. showAdvancedSettingsButton->setVisible (false);
  58980. resized();
  58981. }
  58982. else if (button == showUIButton)
  58983. {
  58984. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58985. if (device != 0 && device->showControlPanel())
  58986. {
  58987. setup.manager->closeAudioDevice();
  58988. setup.manager->restartLastAudioDevice();
  58989. getTopLevelComponent()->toFront (true);
  58990. }
  58991. }
  58992. else if (button == testButton && testButton != 0)
  58993. {
  58994. setup.manager->playTestSound();
  58995. }
  58996. }
  58997. void updateControlPanelButton()
  58998. {
  58999. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59000. showUIButton = 0;
  59001. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59002. {
  59003. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59004. TRANS ("opens the device's own control panel")));
  59005. showUIButton->addButtonListener (this);
  59006. }
  59007. resized();
  59008. }
  59009. void changeListenerCallback (void*)
  59010. {
  59011. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59012. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59013. {
  59014. if (outputDeviceDropDown == 0)
  59015. {
  59016. outputDeviceDropDown = new ComboBox (String::empty);
  59017. outputDeviceDropDown->addListener (this);
  59018. addAndMakeVisible (outputDeviceDropDown);
  59019. outputDeviceLabel = new Label (String::empty,
  59020. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59021. : TRANS ("device:"));
  59022. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59023. if (setup.maxNumOutputChannels > 0)
  59024. {
  59025. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59026. testButton->addButtonListener (this);
  59027. }
  59028. }
  59029. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59030. }
  59031. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59032. {
  59033. if (inputDeviceDropDown == 0)
  59034. {
  59035. inputDeviceDropDown = new ComboBox (String::empty);
  59036. inputDeviceDropDown->addListener (this);
  59037. addAndMakeVisible (inputDeviceDropDown);
  59038. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59039. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59040. addAndMakeVisible (inputLevelMeter
  59041. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59042. }
  59043. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59044. }
  59045. updateControlPanelButton();
  59046. showCorrectDeviceName (inputDeviceDropDown, true);
  59047. showCorrectDeviceName (outputDeviceDropDown, false);
  59048. if (currentDevice != 0)
  59049. {
  59050. if (setup.maxNumOutputChannels > 0
  59051. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59052. {
  59053. if (outputChanList == 0)
  59054. {
  59055. addAndMakeVisible (outputChanList
  59056. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59057. TRANS ("(no audio output channels found)")));
  59058. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59059. outputChanLabel->attachToComponent (outputChanList, true);
  59060. }
  59061. outputChanList->refresh();
  59062. }
  59063. else
  59064. {
  59065. outputChanLabel = 0;
  59066. outputChanList = 0;
  59067. }
  59068. if (setup.maxNumInputChannels > 0
  59069. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59070. {
  59071. if (inputChanList == 0)
  59072. {
  59073. addAndMakeVisible (inputChanList
  59074. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59075. TRANS ("(no audio input channels found)")));
  59076. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59077. inputChanLabel->attachToComponent (inputChanList, true);
  59078. }
  59079. inputChanList->refresh();
  59080. }
  59081. else
  59082. {
  59083. inputChanLabel = 0;
  59084. inputChanList = 0;
  59085. }
  59086. // sample rate..
  59087. {
  59088. if (sampleRateDropDown == 0)
  59089. {
  59090. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59091. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59092. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59093. }
  59094. else
  59095. {
  59096. sampleRateDropDown->clear();
  59097. sampleRateDropDown->removeListener (this);
  59098. }
  59099. const int numRates = currentDevice->getNumSampleRates();
  59100. for (int i = 0; i < numRates; ++i)
  59101. {
  59102. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59103. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59104. }
  59105. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59106. sampleRateDropDown->addListener (this);
  59107. }
  59108. // buffer size
  59109. {
  59110. if (bufferSizeDropDown == 0)
  59111. {
  59112. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59113. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59114. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59115. }
  59116. else
  59117. {
  59118. bufferSizeDropDown->clear();
  59119. bufferSizeDropDown->removeListener (this);
  59120. }
  59121. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59122. double currentRate = currentDevice->getCurrentSampleRate();
  59123. if (currentRate == 0)
  59124. currentRate = 48000.0;
  59125. for (int i = 0; i < numBufferSizes; ++i)
  59126. {
  59127. const int bs = currentDevice->getBufferSizeSamples (i);
  59128. bufferSizeDropDown->addItem (String (bs)
  59129. + " samples ("
  59130. + String (bs * 1000.0 / currentRate, 1)
  59131. + " ms)",
  59132. bs);
  59133. }
  59134. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59135. bufferSizeDropDown->addListener (this);
  59136. }
  59137. }
  59138. else
  59139. {
  59140. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59141. sampleRateLabel = 0;
  59142. bufferSizeLabel = 0;
  59143. sampleRateDropDown = 0;
  59144. bufferSizeDropDown = 0;
  59145. if (outputDeviceDropDown != 0)
  59146. outputDeviceDropDown->setSelectedId (-1, true);
  59147. if (inputDeviceDropDown != 0)
  59148. inputDeviceDropDown->setSelectedId (-1, true);
  59149. }
  59150. resized();
  59151. setSize (getWidth(), getLowestY() + 4);
  59152. }
  59153. private:
  59154. AudioIODeviceType* const type;
  59155. const AudioIODeviceType::DeviceSetupDetails setup;
  59156. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59157. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59158. ScopedPointer<TextButton> testButton;
  59159. ScopedPointer<Component> inputLevelMeter;
  59160. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59161. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59162. {
  59163. if (box != 0)
  59164. {
  59165. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59166. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59167. box->setSelectedId (index + 1, true);
  59168. if (testButton != 0 && ! isInput)
  59169. testButton->setEnabled (index >= 0);
  59170. }
  59171. }
  59172. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59173. {
  59174. const StringArray devs (type->getDeviceNames (isInputs));
  59175. combo.clear (true);
  59176. for (int i = 0; i < devs.size(); ++i)
  59177. combo.addItem (devs[i], i + 1);
  59178. combo.addItem (TRANS("<< none >>"), -1);
  59179. combo.setSelectedId (-1, true);
  59180. }
  59181. int getLowestY() const
  59182. {
  59183. int y = 0;
  59184. for (int i = getNumChildComponents(); --i >= 0;)
  59185. y = jmax (y, getChildComponent (i)->getBottom());
  59186. return y;
  59187. }
  59188. public:
  59189. class ChannelSelectorListBox : public ListBox,
  59190. public ListBoxModel
  59191. {
  59192. public:
  59193. enum BoxType
  59194. {
  59195. audioInputType,
  59196. audioOutputType
  59197. };
  59198. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59199. const BoxType type_,
  59200. const String& noItemsMessage_)
  59201. : ListBox (String::empty, 0),
  59202. setup (setup_),
  59203. type (type_),
  59204. noItemsMessage (noItemsMessage_)
  59205. {
  59206. refresh();
  59207. setModel (this);
  59208. setOutlineThickness (1);
  59209. }
  59210. ~ChannelSelectorListBox()
  59211. {
  59212. }
  59213. void refresh()
  59214. {
  59215. items.clear();
  59216. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59217. if (currentDevice != 0)
  59218. {
  59219. if (type == audioInputType)
  59220. items = currentDevice->getInputChannelNames();
  59221. else if (type == audioOutputType)
  59222. items = currentDevice->getOutputChannelNames();
  59223. if (setup.useStereoPairs)
  59224. {
  59225. StringArray pairs;
  59226. for (int i = 0; i < items.size(); i += 2)
  59227. {
  59228. const String name (items[i]);
  59229. const String name2 (items[i + 1]);
  59230. String commonBit;
  59231. for (int j = 0; j < name.length(); ++j)
  59232. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59233. commonBit = name.substring (0, j);
  59234. // Make sure we only split the name at a space, because otherwise, things
  59235. // like "input 11" + "input 12" would become "input 11 + 2"
  59236. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59237. commonBit = commonBit.dropLastCharacters (1);
  59238. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59239. }
  59240. items = pairs;
  59241. }
  59242. }
  59243. updateContent();
  59244. repaint();
  59245. }
  59246. int getNumRows()
  59247. {
  59248. return items.size();
  59249. }
  59250. void paintListBoxItem (int row,
  59251. Graphics& g,
  59252. int width, int height,
  59253. bool rowIsSelected)
  59254. {
  59255. if (((unsigned int) row) < (unsigned int) items.size())
  59256. {
  59257. if (rowIsSelected)
  59258. g.fillAll (findColour (TextEditor::highlightColourId)
  59259. .withMultipliedAlpha (0.3f));
  59260. const String item (items [row]);
  59261. bool enabled = false;
  59262. AudioDeviceManager::AudioDeviceSetup config;
  59263. setup.manager->getAudioDeviceSetup (config);
  59264. if (setup.useStereoPairs)
  59265. {
  59266. if (type == audioInputType)
  59267. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59268. else if (type == audioOutputType)
  59269. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59270. }
  59271. else
  59272. {
  59273. if (type == audioInputType)
  59274. enabled = config.inputChannels [row];
  59275. else if (type == audioOutputType)
  59276. enabled = config.outputChannels [row];
  59277. }
  59278. const int x = getTickX();
  59279. const float tickW = height * 0.75f;
  59280. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59281. enabled, true, true, false);
  59282. g.setFont (height * 0.6f);
  59283. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59284. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59285. }
  59286. }
  59287. void listBoxItemClicked (int row, const MouseEvent& e)
  59288. {
  59289. selectRow (row);
  59290. if (e.x < getTickX())
  59291. flipEnablement (row);
  59292. }
  59293. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59294. {
  59295. flipEnablement (row);
  59296. }
  59297. void returnKeyPressed (int row)
  59298. {
  59299. flipEnablement (row);
  59300. }
  59301. void paint (Graphics& g)
  59302. {
  59303. ListBox::paint (g);
  59304. if (items.size() == 0)
  59305. {
  59306. g.setColour (Colours::grey);
  59307. g.setFont (13.0f);
  59308. g.drawText (noItemsMessage,
  59309. 0, 0, getWidth(), getHeight() / 2,
  59310. Justification::centred, true);
  59311. }
  59312. }
  59313. int getBestHeight (int maxHeight)
  59314. {
  59315. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59316. getNumRows())
  59317. + getOutlineThickness() * 2;
  59318. }
  59319. juce_UseDebuggingNewOperator
  59320. private:
  59321. const AudioIODeviceType::DeviceSetupDetails setup;
  59322. const BoxType type;
  59323. const String noItemsMessage;
  59324. StringArray items;
  59325. void flipEnablement (const int row)
  59326. {
  59327. jassert (type == audioInputType || type == audioOutputType);
  59328. if (((unsigned int) row) < (unsigned int) items.size())
  59329. {
  59330. AudioDeviceManager::AudioDeviceSetup config;
  59331. setup.manager->getAudioDeviceSetup (config);
  59332. if (setup.useStereoPairs)
  59333. {
  59334. BigInteger bits;
  59335. BigInteger& original = (type == audioInputType ? config.inputChannels
  59336. : config.outputChannels);
  59337. int i;
  59338. for (i = 0; i < 256; i += 2)
  59339. bits.setBit (i / 2, original [i] || original [i + 1]);
  59340. if (type == audioInputType)
  59341. {
  59342. config.useDefaultInputChannels = false;
  59343. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59344. }
  59345. else
  59346. {
  59347. config.useDefaultOutputChannels = false;
  59348. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59349. }
  59350. for (i = 0; i < 256; ++i)
  59351. original.setBit (i, bits [i / 2]);
  59352. }
  59353. else
  59354. {
  59355. if (type == audioInputType)
  59356. {
  59357. config.useDefaultInputChannels = false;
  59358. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59359. }
  59360. else
  59361. {
  59362. config.useDefaultOutputChannels = false;
  59363. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59364. }
  59365. }
  59366. String error (setup.manager->setAudioDeviceSetup (config, true));
  59367. if (! error.isEmpty())
  59368. {
  59369. //xxx
  59370. }
  59371. }
  59372. }
  59373. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59374. {
  59375. const int numActive = chans.countNumberOfSetBits();
  59376. if (chans [index])
  59377. {
  59378. if (numActive > minNumber)
  59379. chans.setBit (index, false);
  59380. }
  59381. else
  59382. {
  59383. if (numActive >= maxNumber)
  59384. {
  59385. const int firstActiveChan = chans.findNextSetBit();
  59386. chans.setBit (index > firstActiveChan
  59387. ? firstActiveChan : chans.getHighestBit(),
  59388. false);
  59389. }
  59390. chans.setBit (index, true);
  59391. }
  59392. }
  59393. int getTickX() const
  59394. {
  59395. return getRowHeight() + 5;
  59396. }
  59397. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59398. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59399. };
  59400. private:
  59401. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59402. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59403. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59404. };
  59405. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59406. const int minInputChannels_,
  59407. const int maxInputChannels_,
  59408. const int minOutputChannels_,
  59409. const int maxOutputChannels_,
  59410. const bool showMidiInputOptions,
  59411. const bool showMidiOutputSelector,
  59412. const bool showChannelsAsStereoPairs_,
  59413. const bool hideAdvancedOptionsWithButton_)
  59414. : deviceManager (deviceManager_),
  59415. deviceTypeDropDown (0),
  59416. deviceTypeDropDownLabel (0),
  59417. minOutputChannels (minOutputChannels_),
  59418. maxOutputChannels (maxOutputChannels_),
  59419. minInputChannels (minInputChannels_),
  59420. maxInputChannels (maxInputChannels_),
  59421. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59422. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59423. {
  59424. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59425. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59426. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59427. {
  59428. deviceTypeDropDown = new ComboBox (String::empty);
  59429. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59430. {
  59431. deviceTypeDropDown
  59432. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59433. i + 1);
  59434. }
  59435. addAndMakeVisible (deviceTypeDropDown);
  59436. deviceTypeDropDown->addListener (this);
  59437. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59438. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59439. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59440. }
  59441. if (showMidiInputOptions)
  59442. {
  59443. addAndMakeVisible (midiInputsList
  59444. = new MidiInputSelectorComponentListBox (deviceManager,
  59445. TRANS("(no midi inputs available)"),
  59446. 0, 0));
  59447. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59448. midiInputsLabel->setJustificationType (Justification::topRight);
  59449. midiInputsLabel->attachToComponent (midiInputsList, true);
  59450. }
  59451. else
  59452. {
  59453. midiInputsList = 0;
  59454. midiInputsLabel = 0;
  59455. }
  59456. if (showMidiOutputSelector)
  59457. {
  59458. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59459. midiOutputSelector->addListener (this);
  59460. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59461. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59462. }
  59463. else
  59464. {
  59465. midiOutputSelector = 0;
  59466. midiOutputLabel = 0;
  59467. }
  59468. deviceManager_.addChangeListener (this);
  59469. changeListenerCallback (0);
  59470. }
  59471. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59472. {
  59473. deviceManager.removeChangeListener (this);
  59474. }
  59475. void AudioDeviceSelectorComponent::resized()
  59476. {
  59477. const int lx = proportionOfWidth (0.35f);
  59478. const int w = proportionOfWidth (0.4f);
  59479. const int h = 24;
  59480. const int space = 6;
  59481. const int dh = h + space;
  59482. int y = 15;
  59483. if (deviceTypeDropDown != 0)
  59484. {
  59485. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59486. y += dh + space * 2;
  59487. }
  59488. if (audioDeviceSettingsComp != 0)
  59489. {
  59490. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59491. y += audioDeviceSettingsComp->getHeight() + space;
  59492. }
  59493. if (midiInputsList != 0)
  59494. {
  59495. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59496. midiInputsList->setBounds (lx, y, w, bh);
  59497. y += bh + space;
  59498. }
  59499. if (midiOutputSelector != 0)
  59500. midiOutputSelector->setBounds (lx, y, w, h);
  59501. }
  59502. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59503. {
  59504. if (child == audioDeviceSettingsComp)
  59505. resized();
  59506. }
  59507. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59508. {
  59509. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59510. if (device != 0 && device->hasControlPanel())
  59511. {
  59512. if (device->showControlPanel())
  59513. deviceManager.restartLastAudioDevice();
  59514. getTopLevelComponent()->toFront (true);
  59515. }
  59516. }
  59517. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59518. {
  59519. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59520. {
  59521. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59522. if (type != 0)
  59523. {
  59524. audioDeviceSettingsComp = 0;
  59525. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59526. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59527. }
  59528. }
  59529. else if (comboBoxThatHasChanged == midiOutputSelector)
  59530. {
  59531. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59532. }
  59533. }
  59534. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59535. {
  59536. if (deviceTypeDropDown != 0)
  59537. {
  59538. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59539. }
  59540. if (audioDeviceSettingsComp == 0
  59541. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59542. {
  59543. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59544. audioDeviceSettingsComp = 0;
  59545. AudioIODeviceType* const type
  59546. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59547. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59548. if (type != 0)
  59549. {
  59550. AudioIODeviceType::DeviceSetupDetails details;
  59551. details.manager = &deviceManager;
  59552. details.minNumInputChannels = minInputChannels;
  59553. details.maxNumInputChannels = maxInputChannels;
  59554. details.minNumOutputChannels = minOutputChannels;
  59555. details.maxNumOutputChannels = maxOutputChannels;
  59556. details.useStereoPairs = showChannelsAsStereoPairs;
  59557. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59558. if (audioDeviceSettingsComp != 0)
  59559. {
  59560. addAndMakeVisible (audioDeviceSettingsComp);
  59561. audioDeviceSettingsComp->resized();
  59562. }
  59563. }
  59564. }
  59565. if (midiInputsList != 0)
  59566. {
  59567. midiInputsList->updateContent();
  59568. midiInputsList->repaint();
  59569. }
  59570. if (midiOutputSelector != 0)
  59571. {
  59572. midiOutputSelector->clear();
  59573. const StringArray midiOuts (MidiOutput::getDevices());
  59574. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59575. midiOutputSelector->addSeparator();
  59576. for (int i = 0; i < midiOuts.size(); ++i)
  59577. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59578. int current = -1;
  59579. if (deviceManager.getDefaultMidiOutput() != 0)
  59580. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59581. midiOutputSelector->setSelectedId (current, true);
  59582. }
  59583. resized();
  59584. }
  59585. END_JUCE_NAMESPACE
  59586. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59587. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59588. BEGIN_JUCE_NAMESPACE
  59589. BubbleComponent::BubbleComponent()
  59590. : side (0),
  59591. allowablePlacements (above | below | left | right),
  59592. arrowTipX (0.0f),
  59593. arrowTipY (0.0f)
  59594. {
  59595. setInterceptsMouseClicks (false, false);
  59596. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59597. setComponentEffect (&shadow);
  59598. }
  59599. BubbleComponent::~BubbleComponent()
  59600. {
  59601. }
  59602. void BubbleComponent::paint (Graphics& g)
  59603. {
  59604. int x = content.getX();
  59605. int y = content.getY();
  59606. int w = content.getWidth();
  59607. int h = content.getHeight();
  59608. int cw, ch;
  59609. getContentSize (cw, ch);
  59610. if (side == 3)
  59611. x += w - cw;
  59612. else if (side != 1)
  59613. x += (w - cw) / 2;
  59614. w = cw;
  59615. if (side == 2)
  59616. y += h - ch;
  59617. else if (side != 0)
  59618. y += (h - ch) / 2;
  59619. h = ch;
  59620. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59621. (float) x, (float) y,
  59622. (float) w, (float) h);
  59623. const int cx = x + (w - cw) / 2;
  59624. const int cy = y + (h - ch) / 2;
  59625. const int indent = 3;
  59626. g.setOrigin (cx + indent, cy + indent);
  59627. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59628. paintContent (g, cw - indent * 2, ch - indent * 2);
  59629. }
  59630. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59631. {
  59632. allowablePlacements = newPlacement;
  59633. }
  59634. void BubbleComponent::setPosition (Component* componentToPointTo)
  59635. {
  59636. jassert (componentToPointTo->isValidComponent());
  59637. Point<int> pos;
  59638. if (getParentComponent() != 0)
  59639. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59640. else
  59641. pos = componentToPointTo->relativePositionToGlobal (pos);
  59642. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59643. }
  59644. void BubbleComponent::setPosition (const int arrowTipX_,
  59645. const int arrowTipY_)
  59646. {
  59647. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59648. }
  59649. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59650. {
  59651. Rectangle<int> availableSpace;
  59652. if (getParentComponent() != 0)
  59653. {
  59654. availableSpace.setSize (getParentComponent()->getWidth(),
  59655. getParentComponent()->getHeight());
  59656. }
  59657. else
  59658. {
  59659. availableSpace = getParentMonitorArea();
  59660. }
  59661. int x = 0;
  59662. int y = 0;
  59663. int w = 150;
  59664. int h = 30;
  59665. getContentSize (w, h);
  59666. w += 30;
  59667. h += 30;
  59668. const float edgeIndent = 2.0f;
  59669. const int arrowLength = jmin (10, h / 3, w / 3);
  59670. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59671. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59672. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59673. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59674. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59675. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59676. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59677. {
  59678. spaceLeft = spaceRight = 0;
  59679. }
  59680. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59681. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59682. {
  59683. spaceAbove = spaceBelow = 0;
  59684. }
  59685. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59686. {
  59687. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59688. arrowTipX = w * 0.5f;
  59689. content.setSize (w, h - arrowLength);
  59690. if (spaceAbove >= spaceBelow)
  59691. {
  59692. // above
  59693. y = rectangleToPointTo.getY() - h;
  59694. content.setPosition (0, 0);
  59695. arrowTipY = h - edgeIndent;
  59696. side = 2;
  59697. }
  59698. else
  59699. {
  59700. // below
  59701. y = rectangleToPointTo.getBottom();
  59702. content.setPosition (0, arrowLength);
  59703. arrowTipY = edgeIndent;
  59704. side = 0;
  59705. }
  59706. }
  59707. else
  59708. {
  59709. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59710. arrowTipY = h * 0.5f;
  59711. content.setSize (w - arrowLength, h);
  59712. if (spaceLeft > spaceRight)
  59713. {
  59714. // on the left
  59715. x = rectangleToPointTo.getX() - w;
  59716. content.setPosition (0, 0);
  59717. arrowTipX = w - edgeIndent;
  59718. side = 3;
  59719. }
  59720. else
  59721. {
  59722. // on the right
  59723. x = rectangleToPointTo.getRight();
  59724. content.setPosition (arrowLength, 0);
  59725. arrowTipX = edgeIndent;
  59726. side = 1;
  59727. }
  59728. }
  59729. setBounds (x, y, w, h);
  59730. }
  59731. END_JUCE_NAMESPACE
  59732. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59733. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59734. BEGIN_JUCE_NAMESPACE
  59735. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59736. : fadeOutLength (fadeOutLengthMs),
  59737. deleteAfterUse (false)
  59738. {
  59739. }
  59740. BubbleMessageComponent::~BubbleMessageComponent()
  59741. {
  59742. fadeOutComponent (fadeOutLength);
  59743. }
  59744. void BubbleMessageComponent::showAt (int x, int y,
  59745. const String& text,
  59746. const int numMillisecondsBeforeRemoving,
  59747. const bool removeWhenMouseClicked,
  59748. const bool deleteSelfAfterUse)
  59749. {
  59750. textLayout.clear();
  59751. textLayout.setText (text, Font (14.0f));
  59752. textLayout.layout (256, Justification::centredLeft, true);
  59753. setPosition (x, y);
  59754. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59755. }
  59756. void BubbleMessageComponent::showAt (Component* const component,
  59757. const String& text,
  59758. const int numMillisecondsBeforeRemoving,
  59759. const bool removeWhenMouseClicked,
  59760. const bool deleteSelfAfterUse)
  59761. {
  59762. textLayout.clear();
  59763. textLayout.setText (text, Font (14.0f));
  59764. textLayout.layout (256, Justification::centredLeft, true);
  59765. setPosition (component);
  59766. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59767. }
  59768. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59769. const bool removeWhenMouseClicked,
  59770. const bool deleteSelfAfterUse)
  59771. {
  59772. setVisible (true);
  59773. deleteAfterUse = deleteSelfAfterUse;
  59774. if (numMillisecondsBeforeRemoving > 0)
  59775. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59776. else
  59777. expiryTime = 0;
  59778. startTimer (77);
  59779. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59780. if (! (removeWhenMouseClicked && isShowing()))
  59781. mouseClickCounter += 0xfffff;
  59782. repaint();
  59783. }
  59784. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59785. {
  59786. w = textLayout.getWidth() + 16;
  59787. h = textLayout.getHeight() + 16;
  59788. }
  59789. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59790. {
  59791. g.setColour (findColour (TooltipWindow::textColourId));
  59792. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59793. }
  59794. void BubbleMessageComponent::timerCallback()
  59795. {
  59796. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59797. {
  59798. stopTimer();
  59799. setVisible (false);
  59800. if (deleteAfterUse)
  59801. delete this;
  59802. }
  59803. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59804. {
  59805. stopTimer();
  59806. fadeOutComponent (fadeOutLength);
  59807. if (deleteAfterUse)
  59808. delete this;
  59809. }
  59810. }
  59811. END_JUCE_NAMESPACE
  59812. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59813. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59814. BEGIN_JUCE_NAMESPACE
  59815. class ColourComponentSlider : public Slider
  59816. {
  59817. public:
  59818. ColourComponentSlider (const String& name)
  59819. : Slider (name)
  59820. {
  59821. setRange (0.0, 255.0, 1.0);
  59822. }
  59823. ~ColourComponentSlider()
  59824. {
  59825. }
  59826. const String getTextFromValue (double value)
  59827. {
  59828. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59829. }
  59830. double getValueFromText (const String& text)
  59831. {
  59832. return (double) text.getHexValue32();
  59833. }
  59834. private:
  59835. ColourComponentSlider (const ColourComponentSlider&);
  59836. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59837. };
  59838. class ColourSpaceMarker : public Component
  59839. {
  59840. public:
  59841. ColourSpaceMarker()
  59842. {
  59843. setInterceptsMouseClicks (false, false);
  59844. }
  59845. ~ColourSpaceMarker()
  59846. {
  59847. }
  59848. void paint (Graphics& g)
  59849. {
  59850. g.setColour (Colour::greyLevel (0.1f));
  59851. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59852. g.setColour (Colour::greyLevel (0.9f));
  59853. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59854. }
  59855. private:
  59856. ColourSpaceMarker (const ColourSpaceMarker&);
  59857. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59858. };
  59859. class ColourSelector::ColourSpaceView : public Component
  59860. {
  59861. public:
  59862. ColourSpaceView (ColourSelector* owner_,
  59863. float& h_, float& s_, float& v_,
  59864. const int edgeSize)
  59865. : owner (owner_),
  59866. h (h_), s (s_), v (v_),
  59867. lastHue (0.0f),
  59868. edge (edgeSize)
  59869. {
  59870. addAndMakeVisible (&marker);
  59871. setMouseCursor (MouseCursor::CrosshairCursor);
  59872. }
  59873. ~ColourSpaceView()
  59874. {
  59875. }
  59876. void paint (Graphics& g)
  59877. {
  59878. if (colours.isNull())
  59879. {
  59880. const int width = getWidth() / 2;
  59881. const int height = getHeight() / 2;
  59882. colours = Image (Image::RGB, width, height, false);
  59883. Image::BitmapData pixels (colours, true);
  59884. for (int y = 0; y < height; ++y)
  59885. {
  59886. const float val = 1.0f - y / (float) height;
  59887. for (int x = 0; x < width; ++x)
  59888. {
  59889. const float sat = x / (float) width;
  59890. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59891. }
  59892. }
  59893. }
  59894. g.setOpacity (1.0f);
  59895. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59896. 0, 0, colours.getWidth(), colours.getHeight());
  59897. }
  59898. void mouseDown (const MouseEvent& e)
  59899. {
  59900. mouseDrag (e);
  59901. }
  59902. void mouseDrag (const MouseEvent& e)
  59903. {
  59904. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59905. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59906. owner->setSV (sat, val);
  59907. }
  59908. void updateIfNeeded()
  59909. {
  59910. if (lastHue != h)
  59911. {
  59912. lastHue = h;
  59913. colours = Image::null;
  59914. repaint();
  59915. }
  59916. updateMarker();
  59917. }
  59918. void resized()
  59919. {
  59920. colours = Image::null;
  59921. updateMarker();
  59922. }
  59923. private:
  59924. ColourSelector* const owner;
  59925. float& h;
  59926. float& s;
  59927. float& v;
  59928. float lastHue;
  59929. ColourSpaceMarker marker;
  59930. const int edge;
  59931. Image colours;
  59932. void updateMarker()
  59933. {
  59934. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59935. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59936. edge * 2, edge * 2);
  59937. }
  59938. ColourSpaceView (const ColourSpaceView&);
  59939. ColourSpaceView& operator= (const ColourSpaceView&);
  59940. };
  59941. class HueSelectorMarker : public Component
  59942. {
  59943. public:
  59944. HueSelectorMarker()
  59945. {
  59946. setInterceptsMouseClicks (false, false);
  59947. }
  59948. ~HueSelectorMarker()
  59949. {
  59950. }
  59951. void paint (Graphics& g)
  59952. {
  59953. Path p;
  59954. p.addTriangle (1.0f, 1.0f,
  59955. getWidth() * 0.3f, getHeight() * 0.5f,
  59956. 1.0f, getHeight() - 1.0f);
  59957. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59958. getWidth() * 0.7f, getHeight() * 0.5f,
  59959. getWidth() - 1.0f, getHeight() - 1.0f);
  59960. g.setColour (Colours::white.withAlpha (0.75f));
  59961. g.fillPath (p);
  59962. g.setColour (Colours::black.withAlpha (0.75f));
  59963. g.strokePath (p, PathStrokeType (1.2f));
  59964. }
  59965. private:
  59966. HueSelectorMarker (const HueSelectorMarker&);
  59967. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59968. };
  59969. class ColourSelector::HueSelectorComp : public Component
  59970. {
  59971. public:
  59972. HueSelectorComp (ColourSelector* owner_,
  59973. float& h_, float& s_, float& v_,
  59974. const int edgeSize)
  59975. : owner (owner_),
  59976. h (h_), s (s_), v (v_),
  59977. lastHue (0.0f),
  59978. edge (edgeSize)
  59979. {
  59980. addAndMakeVisible (&marker);
  59981. }
  59982. ~HueSelectorComp()
  59983. {
  59984. }
  59985. void paint (Graphics& g)
  59986. {
  59987. const float yScale = 1.0f / (getHeight() - edge * 2);
  59988. const Rectangle<int> clip (g.getClipBounds());
  59989. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59990. {
  59991. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59992. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59993. }
  59994. }
  59995. void resized()
  59996. {
  59997. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59998. getWidth(), edge * 2);
  59999. }
  60000. void mouseDown (const MouseEvent& e)
  60001. {
  60002. mouseDrag (e);
  60003. }
  60004. void mouseDrag (const MouseEvent& e)
  60005. {
  60006. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60007. owner->setHue (hue);
  60008. }
  60009. void updateIfNeeded()
  60010. {
  60011. resized();
  60012. }
  60013. private:
  60014. ColourSelector* const owner;
  60015. float& h;
  60016. float& s;
  60017. float& v;
  60018. float lastHue;
  60019. HueSelectorMarker marker;
  60020. const int edge;
  60021. HueSelectorComp (const HueSelectorComp&);
  60022. HueSelectorComp& operator= (const HueSelectorComp&);
  60023. };
  60024. class ColourSelector::SwatchComponent : public Component
  60025. {
  60026. public:
  60027. SwatchComponent (ColourSelector* owner_, int index_)
  60028. : owner (owner_),
  60029. index (index_)
  60030. {
  60031. }
  60032. ~SwatchComponent()
  60033. {
  60034. }
  60035. void paint (Graphics& g)
  60036. {
  60037. const Colour colour (owner->getSwatchColour (index));
  60038. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60039. Colour (0xffdddddd).overlaidWith (colour),
  60040. Colour (0xffffffff).overlaidWith (colour));
  60041. }
  60042. void mouseDown (const MouseEvent&)
  60043. {
  60044. PopupMenu m;
  60045. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60046. m.addSeparator();
  60047. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60048. const int r = m.showAt (this);
  60049. if (r == 1)
  60050. {
  60051. owner->setCurrentColour (owner->getSwatchColour (index));
  60052. }
  60053. else if (r == 2)
  60054. {
  60055. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  60056. {
  60057. owner->setSwatchColour (index, owner->getCurrentColour());
  60058. repaint();
  60059. }
  60060. }
  60061. }
  60062. private:
  60063. ColourSelector* const owner;
  60064. const int index;
  60065. SwatchComponent (const SwatchComponent&);
  60066. SwatchComponent& operator= (const SwatchComponent&);
  60067. };
  60068. ColourSelector::ColourSelector (const int flags_,
  60069. const int edgeGap_,
  60070. const int gapAroundColourSpaceComponent)
  60071. : colour (Colours::white),
  60072. colourSpace (0),
  60073. hueSelector (0),
  60074. flags (flags_),
  60075. edgeGap (edgeGap_)
  60076. {
  60077. // not much point having a selector with no components in it!
  60078. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60079. updateHSV();
  60080. if ((flags & showSliders) != 0)
  60081. {
  60082. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60083. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60084. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60085. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60086. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60087. for (int i = 4; --i >= 0;)
  60088. sliders[i]->addListener (this);
  60089. }
  60090. else
  60091. {
  60092. zeromem (sliders, sizeof (sliders));
  60093. }
  60094. if ((flags & showColourspace) != 0)
  60095. {
  60096. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  60097. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  60098. }
  60099. update();
  60100. }
  60101. ColourSelector::~ColourSelector()
  60102. {
  60103. dispatchPendingMessages();
  60104. swatchComponents.clear();
  60105. deleteAllChildren();
  60106. }
  60107. const Colour ColourSelector::getCurrentColour() const
  60108. {
  60109. return ((flags & showAlphaChannel) != 0) ? colour
  60110. : colour.withAlpha ((uint8) 0xff);
  60111. }
  60112. void ColourSelector::setCurrentColour (const Colour& c)
  60113. {
  60114. if (c != colour)
  60115. {
  60116. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60117. updateHSV();
  60118. update();
  60119. }
  60120. }
  60121. void ColourSelector::setHue (float newH)
  60122. {
  60123. newH = jlimit (0.0f, 1.0f, newH);
  60124. if (h != newH)
  60125. {
  60126. h = newH;
  60127. colour = Colour (h, s, v, colour.getFloatAlpha());
  60128. update();
  60129. }
  60130. }
  60131. void ColourSelector::setSV (float newS, float newV)
  60132. {
  60133. newS = jlimit (0.0f, 1.0f, newS);
  60134. newV = jlimit (0.0f, 1.0f, newV);
  60135. if (s != newS || v != newV)
  60136. {
  60137. s = newS;
  60138. v = newV;
  60139. colour = Colour (h, s, v, colour.getFloatAlpha());
  60140. update();
  60141. }
  60142. }
  60143. void ColourSelector::updateHSV()
  60144. {
  60145. colour.getHSB (h, s, v);
  60146. }
  60147. void ColourSelector::update()
  60148. {
  60149. if (sliders[0] != 0)
  60150. {
  60151. sliders[0]->setValue ((int) colour.getRed());
  60152. sliders[1]->setValue ((int) colour.getGreen());
  60153. sliders[2]->setValue ((int) colour.getBlue());
  60154. sliders[3]->setValue ((int) colour.getAlpha());
  60155. }
  60156. if (colourSpace != 0)
  60157. {
  60158. colourSpace->updateIfNeeded();
  60159. hueSelector->updateIfNeeded();
  60160. }
  60161. if ((flags & showColourAtTop) != 0)
  60162. repaint (previewArea);
  60163. sendChangeMessage (this);
  60164. }
  60165. void ColourSelector::paint (Graphics& g)
  60166. {
  60167. g.fillAll (findColour (backgroundColourId));
  60168. if ((flags & showColourAtTop) != 0)
  60169. {
  60170. const Colour currentColour (getCurrentColour());
  60171. g.fillCheckerBoard (previewArea, 10, 10,
  60172. Colour (0xffdddddd).overlaidWith (currentColour),
  60173. Colour (0xffffffff).overlaidWith (currentColour));
  60174. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60175. g.setFont (14.0f, true);
  60176. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60177. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60178. Justification::centred, false);
  60179. }
  60180. if ((flags & showSliders) != 0)
  60181. {
  60182. g.setColour (findColour (labelTextColourId));
  60183. g.setFont (11.0f);
  60184. for (int i = 4; --i >= 0;)
  60185. {
  60186. if (sliders[i]->isVisible())
  60187. g.drawText (sliders[i]->getName() + ":",
  60188. 0, sliders[i]->getY(),
  60189. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60190. Justification::centredRight, false);
  60191. }
  60192. }
  60193. }
  60194. void ColourSelector::resized()
  60195. {
  60196. const int swatchesPerRow = 8;
  60197. const int swatchHeight = 22;
  60198. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60199. const int numSwatches = getNumSwatches();
  60200. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60201. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60202. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60203. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60204. int y = topSpace;
  60205. if ((flags & showColourspace) != 0)
  60206. {
  60207. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60208. colourSpace->setBounds (edgeGap, y,
  60209. getWidth() - hueWidth - edgeGap - 4,
  60210. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60211. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60212. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60213. colourSpace->getHeight());
  60214. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60215. }
  60216. if ((flags & showSliders) != 0)
  60217. {
  60218. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60219. for (int i = 0; i < numSliders; ++i)
  60220. {
  60221. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60222. proportionOfWidth (0.72f), sliderHeight - 2);
  60223. y += sliderHeight;
  60224. }
  60225. }
  60226. if (numSwatches > 0)
  60227. {
  60228. const int startX = 8;
  60229. const int xGap = 4;
  60230. const int yGap = 4;
  60231. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60232. y += edgeGap;
  60233. if (swatchComponents.size() != numSwatches)
  60234. {
  60235. swatchComponents.clear();
  60236. for (int i = 0; i < numSwatches; ++i)
  60237. {
  60238. SwatchComponent* const sc = new SwatchComponent (this, i);
  60239. swatchComponents.add (sc);
  60240. addAndMakeVisible (sc);
  60241. }
  60242. }
  60243. int x = startX;
  60244. for (int i = 0; i < swatchComponents.size(); ++i)
  60245. {
  60246. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60247. sc->setBounds (x + xGap / 2,
  60248. y + yGap / 2,
  60249. swatchWidth - xGap,
  60250. swatchHeight - yGap);
  60251. if (((i + 1) % swatchesPerRow) == 0)
  60252. {
  60253. x = startX;
  60254. y += swatchHeight;
  60255. }
  60256. else
  60257. {
  60258. x += swatchWidth;
  60259. }
  60260. }
  60261. }
  60262. }
  60263. void ColourSelector::sliderValueChanged (Slider*)
  60264. {
  60265. if (sliders[0] != 0)
  60266. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60267. (uint8) sliders[1]->getValue(),
  60268. (uint8) sliders[2]->getValue(),
  60269. (uint8) sliders[3]->getValue()));
  60270. }
  60271. int ColourSelector::getNumSwatches() const
  60272. {
  60273. return 0;
  60274. }
  60275. const Colour ColourSelector::getSwatchColour (const int) const
  60276. {
  60277. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60278. return Colours::black;
  60279. }
  60280. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60281. {
  60282. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60283. }
  60284. END_JUCE_NAMESPACE
  60285. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60286. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60287. BEGIN_JUCE_NAMESPACE
  60288. class ShadowWindow : public Component
  60289. {
  60290. Component* owner;
  60291. Image shadowImageSections [12];
  60292. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60293. public:
  60294. ShadowWindow (Component* const owner_,
  60295. const int type_,
  60296. const Image shadowImageSections_ [12])
  60297. : owner (owner_),
  60298. type (type_)
  60299. {
  60300. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60301. shadowImageSections [i] = shadowImageSections_ [i];
  60302. setInterceptsMouseClicks (false, false);
  60303. if (owner_->isOnDesktop())
  60304. {
  60305. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60306. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60307. | ComponentPeer::windowIsTemporary
  60308. | ComponentPeer::windowIgnoresKeyPresses);
  60309. }
  60310. else if (owner_->getParentComponent() != 0)
  60311. {
  60312. owner_->getParentComponent()->addChildComponent (this);
  60313. }
  60314. }
  60315. ~ShadowWindow()
  60316. {
  60317. }
  60318. void paint (Graphics& g)
  60319. {
  60320. const Image& topLeft = shadowImageSections [type * 3];
  60321. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60322. const Image& filler = shadowImageSections [type * 3 + 2];
  60323. g.setOpacity (1.0f);
  60324. if (type < 2)
  60325. {
  60326. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60327. g.drawImage (topLeft,
  60328. 0, 0, topLeft.getWidth(), imH,
  60329. 0, 0, topLeft.getWidth(), imH);
  60330. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60331. g.drawImage (bottomRight,
  60332. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60333. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60334. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60335. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60336. }
  60337. else
  60338. {
  60339. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60340. g.drawImage (topLeft,
  60341. 0, 0, imW, topLeft.getHeight(),
  60342. 0, 0, imW, topLeft.getHeight());
  60343. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60344. g.drawImage (bottomRight,
  60345. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60346. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60347. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60348. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60349. }
  60350. }
  60351. void resized()
  60352. {
  60353. repaint(); // (needed for correct repainting)
  60354. }
  60355. private:
  60356. ShadowWindow (const ShadowWindow&);
  60357. ShadowWindow& operator= (const ShadowWindow&);
  60358. };
  60359. DropShadower::DropShadower (const float alpha_,
  60360. const int xOffset_,
  60361. const int yOffset_,
  60362. const float blurRadius_)
  60363. : owner (0),
  60364. numShadows (0),
  60365. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60366. xOffset (xOffset_),
  60367. yOffset (yOffset_),
  60368. alpha (alpha_),
  60369. blurRadius (blurRadius_),
  60370. inDestructor (false),
  60371. reentrant (false)
  60372. {
  60373. }
  60374. DropShadower::~DropShadower()
  60375. {
  60376. if (owner != 0)
  60377. owner->removeComponentListener (this);
  60378. inDestructor = true;
  60379. deleteShadowWindows();
  60380. }
  60381. void DropShadower::deleteShadowWindows()
  60382. {
  60383. if (numShadows > 0)
  60384. {
  60385. int i;
  60386. for (i = numShadows; --i >= 0;)
  60387. delete shadowWindows[i];
  60388. numShadows = 0;
  60389. }
  60390. }
  60391. void DropShadower::setOwner (Component* componentToFollow)
  60392. {
  60393. if (componentToFollow != owner)
  60394. {
  60395. if (owner != 0)
  60396. owner->removeComponentListener (this);
  60397. // (the component can't be null)
  60398. jassert (componentToFollow != 0);
  60399. owner = componentToFollow;
  60400. jassert (owner != 0);
  60401. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60402. owner->addComponentListener (this);
  60403. updateShadows();
  60404. }
  60405. }
  60406. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60407. {
  60408. updateShadows();
  60409. }
  60410. void DropShadower::componentBroughtToFront (Component&)
  60411. {
  60412. bringShadowWindowsToFront();
  60413. }
  60414. void DropShadower::componentChildrenChanged (Component&)
  60415. {
  60416. }
  60417. void DropShadower::componentParentHierarchyChanged (Component&)
  60418. {
  60419. deleteShadowWindows();
  60420. updateShadows();
  60421. }
  60422. void DropShadower::componentVisibilityChanged (Component&)
  60423. {
  60424. updateShadows();
  60425. }
  60426. void DropShadower::updateShadows()
  60427. {
  60428. if (reentrant || inDestructor || (owner == 0))
  60429. return;
  60430. reentrant = true;
  60431. ComponentPeer* const nw = owner->getPeer();
  60432. const bool isOwnerVisible = owner->isVisible()
  60433. && (nw == 0 || ! nw->isMinimised());
  60434. const bool createShadowWindows = numShadows == 0
  60435. && owner->getWidth() > 0
  60436. && owner->getHeight() > 0
  60437. && isOwnerVisible
  60438. && (Desktop::canUseSemiTransparentWindows()
  60439. || owner->getParentComponent() != 0);
  60440. if (createShadowWindows)
  60441. {
  60442. // keep a cached version of the image to save doing the gaussian too often
  60443. String imageId;
  60444. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60445. const int hash = imageId.hashCode();
  60446. Image bigIm (ImageCache::getFromHashCode (hash));
  60447. if (bigIm.isNull())
  60448. {
  60449. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60450. Graphics bigG (bigIm);
  60451. bigG.setColour (Colours::black.withAlpha (alpha));
  60452. bigG.fillRect (shadowEdge + xOffset,
  60453. shadowEdge + yOffset,
  60454. bigIm.getWidth() - (shadowEdge * 2),
  60455. bigIm.getHeight() - (shadowEdge * 2));
  60456. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60457. blurKernel.createGaussianBlur (blurRadius);
  60458. blurKernel.applyToImage (bigIm, bigIm,
  60459. Rectangle<int> (xOffset, yOffset,
  60460. bigIm.getWidth(), bigIm.getHeight()));
  60461. ImageCache::addImageToCache (bigIm, hash);
  60462. }
  60463. const int iw = bigIm.getWidth();
  60464. const int ih = bigIm.getHeight();
  60465. const int shadowEdge2 = shadowEdge * 2;
  60466. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60467. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60468. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60469. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60470. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60471. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60472. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60473. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60474. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60475. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60476. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60477. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60478. for (int i = 0; i < 4; ++i)
  60479. {
  60480. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60481. ++numShadows;
  60482. }
  60483. }
  60484. if (numShadows > 0)
  60485. {
  60486. for (int i = numShadows; --i >= 0;)
  60487. {
  60488. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60489. shadowWindows[i]->setVisible (isOwnerVisible);
  60490. }
  60491. const int x = owner->getX();
  60492. const int y = owner->getY() - shadowEdge;
  60493. const int w = owner->getWidth();
  60494. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60495. shadowWindows[0]->setBounds (x - shadowEdge,
  60496. y,
  60497. shadowEdge,
  60498. h);
  60499. shadowWindows[1]->setBounds (x + w,
  60500. y,
  60501. shadowEdge,
  60502. h);
  60503. shadowWindows[2]->setBounds (x,
  60504. y,
  60505. w,
  60506. shadowEdge);
  60507. shadowWindows[3]->setBounds (x,
  60508. owner->getBottom(),
  60509. w,
  60510. shadowEdge);
  60511. }
  60512. reentrant = false;
  60513. if (createShadowWindows)
  60514. bringShadowWindowsToFront();
  60515. }
  60516. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60517. const int sx, const int sy)
  60518. {
  60519. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60520. Graphics g (shadowImageSections[num]);
  60521. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60522. }
  60523. void DropShadower::bringShadowWindowsToFront()
  60524. {
  60525. if (! (inDestructor || reentrant))
  60526. {
  60527. updateShadows();
  60528. reentrant = true;
  60529. for (int i = numShadows; --i >= 0;)
  60530. shadowWindows[i]->toBehind (owner);
  60531. reentrant = false;
  60532. }
  60533. }
  60534. END_JUCE_NAMESPACE
  60535. /*** End of inlined file: juce_DropShadower.cpp ***/
  60536. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60537. BEGIN_JUCE_NAMESPACE
  60538. class MagnifyingPeer : public ComponentPeer
  60539. {
  60540. public:
  60541. MagnifyingPeer (Component* const component_,
  60542. MagnifierComponent* const magnifierComp_)
  60543. : ComponentPeer (component_, 0),
  60544. magnifierComp (magnifierComp_)
  60545. {
  60546. }
  60547. ~MagnifyingPeer()
  60548. {
  60549. }
  60550. void* getNativeHandle() const { return 0; }
  60551. void setVisible (bool) {}
  60552. void setTitle (const String&) {}
  60553. void setPosition (int, int) {}
  60554. void setSize (int, int) {}
  60555. void setBounds (int, int, int, int, bool) {}
  60556. void setMinimised (bool) {}
  60557. bool isMinimised() const { return false; }
  60558. void setFullScreen (bool) {}
  60559. bool isFullScreen() const { return false; }
  60560. const BorderSize getFrameSize() const { return BorderSize (0); }
  60561. bool setAlwaysOnTop (bool) { return true; }
  60562. void toFront (bool) {}
  60563. void toBehind (ComponentPeer*) {}
  60564. void setIcon (const Image&) {}
  60565. bool isFocused() const
  60566. {
  60567. return magnifierComp->hasKeyboardFocus (true);
  60568. }
  60569. void grabFocus()
  60570. {
  60571. ComponentPeer* peer = magnifierComp->getPeer();
  60572. if (peer != 0)
  60573. peer->grabFocus();
  60574. }
  60575. void textInputRequired (const Point<int>& position)
  60576. {
  60577. ComponentPeer* peer = magnifierComp->getPeer();
  60578. if (peer != 0)
  60579. peer->textInputRequired (position);
  60580. }
  60581. const Rectangle<int> getBounds() const
  60582. {
  60583. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60584. component->getWidth(), component->getHeight());
  60585. }
  60586. const Point<int> getScreenPosition() const
  60587. {
  60588. return magnifierComp->getScreenPosition();
  60589. }
  60590. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60591. {
  60592. const double zoom = magnifierComp->getScaleFactor();
  60593. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60594. roundToInt (relativePosition.getY() * zoom)));
  60595. }
  60596. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60597. {
  60598. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60599. const double zoom = magnifierComp->getScaleFactor();
  60600. return Point<int> (roundToInt (p.getX() / zoom),
  60601. roundToInt (p.getY() / zoom));
  60602. }
  60603. bool contains (const Point<int>& position, bool) const
  60604. {
  60605. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60606. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60607. }
  60608. void repaint (const Rectangle<int>& area)
  60609. {
  60610. const double zoom = magnifierComp->getScaleFactor();
  60611. magnifierComp->repaint ((int) (area.getX() * zoom),
  60612. (int) (area.getY() * zoom),
  60613. roundToInt (area.getWidth() * zoom) + 1,
  60614. roundToInt (area.getHeight() * zoom) + 1);
  60615. }
  60616. void performAnyPendingRepaintsNow()
  60617. {
  60618. }
  60619. juce_UseDebuggingNewOperator
  60620. private:
  60621. MagnifierComponent* const magnifierComp;
  60622. MagnifyingPeer (const MagnifyingPeer&);
  60623. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60624. };
  60625. class PeerHolderComp : public Component
  60626. {
  60627. public:
  60628. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60629. : magnifierComp (magnifierComp_)
  60630. {
  60631. setVisible (true);
  60632. }
  60633. ~PeerHolderComp()
  60634. {
  60635. }
  60636. ComponentPeer* createNewPeer (int, void*)
  60637. {
  60638. return new MagnifyingPeer (this, magnifierComp);
  60639. }
  60640. void childBoundsChanged (Component* c)
  60641. {
  60642. if (c != 0)
  60643. {
  60644. setSize (c->getWidth(), c->getHeight());
  60645. magnifierComp->childBoundsChanged (this);
  60646. }
  60647. }
  60648. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60649. {
  60650. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60651. Component* const p = magnifierComp->getParentComponent();
  60652. if (p != 0)
  60653. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60654. }
  60655. private:
  60656. MagnifierComponent* const magnifierComp;
  60657. PeerHolderComp (const PeerHolderComp&);
  60658. PeerHolderComp& operator= (const PeerHolderComp&);
  60659. };
  60660. MagnifierComponent::MagnifierComponent (Component* const content_,
  60661. const bool deleteContentCompWhenNoLongerNeeded)
  60662. : content (content_),
  60663. scaleFactor (0.0),
  60664. peer (0),
  60665. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60666. quality (Graphics::lowResamplingQuality),
  60667. mouseSource (0, true)
  60668. {
  60669. holderComp = new PeerHolderComp (this);
  60670. setScaleFactor (1.0);
  60671. }
  60672. MagnifierComponent::~MagnifierComponent()
  60673. {
  60674. delete holderComp;
  60675. if (deleteContent)
  60676. delete content;
  60677. }
  60678. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60679. {
  60680. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60681. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60682. if (scaleFactor != newScaleFactor)
  60683. {
  60684. scaleFactor = newScaleFactor;
  60685. if (scaleFactor == 1.0)
  60686. {
  60687. holderComp->removeFromDesktop();
  60688. peer = 0;
  60689. addChildComponent (content);
  60690. childBoundsChanged (content);
  60691. }
  60692. else
  60693. {
  60694. holderComp->addAndMakeVisible (content);
  60695. holderComp->childBoundsChanged (content);
  60696. childBoundsChanged (holderComp);
  60697. holderComp->addToDesktop (0);
  60698. peer = holderComp->getPeer();
  60699. }
  60700. repaint();
  60701. }
  60702. }
  60703. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60704. {
  60705. quality = newQuality;
  60706. }
  60707. void MagnifierComponent::paint (Graphics& g)
  60708. {
  60709. const int w = holderComp->getWidth();
  60710. const int h = holderComp->getHeight();
  60711. if (w == 0 || h == 0)
  60712. return;
  60713. const Rectangle<int> r (g.getClipBounds());
  60714. const int srcX = (int) (r.getX() / scaleFactor);
  60715. const int srcY = (int) (r.getY() / scaleFactor);
  60716. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60717. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60718. if (scaleFactor >= 1.0)
  60719. {
  60720. ++srcW;
  60721. ++srcH;
  60722. }
  60723. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60724. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60725. {
  60726. Graphics g2 (temp);
  60727. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60728. holderComp->paintEntireComponent (g2);
  60729. }
  60730. g.setImageResamplingQuality (quality);
  60731. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60732. }
  60733. void MagnifierComponent::childBoundsChanged (Component* c)
  60734. {
  60735. if (c != 0)
  60736. setSize (roundToInt (c->getWidth() * scaleFactor),
  60737. roundToInt (c->getHeight() * scaleFactor));
  60738. }
  60739. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60740. {
  60741. if (peer != 0)
  60742. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60743. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60744. }
  60745. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60746. {
  60747. passOnMouseEventToPeer (e);
  60748. }
  60749. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60750. {
  60751. passOnMouseEventToPeer (e);
  60752. }
  60753. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60754. {
  60755. passOnMouseEventToPeer (e);
  60756. }
  60757. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60758. {
  60759. passOnMouseEventToPeer (e);
  60760. }
  60761. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60762. {
  60763. passOnMouseEventToPeer (e);
  60764. }
  60765. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60766. {
  60767. passOnMouseEventToPeer (e);
  60768. }
  60769. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60770. {
  60771. if (peer != 0)
  60772. peer->handleMouseWheel (e.source.getIndex(),
  60773. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60774. ix * 256.0f, iy * 256.0f);
  60775. else
  60776. Component::mouseWheelMove (e, ix, iy);
  60777. }
  60778. int MagnifierComponent::scaleInt (const int n) const
  60779. {
  60780. return roundToInt (n / scaleFactor);
  60781. }
  60782. END_JUCE_NAMESPACE
  60783. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60784. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60785. BEGIN_JUCE_NAMESPACE
  60786. class MidiKeyboardUpDownButton : public Button
  60787. {
  60788. public:
  60789. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60790. const int delta_)
  60791. : Button (String::empty),
  60792. owner (owner_),
  60793. delta (delta_)
  60794. {
  60795. setOpaque (true);
  60796. }
  60797. ~MidiKeyboardUpDownButton()
  60798. {
  60799. }
  60800. void clicked()
  60801. {
  60802. int note = owner->getLowestVisibleKey();
  60803. if (delta < 0)
  60804. note = (note - 1) / 12;
  60805. else
  60806. note = note / 12 + 1;
  60807. owner->setLowestVisibleKey (note * 12);
  60808. }
  60809. void paintButton (Graphics& g,
  60810. bool isMouseOverButton,
  60811. bool isButtonDown)
  60812. {
  60813. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60814. isMouseOverButton, isButtonDown,
  60815. delta > 0);
  60816. }
  60817. private:
  60818. MidiKeyboardComponent* const owner;
  60819. const int delta;
  60820. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60821. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60822. };
  60823. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60824. const Orientation orientation_)
  60825. : state (state_),
  60826. xOffset (0),
  60827. blackNoteLength (1),
  60828. keyWidth (16.0f),
  60829. orientation (orientation_),
  60830. midiChannel (1),
  60831. midiInChannelMask (0xffff),
  60832. velocity (1.0f),
  60833. noteUnderMouse (-1),
  60834. mouseDownNote (-1),
  60835. rangeStart (0),
  60836. rangeEnd (127),
  60837. firstKey (12 * 4),
  60838. canScroll (true),
  60839. mouseDragging (false),
  60840. useMousePositionForVelocity (true),
  60841. keyMappingOctave (6),
  60842. octaveNumForMiddleC (3)
  60843. {
  60844. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60845. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60846. // initialise with a default set of querty key-mappings..
  60847. const char* const keymap = "awsedftgyhujkolp;";
  60848. for (int i = String (keymap).length(); --i >= 0;)
  60849. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60850. setOpaque (true);
  60851. setWantsKeyboardFocus (true);
  60852. state.addListener (this);
  60853. }
  60854. MidiKeyboardComponent::~MidiKeyboardComponent()
  60855. {
  60856. state.removeListener (this);
  60857. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60858. deleteAllChildren();
  60859. }
  60860. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60861. {
  60862. keyWidth = widthInPixels;
  60863. resized();
  60864. }
  60865. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60866. {
  60867. if (orientation != newOrientation)
  60868. {
  60869. orientation = newOrientation;
  60870. resized();
  60871. }
  60872. }
  60873. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60874. const int highestNote)
  60875. {
  60876. jassert (lowestNote >= 0 && lowestNote <= 127);
  60877. jassert (highestNote >= 0 && highestNote <= 127);
  60878. jassert (lowestNote <= highestNote);
  60879. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60880. {
  60881. rangeStart = jlimit (0, 127, lowestNote);
  60882. rangeEnd = jlimit (0, 127, highestNote);
  60883. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60884. resized();
  60885. }
  60886. }
  60887. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60888. {
  60889. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60890. if (noteNumber != firstKey)
  60891. {
  60892. firstKey = noteNumber;
  60893. sendChangeMessage (this);
  60894. resized();
  60895. }
  60896. }
  60897. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60898. {
  60899. if (canScroll != canScroll_)
  60900. {
  60901. canScroll = canScroll_;
  60902. resized();
  60903. }
  60904. }
  60905. void MidiKeyboardComponent::colourChanged()
  60906. {
  60907. repaint();
  60908. }
  60909. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60910. {
  60911. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60912. if (midiChannel != midiChannelNumber)
  60913. {
  60914. resetAnyKeysInUse();
  60915. midiChannel = jlimit (1, 16, midiChannelNumber);
  60916. }
  60917. }
  60918. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60919. {
  60920. midiInChannelMask = midiChannelMask;
  60921. triggerAsyncUpdate();
  60922. }
  60923. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60924. {
  60925. velocity = jlimit (0.0f, 1.0f, velocity_);
  60926. useMousePositionForVelocity = useMousePositionForVelocity_;
  60927. }
  60928. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60929. {
  60930. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60931. static const float blackNoteWidth = 0.7f;
  60932. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60933. 1.0f, 2 - blackNoteWidth * 0.4f,
  60934. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60935. 4.0f, 5 - blackNoteWidth * 0.5f,
  60936. 5.0f, 6 - blackNoteWidth * 0.3f,
  60937. 6.0f };
  60938. static const float widths[] = { 1.0f, blackNoteWidth,
  60939. 1.0f, blackNoteWidth,
  60940. 1.0f, 1.0f, blackNoteWidth,
  60941. 1.0f, blackNoteWidth,
  60942. 1.0f, blackNoteWidth,
  60943. 1.0f };
  60944. const int octave = midiNoteNumber / 12;
  60945. const int note = midiNoteNumber % 12;
  60946. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60947. w = roundToInt (widths [note] * keyWidth_);
  60948. }
  60949. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60950. {
  60951. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60952. int rx, rw;
  60953. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60954. x -= xOffset + rx;
  60955. }
  60956. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60957. {
  60958. int x, y;
  60959. getKeyPos (midiNoteNumber, x, y);
  60960. return x;
  60961. }
  60962. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60963. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60964. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60965. {
  60966. if (! reallyContains (pos.getX(), pos.getY(), false))
  60967. return -1;
  60968. Point<int> p (pos);
  60969. if (orientation != horizontalKeyboard)
  60970. {
  60971. p = Point<int> (p.getY(), p.getX());
  60972. if (orientation == verticalKeyboardFacingLeft)
  60973. p = Point<int> (p.getX(), getWidth() - p.getY());
  60974. else
  60975. p = Point<int> (getHeight() - p.getX(), p.getY());
  60976. }
  60977. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60978. }
  60979. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60980. {
  60981. if (pos.getY() < blackNoteLength)
  60982. {
  60983. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60984. {
  60985. for (int i = 0; i < 5; ++i)
  60986. {
  60987. const int note = octaveStart + blackNotes [i];
  60988. if (note >= rangeStart && note <= rangeEnd)
  60989. {
  60990. int kx, kw;
  60991. getKeyPos (note, kx, kw);
  60992. kx += xOffset;
  60993. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60994. {
  60995. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60996. return note;
  60997. }
  60998. }
  60999. }
  61000. }
  61001. }
  61002. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61003. {
  61004. for (int i = 0; i < 7; ++i)
  61005. {
  61006. const int note = octaveStart + whiteNotes [i];
  61007. if (note >= rangeStart && note <= rangeEnd)
  61008. {
  61009. int kx, kw;
  61010. getKeyPos (note, kx, kw);
  61011. kx += xOffset;
  61012. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61013. {
  61014. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61015. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61016. return note;
  61017. }
  61018. }
  61019. }
  61020. }
  61021. mousePositionVelocity = 0;
  61022. return -1;
  61023. }
  61024. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61025. {
  61026. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61027. {
  61028. int x, w;
  61029. getKeyPos (noteNum, x, w);
  61030. if (orientation == horizontalKeyboard)
  61031. repaint (x, 0, w, getHeight());
  61032. else if (orientation == verticalKeyboardFacingLeft)
  61033. repaint (0, x, getWidth(), w);
  61034. else if (orientation == verticalKeyboardFacingRight)
  61035. repaint (0, getHeight() - x - w, getWidth(), w);
  61036. }
  61037. }
  61038. void MidiKeyboardComponent::paint (Graphics& g)
  61039. {
  61040. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61041. const Colour lineColour (findColour (keySeparatorLineColourId));
  61042. const Colour textColour (findColour (textLabelColourId));
  61043. int x, w, octave;
  61044. for (octave = 0; octave < 128; octave += 12)
  61045. {
  61046. for (int white = 0; white < 7; ++white)
  61047. {
  61048. const int noteNum = octave + whiteNotes [white];
  61049. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61050. {
  61051. getKeyPos (noteNum, x, w);
  61052. if (orientation == horizontalKeyboard)
  61053. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61054. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61055. noteUnderMouse == noteNum,
  61056. lineColour, textColour);
  61057. else if (orientation == verticalKeyboardFacingLeft)
  61058. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61059. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61060. noteUnderMouse == noteNum,
  61061. lineColour, textColour);
  61062. else if (orientation == verticalKeyboardFacingRight)
  61063. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61064. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61065. noteUnderMouse == noteNum,
  61066. lineColour, textColour);
  61067. }
  61068. }
  61069. }
  61070. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61071. if (orientation == verticalKeyboardFacingLeft)
  61072. {
  61073. x1 = getWidth() - 1.0f;
  61074. x2 = getWidth() - 5.0f;
  61075. }
  61076. else if (orientation == verticalKeyboardFacingRight)
  61077. x2 = 5.0f;
  61078. else
  61079. y2 = 5.0f;
  61080. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61081. Colours::transparentBlack, x2, y2, false));
  61082. getKeyPos (rangeEnd, x, w);
  61083. x += w;
  61084. if (orientation == verticalKeyboardFacingLeft)
  61085. g.fillRect (getWidth() - 5, 0, 5, x);
  61086. else if (orientation == verticalKeyboardFacingRight)
  61087. g.fillRect (0, 0, 5, x);
  61088. else
  61089. g.fillRect (0, 0, x, 5);
  61090. g.setColour (lineColour);
  61091. if (orientation == verticalKeyboardFacingLeft)
  61092. g.fillRect (0, 0, 1, x);
  61093. else if (orientation == verticalKeyboardFacingRight)
  61094. g.fillRect (getWidth() - 1, 0, 1, x);
  61095. else
  61096. g.fillRect (0, getHeight() - 1, x, 1);
  61097. const Colour blackNoteColour (findColour (blackNoteColourId));
  61098. for (octave = 0; octave < 128; octave += 12)
  61099. {
  61100. for (int black = 0; black < 5; ++black)
  61101. {
  61102. const int noteNum = octave + blackNotes [black];
  61103. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61104. {
  61105. getKeyPos (noteNum, x, w);
  61106. if (orientation == horizontalKeyboard)
  61107. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61108. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61109. noteUnderMouse == noteNum,
  61110. blackNoteColour);
  61111. else if (orientation == verticalKeyboardFacingLeft)
  61112. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61113. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61114. noteUnderMouse == noteNum,
  61115. blackNoteColour);
  61116. else if (orientation == verticalKeyboardFacingRight)
  61117. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61118. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61119. noteUnderMouse == noteNum,
  61120. blackNoteColour);
  61121. }
  61122. }
  61123. }
  61124. }
  61125. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61126. Graphics& g, int x, int y, int w, int h,
  61127. bool isDown, bool isOver,
  61128. const Colour& lineColour,
  61129. const Colour& textColour)
  61130. {
  61131. Colour c (Colours::transparentWhite);
  61132. if (isDown)
  61133. c = findColour (keyDownOverlayColourId);
  61134. if (isOver)
  61135. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61136. g.setColour (c);
  61137. g.fillRect (x, y, w, h);
  61138. const String text (getWhiteNoteText (midiNoteNumber));
  61139. if (! text.isEmpty())
  61140. {
  61141. g.setColour (textColour);
  61142. Font f (jmin (12.0f, keyWidth * 0.9f));
  61143. f.setHorizontalScale (0.8f);
  61144. g.setFont (f);
  61145. Justification justification (Justification::centredBottom);
  61146. if (orientation == verticalKeyboardFacingLeft)
  61147. justification = Justification::centredLeft;
  61148. else if (orientation == verticalKeyboardFacingRight)
  61149. justification = Justification::centredRight;
  61150. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61151. }
  61152. g.setColour (lineColour);
  61153. if (orientation == horizontalKeyboard)
  61154. g.fillRect (x, y, 1, h);
  61155. else if (orientation == verticalKeyboardFacingLeft)
  61156. g.fillRect (x, y, w, 1);
  61157. else if (orientation == verticalKeyboardFacingRight)
  61158. g.fillRect (x, y + h - 1, w, 1);
  61159. if (midiNoteNumber == rangeEnd)
  61160. {
  61161. if (orientation == horizontalKeyboard)
  61162. g.fillRect (x + w, y, 1, h);
  61163. else if (orientation == verticalKeyboardFacingLeft)
  61164. g.fillRect (x, y + h, w, 1);
  61165. else if (orientation == verticalKeyboardFacingRight)
  61166. g.fillRect (x, y - 1, w, 1);
  61167. }
  61168. }
  61169. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61170. Graphics& g, int x, int y, int w, int h,
  61171. bool isDown, bool isOver,
  61172. const Colour& noteFillColour)
  61173. {
  61174. Colour c (noteFillColour);
  61175. if (isDown)
  61176. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61177. if (isOver)
  61178. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61179. g.setColour (c);
  61180. g.fillRect (x, y, w, h);
  61181. if (isDown)
  61182. {
  61183. g.setColour (noteFillColour);
  61184. g.drawRect (x, y, w, h);
  61185. }
  61186. else
  61187. {
  61188. const int xIndent = jmax (1, jmin (w, h) / 8);
  61189. g.setColour (c.brighter());
  61190. if (orientation == horizontalKeyboard)
  61191. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61192. else if (orientation == verticalKeyboardFacingLeft)
  61193. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61194. else if (orientation == verticalKeyboardFacingRight)
  61195. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61196. }
  61197. }
  61198. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61199. {
  61200. octaveNumForMiddleC = octaveNumForMiddleC_;
  61201. repaint();
  61202. }
  61203. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61204. {
  61205. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61206. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61207. return String::empty;
  61208. }
  61209. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61210. const bool isMouseOver_,
  61211. const bool isButtonDown,
  61212. const bool movesOctavesUp)
  61213. {
  61214. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61215. float angle;
  61216. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61217. angle = movesOctavesUp ? 0.0f : 0.5f;
  61218. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61219. angle = movesOctavesUp ? 0.25f : 0.75f;
  61220. else
  61221. angle = movesOctavesUp ? 0.75f : 0.25f;
  61222. Path path;
  61223. path.lineTo (0.0f, 1.0f);
  61224. path.lineTo (1.0f, 0.5f);
  61225. path.closeSubPath();
  61226. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61227. g.setColour (findColour (upDownButtonArrowColourId)
  61228. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61229. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61230. w - 2.0f,
  61231. h - 2.0f,
  61232. true));
  61233. }
  61234. void MidiKeyboardComponent::resized()
  61235. {
  61236. int w = getWidth();
  61237. int h = getHeight();
  61238. if (w > 0 && h > 0)
  61239. {
  61240. if (orientation != horizontalKeyboard)
  61241. swapVariables (w, h);
  61242. blackNoteLength = roundToInt (h * 0.7f);
  61243. int kx2, kw2;
  61244. getKeyPos (rangeEnd, kx2, kw2);
  61245. kx2 += kw2;
  61246. if (firstKey != rangeStart)
  61247. {
  61248. int kx1, kw1;
  61249. getKeyPos (rangeStart, kx1, kw1);
  61250. if (kx2 - kx1 <= w)
  61251. {
  61252. firstKey = rangeStart;
  61253. sendChangeMessage (this);
  61254. repaint();
  61255. }
  61256. }
  61257. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61258. scrollDown->setVisible (showScrollButtons);
  61259. scrollUp->setVisible (showScrollButtons);
  61260. xOffset = 0;
  61261. if (showScrollButtons)
  61262. {
  61263. const int scrollButtonW = jmin (12, w / 2);
  61264. if (orientation == horizontalKeyboard)
  61265. {
  61266. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61267. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61268. }
  61269. else if (orientation == verticalKeyboardFacingLeft)
  61270. {
  61271. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61272. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61273. }
  61274. else if (orientation == verticalKeyboardFacingRight)
  61275. {
  61276. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61277. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61278. }
  61279. int endOfLastKey, kw;
  61280. getKeyPos (rangeEnd, endOfLastKey, kw);
  61281. endOfLastKey += kw;
  61282. float mousePositionVelocity;
  61283. const int spaceAvailable = w - scrollButtonW * 2;
  61284. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61285. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61286. {
  61287. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61288. sendChangeMessage (this);
  61289. }
  61290. int newOffset = 0;
  61291. getKeyPos (firstKey, newOffset, kw);
  61292. xOffset = newOffset - scrollButtonW;
  61293. }
  61294. else
  61295. {
  61296. firstKey = rangeStart;
  61297. }
  61298. timerCallback();
  61299. repaint();
  61300. }
  61301. }
  61302. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61303. {
  61304. triggerAsyncUpdate();
  61305. }
  61306. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61307. {
  61308. triggerAsyncUpdate();
  61309. }
  61310. void MidiKeyboardComponent::handleAsyncUpdate()
  61311. {
  61312. for (int i = rangeStart; i <= rangeEnd; ++i)
  61313. {
  61314. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61315. {
  61316. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61317. repaintNote (i);
  61318. }
  61319. }
  61320. }
  61321. void MidiKeyboardComponent::resetAnyKeysInUse()
  61322. {
  61323. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61324. {
  61325. state.allNotesOff (midiChannel);
  61326. keysPressed.clear();
  61327. mouseDownNote = -1;
  61328. }
  61329. }
  61330. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61331. {
  61332. float mousePositionVelocity = 0.0f;
  61333. const int newNote = (mouseDragging || isMouseOver())
  61334. ? xyToNote (pos, mousePositionVelocity) : -1;
  61335. if (noteUnderMouse != newNote)
  61336. {
  61337. if (mouseDownNote >= 0)
  61338. {
  61339. state.noteOff (midiChannel, mouseDownNote);
  61340. mouseDownNote = -1;
  61341. }
  61342. if (mouseDragging && newNote >= 0)
  61343. {
  61344. if (! useMousePositionForVelocity)
  61345. mousePositionVelocity = 1.0f;
  61346. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61347. mouseDownNote = newNote;
  61348. }
  61349. repaintNote (noteUnderMouse);
  61350. noteUnderMouse = newNote;
  61351. repaintNote (noteUnderMouse);
  61352. }
  61353. else if (mouseDownNote >= 0 && ! mouseDragging)
  61354. {
  61355. state.noteOff (midiChannel, mouseDownNote);
  61356. mouseDownNote = -1;
  61357. }
  61358. }
  61359. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61360. {
  61361. updateNoteUnderMouse (e.getPosition());
  61362. stopTimer();
  61363. }
  61364. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61365. {
  61366. float mousePositionVelocity;
  61367. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61368. if (newNote >= 0)
  61369. mouseDraggedToKey (newNote, e);
  61370. updateNoteUnderMouse (e.getPosition());
  61371. }
  61372. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61373. {
  61374. return true;
  61375. }
  61376. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61377. {
  61378. }
  61379. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61380. {
  61381. float mousePositionVelocity;
  61382. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61383. mouseDragging = false;
  61384. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61385. {
  61386. repaintNote (noteUnderMouse);
  61387. noteUnderMouse = -1;
  61388. mouseDragging = true;
  61389. updateNoteUnderMouse (e.getPosition());
  61390. startTimer (500);
  61391. }
  61392. }
  61393. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61394. {
  61395. mouseDragging = false;
  61396. updateNoteUnderMouse (e.getPosition());
  61397. stopTimer();
  61398. }
  61399. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61400. {
  61401. updateNoteUnderMouse (e.getPosition());
  61402. }
  61403. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61404. {
  61405. updateNoteUnderMouse (e.getPosition());
  61406. }
  61407. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61408. {
  61409. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61410. }
  61411. void MidiKeyboardComponent::timerCallback()
  61412. {
  61413. updateNoteUnderMouse (getMouseXYRelative());
  61414. }
  61415. void MidiKeyboardComponent::clearKeyMappings()
  61416. {
  61417. resetAnyKeysInUse();
  61418. keyPressNotes.clear();
  61419. keyPresses.clear();
  61420. }
  61421. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61422. const int midiNoteOffsetFromC)
  61423. {
  61424. removeKeyPressForNote (midiNoteOffsetFromC);
  61425. keyPressNotes.add (midiNoteOffsetFromC);
  61426. keyPresses.add (key);
  61427. }
  61428. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61429. {
  61430. for (int i = keyPressNotes.size(); --i >= 0;)
  61431. {
  61432. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61433. {
  61434. keyPressNotes.remove (i);
  61435. keyPresses.remove (i);
  61436. }
  61437. }
  61438. }
  61439. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61440. {
  61441. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61442. keyMappingOctave = newOctaveNumber;
  61443. }
  61444. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61445. {
  61446. bool keyPressUsed = false;
  61447. for (int i = keyPresses.size(); --i >= 0;)
  61448. {
  61449. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61450. if (keyPresses.getReference(i).isCurrentlyDown())
  61451. {
  61452. if (! keysPressed [note])
  61453. {
  61454. keysPressed.setBit (note);
  61455. state.noteOn (midiChannel, note, velocity);
  61456. keyPressUsed = true;
  61457. }
  61458. }
  61459. else
  61460. {
  61461. if (keysPressed [note])
  61462. {
  61463. keysPressed.clearBit (note);
  61464. state.noteOff (midiChannel, note);
  61465. keyPressUsed = true;
  61466. }
  61467. }
  61468. }
  61469. return keyPressUsed;
  61470. }
  61471. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61472. {
  61473. resetAnyKeysInUse();
  61474. }
  61475. END_JUCE_NAMESPACE
  61476. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61477. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61478. #if JUCE_OPENGL
  61479. BEGIN_JUCE_NAMESPACE
  61480. extern void juce_glViewport (const int w, const int h);
  61481. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61482. const int alphaBits_,
  61483. const int depthBufferBits_,
  61484. const int stencilBufferBits_)
  61485. : redBits (bitsPerRGBComponent),
  61486. greenBits (bitsPerRGBComponent),
  61487. blueBits (bitsPerRGBComponent),
  61488. alphaBits (alphaBits_),
  61489. depthBufferBits (depthBufferBits_),
  61490. stencilBufferBits (stencilBufferBits_),
  61491. accumulationBufferRedBits (0),
  61492. accumulationBufferGreenBits (0),
  61493. accumulationBufferBlueBits (0),
  61494. accumulationBufferAlphaBits (0),
  61495. fullSceneAntiAliasingNumSamples (0)
  61496. {
  61497. }
  61498. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61499. : redBits (other.redBits),
  61500. greenBits (other.greenBits),
  61501. blueBits (other.blueBits),
  61502. alphaBits (other.alphaBits),
  61503. depthBufferBits (other.depthBufferBits),
  61504. stencilBufferBits (other.stencilBufferBits),
  61505. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61506. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61507. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61508. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61509. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61510. {
  61511. }
  61512. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61513. {
  61514. redBits = other.redBits;
  61515. greenBits = other.greenBits;
  61516. blueBits = other.blueBits;
  61517. alphaBits = other.alphaBits;
  61518. depthBufferBits = other.depthBufferBits;
  61519. stencilBufferBits = other.stencilBufferBits;
  61520. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61521. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61522. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61523. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61524. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61525. return *this;
  61526. }
  61527. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61528. {
  61529. return redBits == other.redBits
  61530. && greenBits == other.greenBits
  61531. && blueBits == other.blueBits
  61532. && alphaBits == other.alphaBits
  61533. && depthBufferBits == other.depthBufferBits
  61534. && stencilBufferBits == other.stencilBufferBits
  61535. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61536. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61537. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61538. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61539. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61540. }
  61541. static Array<OpenGLContext*> knownContexts;
  61542. OpenGLContext::OpenGLContext() throw()
  61543. {
  61544. knownContexts.add (this);
  61545. }
  61546. OpenGLContext::~OpenGLContext()
  61547. {
  61548. knownContexts.removeValue (this);
  61549. }
  61550. OpenGLContext* OpenGLContext::getCurrentContext()
  61551. {
  61552. for (int i = knownContexts.size(); --i >= 0;)
  61553. {
  61554. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61555. if (oglc->isActive())
  61556. return oglc;
  61557. }
  61558. return 0;
  61559. }
  61560. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61561. {
  61562. public:
  61563. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61564. : ComponentMovementWatcher (owner_),
  61565. owner (owner_),
  61566. wasShowing (false)
  61567. {
  61568. }
  61569. ~OpenGLComponentWatcher() {}
  61570. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61571. {
  61572. owner->updateContextPosition();
  61573. }
  61574. void componentPeerChanged()
  61575. {
  61576. const ScopedLock sl (owner->getContextLock());
  61577. owner->deleteContext();
  61578. }
  61579. void componentVisibilityChanged (Component&)
  61580. {
  61581. const bool isShowingNow = owner->isShowing();
  61582. if (wasShowing != isShowingNow)
  61583. {
  61584. wasShowing = isShowingNow;
  61585. if (! isShowingNow)
  61586. {
  61587. const ScopedLock sl (owner->getContextLock());
  61588. owner->deleteContext();
  61589. }
  61590. }
  61591. }
  61592. juce_UseDebuggingNewOperator
  61593. private:
  61594. OpenGLComponent* const owner;
  61595. bool wasShowing;
  61596. };
  61597. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61598. : type (type_),
  61599. contextToShareListsWith (0),
  61600. needToUpdateViewport (true)
  61601. {
  61602. setOpaque (true);
  61603. componentWatcher = new OpenGLComponentWatcher (this);
  61604. }
  61605. OpenGLComponent::~OpenGLComponent()
  61606. {
  61607. deleteContext();
  61608. componentWatcher = 0;
  61609. }
  61610. void OpenGLComponent::deleteContext()
  61611. {
  61612. const ScopedLock sl (contextLock);
  61613. context = 0;
  61614. }
  61615. void OpenGLComponent::updateContextPosition()
  61616. {
  61617. needToUpdateViewport = true;
  61618. if (getWidth() > 0 && getHeight() > 0)
  61619. {
  61620. Component* const topComp = getTopLevelComponent();
  61621. if (topComp->getPeer() != 0)
  61622. {
  61623. const ScopedLock sl (contextLock);
  61624. if (context != 0)
  61625. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61626. getScreenY() - topComp->getScreenY(),
  61627. getWidth(),
  61628. getHeight(),
  61629. topComp->getHeight());
  61630. }
  61631. }
  61632. }
  61633. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61634. {
  61635. OpenGLPixelFormat pf;
  61636. const ScopedLock sl (contextLock);
  61637. if (context != 0)
  61638. pf = context->getPixelFormat();
  61639. return pf;
  61640. }
  61641. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61642. {
  61643. if (! (preferredPixelFormat == formatToUse))
  61644. {
  61645. const ScopedLock sl (contextLock);
  61646. deleteContext();
  61647. preferredPixelFormat = formatToUse;
  61648. }
  61649. }
  61650. void OpenGLComponent::shareWith (OpenGLContext* c)
  61651. {
  61652. if (contextToShareListsWith != c)
  61653. {
  61654. const ScopedLock sl (contextLock);
  61655. deleteContext();
  61656. contextToShareListsWith = c;
  61657. }
  61658. }
  61659. bool OpenGLComponent::makeCurrentContextActive()
  61660. {
  61661. if (context == 0)
  61662. {
  61663. const ScopedLock sl (contextLock);
  61664. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61665. {
  61666. context = createContext();
  61667. if (context != 0)
  61668. {
  61669. updateContextPosition();
  61670. if (context->makeActive())
  61671. newOpenGLContextCreated();
  61672. }
  61673. }
  61674. }
  61675. return context != 0 && context->makeActive();
  61676. }
  61677. void OpenGLComponent::makeCurrentContextInactive()
  61678. {
  61679. if (context != 0)
  61680. context->makeInactive();
  61681. }
  61682. bool OpenGLComponent::isActiveContext() const throw()
  61683. {
  61684. return context != 0 && context->isActive();
  61685. }
  61686. void OpenGLComponent::swapBuffers()
  61687. {
  61688. if (context != 0)
  61689. context->swapBuffers();
  61690. }
  61691. void OpenGLComponent::paint (Graphics&)
  61692. {
  61693. if (renderAndSwapBuffers())
  61694. {
  61695. ComponentPeer* const peer = getPeer();
  61696. if (peer != 0)
  61697. {
  61698. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61699. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61700. }
  61701. }
  61702. }
  61703. bool OpenGLComponent::renderAndSwapBuffers()
  61704. {
  61705. const ScopedLock sl (contextLock);
  61706. if (! makeCurrentContextActive())
  61707. return false;
  61708. if (needToUpdateViewport)
  61709. {
  61710. needToUpdateViewport = false;
  61711. juce_glViewport (getWidth(), getHeight());
  61712. }
  61713. renderOpenGL();
  61714. swapBuffers();
  61715. return true;
  61716. }
  61717. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61718. {
  61719. Component::internalRepaint (x, y, w, h);
  61720. if (context != 0)
  61721. context->repaint();
  61722. }
  61723. END_JUCE_NAMESPACE
  61724. #endif
  61725. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61726. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61727. BEGIN_JUCE_NAMESPACE
  61728. PreferencesPanel::PreferencesPanel()
  61729. : buttonSize (70)
  61730. {
  61731. }
  61732. PreferencesPanel::~PreferencesPanel()
  61733. {
  61734. currentPage = 0;
  61735. deleteAllChildren();
  61736. }
  61737. void PreferencesPanel::addSettingsPage (const String& title,
  61738. const Drawable* icon,
  61739. const Drawable* overIcon,
  61740. const Drawable* downIcon)
  61741. {
  61742. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61743. button->setImages (icon, overIcon, downIcon);
  61744. button->setRadioGroupId (1);
  61745. button->addButtonListener (this);
  61746. button->setClickingTogglesState (true);
  61747. button->setWantsKeyboardFocus (false);
  61748. addAndMakeVisible (button);
  61749. resized();
  61750. if (currentPage == 0)
  61751. setCurrentPage (title);
  61752. }
  61753. void PreferencesPanel::addSettingsPage (const String& title,
  61754. const void* imageData,
  61755. const int imageDataSize)
  61756. {
  61757. DrawableImage icon, iconOver, iconDown;
  61758. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61759. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61760. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61761. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61762. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61763. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61764. }
  61765. class PrefsDialogWindow : public DialogWindow
  61766. {
  61767. public:
  61768. PrefsDialogWindow (const String& dialogtitle,
  61769. const Colour& backgroundColour)
  61770. : DialogWindow (dialogtitle, backgroundColour, true)
  61771. {
  61772. }
  61773. ~PrefsDialogWindow()
  61774. {
  61775. }
  61776. void closeButtonPressed()
  61777. {
  61778. exitModalState (0);
  61779. }
  61780. private:
  61781. PrefsDialogWindow (const PrefsDialogWindow&);
  61782. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61783. };
  61784. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61785. int dialogWidth,
  61786. int dialogHeight,
  61787. const Colour& backgroundColour)
  61788. {
  61789. setSize (dialogWidth, dialogHeight);
  61790. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61791. dw.setContentComponent (this, true, true);
  61792. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61793. dw.runModalLoop();
  61794. dw.setContentComponent (0, false, false);
  61795. }
  61796. void PreferencesPanel::resized()
  61797. {
  61798. int x = 0;
  61799. for (int i = 0; i < getNumChildComponents(); ++i)
  61800. {
  61801. Component* c = getChildComponent (i);
  61802. if (dynamic_cast <DrawableButton*> (c) == 0)
  61803. {
  61804. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61805. }
  61806. else
  61807. {
  61808. c->setBounds (x, 0, buttonSize, buttonSize);
  61809. x += buttonSize;
  61810. }
  61811. }
  61812. }
  61813. void PreferencesPanel::paint (Graphics& g)
  61814. {
  61815. g.setColour (Colours::grey);
  61816. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61817. }
  61818. void PreferencesPanel::setCurrentPage (const String& pageName)
  61819. {
  61820. if (currentPageName != pageName)
  61821. {
  61822. currentPageName = pageName;
  61823. currentPage = 0;
  61824. currentPage = createComponentForPage (pageName);
  61825. if (currentPage != 0)
  61826. {
  61827. addAndMakeVisible (currentPage);
  61828. currentPage->toBack();
  61829. resized();
  61830. }
  61831. for (int i = 0; i < getNumChildComponents(); ++i)
  61832. {
  61833. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61834. if (db != 0 && db->getName() == pageName)
  61835. {
  61836. db->setToggleState (true, false);
  61837. break;
  61838. }
  61839. }
  61840. }
  61841. }
  61842. void PreferencesPanel::buttonClicked (Button*)
  61843. {
  61844. for (int i = 0; i < getNumChildComponents(); ++i)
  61845. {
  61846. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61847. if (db != 0 && db->getToggleState())
  61848. {
  61849. setCurrentPage (db->getName());
  61850. break;
  61851. }
  61852. }
  61853. }
  61854. END_JUCE_NAMESPACE
  61855. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61856. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61857. #if JUCE_WINDOWS || JUCE_LINUX
  61858. BEGIN_JUCE_NAMESPACE
  61859. SystemTrayIconComponent::SystemTrayIconComponent()
  61860. {
  61861. addToDesktop (0);
  61862. }
  61863. SystemTrayIconComponent::~SystemTrayIconComponent()
  61864. {
  61865. }
  61866. END_JUCE_NAMESPACE
  61867. #endif
  61868. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61869. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61870. BEGIN_JUCE_NAMESPACE
  61871. class AlertWindowTextEditor : public TextEditor
  61872. {
  61873. public:
  61874. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61875. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61876. {
  61877. setSelectAllWhenFocused (true);
  61878. }
  61879. ~AlertWindowTextEditor()
  61880. {
  61881. }
  61882. void returnPressed()
  61883. {
  61884. // pass these up the component hierarchy to be trigger the buttons
  61885. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61886. }
  61887. void escapePressed()
  61888. {
  61889. // pass these up the component hierarchy to be trigger the buttons
  61890. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61891. }
  61892. private:
  61893. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61894. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61895. static juce_wchar getDefaultPasswordChar() throw()
  61896. {
  61897. #if JUCE_LINUX
  61898. return 0x2022;
  61899. #else
  61900. return 0x25cf;
  61901. #endif
  61902. }
  61903. };
  61904. AlertWindow::AlertWindow (const String& title,
  61905. const String& message,
  61906. AlertIconType iconType,
  61907. Component* associatedComponent_)
  61908. : TopLevelWindow (title, true),
  61909. alertIconType (iconType),
  61910. associatedComponent (associatedComponent_)
  61911. {
  61912. if (message.isEmpty())
  61913. text = " "; // to force an update if the message is empty
  61914. setMessage (message);
  61915. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61916. {
  61917. Component* const c = Desktop::getInstance().getComponent (i);
  61918. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61919. {
  61920. setAlwaysOnTop (true);
  61921. break;
  61922. }
  61923. }
  61924. if (! JUCEApplication::isStandaloneApp())
  61925. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61926. lookAndFeelChanged();
  61927. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61928. }
  61929. AlertWindow::~AlertWindow()
  61930. {
  61931. for (int i = customComps.size(); --i >= 0;)
  61932. removeChildComponent ((Component*) customComps[i]);
  61933. deleteAllChildren();
  61934. }
  61935. void AlertWindow::userTriedToCloseWindow()
  61936. {
  61937. exitModalState (0);
  61938. }
  61939. void AlertWindow::setMessage (const String& message)
  61940. {
  61941. const String newMessage (message.substring (0, 2048));
  61942. if (text != newMessage)
  61943. {
  61944. text = newMessage;
  61945. font.setHeight (15.0f);
  61946. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61947. textLayout.setText (getName() + "\n\n", titleFont);
  61948. textLayout.appendText (text, font);
  61949. updateLayout (true);
  61950. repaint();
  61951. }
  61952. }
  61953. void AlertWindow::buttonClicked (Button* button)
  61954. {
  61955. for (int i = 0; i < buttons.size(); i++)
  61956. {
  61957. TextButton* const c = (TextButton*) buttons[i];
  61958. if (button->getName() == c->getName())
  61959. {
  61960. if (c->getParentComponent() != 0)
  61961. c->getParentComponent()->exitModalState (c->getCommandID());
  61962. break;
  61963. }
  61964. }
  61965. }
  61966. void AlertWindow::addButton (const String& name,
  61967. const int returnValue,
  61968. const KeyPress& shortcutKey1,
  61969. const KeyPress& shortcutKey2)
  61970. {
  61971. TextButton* const b = new TextButton (name, String::empty);
  61972. b->setWantsKeyboardFocus (true);
  61973. b->setMouseClickGrabsKeyboardFocus (false);
  61974. b->setCommandToTrigger (0, returnValue, false);
  61975. b->addShortcut (shortcutKey1);
  61976. b->addShortcut (shortcutKey2);
  61977. b->addButtonListener (this);
  61978. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61979. addAndMakeVisible (b, 0);
  61980. buttons.add (b);
  61981. updateLayout (false);
  61982. }
  61983. int AlertWindow::getNumButtons() const
  61984. {
  61985. return buttons.size();
  61986. }
  61987. void AlertWindow::triggerButtonClick (const String& buttonName)
  61988. {
  61989. for (int i = buttons.size(); --i >= 0;)
  61990. {
  61991. TextButton* const b = (TextButton*) buttons[i];
  61992. if (buttonName == b->getName())
  61993. {
  61994. b->triggerClick();
  61995. break;
  61996. }
  61997. }
  61998. }
  61999. void AlertWindow::addTextEditor (const String& name,
  62000. const String& initialContents,
  62001. const String& onScreenLabel,
  62002. const bool isPasswordBox)
  62003. {
  62004. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62005. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62006. tc->setFont (font);
  62007. tc->setText (initialContents);
  62008. tc->setCaretPosition (initialContents.length());
  62009. addAndMakeVisible (tc);
  62010. textBoxes.add (tc);
  62011. allComps.add (tc);
  62012. textboxNames.add (onScreenLabel);
  62013. updateLayout (false);
  62014. }
  62015. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62016. {
  62017. for (int i = textBoxes.size(); --i >= 0;)
  62018. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  62019. return ((TextEditor*)textBoxes[i])->getText();
  62020. return String::empty;
  62021. }
  62022. void AlertWindow::addComboBox (const String& name,
  62023. const StringArray& items,
  62024. const String& onScreenLabel)
  62025. {
  62026. ComboBox* const cb = new ComboBox (name);
  62027. for (int i = 0; i < items.size(); ++i)
  62028. cb->addItem (items[i], i + 1);
  62029. addAndMakeVisible (cb);
  62030. cb->setSelectedItemIndex (0);
  62031. comboBoxes.add (cb);
  62032. allComps.add (cb);
  62033. comboBoxNames.add (onScreenLabel);
  62034. updateLayout (false);
  62035. }
  62036. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62037. {
  62038. for (int i = comboBoxes.size(); --i >= 0;)
  62039. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62040. return (ComboBox*) comboBoxes[i];
  62041. return 0;
  62042. }
  62043. class AlertTextComp : public TextEditor
  62044. {
  62045. public:
  62046. AlertTextComp (const String& message,
  62047. const Font& font)
  62048. {
  62049. setReadOnly (true);
  62050. setMultiLine (true, true);
  62051. setCaretVisible (false);
  62052. setScrollbarsShown (true);
  62053. lookAndFeelChanged();
  62054. setWantsKeyboardFocus (false);
  62055. setFont (font);
  62056. setText (message, false);
  62057. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62058. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62059. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62060. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62061. }
  62062. ~AlertTextComp()
  62063. {
  62064. }
  62065. int getPreferredWidth() const throw() { return bestWidth; }
  62066. void updateLayout (const int width)
  62067. {
  62068. TextLayout text;
  62069. text.appendText (getText(), getFont());
  62070. text.layout (width - 8, Justification::topLeft, true);
  62071. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62072. }
  62073. private:
  62074. int bestWidth;
  62075. AlertTextComp (const AlertTextComp&);
  62076. AlertTextComp& operator= (const AlertTextComp&);
  62077. };
  62078. void AlertWindow::addTextBlock (const String& textBlock)
  62079. {
  62080. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62081. textBlocks.add (c);
  62082. allComps.add (c);
  62083. addAndMakeVisible (c);
  62084. updateLayout (false);
  62085. }
  62086. void AlertWindow::addProgressBarComponent (double& progressValue)
  62087. {
  62088. ProgressBar* const pb = new ProgressBar (progressValue);
  62089. progressBars.add (pb);
  62090. allComps.add (pb);
  62091. addAndMakeVisible (pb);
  62092. updateLayout (false);
  62093. }
  62094. void AlertWindow::addCustomComponent (Component* const component)
  62095. {
  62096. customComps.add (component);
  62097. allComps.add (component);
  62098. addAndMakeVisible (component);
  62099. updateLayout (false);
  62100. }
  62101. int AlertWindow::getNumCustomComponents() const
  62102. {
  62103. return customComps.size();
  62104. }
  62105. Component* AlertWindow::getCustomComponent (const int index) const
  62106. {
  62107. return (Component*) customComps [index];
  62108. }
  62109. Component* AlertWindow::removeCustomComponent (const int index)
  62110. {
  62111. Component* const c = getCustomComponent (index);
  62112. if (c != 0)
  62113. {
  62114. customComps.removeValue (c);
  62115. allComps.removeValue (c);
  62116. removeChildComponent (c);
  62117. updateLayout (false);
  62118. }
  62119. return c;
  62120. }
  62121. void AlertWindow::paint (Graphics& g)
  62122. {
  62123. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62124. g.setColour (findColour (textColourId));
  62125. g.setFont (getLookAndFeel().getAlertWindowFont());
  62126. int i;
  62127. for (i = textBoxes.size(); --i >= 0;)
  62128. {
  62129. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62130. g.drawFittedText (textboxNames[i],
  62131. te->getX(), te->getY() - 14,
  62132. te->getWidth(), 14,
  62133. Justification::centredLeft, 1);
  62134. }
  62135. for (i = comboBoxNames.size(); --i >= 0;)
  62136. {
  62137. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62138. g.drawFittedText (comboBoxNames[i],
  62139. cb->getX(), cb->getY() - 14,
  62140. cb->getWidth(), 14,
  62141. Justification::centredLeft, 1);
  62142. }
  62143. for (i = customComps.size(); --i >= 0;)
  62144. {
  62145. const Component* const c = (Component*) customComps[i];
  62146. g.drawFittedText (c->getName(),
  62147. c->getX(), c->getY() - 14,
  62148. c->getWidth(), 14,
  62149. Justification::centredLeft, 1);
  62150. }
  62151. }
  62152. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62153. {
  62154. const int titleH = 24;
  62155. const int iconWidth = 80;
  62156. const int wid = jmax (font.getStringWidth (text),
  62157. font.getStringWidth (getName()));
  62158. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62159. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62160. const int edgeGap = 10;
  62161. const int labelHeight = 18;
  62162. int iconSpace;
  62163. if (alertIconType == NoIcon)
  62164. {
  62165. textLayout.layout (w, Justification::horizontallyCentred, true);
  62166. iconSpace = 0;
  62167. }
  62168. else
  62169. {
  62170. textLayout.layout (w, Justification::left, true);
  62171. iconSpace = iconWidth;
  62172. }
  62173. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62174. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62175. const int textLayoutH = textLayout.getHeight();
  62176. const int textBottom = 16 + titleH + textLayoutH;
  62177. int h = textBottom;
  62178. int buttonW = 40;
  62179. int i;
  62180. for (i = 0; i < buttons.size(); ++i)
  62181. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62182. w = jmax (buttonW, w);
  62183. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62184. if (buttons.size() > 0)
  62185. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62186. for (i = customComps.size(); --i >= 0;)
  62187. {
  62188. Component* c = (Component*) customComps[i];
  62189. w = jmax (w, (c->getWidth() * 100) / 80);
  62190. h += 10 + c->getHeight();
  62191. if (c->getName().isNotEmpty())
  62192. h += labelHeight;
  62193. }
  62194. for (i = textBlocks.size(); --i >= 0;)
  62195. {
  62196. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62197. w = jmax (w, ac->getPreferredWidth());
  62198. }
  62199. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62200. for (i = textBlocks.size(); --i >= 0;)
  62201. {
  62202. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62203. ac->updateLayout ((int) (w * 0.8f));
  62204. h += ac->getHeight() + 10;
  62205. }
  62206. h = jmin (getParentHeight() - 50, h);
  62207. if (onlyIncreaseSize)
  62208. {
  62209. w = jmax (w, getWidth());
  62210. h = jmax (h, getHeight());
  62211. }
  62212. if (! isVisible())
  62213. {
  62214. centreAroundComponent (associatedComponent, w, h);
  62215. }
  62216. else
  62217. {
  62218. const int cx = getX() + getWidth() / 2;
  62219. const int cy = getY() + getHeight() / 2;
  62220. setBounds (cx - w / 2,
  62221. cy - h / 2,
  62222. w, h);
  62223. }
  62224. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62225. const int spacer = 16;
  62226. int totalWidth = -spacer;
  62227. for (i = buttons.size(); --i >= 0;)
  62228. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62229. int x = (w - totalWidth) / 2;
  62230. int y = (int) (getHeight() * 0.95f);
  62231. for (i = 0; i < buttons.size(); ++i)
  62232. {
  62233. TextButton* const c = (TextButton*) buttons[i];
  62234. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62235. c->setTopLeftPosition (x, ny);
  62236. if (ny < y)
  62237. y = ny;
  62238. x += c->getWidth() + spacer;
  62239. c->toFront (false);
  62240. }
  62241. y = textBottom;
  62242. for (i = 0; i < allComps.size(); ++i)
  62243. {
  62244. Component* const c = (Component*) allComps[i];
  62245. h = 22;
  62246. const int comboIndex = comboBoxes.indexOf (c);
  62247. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62248. y += labelHeight;
  62249. const int tbIndex = textBoxes.indexOf (c);
  62250. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62251. y += labelHeight;
  62252. if (customComps.contains (c))
  62253. {
  62254. if (c->getName().isNotEmpty())
  62255. y += labelHeight;
  62256. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62257. h = c->getHeight();
  62258. }
  62259. else if (textBlocks.contains (c))
  62260. {
  62261. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62262. h = c->getHeight();
  62263. }
  62264. else
  62265. {
  62266. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62267. }
  62268. y += h + 10;
  62269. }
  62270. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62271. }
  62272. bool AlertWindow::containsAnyExtraComponents() const
  62273. {
  62274. return textBoxes.size()
  62275. + comboBoxes.size()
  62276. + progressBars.size()
  62277. + customComps.size() > 0;
  62278. }
  62279. void AlertWindow::mouseDown (const MouseEvent&)
  62280. {
  62281. dragger.startDraggingComponent (this, &constrainer);
  62282. }
  62283. void AlertWindow::mouseDrag (const MouseEvent& e)
  62284. {
  62285. dragger.dragComponent (this, e);
  62286. }
  62287. bool AlertWindow::keyPressed (const KeyPress& key)
  62288. {
  62289. for (int i = buttons.size(); --i >= 0;)
  62290. {
  62291. TextButton* const b = (TextButton*) buttons[i];
  62292. if (b->isRegisteredForShortcut (key))
  62293. {
  62294. b->triggerClick();
  62295. return true;
  62296. }
  62297. }
  62298. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62299. {
  62300. exitModalState (0);
  62301. return true;
  62302. }
  62303. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62304. {
  62305. ((TextButton*) buttons.getFirst())->triggerClick();
  62306. return true;
  62307. }
  62308. return false;
  62309. }
  62310. void AlertWindow::lookAndFeelChanged()
  62311. {
  62312. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62313. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62314. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62315. }
  62316. int AlertWindow::getDesktopWindowStyleFlags() const
  62317. {
  62318. return getLookAndFeel().getAlertBoxWindowFlags();
  62319. }
  62320. struct AlertWindowInfo
  62321. {
  62322. String title, message, button1, button2, button3;
  62323. AlertWindow::AlertIconType iconType;
  62324. int numButtons;
  62325. Component::SafePointer<Component> associatedComponent;
  62326. int run() const
  62327. {
  62328. return (int) (pointer_sized_int)
  62329. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62330. }
  62331. private:
  62332. int show() const
  62333. {
  62334. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62335. : LookAndFeel::getDefaultLookAndFeel();
  62336. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62337. iconType, numButtons, associatedComponent));
  62338. jassert (alertBox != 0); // you have to return one of these!
  62339. return alertBox->runModalLoop();
  62340. }
  62341. static void* showCallback (void* userData)
  62342. {
  62343. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62344. }
  62345. };
  62346. void AlertWindow::showMessageBox (AlertIconType iconType,
  62347. const String& title,
  62348. const String& message,
  62349. const String& buttonText,
  62350. Component* associatedComponent)
  62351. {
  62352. AlertWindowInfo info;
  62353. info.title = title;
  62354. info.message = message;
  62355. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62356. info.iconType = iconType;
  62357. info.numButtons = 1;
  62358. info.associatedComponent = associatedComponent;
  62359. info.run();
  62360. }
  62361. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62362. const String& title,
  62363. const String& message,
  62364. const String& button1Text,
  62365. const String& button2Text,
  62366. Component* associatedComponent)
  62367. {
  62368. AlertWindowInfo info;
  62369. info.title = title;
  62370. info.message = message;
  62371. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62372. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62373. info.iconType = iconType;
  62374. info.numButtons = 2;
  62375. info.associatedComponent = associatedComponent;
  62376. return info.run() != 0;
  62377. }
  62378. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62379. const String& title,
  62380. const String& message,
  62381. const String& button1Text,
  62382. const String& button2Text,
  62383. const String& button3Text,
  62384. Component* associatedComponent)
  62385. {
  62386. AlertWindowInfo info;
  62387. info.title = title;
  62388. info.message = message;
  62389. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62390. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62391. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62392. info.iconType = iconType;
  62393. info.numButtons = 3;
  62394. info.associatedComponent = associatedComponent;
  62395. return info.run();
  62396. }
  62397. END_JUCE_NAMESPACE
  62398. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62399. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62400. BEGIN_JUCE_NAMESPACE
  62401. CallOutBox::CallOutBox (Component& contentComponent,
  62402. Component& componentToPointTo,
  62403. Component* const parentComponent)
  62404. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62405. {
  62406. addAndMakeVisible (&content);
  62407. if (parentComponent != 0)
  62408. {
  62409. updatePosition (parentComponent->getLocalBounds(),
  62410. componentToPointTo.getLocalBounds()
  62411. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  62412. parentComponent->addAndMakeVisible (this);
  62413. }
  62414. else
  62415. {
  62416. if (! JUCEApplication::isStandaloneApp())
  62417. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62418. updatePosition (componentToPointTo.getScreenBounds(),
  62419. componentToPointTo.getParentMonitorArea());
  62420. addToDesktop (ComponentPeer::windowIsTemporary);
  62421. }
  62422. }
  62423. CallOutBox::~CallOutBox()
  62424. {
  62425. }
  62426. void CallOutBox::setArrowSize (const float newSize)
  62427. {
  62428. arrowSize = newSize;
  62429. borderSpace = jmax (20, (int) arrowSize);
  62430. refreshPath();
  62431. }
  62432. void CallOutBox::paint (Graphics& g)
  62433. {
  62434. if (background.isNull())
  62435. {
  62436. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62437. Graphics g (background);
  62438. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62439. }
  62440. g.setColour (Colours::black);
  62441. g.drawImageAt (background, 0, 0);
  62442. }
  62443. void CallOutBox::resized()
  62444. {
  62445. content.setTopLeftPosition (borderSpace, borderSpace);
  62446. refreshPath();
  62447. }
  62448. void CallOutBox::moved()
  62449. {
  62450. refreshPath();
  62451. }
  62452. void CallOutBox::childBoundsChanged (Component*)
  62453. {
  62454. updatePosition (targetArea, availableArea);
  62455. }
  62456. bool CallOutBox::hitTest (int x, int y)
  62457. {
  62458. return outline.contains ((float) x, (float) y);
  62459. }
  62460. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62461. void CallOutBox::inputAttemptWhenModal()
  62462. {
  62463. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62464. if (targetArea.contains (mousePos))
  62465. {
  62466. // if you click on the area that originally popped-up the callout, you expect it
  62467. // to get rid of the box, but deleting the box here allows the click to pass through and
  62468. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62469. postCommandMessage (callOutBoxDismissCommandId);
  62470. }
  62471. else
  62472. {
  62473. exitModalState (0);
  62474. setVisible (false);
  62475. }
  62476. }
  62477. void CallOutBox::handleCommandMessage (int commandId)
  62478. {
  62479. Component::handleCommandMessage (commandId);
  62480. if (commandId == callOutBoxDismissCommandId)
  62481. {
  62482. exitModalState (0);
  62483. setVisible (false);
  62484. }
  62485. }
  62486. bool CallOutBox::keyPressed (const KeyPress& key)
  62487. {
  62488. if (key.isKeyCode (KeyPress::escapeKey))
  62489. {
  62490. inputAttemptWhenModal();
  62491. return true;
  62492. }
  62493. return false;
  62494. }
  62495. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62496. {
  62497. targetArea = newAreaToPointTo;
  62498. availableArea = newAreaToFitIn;
  62499. Rectangle<int> bounds (0, 0,
  62500. content.getWidth() + borderSpace * 2,
  62501. content.getHeight() + borderSpace * 2);
  62502. const int hw = bounds.getWidth() / 2;
  62503. const int hh = bounds.getHeight() / 2;
  62504. const float hwReduced = (float) (hw - borderSpace * 3);
  62505. const float hhReduced = (float) (hh - borderSpace * 3);
  62506. const float arrowIndent = borderSpace - arrowSize;
  62507. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62508. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62509. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62510. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62511. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62512. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62513. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62514. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62515. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62516. float nearest = 1.0e9f;
  62517. for (int i = 0; i < 4; ++i)
  62518. {
  62519. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62520. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62521. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62522. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62523. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62524. distanceFromCentre *= 2.0f;
  62525. if (distanceFromCentre < nearest)
  62526. {
  62527. nearest = distanceFromCentre;
  62528. targetPoint = targets[i];
  62529. bounds.setPosition ((int) (centre.getX() - hw),
  62530. (int) (centre.getY() - hh));
  62531. }
  62532. }
  62533. setBounds (bounds);
  62534. }
  62535. void CallOutBox::refreshPath()
  62536. {
  62537. repaint();
  62538. background = Image::null;
  62539. outline.clear();
  62540. const float gap = 4.5f;
  62541. const float cornerSize = 9.0f;
  62542. const float cornerSize2 = 2.0f * cornerSize;
  62543. const float arrowBaseWidth = arrowSize * 0.7f;
  62544. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62545. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62546. outline.startNewSubPath (left + cornerSize, top);
  62547. if (targetY <= top)
  62548. {
  62549. outline.lineTo (targetX - arrowBaseWidth, top);
  62550. outline.lineTo (targetX, targetY);
  62551. outline.lineTo (targetX + arrowBaseWidth, top);
  62552. }
  62553. outline.lineTo (right - cornerSize, top);
  62554. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62555. if (targetX >= right)
  62556. {
  62557. outline.lineTo (right, targetY - arrowBaseWidth);
  62558. outline.lineTo (targetX, targetY);
  62559. outline.lineTo (right, targetY + arrowBaseWidth);
  62560. }
  62561. outline.lineTo (right, bottom - cornerSize);
  62562. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62563. if (targetY >= bottom)
  62564. {
  62565. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62566. outline.lineTo (targetX, targetY);
  62567. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62568. }
  62569. outline.lineTo (left + cornerSize, bottom);
  62570. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62571. if (targetX <= left)
  62572. {
  62573. outline.lineTo (left, targetY + arrowBaseWidth);
  62574. outline.lineTo (targetX, targetY);
  62575. outline.lineTo (left, targetY - arrowBaseWidth);
  62576. }
  62577. outline.lineTo (left, top + cornerSize);
  62578. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62579. outline.closeSubPath();
  62580. }
  62581. END_JUCE_NAMESPACE
  62582. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62583. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62584. BEGIN_JUCE_NAMESPACE
  62585. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62586. static Array <ComponentPeer*> heavyweightPeers;
  62587. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62588. : component (component_),
  62589. styleFlags (styleFlags_),
  62590. lastPaintTime (0),
  62591. constrainer (0),
  62592. lastDragAndDropCompUnderMouse (0),
  62593. fakeMouseMessageSent (false),
  62594. isWindowMinimised (false)
  62595. {
  62596. heavyweightPeers.add (this);
  62597. }
  62598. ComponentPeer::~ComponentPeer()
  62599. {
  62600. heavyweightPeers.removeValue (this);
  62601. Desktop::getInstance().triggerFocusCallback();
  62602. }
  62603. int ComponentPeer::getNumPeers() throw()
  62604. {
  62605. return heavyweightPeers.size();
  62606. }
  62607. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62608. {
  62609. return heavyweightPeers [index];
  62610. }
  62611. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62612. {
  62613. for (int i = heavyweightPeers.size(); --i >= 0;)
  62614. {
  62615. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62616. if (peer->getComponent() == component)
  62617. return peer;
  62618. }
  62619. return 0;
  62620. }
  62621. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62622. {
  62623. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62624. }
  62625. void ComponentPeer::updateCurrentModifiers() throw()
  62626. {
  62627. ModifierKeys::updateCurrentModifiers();
  62628. }
  62629. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62630. {
  62631. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62632. jassert (mouse != 0); // not enough sources!
  62633. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62634. }
  62635. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62636. {
  62637. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62638. jassert (mouse != 0); // not enough sources!
  62639. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62640. }
  62641. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62642. {
  62643. Graphics g (&contextToPaintTo);
  62644. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62645. g.saveState();
  62646. #endif
  62647. JUCE_TRY
  62648. {
  62649. component->paintEntireComponent (g);
  62650. }
  62651. JUCE_CATCH_EXCEPTION
  62652. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62653. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62654. // clearly when things are being repainted.
  62655. {
  62656. g.restoreState();
  62657. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62658. (uint8) Random::getSystemRandom().nextInt (255),
  62659. (uint8) Random::getSystemRandom().nextInt (255),
  62660. (uint8) 0x50));
  62661. }
  62662. #endif
  62663. }
  62664. bool ComponentPeer::handleKeyPress (const int keyCode,
  62665. const juce_wchar textCharacter)
  62666. {
  62667. updateCurrentModifiers();
  62668. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62669. ? Component::getCurrentlyFocusedComponent()
  62670. : component;
  62671. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62672. {
  62673. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62674. if (currentModalComp != 0)
  62675. target = currentModalComp;
  62676. }
  62677. const KeyPress keyInfo (keyCode,
  62678. ModifierKeys::getCurrentModifiers().getRawFlags()
  62679. & ModifierKeys::allKeyboardModifiers,
  62680. textCharacter);
  62681. bool keyWasUsed = false;
  62682. while (target != 0)
  62683. {
  62684. const Component::SafePointer<Component> deletionChecker (target);
  62685. if (target->keyListeners_ != 0)
  62686. {
  62687. for (int i = target->keyListeners_->size(); --i >= 0;)
  62688. {
  62689. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62690. if (keyWasUsed || deletionChecker == 0)
  62691. return keyWasUsed;
  62692. i = jmin (i, target->keyListeners_->size());
  62693. }
  62694. }
  62695. keyWasUsed = target->keyPressed (keyInfo);
  62696. if (keyWasUsed || deletionChecker == 0)
  62697. break;
  62698. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62699. {
  62700. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62701. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62702. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62703. break;
  62704. }
  62705. target = target->parentComponent_;
  62706. }
  62707. return keyWasUsed;
  62708. }
  62709. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62710. {
  62711. updateCurrentModifiers();
  62712. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62713. ? Component::getCurrentlyFocusedComponent()
  62714. : component;
  62715. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62716. {
  62717. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62718. if (currentModalComp != 0)
  62719. target = currentModalComp;
  62720. }
  62721. bool keyWasUsed = false;
  62722. while (target != 0)
  62723. {
  62724. const Component::SafePointer<Component> deletionChecker (target);
  62725. keyWasUsed = target->keyStateChanged (isKeyDown);
  62726. if (keyWasUsed || deletionChecker == 0)
  62727. break;
  62728. if (target->keyListeners_ != 0)
  62729. {
  62730. for (int i = target->keyListeners_->size(); --i >= 0;)
  62731. {
  62732. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62733. if (keyWasUsed || deletionChecker == 0)
  62734. return keyWasUsed;
  62735. i = jmin (i, target->keyListeners_->size());
  62736. }
  62737. }
  62738. target = target->parentComponent_;
  62739. }
  62740. return keyWasUsed;
  62741. }
  62742. void ComponentPeer::handleModifierKeysChange()
  62743. {
  62744. updateCurrentModifiers();
  62745. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62746. if (target == 0)
  62747. target = Component::getCurrentlyFocusedComponent();
  62748. if (target == 0)
  62749. target = component;
  62750. if (target != 0)
  62751. target->internalModifierKeysChanged();
  62752. }
  62753. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62754. {
  62755. Component* const c = Component::getCurrentlyFocusedComponent();
  62756. if (component->isParentOf (c))
  62757. {
  62758. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62759. if (ti != 0 && ti->isTextInputActive())
  62760. return ti;
  62761. }
  62762. return 0;
  62763. }
  62764. void ComponentPeer::handleBroughtToFront()
  62765. {
  62766. updateCurrentModifiers();
  62767. if (component != 0)
  62768. component->internalBroughtToFront();
  62769. }
  62770. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62771. {
  62772. constrainer = newConstrainer;
  62773. }
  62774. void ComponentPeer::handleMovedOrResized()
  62775. {
  62776. jassert (component->isValidComponent());
  62777. updateCurrentModifiers();
  62778. const bool nowMinimised = isMinimised();
  62779. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62780. {
  62781. const Component::SafePointer<Component> deletionChecker (component);
  62782. const Rectangle<int> newBounds (getBounds());
  62783. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62784. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62785. if (wasMoved || wasResized)
  62786. {
  62787. component->bounds_ = newBounds;
  62788. if (wasResized)
  62789. component->repaint();
  62790. component->sendMovedResizedMessages (wasMoved, wasResized);
  62791. if (deletionChecker == 0)
  62792. return;
  62793. }
  62794. }
  62795. if (isWindowMinimised != nowMinimised)
  62796. {
  62797. isWindowMinimised = nowMinimised;
  62798. component->minimisationStateChanged (nowMinimised);
  62799. component->sendVisibilityChangeMessage();
  62800. }
  62801. if (! isFullScreen())
  62802. lastNonFullscreenBounds = component->getBounds();
  62803. }
  62804. void ComponentPeer::handleFocusGain()
  62805. {
  62806. updateCurrentModifiers();
  62807. if (component->isParentOf (lastFocusedComponent))
  62808. {
  62809. Component::currentlyFocusedComponent = lastFocusedComponent;
  62810. Desktop::getInstance().triggerFocusCallback();
  62811. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62812. }
  62813. else
  62814. {
  62815. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62816. component->grabKeyboardFocus();
  62817. else
  62818. Component::bringModalComponentToFront();
  62819. }
  62820. }
  62821. void ComponentPeer::handleFocusLoss()
  62822. {
  62823. updateCurrentModifiers();
  62824. if (component->hasKeyboardFocus (true))
  62825. {
  62826. lastFocusedComponent = Component::currentlyFocusedComponent;
  62827. if (lastFocusedComponent != 0)
  62828. {
  62829. Component::currentlyFocusedComponent = 0;
  62830. Desktop::getInstance().triggerFocusCallback();
  62831. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62832. }
  62833. }
  62834. }
  62835. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62836. {
  62837. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62838. ? static_cast <Component*> (lastFocusedComponent)
  62839. : component;
  62840. }
  62841. void ComponentPeer::handleScreenSizeChange()
  62842. {
  62843. updateCurrentModifiers();
  62844. component->parentSizeChanged();
  62845. handleMovedOrResized();
  62846. }
  62847. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62848. {
  62849. lastNonFullscreenBounds = newBounds;
  62850. }
  62851. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62852. {
  62853. return lastNonFullscreenBounds;
  62854. }
  62855. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62856. const StringArray& files,
  62857. FileDragAndDropTarget* const lastOne)
  62858. {
  62859. while (c != 0)
  62860. {
  62861. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62862. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62863. return t;
  62864. c = c->getParentComponent();
  62865. }
  62866. return 0;
  62867. }
  62868. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62869. {
  62870. updateCurrentModifiers();
  62871. FileDragAndDropTarget* lastTarget
  62872. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62873. FileDragAndDropTarget* newTarget = 0;
  62874. Component* const compUnderMouse = component->getComponentAt (position);
  62875. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62876. {
  62877. lastDragAndDropCompUnderMouse = compUnderMouse;
  62878. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62879. if (newTarget != lastTarget)
  62880. {
  62881. if (lastTarget != 0)
  62882. lastTarget->fileDragExit (files);
  62883. dragAndDropTargetComponent = 0;
  62884. if (newTarget != 0)
  62885. {
  62886. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62887. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62888. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62889. }
  62890. }
  62891. }
  62892. else
  62893. {
  62894. newTarget = lastTarget;
  62895. }
  62896. if (newTarget != 0)
  62897. {
  62898. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62899. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62900. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62901. }
  62902. }
  62903. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62904. {
  62905. handleFileDragMove (files, Point<int> (-1, -1));
  62906. jassert (dragAndDropTargetComponent == 0);
  62907. lastDragAndDropCompUnderMouse = 0;
  62908. }
  62909. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62910. {
  62911. handleFileDragMove (files, position);
  62912. if (dragAndDropTargetComponent != 0)
  62913. {
  62914. FileDragAndDropTarget* const target
  62915. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62916. dragAndDropTargetComponent = 0;
  62917. lastDragAndDropCompUnderMouse = 0;
  62918. if (target != 0)
  62919. {
  62920. Component* const targetComp = dynamic_cast <Component*> (target);
  62921. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62922. {
  62923. targetComp->internalModalInputAttempt();
  62924. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62925. return;
  62926. }
  62927. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62928. target->filesDropped (files, pos.getX(), pos.getY());
  62929. }
  62930. }
  62931. }
  62932. void ComponentPeer::handleUserClosingWindow()
  62933. {
  62934. updateCurrentModifiers();
  62935. component->userTriedToCloseWindow();
  62936. }
  62937. void ComponentPeer::bringModalComponentToFront()
  62938. {
  62939. Component::bringModalComponentToFront();
  62940. }
  62941. void ComponentPeer::clearMaskedRegion()
  62942. {
  62943. maskedRegion.clear();
  62944. }
  62945. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62946. {
  62947. maskedRegion.add (x, y, w, h);
  62948. }
  62949. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62950. {
  62951. StringArray s;
  62952. s.add ("Software Renderer");
  62953. return s;
  62954. }
  62955. int ComponentPeer::getCurrentRenderingEngine() throw()
  62956. {
  62957. return 0;
  62958. }
  62959. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62960. {
  62961. }
  62962. END_JUCE_NAMESPACE
  62963. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62964. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62965. BEGIN_JUCE_NAMESPACE
  62966. DialogWindow::DialogWindow (const String& name,
  62967. const Colour& backgroundColour_,
  62968. const bool escapeKeyTriggersCloseButton_,
  62969. const bool addToDesktop_)
  62970. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62971. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62972. {
  62973. }
  62974. DialogWindow::~DialogWindow()
  62975. {
  62976. }
  62977. void DialogWindow::resized()
  62978. {
  62979. DocumentWindow::resized();
  62980. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62981. if (escapeKeyTriggersCloseButton
  62982. && getCloseButton() != 0
  62983. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62984. {
  62985. getCloseButton()->addShortcut (esc);
  62986. }
  62987. }
  62988. class TempDialogWindow : public DialogWindow
  62989. {
  62990. public:
  62991. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62992. : DialogWindow (title, colour, escapeCloses, true)
  62993. {
  62994. if (! JUCEApplication::isStandaloneApp())
  62995. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62996. }
  62997. ~TempDialogWindow()
  62998. {
  62999. }
  63000. void closeButtonPressed()
  63001. {
  63002. setVisible (false);
  63003. }
  63004. private:
  63005. TempDialogWindow (const TempDialogWindow&);
  63006. TempDialogWindow& operator= (const TempDialogWindow&);
  63007. };
  63008. int DialogWindow::showModalDialog (const String& dialogTitle,
  63009. Component* contentComponent,
  63010. Component* componentToCentreAround,
  63011. const Colour& colour,
  63012. const bool escapeKeyTriggersCloseButton,
  63013. const bool shouldBeResizable,
  63014. const bool useBottomRightCornerResizer)
  63015. {
  63016. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63017. dw.setContentComponent (contentComponent, true, true);
  63018. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63019. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63020. const int result = dw.runModalLoop();
  63021. dw.setContentComponent (0, false);
  63022. return result;
  63023. }
  63024. END_JUCE_NAMESPACE
  63025. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63026. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63027. BEGIN_JUCE_NAMESPACE
  63028. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63029. {
  63030. public:
  63031. ButtonListenerProxy (DocumentWindow& owner_)
  63032. : owner (owner_)
  63033. {
  63034. }
  63035. void buttonClicked (Button* button)
  63036. {
  63037. if (button == owner.getMinimiseButton())
  63038. owner.minimiseButtonPressed();
  63039. else if (button == owner.getMaximiseButton())
  63040. owner.maximiseButtonPressed();
  63041. else if (button == owner.getCloseButton())
  63042. owner.closeButtonPressed();
  63043. }
  63044. juce_UseDebuggingNewOperator
  63045. private:
  63046. DocumentWindow& owner;
  63047. ButtonListenerProxy (const ButtonListenerProxy&);
  63048. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63049. };
  63050. DocumentWindow::DocumentWindow (const String& title,
  63051. const Colour& backgroundColour,
  63052. const int requiredButtons_,
  63053. const bool addToDesktop_)
  63054. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63055. titleBarHeight (26),
  63056. menuBarHeight (24),
  63057. requiredButtons (requiredButtons_),
  63058. #if JUCE_MAC
  63059. positionTitleBarButtonsOnLeft (true),
  63060. #else
  63061. positionTitleBarButtonsOnLeft (false),
  63062. #endif
  63063. drawTitleTextCentred (true),
  63064. menuBarModel (0)
  63065. {
  63066. setResizeLimits (128, 128, 32768, 32768);
  63067. lookAndFeelChanged();
  63068. }
  63069. DocumentWindow::~DocumentWindow()
  63070. {
  63071. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63072. titleBarButtons[i] = 0;
  63073. menuBar = 0;
  63074. }
  63075. void DocumentWindow::repaintTitleBar()
  63076. {
  63077. repaint (getTitleBarArea());
  63078. }
  63079. void DocumentWindow::setName (const String& newName)
  63080. {
  63081. if (newName != getName())
  63082. {
  63083. Component::setName (newName);
  63084. repaintTitleBar();
  63085. }
  63086. }
  63087. void DocumentWindow::setIcon (const Image& imageToUse)
  63088. {
  63089. titleBarIcon = imageToUse;
  63090. repaintTitleBar();
  63091. }
  63092. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63093. {
  63094. titleBarHeight = newHeight;
  63095. resized();
  63096. repaintTitleBar();
  63097. }
  63098. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63099. const bool positionTitleBarButtonsOnLeft_)
  63100. {
  63101. requiredButtons = requiredButtons_;
  63102. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63103. lookAndFeelChanged();
  63104. }
  63105. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63106. {
  63107. drawTitleTextCentred = textShouldBeCentred;
  63108. repaintTitleBar();
  63109. }
  63110. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63111. const int menuBarHeight_)
  63112. {
  63113. if (menuBarModel != menuBarModel_)
  63114. {
  63115. menuBar = 0;
  63116. menuBarModel = menuBarModel_;
  63117. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63118. : getLookAndFeel().getDefaultMenuBarHeight();
  63119. if (menuBarModel != 0)
  63120. {
  63121. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63122. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63123. menuBar->setEnabled (isActiveWindow());
  63124. }
  63125. resized();
  63126. }
  63127. }
  63128. void DocumentWindow::closeButtonPressed()
  63129. {
  63130. /* If you've got a close button, you have to override this method to get
  63131. rid of your window!
  63132. If the window is just a pop-up, you should override this method and make
  63133. it delete the window in whatever way is appropriate for your app. E.g. you
  63134. might just want to call "delete this".
  63135. If your app is centred around this window such that the whole app should quit when
  63136. the window is closed, then you will probably want to use this method as an opportunity
  63137. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63138. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63139. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63140. or closing it via the taskbar icon on Windows).
  63141. */
  63142. jassertfalse;
  63143. }
  63144. void DocumentWindow::minimiseButtonPressed()
  63145. {
  63146. setMinimised (true);
  63147. }
  63148. void DocumentWindow::maximiseButtonPressed()
  63149. {
  63150. setFullScreen (! isFullScreen());
  63151. }
  63152. void DocumentWindow::paint (Graphics& g)
  63153. {
  63154. ResizableWindow::paint (g);
  63155. if (resizableBorder == 0)
  63156. {
  63157. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63158. const BorderSize border (getBorderThickness());
  63159. g.fillRect (0, 0, getWidth(), border.getTop());
  63160. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63161. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63162. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63163. }
  63164. const Rectangle<int> titleBarArea (getTitleBarArea());
  63165. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63166. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  63167. int titleSpaceX1 = 6;
  63168. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63169. for (int i = 0; i < 3; ++i)
  63170. {
  63171. if (titleBarButtons[i] != 0)
  63172. {
  63173. if (positionTitleBarButtonsOnLeft)
  63174. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63175. else
  63176. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63177. }
  63178. }
  63179. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63180. titleBarArea.getWidth(),
  63181. titleBarArea.getHeight(),
  63182. titleSpaceX1,
  63183. jmax (1, titleSpaceX2 - titleSpaceX1),
  63184. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63185. ! drawTitleTextCentred);
  63186. }
  63187. void DocumentWindow::resized()
  63188. {
  63189. ResizableWindow::resized();
  63190. if (titleBarButtons[1] != 0)
  63191. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63192. const Rectangle<int> titleBarArea (getTitleBarArea());
  63193. getLookAndFeel()
  63194. .positionDocumentWindowButtons (*this,
  63195. titleBarArea.getX(), titleBarArea.getY(),
  63196. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63197. titleBarButtons[0],
  63198. titleBarButtons[1],
  63199. titleBarButtons[2],
  63200. positionTitleBarButtonsOnLeft);
  63201. if (menuBar != 0)
  63202. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63203. titleBarArea.getWidth(), menuBarHeight);
  63204. }
  63205. const BorderSize DocumentWindow::getBorderThickness()
  63206. {
  63207. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63208. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63209. }
  63210. const BorderSize DocumentWindow::getContentComponentBorder()
  63211. {
  63212. BorderSize border (getBorderThickness());
  63213. border.setTop (border.getTop()
  63214. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63215. + (menuBar != 0 ? menuBarHeight : 0));
  63216. return border;
  63217. }
  63218. int DocumentWindow::getTitleBarHeight() const
  63219. {
  63220. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63221. }
  63222. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63223. {
  63224. const BorderSize border (getBorderThickness());
  63225. return Rectangle<int> (border.getLeft(), border.getTop(),
  63226. getWidth() - border.getLeftAndRight(),
  63227. getTitleBarHeight());
  63228. }
  63229. Button* DocumentWindow::getCloseButton() const throw()
  63230. {
  63231. return titleBarButtons[2];
  63232. }
  63233. Button* DocumentWindow::getMinimiseButton() const throw()
  63234. {
  63235. return titleBarButtons[0];
  63236. }
  63237. Button* DocumentWindow::getMaximiseButton() const throw()
  63238. {
  63239. return titleBarButtons[1];
  63240. }
  63241. int DocumentWindow::getDesktopWindowStyleFlags() const
  63242. {
  63243. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63244. if ((requiredButtons & minimiseButton) != 0)
  63245. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63246. if ((requiredButtons & maximiseButton) != 0)
  63247. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63248. if ((requiredButtons & closeButton) != 0)
  63249. styleFlags |= ComponentPeer::windowHasCloseButton;
  63250. return styleFlags;
  63251. }
  63252. void DocumentWindow::lookAndFeelChanged()
  63253. {
  63254. int i;
  63255. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63256. titleBarButtons[i] = 0;
  63257. if (! isUsingNativeTitleBar())
  63258. {
  63259. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63260. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63261. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63262. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63263. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63264. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63265. for (i = 0; i < 3; ++i)
  63266. {
  63267. if (titleBarButtons[i] != 0)
  63268. {
  63269. if (buttonListener == 0)
  63270. buttonListener = new ButtonListenerProxy (*this);
  63271. titleBarButtons[i]->addButtonListener (buttonListener);
  63272. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63273. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63274. Component::addAndMakeVisible (titleBarButtons[i]);
  63275. }
  63276. }
  63277. if (getCloseButton() != 0)
  63278. {
  63279. #if JUCE_MAC
  63280. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63281. #else
  63282. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63283. #endif
  63284. }
  63285. }
  63286. activeWindowStatusChanged();
  63287. ResizableWindow::lookAndFeelChanged();
  63288. }
  63289. void DocumentWindow::parentHierarchyChanged()
  63290. {
  63291. lookAndFeelChanged();
  63292. }
  63293. void DocumentWindow::activeWindowStatusChanged()
  63294. {
  63295. ResizableWindow::activeWindowStatusChanged();
  63296. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63297. if (titleBarButtons[i] != 0)
  63298. titleBarButtons[i]->setEnabled (isActiveWindow());
  63299. if (menuBar != 0)
  63300. menuBar->setEnabled (isActiveWindow());
  63301. }
  63302. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63303. {
  63304. if (getTitleBarArea().contains (e.x, e.y)
  63305. && getMaximiseButton() != 0)
  63306. {
  63307. getMaximiseButton()->triggerClick();
  63308. }
  63309. }
  63310. void DocumentWindow::userTriedToCloseWindow()
  63311. {
  63312. closeButtonPressed();
  63313. }
  63314. END_JUCE_NAMESPACE
  63315. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63316. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63317. BEGIN_JUCE_NAMESPACE
  63318. ResizableWindow::ResizableWindow (const String& name,
  63319. const bool addToDesktop_)
  63320. : TopLevelWindow (name, addToDesktop_),
  63321. resizeToFitContent (false),
  63322. fullscreen (false),
  63323. lastNonFullScreenPos (50, 50, 256, 256),
  63324. constrainer (0)
  63325. #if JUCE_DEBUG
  63326. , hasBeenResized (false)
  63327. #endif
  63328. {
  63329. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63330. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63331. if (addToDesktop_)
  63332. Component::addToDesktop (getDesktopWindowStyleFlags());
  63333. }
  63334. ResizableWindow::ResizableWindow (const String& name,
  63335. const Colour& backgroundColour_,
  63336. const bool addToDesktop_)
  63337. : TopLevelWindow (name, addToDesktop_),
  63338. resizeToFitContent (false),
  63339. fullscreen (false),
  63340. lastNonFullScreenPos (50, 50, 256, 256),
  63341. constrainer (0)
  63342. #if JUCE_DEBUG
  63343. , hasBeenResized (false)
  63344. #endif
  63345. {
  63346. setBackgroundColour (backgroundColour_);
  63347. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63348. if (addToDesktop_)
  63349. Component::addToDesktop (getDesktopWindowStyleFlags());
  63350. }
  63351. ResizableWindow::~ResizableWindow()
  63352. {
  63353. resizableCorner = 0;
  63354. resizableBorder = 0;
  63355. contentComponent.deleteAndZero();
  63356. // have you been adding your own components directly to this window..? tut tut tut.
  63357. // Read the instructions for using a ResizableWindow!
  63358. jassert (getNumChildComponents() == 0);
  63359. }
  63360. int ResizableWindow::getDesktopWindowStyleFlags() const
  63361. {
  63362. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63363. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63364. styleFlags |= ComponentPeer::windowIsResizable;
  63365. return styleFlags;
  63366. }
  63367. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63368. const bool deleteOldOne,
  63369. const bool resizeToFit)
  63370. {
  63371. resizeToFitContent = resizeToFit;
  63372. if (newContentComponent != static_cast <Component*> (contentComponent))
  63373. {
  63374. if (deleteOldOne)
  63375. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63376. // external deletion of the content comp)
  63377. else
  63378. removeChildComponent (contentComponent);
  63379. contentComponent = newContentComponent;
  63380. Component::addAndMakeVisible (contentComponent);
  63381. }
  63382. if (resizeToFit)
  63383. childBoundsChanged (contentComponent);
  63384. resized(); // must always be called to position the new content comp
  63385. }
  63386. void ResizableWindow::setContentComponentSize (int width, int height)
  63387. {
  63388. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63389. const BorderSize border (getContentComponentBorder());
  63390. setSize (width + border.getLeftAndRight(),
  63391. height + border.getTopAndBottom());
  63392. }
  63393. const BorderSize ResizableWindow::getBorderThickness()
  63394. {
  63395. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63396. }
  63397. const BorderSize ResizableWindow::getContentComponentBorder()
  63398. {
  63399. return getBorderThickness();
  63400. }
  63401. void ResizableWindow::moved()
  63402. {
  63403. updateLastPos();
  63404. }
  63405. void ResizableWindow::visibilityChanged()
  63406. {
  63407. TopLevelWindow::visibilityChanged();
  63408. updateLastPos();
  63409. }
  63410. void ResizableWindow::resized()
  63411. {
  63412. if (resizableBorder != 0)
  63413. {
  63414. resizableBorder->setVisible (! isFullScreen());
  63415. resizableBorder->setBorderThickness (getBorderThickness());
  63416. resizableBorder->setSize (getWidth(), getHeight());
  63417. resizableBorder->toBack();
  63418. }
  63419. if (resizableCorner != 0)
  63420. {
  63421. resizableCorner->setVisible (! isFullScreen());
  63422. const int resizerSize = 18;
  63423. resizableCorner->setBounds (getWidth() - resizerSize,
  63424. getHeight() - resizerSize,
  63425. resizerSize, resizerSize);
  63426. }
  63427. if (contentComponent != 0)
  63428. contentComponent->setBoundsInset (getContentComponentBorder());
  63429. updateLastPos();
  63430. #if JUCE_DEBUG
  63431. hasBeenResized = true;
  63432. #endif
  63433. }
  63434. void ResizableWindow::childBoundsChanged (Component* child)
  63435. {
  63436. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63437. {
  63438. // not going to look very good if this component has a zero size..
  63439. jassert (child->getWidth() > 0);
  63440. jassert (child->getHeight() > 0);
  63441. const BorderSize borders (getContentComponentBorder());
  63442. setSize (child->getWidth() + borders.getLeftAndRight(),
  63443. child->getHeight() + borders.getTopAndBottom());
  63444. }
  63445. }
  63446. void ResizableWindow::activeWindowStatusChanged()
  63447. {
  63448. const BorderSize border (getContentComponentBorder());
  63449. Rectangle<int> area (getLocalBounds());
  63450. repaint (area.removeFromTop (border.getTop()));
  63451. repaint (area.removeFromLeft (border.getLeft()));
  63452. repaint (area.removeFromRight (border.getRight()));
  63453. repaint (area.removeFromBottom (border.getBottom()));
  63454. }
  63455. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63456. const bool useBottomRightCornerResizer)
  63457. {
  63458. if (shouldBeResizable)
  63459. {
  63460. if (useBottomRightCornerResizer)
  63461. {
  63462. resizableBorder = 0;
  63463. if (resizableCorner == 0)
  63464. {
  63465. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63466. resizableCorner->setAlwaysOnTop (true);
  63467. }
  63468. }
  63469. else
  63470. {
  63471. resizableCorner = 0;
  63472. if (resizableBorder == 0)
  63473. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63474. }
  63475. }
  63476. else
  63477. {
  63478. resizableCorner = 0;
  63479. resizableBorder = 0;
  63480. }
  63481. if (isUsingNativeTitleBar())
  63482. recreateDesktopWindow();
  63483. childBoundsChanged (contentComponent);
  63484. resized();
  63485. }
  63486. bool ResizableWindow::isResizable() const throw()
  63487. {
  63488. return resizableCorner != 0
  63489. || resizableBorder != 0;
  63490. }
  63491. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63492. const int newMinimumHeight,
  63493. const int newMaximumWidth,
  63494. const int newMaximumHeight) throw()
  63495. {
  63496. // if you've set up a custom constrainer then these settings won't have any effect..
  63497. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63498. if (constrainer == 0)
  63499. setConstrainer (&defaultConstrainer);
  63500. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63501. newMaximumWidth, newMaximumHeight);
  63502. setBoundsConstrained (getBounds());
  63503. }
  63504. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63505. {
  63506. if (constrainer != newConstrainer)
  63507. {
  63508. constrainer = newConstrainer;
  63509. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63510. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63511. resizableCorner = 0;
  63512. resizableBorder = 0;
  63513. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63514. ComponentPeer* const peer = getPeer();
  63515. if (peer != 0)
  63516. peer->setConstrainer (newConstrainer);
  63517. }
  63518. }
  63519. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63520. {
  63521. if (constrainer != 0)
  63522. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63523. else
  63524. setBounds (bounds);
  63525. }
  63526. void ResizableWindow::paint (Graphics& g)
  63527. {
  63528. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63529. getBorderThickness(), *this);
  63530. if (! isFullScreen())
  63531. {
  63532. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63533. getBorderThickness(), *this);
  63534. }
  63535. #if JUCE_DEBUG
  63536. /* If this fails, then you've probably written a subclass with a resized()
  63537. callback but forgotten to make it call its parent class's resized() method.
  63538. It's important when you override methods like resized(), moved(),
  63539. etc., that you make sure the base class methods also get called.
  63540. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63541. because your content should all be inside the content component - and it's the
  63542. content component's resized() method that you should be using to do your
  63543. layout.
  63544. */
  63545. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63546. #endif
  63547. }
  63548. void ResizableWindow::lookAndFeelChanged()
  63549. {
  63550. resized();
  63551. if (isOnDesktop())
  63552. {
  63553. Component::addToDesktop (getDesktopWindowStyleFlags());
  63554. ComponentPeer* const peer = getPeer();
  63555. if (peer != 0)
  63556. peer->setConstrainer (constrainer);
  63557. }
  63558. }
  63559. const Colour ResizableWindow::getBackgroundColour() const throw()
  63560. {
  63561. return findColour (backgroundColourId, false);
  63562. }
  63563. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63564. {
  63565. Colour backgroundColour (newColour);
  63566. if (! Desktop::canUseSemiTransparentWindows())
  63567. backgroundColour = newColour.withAlpha (1.0f);
  63568. setColour (backgroundColourId, backgroundColour);
  63569. setOpaque (backgroundColour.isOpaque());
  63570. repaint();
  63571. }
  63572. bool ResizableWindow::isFullScreen() const
  63573. {
  63574. if (isOnDesktop())
  63575. {
  63576. ComponentPeer* const peer = getPeer();
  63577. return peer != 0 && peer->isFullScreen();
  63578. }
  63579. return fullscreen;
  63580. }
  63581. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63582. {
  63583. if (shouldBeFullScreen != isFullScreen())
  63584. {
  63585. updateLastPos();
  63586. fullscreen = shouldBeFullScreen;
  63587. if (isOnDesktop())
  63588. {
  63589. ComponentPeer* const peer = getPeer();
  63590. if (peer != 0)
  63591. {
  63592. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63593. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63594. peer->setFullScreen (shouldBeFullScreen);
  63595. if (! shouldBeFullScreen)
  63596. setBounds (lastPos);
  63597. }
  63598. else
  63599. {
  63600. jassertfalse;
  63601. }
  63602. }
  63603. else
  63604. {
  63605. if (shouldBeFullScreen)
  63606. setBounds (0, 0, getParentWidth(), getParentHeight());
  63607. else
  63608. setBounds (lastNonFullScreenPos);
  63609. }
  63610. resized();
  63611. }
  63612. }
  63613. bool ResizableWindow::isMinimised() const
  63614. {
  63615. ComponentPeer* const peer = getPeer();
  63616. return (peer != 0) && peer->isMinimised();
  63617. }
  63618. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63619. {
  63620. if (shouldMinimise != isMinimised())
  63621. {
  63622. ComponentPeer* const peer = getPeer();
  63623. if (peer != 0)
  63624. {
  63625. updateLastPos();
  63626. peer->setMinimised (shouldMinimise);
  63627. }
  63628. else
  63629. {
  63630. jassertfalse;
  63631. }
  63632. }
  63633. }
  63634. void ResizableWindow::updateLastPos()
  63635. {
  63636. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63637. {
  63638. lastNonFullScreenPos = getBounds();
  63639. }
  63640. }
  63641. void ResizableWindow::parentSizeChanged()
  63642. {
  63643. if (isFullScreen() && getParentComponent() != 0)
  63644. {
  63645. setBounds (0, 0, getParentWidth(), getParentHeight());
  63646. }
  63647. }
  63648. const String ResizableWindow::getWindowStateAsString()
  63649. {
  63650. updateLastPos();
  63651. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63652. }
  63653. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63654. {
  63655. StringArray tokens;
  63656. tokens.addTokens (s, false);
  63657. tokens.removeEmptyStrings();
  63658. tokens.trim();
  63659. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63660. const int firstCoord = fs ? 1 : 0;
  63661. if (tokens.size() != firstCoord + 4)
  63662. return false;
  63663. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63664. tokens[firstCoord + 1].getIntValue(),
  63665. tokens[firstCoord + 2].getIntValue(),
  63666. tokens[firstCoord + 3].getIntValue());
  63667. if (newPos.isEmpty())
  63668. return false;
  63669. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63670. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63671. if (peer != 0)
  63672. peer->getFrameSize().addTo (newPos);
  63673. if (! screen.contains (newPos))
  63674. {
  63675. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63676. jmin (newPos.getHeight(), screen.getHeight()));
  63677. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63678. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63679. }
  63680. if (peer != 0)
  63681. {
  63682. peer->getFrameSize().subtractFrom (newPos);
  63683. peer->setNonFullScreenBounds (newPos);
  63684. }
  63685. lastNonFullScreenPos = newPos;
  63686. setFullScreen (fs);
  63687. if (! fs)
  63688. setBoundsConstrained (newPos);
  63689. return true;
  63690. }
  63691. void ResizableWindow::mouseDown (const MouseEvent&)
  63692. {
  63693. if (! isFullScreen())
  63694. dragger.startDraggingComponent (this, constrainer);
  63695. }
  63696. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63697. {
  63698. if (! isFullScreen())
  63699. dragger.dragComponent (this, e);
  63700. }
  63701. #if JUCE_DEBUG
  63702. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63703. {
  63704. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63705. manages its child components automatically, and if you add your own it'll cause
  63706. trouble. Instead, use setContentComponent() to give it a component which
  63707. will be automatically resized and kept in the right place - then you can add
  63708. subcomponents to the content comp. See the notes for the ResizableWindow class
  63709. for more info.
  63710. If you really know what you're doing and want to avoid this assertion, just call
  63711. Component::addChildComponent directly.
  63712. */
  63713. jassertfalse;
  63714. Component::addChildComponent (child, zOrder);
  63715. }
  63716. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63717. {
  63718. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63719. manages its child components automatically, and if you add your own it'll cause
  63720. trouble. Instead, use setContentComponent() to give it a component which
  63721. will be automatically resized and kept in the right place - then you can add
  63722. subcomponents to the content comp. See the notes for the ResizableWindow class
  63723. for more info.
  63724. If you really know what you're doing and want to avoid this assertion, just call
  63725. Component::addAndMakeVisible directly.
  63726. */
  63727. jassertfalse;
  63728. Component::addAndMakeVisible (child, zOrder);
  63729. }
  63730. #endif
  63731. END_JUCE_NAMESPACE
  63732. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63733. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63734. BEGIN_JUCE_NAMESPACE
  63735. SplashScreen::SplashScreen()
  63736. {
  63737. setOpaque (true);
  63738. }
  63739. SplashScreen::~SplashScreen()
  63740. {
  63741. }
  63742. void SplashScreen::show (const String& title,
  63743. const Image& backgroundImage_,
  63744. const int minimumTimeToDisplayFor,
  63745. const bool useDropShadow,
  63746. const bool removeOnMouseClick)
  63747. {
  63748. backgroundImage = backgroundImage_;
  63749. jassert (backgroundImage_.isValid());
  63750. if (backgroundImage_.isValid())
  63751. {
  63752. setOpaque (! backgroundImage_.hasAlphaChannel());
  63753. show (title,
  63754. backgroundImage_.getWidth(),
  63755. backgroundImage_.getHeight(),
  63756. minimumTimeToDisplayFor,
  63757. useDropShadow,
  63758. removeOnMouseClick);
  63759. }
  63760. }
  63761. void SplashScreen::show (const String& title,
  63762. const int width,
  63763. const int height,
  63764. const int minimumTimeToDisplayFor,
  63765. const bool useDropShadow,
  63766. const bool removeOnMouseClick)
  63767. {
  63768. setName (title);
  63769. setAlwaysOnTop (true);
  63770. setVisible (true);
  63771. centreWithSize (width, height);
  63772. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63773. toFront (false);
  63774. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63775. repaint();
  63776. originalClickCounter = removeOnMouseClick
  63777. ? Desktop::getMouseButtonClickCounter()
  63778. : std::numeric_limits<int>::max();
  63779. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63780. startTimer (50);
  63781. }
  63782. void SplashScreen::paint (Graphics& g)
  63783. {
  63784. g.setOpacity (1.0f);
  63785. g.drawImage (backgroundImage,
  63786. 0, 0, getWidth(), getHeight(),
  63787. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63788. }
  63789. void SplashScreen::timerCallback()
  63790. {
  63791. if (Time::getCurrentTime() > earliestTimeToDelete
  63792. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63793. {
  63794. delete this;
  63795. }
  63796. }
  63797. END_JUCE_NAMESPACE
  63798. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63799. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63800. BEGIN_JUCE_NAMESPACE
  63801. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63802. const bool hasProgressBar,
  63803. const bool hasCancelButton,
  63804. const int timeOutMsWhenCancelling_,
  63805. const String& cancelButtonText)
  63806. : Thread ("Juce Progress Window"),
  63807. progress (0.0),
  63808. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63809. {
  63810. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63811. .createAlertWindow (title, String::empty, cancelButtonText,
  63812. String::empty, String::empty,
  63813. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63814. if (hasProgressBar)
  63815. alertWindow->addProgressBarComponent (progress);
  63816. }
  63817. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63818. {
  63819. stopThread (timeOutMsWhenCancelling);
  63820. }
  63821. bool ThreadWithProgressWindow::runThread (const int priority)
  63822. {
  63823. startThread (priority);
  63824. startTimer (100);
  63825. {
  63826. const ScopedLock sl (messageLock);
  63827. alertWindow->setMessage (message);
  63828. }
  63829. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63830. stopThread (timeOutMsWhenCancelling);
  63831. alertWindow->setVisible (false);
  63832. return finishedNaturally;
  63833. }
  63834. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63835. {
  63836. progress = newProgress;
  63837. }
  63838. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63839. {
  63840. const ScopedLock sl (messageLock);
  63841. message = newStatusMessage;
  63842. }
  63843. void ThreadWithProgressWindow::timerCallback()
  63844. {
  63845. if (! isThreadRunning())
  63846. {
  63847. // thread has finished normally..
  63848. alertWindow->exitModalState (1);
  63849. alertWindow->setVisible (false);
  63850. }
  63851. else
  63852. {
  63853. const ScopedLock sl (messageLock);
  63854. alertWindow->setMessage (message);
  63855. }
  63856. }
  63857. END_JUCE_NAMESPACE
  63858. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63859. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63860. BEGIN_JUCE_NAMESPACE
  63861. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63862. const int millisecondsBeforeTipAppears_)
  63863. : Component ("tooltip"),
  63864. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63865. mouseClicks (0),
  63866. lastHideTime (0),
  63867. lastComponentUnderMouse (0),
  63868. changedCompsSinceShown (true)
  63869. {
  63870. if (Desktop::getInstance().getMainMouseSource().canHover())
  63871. startTimer (123);
  63872. setAlwaysOnTop (true);
  63873. setOpaque (true);
  63874. if (parentComponent != 0)
  63875. parentComponent->addChildComponent (this);
  63876. }
  63877. TooltipWindow::~TooltipWindow()
  63878. {
  63879. hide();
  63880. }
  63881. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63882. {
  63883. millisecondsBeforeTipAppears = newTimeMs;
  63884. }
  63885. void TooltipWindow::paint (Graphics& g)
  63886. {
  63887. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63888. }
  63889. void TooltipWindow::mouseEnter (const MouseEvent&)
  63890. {
  63891. hide();
  63892. }
  63893. void TooltipWindow::showFor (const String& tip)
  63894. {
  63895. jassert (tip.isNotEmpty());
  63896. if (tipShowing != tip)
  63897. repaint();
  63898. tipShowing = tip;
  63899. Point<int> mousePos (Desktop::getMousePosition());
  63900. if (getParentComponent() != 0)
  63901. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  63902. int x, y, w, h;
  63903. getLookAndFeel().getTooltipSize (tip, w, h);
  63904. if (mousePos.getX() > getParentWidth() / 2)
  63905. x = mousePos.getX() - (w + 12);
  63906. else
  63907. x = mousePos.getX() + 24;
  63908. if (mousePos.getY() > getParentHeight() / 2)
  63909. y = mousePos.getY() - (h + 6);
  63910. else
  63911. y = mousePos.getY() + 6;
  63912. setBounds (x, y, w, h);
  63913. setVisible (true);
  63914. if (getParentComponent() == 0)
  63915. {
  63916. addToDesktop (ComponentPeer::windowHasDropShadow
  63917. | ComponentPeer::windowIsTemporary
  63918. | ComponentPeer::windowIgnoresKeyPresses);
  63919. }
  63920. toFront (false);
  63921. }
  63922. const String TooltipWindow::getTipFor (Component* const c)
  63923. {
  63924. if (c != 0
  63925. && Process::isForegroundProcess()
  63926. && ! Component::isMouseButtonDownAnywhere())
  63927. {
  63928. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63929. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63930. return ttc->getTooltip();
  63931. }
  63932. return String::empty;
  63933. }
  63934. void TooltipWindow::hide()
  63935. {
  63936. tipShowing = String::empty;
  63937. removeFromDesktop();
  63938. setVisible (false);
  63939. }
  63940. void TooltipWindow::timerCallback()
  63941. {
  63942. const unsigned int now = Time::getApproximateMillisecondCounter();
  63943. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63944. const String newTip (getTipFor (newComp));
  63945. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63946. lastComponentUnderMouse = newComp;
  63947. lastTipUnderMouse = newTip;
  63948. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63949. const bool mouseWasClicked = clickCount > mouseClicks;
  63950. mouseClicks = clickCount;
  63951. const Point<int> mousePos (Desktop::getMousePosition());
  63952. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63953. lastMousePos = mousePos;
  63954. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63955. lastCompChangeTime = now;
  63956. if (isVisible() || now < lastHideTime + 500)
  63957. {
  63958. // if a tip is currently visible (or has just disappeared), update to a new one
  63959. // immediately if needed..
  63960. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63961. {
  63962. if (isVisible())
  63963. {
  63964. lastHideTime = now;
  63965. hide();
  63966. }
  63967. }
  63968. else if (tipChanged)
  63969. {
  63970. showFor (newTip);
  63971. }
  63972. }
  63973. else
  63974. {
  63975. // if there isn't currently a tip, but one is needed, only let it
  63976. // appear after a timeout..
  63977. if (newTip.isNotEmpty()
  63978. && newTip != tipShowing
  63979. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63980. {
  63981. showFor (newTip);
  63982. }
  63983. }
  63984. }
  63985. END_JUCE_NAMESPACE
  63986. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63987. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63988. BEGIN_JUCE_NAMESPACE
  63989. /** Keeps track of the active top level window.
  63990. */
  63991. class TopLevelWindowManager : public Timer,
  63992. public DeletedAtShutdown
  63993. {
  63994. public:
  63995. TopLevelWindowManager()
  63996. : currentActive (0)
  63997. {
  63998. }
  63999. ~TopLevelWindowManager()
  64000. {
  64001. clearSingletonInstance();
  64002. }
  64003. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64004. void timerCallback()
  64005. {
  64006. startTimer (jmin (1731, getTimerInterval() * 2));
  64007. TopLevelWindow* active = 0;
  64008. if (Process::isForegroundProcess())
  64009. {
  64010. active = currentActive;
  64011. Component* const c = Component::getCurrentlyFocusedComponent();
  64012. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64013. if (tlw == 0 && c != 0)
  64014. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64015. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64016. if (tlw != 0)
  64017. active = tlw;
  64018. }
  64019. if (active != currentActive)
  64020. {
  64021. currentActive = active;
  64022. for (int i = windows.size(); --i >= 0;)
  64023. {
  64024. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64025. tlw->setWindowActive (isWindowActive (tlw));
  64026. i = jmin (i, windows.size() - 1);
  64027. }
  64028. Desktop::getInstance().triggerFocusCallback();
  64029. }
  64030. }
  64031. bool addWindow (TopLevelWindow* const w)
  64032. {
  64033. windows.add (w);
  64034. startTimer (10);
  64035. return isWindowActive (w);
  64036. }
  64037. void removeWindow (TopLevelWindow* const w)
  64038. {
  64039. startTimer (10);
  64040. if (currentActive == w)
  64041. currentActive = 0;
  64042. windows.removeValue (w);
  64043. if (windows.size() == 0)
  64044. deleteInstance();
  64045. }
  64046. Array <TopLevelWindow*> windows;
  64047. private:
  64048. TopLevelWindow* currentActive;
  64049. bool isWindowActive (TopLevelWindow* const tlw) const
  64050. {
  64051. return (tlw == currentActive
  64052. || tlw->isParentOf (currentActive)
  64053. || tlw->hasKeyboardFocus (true))
  64054. && tlw->isShowing();
  64055. }
  64056. TopLevelWindowManager (const TopLevelWindowManager&);
  64057. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64058. };
  64059. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64060. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64061. {
  64062. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64063. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64064. }
  64065. TopLevelWindow::TopLevelWindow (const String& name,
  64066. const bool addToDesktop_)
  64067. : Component (name),
  64068. useDropShadow (true),
  64069. useNativeTitleBar (false),
  64070. windowIsActive_ (false)
  64071. {
  64072. setOpaque (true);
  64073. if (addToDesktop_)
  64074. Component::addToDesktop (getDesktopWindowStyleFlags());
  64075. else
  64076. setDropShadowEnabled (true);
  64077. setWantsKeyboardFocus (true);
  64078. setBroughtToFrontOnMouseClick (true);
  64079. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64080. }
  64081. TopLevelWindow::~TopLevelWindow()
  64082. {
  64083. shadower = 0;
  64084. TopLevelWindowManager::getInstance()->removeWindow (this);
  64085. }
  64086. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64087. {
  64088. if (hasKeyboardFocus (true))
  64089. TopLevelWindowManager::getInstance()->timerCallback();
  64090. else
  64091. TopLevelWindowManager::getInstance()->startTimer (10);
  64092. }
  64093. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64094. {
  64095. if (windowIsActive_ != isNowActive)
  64096. {
  64097. windowIsActive_ = isNowActive;
  64098. activeWindowStatusChanged();
  64099. }
  64100. }
  64101. void TopLevelWindow::activeWindowStatusChanged()
  64102. {
  64103. }
  64104. void TopLevelWindow::parentHierarchyChanged()
  64105. {
  64106. setDropShadowEnabled (useDropShadow);
  64107. }
  64108. void TopLevelWindow::visibilityChanged()
  64109. {
  64110. if (isShowing())
  64111. toFront (true);
  64112. }
  64113. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64114. {
  64115. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64116. if (useDropShadow)
  64117. styleFlags |= ComponentPeer::windowHasDropShadow;
  64118. if (useNativeTitleBar)
  64119. styleFlags |= ComponentPeer::windowHasTitleBar;
  64120. return styleFlags;
  64121. }
  64122. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64123. {
  64124. useDropShadow = useShadow;
  64125. if (isOnDesktop())
  64126. {
  64127. shadower = 0;
  64128. Component::addToDesktop (getDesktopWindowStyleFlags());
  64129. }
  64130. else
  64131. {
  64132. if (useShadow && isOpaque())
  64133. {
  64134. if (shadower == 0)
  64135. {
  64136. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64137. if (shadower != 0)
  64138. shadower->setOwner (this);
  64139. }
  64140. }
  64141. else
  64142. {
  64143. shadower = 0;
  64144. }
  64145. }
  64146. }
  64147. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64148. {
  64149. if (useNativeTitleBar != useNativeTitleBar_)
  64150. {
  64151. useNativeTitleBar = useNativeTitleBar_;
  64152. recreateDesktopWindow();
  64153. sendLookAndFeelChange();
  64154. }
  64155. }
  64156. void TopLevelWindow::recreateDesktopWindow()
  64157. {
  64158. if (isOnDesktop())
  64159. {
  64160. Component::addToDesktop (getDesktopWindowStyleFlags());
  64161. toFront (true);
  64162. }
  64163. }
  64164. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64165. {
  64166. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64167. because this class needs to make sure its layout corresponds with settings like whether
  64168. it's got a native title bar or not.
  64169. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64170. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64171. method, then add or remove whatever flags are necessary from this value before returning it.
  64172. */
  64173. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64174. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64175. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64176. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64177. sendLookAndFeelChange();
  64178. }
  64179. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64180. {
  64181. if (c == 0)
  64182. c = TopLevelWindow::getActiveTopLevelWindow();
  64183. if (c == 0)
  64184. {
  64185. centreWithSize (width, height);
  64186. }
  64187. else
  64188. {
  64189. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64190. (c->getHeight() - height) / 2)));
  64191. Rectangle<int> parentArea (c->getParentMonitorArea());
  64192. if (getParentComponent() != 0)
  64193. {
  64194. p = getParentComponent()->globalPositionToRelative (p);
  64195. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64196. }
  64197. parentArea.reduce (12, 12);
  64198. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64199. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64200. width, height);
  64201. }
  64202. }
  64203. int TopLevelWindow::getNumTopLevelWindows() throw()
  64204. {
  64205. return TopLevelWindowManager::getInstance()->windows.size();
  64206. }
  64207. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64208. {
  64209. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64210. }
  64211. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64212. {
  64213. TopLevelWindow* best = 0;
  64214. int bestNumTWLParents = -1;
  64215. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64216. {
  64217. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64218. if (tlw->isActiveWindow())
  64219. {
  64220. int numTWLParents = 0;
  64221. const Component* c = tlw->getParentComponent();
  64222. while (c != 0)
  64223. {
  64224. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64225. ++numTWLParents;
  64226. c = c->getParentComponent();
  64227. }
  64228. if (bestNumTWLParents < numTWLParents)
  64229. {
  64230. best = tlw;
  64231. bestNumTWLParents = numTWLParents;
  64232. }
  64233. }
  64234. }
  64235. return best;
  64236. }
  64237. END_JUCE_NAMESPACE
  64238. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64239. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64240. BEGIN_JUCE_NAMESPACE
  64241. namespace RelativeCoordinateHelpers
  64242. {
  64243. static void skipComma (const juce_wchar* const s, int& i)
  64244. {
  64245. while (CharacterFunctions::isWhitespace (s[i]))
  64246. ++i;
  64247. if (s[i] == ',')
  64248. ++i;
  64249. }
  64250. }
  64251. const String RelativeCoordinate::Strings::parent ("parent");
  64252. const String RelativeCoordinate::Strings::left ("left");
  64253. const String RelativeCoordinate::Strings::right ("right");
  64254. const String RelativeCoordinate::Strings::top ("top");
  64255. const String RelativeCoordinate::Strings::bottom ("bottom");
  64256. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64257. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64258. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64259. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64260. RelativeCoordinate::RelativeCoordinate()
  64261. {
  64262. }
  64263. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64264. : term (term_)
  64265. {
  64266. }
  64267. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64268. : term (other.term)
  64269. {
  64270. }
  64271. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64272. {
  64273. term = other.term;
  64274. return *this;
  64275. }
  64276. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64277. : term (absoluteDistanceFromOrigin)
  64278. {
  64279. }
  64280. RelativeCoordinate::RelativeCoordinate (const String& s)
  64281. {
  64282. try
  64283. {
  64284. term = Expression (s);
  64285. }
  64286. catch (...)
  64287. {}
  64288. }
  64289. RelativeCoordinate::~RelativeCoordinate()
  64290. {
  64291. }
  64292. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64293. {
  64294. return term.toString() == other.term.toString();
  64295. }
  64296. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64297. {
  64298. return ! operator== (other);
  64299. }
  64300. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64301. {
  64302. try
  64303. {
  64304. if (context != 0)
  64305. return term.evaluate (*context);
  64306. else
  64307. return term.evaluate();
  64308. }
  64309. catch (...)
  64310. {}
  64311. return 0.0;
  64312. }
  64313. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64314. {
  64315. try
  64316. {
  64317. if (context != 0)
  64318. term.evaluate (*context);
  64319. else
  64320. term.evaluate();
  64321. }
  64322. catch (...)
  64323. {
  64324. return true;
  64325. }
  64326. return false;
  64327. }
  64328. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64329. {
  64330. try
  64331. {
  64332. if (context != 0)
  64333. {
  64334. term = term.adjustedToGiveNewResult (newPos, *context);
  64335. }
  64336. else
  64337. {
  64338. Expression::EvaluationContext defaultContext;
  64339. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64340. }
  64341. }
  64342. catch (...)
  64343. {}
  64344. }
  64345. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64346. {
  64347. try
  64348. {
  64349. if (context != 0)
  64350. return term.referencesSymbol (coordName, *context);
  64351. Expression::EvaluationContext defaultContext;
  64352. return term.referencesSymbol (coordName, defaultContext);
  64353. }
  64354. catch (...)
  64355. {}
  64356. return false;
  64357. }
  64358. bool RelativeCoordinate::isDynamic() const
  64359. {
  64360. return term.usesAnySymbols();
  64361. }
  64362. const String RelativeCoordinate::toString() const
  64363. {
  64364. return term.toString();
  64365. }
  64366. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName,
  64367. const Expression::EvaluationContext* context)
  64368. {
  64369. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64370. if (term.referencesSymbol (oldName, *context))
  64371. {
  64372. const double oldValue = resolve (context);
  64373. term = term.withRenamedSymbol (oldName, newName);
  64374. moveToAbsolute (oldValue, context);
  64375. }
  64376. }
  64377. RelativePoint::RelativePoint()
  64378. {
  64379. }
  64380. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64381. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64382. {
  64383. }
  64384. RelativePoint::RelativePoint (const float x_, const float y_)
  64385. : x (x_), y (y_)
  64386. {
  64387. }
  64388. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64389. : x (x_), y (y_)
  64390. {
  64391. }
  64392. RelativePoint::RelativePoint (const String& s)
  64393. {
  64394. int i = 0;
  64395. x = RelativeCoordinate (Expression::parse (s, i));
  64396. RelativeCoordinateHelpers::skipComma (s, i);
  64397. y = RelativeCoordinate (Expression::parse (s, i));
  64398. }
  64399. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64400. {
  64401. return x == other.x && y == other.y;
  64402. }
  64403. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64404. {
  64405. return ! operator== (other);
  64406. }
  64407. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64408. {
  64409. return Point<float> ((float) x.resolve (context),
  64410. (float) y.resolve (context));
  64411. }
  64412. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64413. {
  64414. x.moveToAbsolute (newPos.getX(), context);
  64415. y.moveToAbsolute (newPos.getY(), context);
  64416. }
  64417. const String RelativePoint::toString() const
  64418. {
  64419. return x.toString() + ", " + y.toString();
  64420. }
  64421. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName, const Expression::EvaluationContext* context)
  64422. {
  64423. x.renameSymbolIfUsed (oldName, newName, context);
  64424. y.renameSymbolIfUsed (oldName, newName, context);
  64425. }
  64426. bool RelativePoint::isDynamic() const
  64427. {
  64428. return x.isDynamic() || y.isDynamic();
  64429. }
  64430. RelativeRectangle::RelativeRectangle()
  64431. {
  64432. }
  64433. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64434. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64435. : left (left_), right (right_), top (top_), bottom (bottom_)
  64436. {
  64437. }
  64438. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64439. : left (rect.getX()),
  64440. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64441. top (rect.getY()),
  64442. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64443. {
  64444. }
  64445. RelativeRectangle::RelativeRectangle (const String& s)
  64446. {
  64447. int i = 0;
  64448. left = RelativeCoordinate (Expression::parse (s, i));
  64449. RelativeCoordinateHelpers::skipComma (s, i);
  64450. top = RelativeCoordinate (Expression::parse (s, i));
  64451. RelativeCoordinateHelpers::skipComma (s, i);
  64452. right = RelativeCoordinate (Expression::parse (s, i));
  64453. RelativeCoordinateHelpers::skipComma (s, i);
  64454. bottom = RelativeCoordinate (Expression::parse (s, i));
  64455. }
  64456. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64457. {
  64458. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64459. }
  64460. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64461. {
  64462. return ! operator== (other);
  64463. }
  64464. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64465. {
  64466. const double l = left.resolve (context);
  64467. const double r = right.resolve (context);
  64468. const double t = top.resolve (context);
  64469. const double b = bottom.resolve (context);
  64470. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64471. }
  64472. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64473. {
  64474. left.moveToAbsolute (newPos.getX(), context);
  64475. right.moveToAbsolute (newPos.getRight(), context);
  64476. top.moveToAbsolute (newPos.getY(), context);
  64477. bottom.moveToAbsolute (newPos.getBottom(), context);
  64478. }
  64479. const String RelativeRectangle::toString() const
  64480. {
  64481. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64482. }
  64483. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName,
  64484. const Expression::EvaluationContext* context)
  64485. {
  64486. left.renameSymbolIfUsed (oldName, newName, context);
  64487. right.renameSymbolIfUsed (oldName, newName, context);
  64488. top.renameSymbolIfUsed (oldName, newName, context);
  64489. bottom.renameSymbolIfUsed (oldName, newName, context);
  64490. }
  64491. RelativePointPath::RelativePointPath()
  64492. : usesNonZeroWinding (true),
  64493. containsDynamicPoints (false)
  64494. {
  64495. }
  64496. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64497. : usesNonZeroWinding (true),
  64498. containsDynamicPoints (false)
  64499. {
  64500. ValueTree state (DrawablePath::valueTreeType);
  64501. other.writeTo (state, 0);
  64502. parse (state);
  64503. }
  64504. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64505. : usesNonZeroWinding (true),
  64506. containsDynamicPoints (false)
  64507. {
  64508. parse (drawable);
  64509. }
  64510. RelativePointPath::RelativePointPath (const Path& path)
  64511. {
  64512. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64513. Path::Iterator i (path);
  64514. while (i.next())
  64515. {
  64516. switch (i.elementType)
  64517. {
  64518. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64519. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64520. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64521. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64522. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64523. default: jassertfalse; break;
  64524. }
  64525. }
  64526. }
  64527. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64528. {
  64529. DrawablePath::ValueTreeWrapper wrapper (state);
  64530. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64531. ValueTree pathTree (wrapper.getPathState());
  64532. pathTree.removeAllChildren (undoManager);
  64533. for (int i = 0; i < elements.size(); ++i)
  64534. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64535. }
  64536. void RelativePointPath::parse (const ValueTree& state)
  64537. {
  64538. DrawablePath::ValueTreeWrapper wrapper (state);
  64539. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64540. RelativePoint points[3];
  64541. const ValueTree pathTree (wrapper.getPathState());
  64542. const int num = pathTree.getNumChildren();
  64543. for (int i = 0; i < num; ++i)
  64544. {
  64545. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64546. const int numCps = e.getNumControlPoints();
  64547. for (int j = 0; j < numCps; ++j)
  64548. {
  64549. points[j] = e.getControlPoint (j);
  64550. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64551. }
  64552. const Identifier type (e.getType());
  64553. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64554. elements.add (new StartSubPath (points[0]));
  64555. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64556. elements.add (new CloseSubPath());
  64557. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64558. elements.add (new LineTo (points[0]));
  64559. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64560. elements.add (new QuadraticTo (points[0], points[1]));
  64561. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64562. elements.add (new CubicTo (points[0], points[1], points[2]));
  64563. else
  64564. jassertfalse;
  64565. }
  64566. }
  64567. RelativePointPath::~RelativePointPath()
  64568. {
  64569. }
  64570. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64571. {
  64572. elements.swapWithArray (other.elements);
  64573. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64574. }
  64575. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64576. {
  64577. for (int i = 0; i < elements.size(); ++i)
  64578. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64579. }
  64580. bool RelativePointPath::containsAnyDynamicPoints() const
  64581. {
  64582. return containsDynamicPoints;
  64583. }
  64584. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64585. {
  64586. }
  64587. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64588. : ElementBase (startSubPathElement), startPos (pos)
  64589. {
  64590. }
  64591. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64592. {
  64593. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64594. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64595. return v;
  64596. }
  64597. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64598. {
  64599. path.startNewSubPath (startPos.resolve (coordFinder));
  64600. }
  64601. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64602. {
  64603. numPoints = 1;
  64604. return &startPos;
  64605. }
  64606. RelativePointPath::CloseSubPath::CloseSubPath()
  64607. : ElementBase (closeSubPathElement)
  64608. {
  64609. }
  64610. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64611. {
  64612. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64613. }
  64614. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64615. {
  64616. path.closeSubPath();
  64617. }
  64618. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64619. {
  64620. numPoints = 0;
  64621. return 0;
  64622. }
  64623. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64624. : ElementBase (lineToElement), endPoint (endPoint_)
  64625. {
  64626. }
  64627. const ValueTree RelativePointPath::LineTo::createTree() const
  64628. {
  64629. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64630. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64631. return v;
  64632. }
  64633. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64634. {
  64635. path.lineTo (endPoint.resolve (coordFinder));
  64636. }
  64637. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64638. {
  64639. numPoints = 1;
  64640. return &endPoint;
  64641. }
  64642. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64643. : ElementBase (quadraticToElement)
  64644. {
  64645. controlPoints[0] = controlPoint;
  64646. controlPoints[1] = endPoint;
  64647. }
  64648. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64649. {
  64650. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64651. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64652. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64653. return v;
  64654. }
  64655. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64656. {
  64657. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64658. controlPoints[1].resolve (coordFinder));
  64659. }
  64660. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64661. {
  64662. numPoints = 2;
  64663. return controlPoints;
  64664. }
  64665. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64666. : ElementBase (cubicToElement)
  64667. {
  64668. controlPoints[0] = controlPoint1;
  64669. controlPoints[1] = controlPoint2;
  64670. controlPoints[2] = endPoint;
  64671. }
  64672. const ValueTree RelativePointPath::CubicTo::createTree() const
  64673. {
  64674. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64675. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64676. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64677. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64678. return v;
  64679. }
  64680. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64681. {
  64682. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64683. controlPoints[1].resolve (coordFinder),
  64684. controlPoints[2].resolve (coordFinder));
  64685. }
  64686. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64687. {
  64688. numPoints = 3;
  64689. return controlPoints;
  64690. }
  64691. RelativeParallelogram::RelativeParallelogram()
  64692. {
  64693. }
  64694. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64695. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64696. {
  64697. }
  64698. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64699. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64700. {
  64701. }
  64702. RelativeParallelogram::~RelativeParallelogram()
  64703. {
  64704. }
  64705. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64706. {
  64707. points[0] = topLeft.resolve (coordFinder);
  64708. points[1] = topRight.resolve (coordFinder);
  64709. points[2] = bottomLeft.resolve (coordFinder);
  64710. }
  64711. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64712. {
  64713. resolveThreePoints (points, coordFinder);
  64714. points[3] = points[1] + (points[2] - points[0]);
  64715. }
  64716. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64717. {
  64718. Point<float> points[4];
  64719. resolveFourCorners (points, coordFinder);
  64720. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64721. }
  64722. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64723. {
  64724. Point<float> points[4];
  64725. resolveFourCorners (points, coordFinder);
  64726. path.startNewSubPath (points[0]);
  64727. path.lineTo (points[1]);
  64728. path.lineTo (points[3]);
  64729. path.lineTo (points[2]);
  64730. path.closeSubPath();
  64731. }
  64732. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64733. {
  64734. Point<float> corners[3];
  64735. resolveThreePoints (corners, coordFinder);
  64736. const Line<float> top (corners[0], corners[1]);
  64737. const Line<float> left (corners[0], corners[2]);
  64738. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64739. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64740. topRight.moveToAbsolute (newTopRight, coordFinder);
  64741. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64742. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64743. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64744. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64745. }
  64746. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64747. {
  64748. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64749. }
  64750. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64751. {
  64752. return ! operator== (other);
  64753. }
  64754. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64755. {
  64756. const Point<float> tr (corners[1] - corners[0]);
  64757. const Point<float> bl (corners[2] - corners[0]);
  64758. target -= corners[0];
  64759. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64760. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64761. }
  64762. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64763. {
  64764. return corners[0]
  64765. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64766. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64767. }
  64768. END_JUCE_NAMESPACE
  64769. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64770. #endif
  64771. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64772. /*** Start of inlined file: juce_Colour.cpp ***/
  64773. BEGIN_JUCE_NAMESPACE
  64774. namespace ColourHelpers
  64775. {
  64776. static uint8 floatAlphaToInt (const float alpha) throw()
  64777. {
  64778. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64779. }
  64780. static void convertHSBtoRGB (float h, float s, float v,
  64781. uint8& r, uint8& g, uint8& b) throw()
  64782. {
  64783. v = jlimit (0.0f, 1.0f, v);
  64784. v *= 255.0f;
  64785. const uint8 intV = (uint8) roundToInt (v);
  64786. if (s <= 0)
  64787. {
  64788. r = intV;
  64789. g = intV;
  64790. b = intV;
  64791. }
  64792. else
  64793. {
  64794. s = jmin (1.0f, s);
  64795. h = jlimit (0.0f, 1.0f, h);
  64796. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64797. const float f = h - std::floor (h);
  64798. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64799. const float y = v * (1.0f - s * f);
  64800. const float z = v * (1.0f - (s * (1.0f - f)));
  64801. if (h < 1.0f)
  64802. {
  64803. r = intV;
  64804. g = (uint8) roundToInt (z);
  64805. b = x;
  64806. }
  64807. else if (h < 2.0f)
  64808. {
  64809. r = (uint8) roundToInt (y);
  64810. g = intV;
  64811. b = x;
  64812. }
  64813. else if (h < 3.0f)
  64814. {
  64815. r = x;
  64816. g = intV;
  64817. b = (uint8) roundToInt (z);
  64818. }
  64819. else if (h < 4.0f)
  64820. {
  64821. r = x;
  64822. g = (uint8) roundToInt (y);
  64823. b = intV;
  64824. }
  64825. else if (h < 5.0f)
  64826. {
  64827. r = (uint8) roundToInt (z);
  64828. g = x;
  64829. b = intV;
  64830. }
  64831. else if (h < 6.0f)
  64832. {
  64833. r = intV;
  64834. g = x;
  64835. b = (uint8) roundToInt (y);
  64836. }
  64837. else
  64838. {
  64839. r = 0;
  64840. g = 0;
  64841. b = 0;
  64842. }
  64843. }
  64844. }
  64845. }
  64846. Colour::Colour() throw()
  64847. : argb (0)
  64848. {
  64849. }
  64850. Colour::Colour (const Colour& other) throw()
  64851. : argb (other.argb)
  64852. {
  64853. }
  64854. Colour& Colour::operator= (const Colour& other) throw()
  64855. {
  64856. argb = other.argb;
  64857. return *this;
  64858. }
  64859. bool Colour::operator== (const Colour& other) const throw()
  64860. {
  64861. return argb.getARGB() == other.argb.getARGB();
  64862. }
  64863. bool Colour::operator!= (const Colour& other) const throw()
  64864. {
  64865. return argb.getARGB() != other.argb.getARGB();
  64866. }
  64867. Colour::Colour (const uint32 argb_) throw()
  64868. : argb (argb_)
  64869. {
  64870. }
  64871. Colour::Colour (const uint8 red,
  64872. const uint8 green,
  64873. const uint8 blue) throw()
  64874. {
  64875. argb.setARGB (0xff, red, green, blue);
  64876. }
  64877. const Colour Colour::fromRGB (const uint8 red,
  64878. const uint8 green,
  64879. const uint8 blue) throw()
  64880. {
  64881. return Colour (red, green, blue);
  64882. }
  64883. Colour::Colour (const uint8 red,
  64884. const uint8 green,
  64885. const uint8 blue,
  64886. const uint8 alpha) throw()
  64887. {
  64888. argb.setARGB (alpha, red, green, blue);
  64889. }
  64890. const Colour Colour::fromRGBA (const uint8 red,
  64891. const uint8 green,
  64892. const uint8 blue,
  64893. const uint8 alpha) throw()
  64894. {
  64895. return Colour (red, green, blue, alpha);
  64896. }
  64897. Colour::Colour (const uint8 red,
  64898. const uint8 green,
  64899. const uint8 blue,
  64900. const float alpha) throw()
  64901. {
  64902. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64903. }
  64904. const Colour Colour::fromRGBAFloat (const uint8 red,
  64905. const uint8 green,
  64906. const uint8 blue,
  64907. const float alpha) throw()
  64908. {
  64909. return Colour (red, green, blue, alpha);
  64910. }
  64911. Colour::Colour (const float hue,
  64912. const float saturation,
  64913. const float brightness,
  64914. const float alpha) throw()
  64915. {
  64916. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64917. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64918. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64919. }
  64920. const Colour Colour::fromHSV (const float hue,
  64921. const float saturation,
  64922. const float brightness,
  64923. const float alpha) throw()
  64924. {
  64925. return Colour (hue, saturation, brightness, alpha);
  64926. }
  64927. Colour::Colour (const float hue,
  64928. const float saturation,
  64929. const float brightness,
  64930. const uint8 alpha) throw()
  64931. {
  64932. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64933. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64934. argb.setARGB (alpha, r, g, b);
  64935. }
  64936. Colour::~Colour() throw()
  64937. {
  64938. }
  64939. const PixelARGB Colour::getPixelARGB() const throw()
  64940. {
  64941. PixelARGB p (argb);
  64942. p.premultiply();
  64943. return p;
  64944. }
  64945. uint32 Colour::getARGB() const throw()
  64946. {
  64947. return argb.getARGB();
  64948. }
  64949. bool Colour::isTransparent() const throw()
  64950. {
  64951. return getAlpha() == 0;
  64952. }
  64953. bool Colour::isOpaque() const throw()
  64954. {
  64955. return getAlpha() == 0xff;
  64956. }
  64957. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64958. {
  64959. PixelARGB newCol (argb);
  64960. newCol.setAlpha (newAlpha);
  64961. return Colour (newCol.getARGB());
  64962. }
  64963. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64964. {
  64965. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64966. PixelARGB newCol (argb);
  64967. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64968. return Colour (newCol.getARGB());
  64969. }
  64970. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64971. {
  64972. jassert (alphaMultiplier >= 0);
  64973. PixelARGB newCol (argb);
  64974. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64975. return Colour (newCol.getARGB());
  64976. }
  64977. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64978. {
  64979. const int destAlpha = getAlpha();
  64980. if (destAlpha > 0)
  64981. {
  64982. const int invA = 0xff - (int) src.getAlpha();
  64983. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64984. if (resA > 0)
  64985. {
  64986. const int da = (invA * destAlpha) / resA;
  64987. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64988. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64989. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64990. (uint8) resA);
  64991. }
  64992. return *this;
  64993. }
  64994. else
  64995. {
  64996. return src;
  64997. }
  64998. }
  64999. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65000. {
  65001. if (proportionOfOther <= 0)
  65002. return *this;
  65003. if (proportionOfOther >= 1.0f)
  65004. return other;
  65005. PixelARGB c1 (getPixelARGB());
  65006. const PixelARGB c2 (other.getPixelARGB());
  65007. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65008. c1.unpremultiply();
  65009. return Colour (c1.getARGB());
  65010. }
  65011. float Colour::getFloatRed() const throw()
  65012. {
  65013. return getRed() / 255.0f;
  65014. }
  65015. float Colour::getFloatGreen() const throw()
  65016. {
  65017. return getGreen() / 255.0f;
  65018. }
  65019. float Colour::getFloatBlue() const throw()
  65020. {
  65021. return getBlue() / 255.0f;
  65022. }
  65023. float Colour::getFloatAlpha() const throw()
  65024. {
  65025. return getAlpha() / 255.0f;
  65026. }
  65027. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65028. {
  65029. const int r = getRed();
  65030. const int g = getGreen();
  65031. const int b = getBlue();
  65032. const int hi = jmax (r, g, b);
  65033. const int lo = jmin (r, g, b);
  65034. if (hi != 0)
  65035. {
  65036. s = (hi - lo) / (float) hi;
  65037. if (s != 0)
  65038. {
  65039. const float invDiff = 1.0f / (hi - lo);
  65040. const float red = (hi - r) * invDiff;
  65041. const float green = (hi - g) * invDiff;
  65042. const float blue = (hi - b) * invDiff;
  65043. if (r == hi)
  65044. h = blue - green;
  65045. else if (g == hi)
  65046. h = 2.0f + red - blue;
  65047. else
  65048. h = 4.0f + green - red;
  65049. h *= 1.0f / 6.0f;
  65050. if (h < 0)
  65051. ++h;
  65052. }
  65053. else
  65054. {
  65055. h = 0;
  65056. }
  65057. }
  65058. else
  65059. {
  65060. s = 0;
  65061. h = 0;
  65062. }
  65063. v = hi / 255.0f;
  65064. }
  65065. float Colour::getHue() const throw()
  65066. {
  65067. float h, s, b;
  65068. getHSB (h, s, b);
  65069. return h;
  65070. }
  65071. const Colour Colour::withHue (const float hue) const throw()
  65072. {
  65073. float h, s, b;
  65074. getHSB (h, s, b);
  65075. return Colour (hue, s, b, getAlpha());
  65076. }
  65077. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65078. {
  65079. float h, s, b;
  65080. getHSB (h, s, b);
  65081. h += amountToRotate;
  65082. h -= std::floor (h);
  65083. return Colour (h, s, b, getAlpha());
  65084. }
  65085. float Colour::getSaturation() const throw()
  65086. {
  65087. float h, s, b;
  65088. getHSB (h, s, b);
  65089. return s;
  65090. }
  65091. const Colour Colour::withSaturation (const float saturation) const throw()
  65092. {
  65093. float h, s, b;
  65094. getHSB (h, s, b);
  65095. return Colour (h, saturation, b, getAlpha());
  65096. }
  65097. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65098. {
  65099. float h, s, b;
  65100. getHSB (h, s, b);
  65101. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65102. }
  65103. float Colour::getBrightness() const throw()
  65104. {
  65105. float h, s, b;
  65106. getHSB (h, s, b);
  65107. return b;
  65108. }
  65109. const Colour Colour::withBrightness (const float brightness) const throw()
  65110. {
  65111. float h, s, b;
  65112. getHSB (h, s, b);
  65113. return Colour (h, s, brightness, getAlpha());
  65114. }
  65115. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65116. {
  65117. float h, s, b;
  65118. getHSB (h, s, b);
  65119. b *= amount;
  65120. if (b > 1.0f)
  65121. b = 1.0f;
  65122. return Colour (h, s, b, getAlpha());
  65123. }
  65124. const Colour Colour::brighter (float amount) const throw()
  65125. {
  65126. amount = 1.0f / (1.0f + amount);
  65127. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65128. (uint8) (255 - (amount * (255 - getGreen()))),
  65129. (uint8) (255 - (amount * (255 - getBlue()))),
  65130. getAlpha());
  65131. }
  65132. const Colour Colour::darker (float amount) const throw()
  65133. {
  65134. amount = 1.0f / (1.0f + amount);
  65135. return Colour ((uint8) (amount * getRed()),
  65136. (uint8) (amount * getGreen()),
  65137. (uint8) (amount * getBlue()),
  65138. getAlpha());
  65139. }
  65140. const Colour Colour::greyLevel (const float brightness) throw()
  65141. {
  65142. const uint8 level
  65143. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65144. return Colour (level, level, level);
  65145. }
  65146. const Colour Colour::contrasting (const float amount) const throw()
  65147. {
  65148. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65149. ? Colours::black
  65150. : Colours::white).withAlpha (amount));
  65151. }
  65152. const Colour Colour::contrasting (const Colour& colour1,
  65153. const Colour& colour2) throw()
  65154. {
  65155. const float b1 = colour1.getBrightness();
  65156. const float b2 = colour2.getBrightness();
  65157. float best = 0.0f;
  65158. float bestDist = 0.0f;
  65159. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65160. {
  65161. const float d1 = std::abs (i - b1);
  65162. const float d2 = std::abs (i - b2);
  65163. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65164. if (dist > bestDist)
  65165. {
  65166. best = i;
  65167. bestDist = dist;
  65168. }
  65169. }
  65170. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65171. .withBrightness (best);
  65172. }
  65173. const String Colour::toString() const
  65174. {
  65175. return String::toHexString ((int) argb.getARGB());
  65176. }
  65177. const Colour Colour::fromString (const String& encodedColourString)
  65178. {
  65179. return Colour ((uint32) encodedColourString.getHexValue32());
  65180. }
  65181. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65182. {
  65183. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65184. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65185. .toUpperCase();
  65186. }
  65187. END_JUCE_NAMESPACE
  65188. /*** End of inlined file: juce_Colour.cpp ***/
  65189. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65190. BEGIN_JUCE_NAMESPACE
  65191. ColourGradient::ColourGradient() throw()
  65192. {
  65193. #if JUCE_DEBUG
  65194. point1.setX (987654.0f);
  65195. #endif
  65196. }
  65197. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65198. const Colour& colour2, const float x2_, const float y2_,
  65199. const bool isRadial_)
  65200. : point1 (x1_, y1_),
  65201. point2 (x2_, y2_),
  65202. isRadial (isRadial_)
  65203. {
  65204. colours.add (ColourPoint (0.0, colour1));
  65205. colours.add (ColourPoint (1.0, colour2));
  65206. }
  65207. ColourGradient::~ColourGradient()
  65208. {
  65209. }
  65210. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65211. {
  65212. return point1 == other.point1 && point2 == other.point2
  65213. && isRadial == other.isRadial
  65214. && colours == other.colours;
  65215. }
  65216. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65217. {
  65218. return ! operator== (other);
  65219. }
  65220. void ColourGradient::clearColours()
  65221. {
  65222. colours.clear();
  65223. }
  65224. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65225. {
  65226. // must be within the two end-points
  65227. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65228. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65229. int i;
  65230. for (i = 0; i < colours.size(); ++i)
  65231. if (colours.getReference(i).position > pos)
  65232. break;
  65233. colours.insert (i, ColourPoint (pos, colour));
  65234. return i;
  65235. }
  65236. void ColourGradient::removeColour (int index)
  65237. {
  65238. jassert (index > 0 && index < colours.size() - 1);
  65239. colours.remove (index);
  65240. }
  65241. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65242. {
  65243. for (int i = 0; i < colours.size(); ++i)
  65244. {
  65245. Colour& c = colours.getReference(i).colour;
  65246. c = c.withMultipliedAlpha (multiplier);
  65247. }
  65248. }
  65249. int ColourGradient::getNumColours() const throw()
  65250. {
  65251. return colours.size();
  65252. }
  65253. double ColourGradient::getColourPosition (const int index) const throw()
  65254. {
  65255. if (((unsigned int) index) < (unsigned int) colours.size())
  65256. return colours.getReference (index).position;
  65257. return 0;
  65258. }
  65259. const Colour ColourGradient::getColour (const int index) const throw()
  65260. {
  65261. if (((unsigned int) index) < (unsigned int) colours.size())
  65262. return colours.getReference (index).colour;
  65263. return Colour();
  65264. }
  65265. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65266. {
  65267. if (((unsigned int) index) < (unsigned int) colours.size())
  65268. colours.getReference (index).colour = newColour;
  65269. }
  65270. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65271. {
  65272. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65273. if (position <= 0 || colours.size() <= 1)
  65274. return colours.getReference(0).colour;
  65275. int i = colours.size() - 1;
  65276. while (position < colours.getReference(i).position)
  65277. --i;
  65278. const ColourPoint& p1 = colours.getReference (i);
  65279. if (i >= colours.size() - 1)
  65280. return p1.colour;
  65281. const ColourPoint& p2 = colours.getReference (i + 1);
  65282. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65283. }
  65284. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65285. {
  65286. #if JUCE_DEBUG
  65287. // trying to use the object without setting its co-ordinates? Have a careful read of
  65288. // the comments for the constructors.
  65289. jassert (point1.getX() != 987654.0f);
  65290. #endif
  65291. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65292. 3 * (int) point1.transformedBy (transform)
  65293. .getDistanceFrom (point2.transformedBy (transform)));
  65294. lookupTable.malloc (numEntries);
  65295. if (colours.size() >= 2)
  65296. {
  65297. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65298. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65299. int index = 0;
  65300. for (int j = 1; j < colours.size(); ++j)
  65301. {
  65302. const ColourPoint& p = colours.getReference (j);
  65303. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65304. const PixelARGB pix2 (p.colour.getPixelARGB());
  65305. for (int i = 0; i < numToDo; ++i)
  65306. {
  65307. jassert (index >= 0 && index < numEntries);
  65308. lookupTable[index] = pix1;
  65309. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65310. ++index;
  65311. }
  65312. pix1 = pix2;
  65313. }
  65314. while (index < numEntries)
  65315. lookupTable [index++] = pix1;
  65316. }
  65317. else
  65318. {
  65319. jassertfalse; // no colours specified!
  65320. }
  65321. return numEntries;
  65322. }
  65323. bool ColourGradient::isOpaque() const throw()
  65324. {
  65325. for (int i = 0; i < colours.size(); ++i)
  65326. if (! colours.getReference(i).colour.isOpaque())
  65327. return false;
  65328. return true;
  65329. }
  65330. bool ColourGradient::isInvisible() const throw()
  65331. {
  65332. for (int i = 0; i < colours.size(); ++i)
  65333. if (! colours.getReference(i).colour.isTransparent())
  65334. return false;
  65335. return true;
  65336. }
  65337. END_JUCE_NAMESPACE
  65338. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65339. /*** Start of inlined file: juce_Colours.cpp ***/
  65340. BEGIN_JUCE_NAMESPACE
  65341. const Colour Colours::transparentBlack (0);
  65342. const Colour Colours::transparentWhite (0x00ffffff);
  65343. const Colour Colours::aliceblue (0xfff0f8ff);
  65344. const Colour Colours::antiquewhite (0xfffaebd7);
  65345. const Colour Colours::aqua (0xff00ffff);
  65346. const Colour Colours::aquamarine (0xff7fffd4);
  65347. const Colour Colours::azure (0xfff0ffff);
  65348. const Colour Colours::beige (0xfff5f5dc);
  65349. const Colour Colours::bisque (0xffffe4c4);
  65350. const Colour Colours::black (0xff000000);
  65351. const Colour Colours::blanchedalmond (0xffffebcd);
  65352. const Colour Colours::blue (0xff0000ff);
  65353. const Colour Colours::blueviolet (0xff8a2be2);
  65354. const Colour Colours::brown (0xffa52a2a);
  65355. const Colour Colours::burlywood (0xffdeb887);
  65356. const Colour Colours::cadetblue (0xff5f9ea0);
  65357. const Colour Colours::chartreuse (0xff7fff00);
  65358. const Colour Colours::chocolate (0xffd2691e);
  65359. const Colour Colours::coral (0xffff7f50);
  65360. const Colour Colours::cornflowerblue (0xff6495ed);
  65361. const Colour Colours::cornsilk (0xfffff8dc);
  65362. const Colour Colours::crimson (0xffdc143c);
  65363. const Colour Colours::cyan (0xff00ffff);
  65364. const Colour Colours::darkblue (0xff00008b);
  65365. const Colour Colours::darkcyan (0xff008b8b);
  65366. const Colour Colours::darkgoldenrod (0xffb8860b);
  65367. const Colour Colours::darkgrey (0xff555555);
  65368. const Colour Colours::darkgreen (0xff006400);
  65369. const Colour Colours::darkkhaki (0xffbdb76b);
  65370. const Colour Colours::darkmagenta (0xff8b008b);
  65371. const Colour Colours::darkolivegreen (0xff556b2f);
  65372. const Colour Colours::darkorange (0xffff8c00);
  65373. const Colour Colours::darkorchid (0xff9932cc);
  65374. const Colour Colours::darkred (0xff8b0000);
  65375. const Colour Colours::darksalmon (0xffe9967a);
  65376. const Colour Colours::darkseagreen (0xff8fbc8f);
  65377. const Colour Colours::darkslateblue (0xff483d8b);
  65378. const Colour Colours::darkslategrey (0xff2f4f4f);
  65379. const Colour Colours::darkturquoise (0xff00ced1);
  65380. const Colour Colours::darkviolet (0xff9400d3);
  65381. const Colour Colours::deeppink (0xffff1493);
  65382. const Colour Colours::deepskyblue (0xff00bfff);
  65383. const Colour Colours::dimgrey (0xff696969);
  65384. const Colour Colours::dodgerblue (0xff1e90ff);
  65385. const Colour Colours::firebrick (0xffb22222);
  65386. const Colour Colours::floralwhite (0xfffffaf0);
  65387. const Colour Colours::forestgreen (0xff228b22);
  65388. const Colour Colours::fuchsia (0xffff00ff);
  65389. const Colour Colours::gainsboro (0xffdcdcdc);
  65390. const Colour Colours::gold (0xffffd700);
  65391. const Colour Colours::goldenrod (0xffdaa520);
  65392. const Colour Colours::grey (0xff808080);
  65393. const Colour Colours::green (0xff008000);
  65394. const Colour Colours::greenyellow (0xffadff2f);
  65395. const Colour Colours::honeydew (0xfff0fff0);
  65396. const Colour Colours::hotpink (0xffff69b4);
  65397. const Colour Colours::indianred (0xffcd5c5c);
  65398. const Colour Colours::indigo (0xff4b0082);
  65399. const Colour Colours::ivory (0xfffffff0);
  65400. const Colour Colours::khaki (0xfff0e68c);
  65401. const Colour Colours::lavender (0xffe6e6fa);
  65402. const Colour Colours::lavenderblush (0xfffff0f5);
  65403. const Colour Colours::lemonchiffon (0xfffffacd);
  65404. const Colour Colours::lightblue (0xffadd8e6);
  65405. const Colour Colours::lightcoral (0xfff08080);
  65406. const Colour Colours::lightcyan (0xffe0ffff);
  65407. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65408. const Colour Colours::lightgreen (0xff90ee90);
  65409. const Colour Colours::lightgrey (0xffd3d3d3);
  65410. const Colour Colours::lightpink (0xffffb6c1);
  65411. const Colour Colours::lightsalmon (0xffffa07a);
  65412. const Colour Colours::lightseagreen (0xff20b2aa);
  65413. const Colour Colours::lightskyblue (0xff87cefa);
  65414. const Colour Colours::lightslategrey (0xff778899);
  65415. const Colour Colours::lightsteelblue (0xffb0c4de);
  65416. const Colour Colours::lightyellow (0xffffffe0);
  65417. const Colour Colours::lime (0xff00ff00);
  65418. const Colour Colours::limegreen (0xff32cd32);
  65419. const Colour Colours::linen (0xfffaf0e6);
  65420. const Colour Colours::magenta (0xffff00ff);
  65421. const Colour Colours::maroon (0xff800000);
  65422. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65423. const Colour Colours::mediumblue (0xff0000cd);
  65424. const Colour Colours::mediumorchid (0xffba55d3);
  65425. const Colour Colours::mediumpurple (0xff9370db);
  65426. const Colour Colours::mediumseagreen (0xff3cb371);
  65427. const Colour Colours::mediumslateblue (0xff7b68ee);
  65428. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65429. const Colour Colours::mediumturquoise (0xff48d1cc);
  65430. const Colour Colours::mediumvioletred (0xffc71585);
  65431. const Colour Colours::midnightblue (0xff191970);
  65432. const Colour Colours::mintcream (0xfff5fffa);
  65433. const Colour Colours::mistyrose (0xffffe4e1);
  65434. const Colour Colours::navajowhite (0xffffdead);
  65435. const Colour Colours::navy (0xff000080);
  65436. const Colour Colours::oldlace (0xfffdf5e6);
  65437. const Colour Colours::olive (0xff808000);
  65438. const Colour Colours::olivedrab (0xff6b8e23);
  65439. const Colour Colours::orange (0xffffa500);
  65440. const Colour Colours::orangered (0xffff4500);
  65441. const Colour Colours::orchid (0xffda70d6);
  65442. const Colour Colours::palegoldenrod (0xffeee8aa);
  65443. const Colour Colours::palegreen (0xff98fb98);
  65444. const Colour Colours::paleturquoise (0xffafeeee);
  65445. const Colour Colours::palevioletred (0xffdb7093);
  65446. const Colour Colours::papayawhip (0xffffefd5);
  65447. const Colour Colours::peachpuff (0xffffdab9);
  65448. const Colour Colours::peru (0xffcd853f);
  65449. const Colour Colours::pink (0xffffc0cb);
  65450. const Colour Colours::plum (0xffdda0dd);
  65451. const Colour Colours::powderblue (0xffb0e0e6);
  65452. const Colour Colours::purple (0xff800080);
  65453. const Colour Colours::red (0xffff0000);
  65454. const Colour Colours::rosybrown (0xffbc8f8f);
  65455. const Colour Colours::royalblue (0xff4169e1);
  65456. const Colour Colours::saddlebrown (0xff8b4513);
  65457. const Colour Colours::salmon (0xfffa8072);
  65458. const Colour Colours::sandybrown (0xfff4a460);
  65459. const Colour Colours::seagreen (0xff2e8b57);
  65460. const Colour Colours::seashell (0xfffff5ee);
  65461. const Colour Colours::sienna (0xffa0522d);
  65462. const Colour Colours::silver (0xffc0c0c0);
  65463. const Colour Colours::skyblue (0xff87ceeb);
  65464. const Colour Colours::slateblue (0xff6a5acd);
  65465. const Colour Colours::slategrey (0xff708090);
  65466. const Colour Colours::snow (0xfffffafa);
  65467. const Colour Colours::springgreen (0xff00ff7f);
  65468. const Colour Colours::steelblue (0xff4682b4);
  65469. const Colour Colours::tan (0xffd2b48c);
  65470. const Colour Colours::teal (0xff008080);
  65471. const Colour Colours::thistle (0xffd8bfd8);
  65472. const Colour Colours::tomato (0xffff6347);
  65473. const Colour Colours::turquoise (0xff40e0d0);
  65474. const Colour Colours::violet (0xffee82ee);
  65475. const Colour Colours::wheat (0xfff5deb3);
  65476. const Colour Colours::white (0xffffffff);
  65477. const Colour Colours::whitesmoke (0xfff5f5f5);
  65478. const Colour Colours::yellow (0xffffff00);
  65479. const Colour Colours::yellowgreen (0xff9acd32);
  65480. const Colour Colours::findColourForName (const String& colourName,
  65481. const Colour& defaultColour)
  65482. {
  65483. static const int presets[] =
  65484. {
  65485. // (first value is the string's hashcode, second is ARGB)
  65486. 0x05978fff, 0xff000000, /* black */
  65487. 0x06bdcc29, 0xffffffff, /* white */
  65488. 0x002e305a, 0xff0000ff, /* blue */
  65489. 0x00308adf, 0xff808080, /* grey */
  65490. 0x05e0cf03, 0xff008000, /* green */
  65491. 0x0001b891, 0xffff0000, /* red */
  65492. 0xd43c6474, 0xffffff00, /* yellow */
  65493. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65494. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65495. 0x002dcebc, 0xff00ffff, /* aqua */
  65496. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65497. 0x0590228f, 0xfff0ffff, /* azure */
  65498. 0x05947fe4, 0xfff5f5dc, /* beige */
  65499. 0xad388e35, 0xffffe4c4, /* bisque */
  65500. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65501. 0x39129959, 0xff8a2be2, /* blueviolet */
  65502. 0x059a8136, 0xffa52a2a, /* brown */
  65503. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65504. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65505. 0x6b748956, 0xff7fff00, /* chartreuse */
  65506. 0x2903623c, 0xffd2691e, /* chocolate */
  65507. 0x05a74431, 0xffff7f50, /* coral */
  65508. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65509. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65510. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65511. 0x002ed323, 0xff00ffff, /* cyan */
  65512. 0x67cc74d0, 0xff00008b, /* darkblue */
  65513. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65514. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65515. 0x67cecf55, 0xff555555, /* darkgrey */
  65516. 0x920b194d, 0xff006400, /* darkgreen */
  65517. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65518. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65519. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65520. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65521. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65522. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65523. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65524. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65525. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65526. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65527. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65528. 0xc8769375, 0xff9400d3, /* darkviolet */
  65529. 0x25832862, 0xffff1493, /* deeppink */
  65530. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65531. 0x634c8b67, 0xff696969, /* dimgrey */
  65532. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65533. 0xef19e3cb, 0xffb22222, /* firebrick */
  65534. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65535. 0xd086fd06, 0xff228b22, /* forestgreen */
  65536. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65537. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65538. 0x00308060, 0xffffd700, /* gold */
  65539. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65540. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65541. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65542. 0x41892743, 0xffff69b4, /* hotpink */
  65543. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65544. 0xb969fed2, 0xff4b0082, /* indigo */
  65545. 0x05fef6a9, 0xfffffff0, /* ivory */
  65546. 0x06149302, 0xfff0e68c, /* khaki */
  65547. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65548. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65549. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65550. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65551. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65552. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65553. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65554. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65555. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65556. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65557. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65558. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65559. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65560. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65561. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65562. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65563. 0x0032afd5, 0xff00ff00, /* lime */
  65564. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65565. 0x06234efa, 0xfffaf0e6, /* linen */
  65566. 0x316858a9, 0xffff00ff, /* magenta */
  65567. 0xbf8ca470, 0xff800000, /* maroon */
  65568. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65569. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65570. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65571. 0x07556b71, 0xff9370db, /* mediumpurple */
  65572. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65573. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65574. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65575. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65576. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65577. 0x168eb32a, 0xff191970, /* midnightblue */
  65578. 0x4306b960, 0xfff5fffa, /* mintcream */
  65579. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65580. 0xe97218a6, 0xffffdead, /* navajowhite */
  65581. 0x00337bb6, 0xff000080, /* navy */
  65582. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65583. 0x064ee1db, 0xff808000, /* olive */
  65584. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65585. 0xc3de262e, 0xffffa500, /* orange */
  65586. 0x58bebba3, 0xffff4500, /* orangered */
  65587. 0xc3def8a3, 0xffda70d6, /* orchid */
  65588. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65589. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65590. 0x74022737, 0xffafeeee, /* paleturquoise */
  65591. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65592. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65593. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65594. 0x003472f8, 0xffcd853f, /* peru */
  65595. 0x00348176, 0xffffc0cb, /* pink */
  65596. 0x00348d94, 0xffdda0dd, /* plum */
  65597. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65598. 0xc5c507bc, 0xff800080, /* purple */
  65599. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65600. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65601. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65602. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65603. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65604. 0x34636c14, 0xff2e8b57, /* seagreen */
  65605. 0x3507fb41, 0xfffff5ee, /* seashell */
  65606. 0xca348772, 0xffa0522d, /* sienna */
  65607. 0xca37d30d, 0xffc0c0c0, /* silver */
  65608. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65609. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65610. 0x44ab37f8, 0xff708090, /* slategrey */
  65611. 0x0035f183, 0xfffffafa, /* snow */
  65612. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65613. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65614. 0x0001bfa1, 0xffd2b48c, /* tan */
  65615. 0x0036425c, 0xff008080, /* teal */
  65616. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65617. 0xcc41600a, 0xffff6347, /* tomato */
  65618. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65619. 0xcf57947f, 0xffee82ee, /* violet */
  65620. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65621. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65622. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65623. };
  65624. const int hash = colourName.trim().toLowerCase().hashCode();
  65625. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65626. if (presets [i] == hash)
  65627. return Colour (presets [i + 1]);
  65628. return defaultColour;
  65629. }
  65630. END_JUCE_NAMESPACE
  65631. /*** End of inlined file: juce_Colours.cpp ***/
  65632. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65633. BEGIN_JUCE_NAMESPACE
  65634. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65635. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65636. const Path& path, const AffineTransform& transform)
  65637. : bounds (bounds_),
  65638. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65639. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65640. needToCheckEmptinesss (true)
  65641. {
  65642. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65643. int* t = table;
  65644. for (int i = bounds.getHeight(); --i >= 0;)
  65645. {
  65646. *t = 0;
  65647. t += lineStrideElements;
  65648. }
  65649. const int topLimit = bounds.getY() << 8;
  65650. const int heightLimit = bounds.getHeight() << 8;
  65651. const int leftLimit = bounds.getX() << 8;
  65652. const int rightLimit = bounds.getRight() << 8;
  65653. PathFlatteningIterator iter (path, transform);
  65654. while (iter.next())
  65655. {
  65656. int y1 = roundToInt (iter.y1 * 256.0f);
  65657. int y2 = roundToInt (iter.y2 * 256.0f);
  65658. if (y1 != y2)
  65659. {
  65660. y1 -= topLimit;
  65661. y2 -= topLimit;
  65662. const int startY = y1;
  65663. int direction = -1;
  65664. if (y1 > y2)
  65665. {
  65666. swapVariables (y1, y2);
  65667. direction = 1;
  65668. }
  65669. if (y1 < 0)
  65670. y1 = 0;
  65671. if (y2 > heightLimit)
  65672. y2 = heightLimit;
  65673. if (y1 < y2)
  65674. {
  65675. const double startX = 256.0f * iter.x1;
  65676. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65677. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65678. do
  65679. {
  65680. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65681. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65682. if (x < leftLimit)
  65683. x = leftLimit;
  65684. else if (x >= rightLimit)
  65685. x = rightLimit - 1;
  65686. addEdgePoint (x, y1 >> 8, direction * step);
  65687. y1 += step;
  65688. }
  65689. while (y1 < y2);
  65690. }
  65691. }
  65692. }
  65693. sanitiseLevels (path.isUsingNonZeroWinding());
  65694. }
  65695. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65696. : bounds (rectangleToAdd),
  65697. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65698. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65699. needToCheckEmptinesss (true)
  65700. {
  65701. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65702. table[0] = 0;
  65703. const int x1 = rectangleToAdd.getX() << 8;
  65704. const int x2 = rectangleToAdd.getRight() << 8;
  65705. int* t = table;
  65706. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65707. {
  65708. t[0] = 2;
  65709. t[1] = x1;
  65710. t[2] = 255;
  65711. t[3] = x2;
  65712. t[4] = 0;
  65713. t += lineStrideElements;
  65714. }
  65715. }
  65716. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65717. : bounds (rectanglesToAdd.getBounds()),
  65718. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65719. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65720. needToCheckEmptinesss (true)
  65721. {
  65722. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65723. int* t = table;
  65724. for (int i = bounds.getHeight(); --i >= 0;)
  65725. {
  65726. *t = 0;
  65727. t += lineStrideElements;
  65728. }
  65729. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65730. {
  65731. const Rectangle<int>* const r = iter.getRectangle();
  65732. const int x1 = r->getX() << 8;
  65733. const int x2 = r->getRight() << 8;
  65734. int y = r->getY() - bounds.getY();
  65735. for (int j = r->getHeight(); --j >= 0;)
  65736. {
  65737. addEdgePoint (x1, y, 255);
  65738. addEdgePoint (x2, y, -255);
  65739. ++y;
  65740. }
  65741. }
  65742. sanitiseLevels (true);
  65743. }
  65744. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65745. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65746. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65747. 2 + (int) rectangleToAdd.getWidth(),
  65748. 2 + (int) rectangleToAdd.getHeight())),
  65749. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65750. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65751. needToCheckEmptinesss (true)
  65752. {
  65753. jassert (! rectangleToAdd.isEmpty());
  65754. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65755. table[0] = 0;
  65756. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65757. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65758. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65759. jassert (y1 < 256);
  65760. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65761. if (x2 <= x1 || y2 <= y1)
  65762. {
  65763. bounds.setHeight (0);
  65764. return;
  65765. }
  65766. int lineY = 0;
  65767. int* t = table;
  65768. if ((y1 >> 8) == (y2 >> 8))
  65769. {
  65770. t[0] = 2;
  65771. t[1] = x1;
  65772. t[2] = y2 - y1;
  65773. t[3] = x2;
  65774. t[4] = 0;
  65775. ++lineY;
  65776. t += lineStrideElements;
  65777. }
  65778. else
  65779. {
  65780. t[0] = 2;
  65781. t[1] = x1;
  65782. t[2] = 255 - (y1 & 255);
  65783. t[3] = x2;
  65784. t[4] = 0;
  65785. ++lineY;
  65786. t += lineStrideElements;
  65787. while (lineY < (y2 >> 8))
  65788. {
  65789. t[0] = 2;
  65790. t[1] = x1;
  65791. t[2] = 255;
  65792. t[3] = x2;
  65793. t[4] = 0;
  65794. ++lineY;
  65795. t += lineStrideElements;
  65796. }
  65797. jassert (lineY < bounds.getHeight());
  65798. t[0] = 2;
  65799. t[1] = x1;
  65800. t[2] = y2 & 255;
  65801. t[3] = x2;
  65802. t[4] = 0;
  65803. ++lineY;
  65804. t += lineStrideElements;
  65805. }
  65806. while (lineY < bounds.getHeight())
  65807. {
  65808. t[0] = 0;
  65809. t += lineStrideElements;
  65810. ++lineY;
  65811. }
  65812. }
  65813. EdgeTable::EdgeTable (const EdgeTable& other)
  65814. {
  65815. operator= (other);
  65816. }
  65817. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65818. {
  65819. bounds = other.bounds;
  65820. maxEdgesPerLine = other.maxEdgesPerLine;
  65821. lineStrideElements = other.lineStrideElements;
  65822. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65823. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65824. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65825. return *this;
  65826. }
  65827. EdgeTable::~EdgeTable()
  65828. {
  65829. }
  65830. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65831. {
  65832. while (--numLines >= 0)
  65833. {
  65834. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65835. src += srcLineStride;
  65836. dest += destLineStride;
  65837. }
  65838. }
  65839. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65840. {
  65841. // Convert the table from relative windings to absolute levels..
  65842. int* lineStart = table;
  65843. for (int i = bounds.getHeight(); --i >= 0;)
  65844. {
  65845. int* line = lineStart;
  65846. lineStart += lineStrideElements;
  65847. int num = *line;
  65848. if (num == 0)
  65849. continue;
  65850. int level = 0;
  65851. if (useNonZeroWinding)
  65852. {
  65853. while (--num > 0)
  65854. {
  65855. line += 2;
  65856. level += *line;
  65857. int corrected = abs (level);
  65858. if (corrected >> 8)
  65859. corrected = 255;
  65860. *line = corrected;
  65861. }
  65862. }
  65863. else
  65864. {
  65865. while (--num > 0)
  65866. {
  65867. line += 2;
  65868. level += *line;
  65869. int corrected = abs (level);
  65870. if (corrected >> 8)
  65871. {
  65872. corrected &= 511;
  65873. if (corrected >> 8)
  65874. corrected = 511 - corrected;
  65875. }
  65876. *line = corrected;
  65877. }
  65878. }
  65879. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65880. }
  65881. }
  65882. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65883. {
  65884. if (newNumEdgesPerLine != maxEdgesPerLine)
  65885. {
  65886. maxEdgesPerLine = newNumEdgesPerLine;
  65887. jassert (bounds.getHeight() > 0);
  65888. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65889. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65890. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65891. table.swapWith (newTable);
  65892. lineStrideElements = newLineStrideElements;
  65893. }
  65894. }
  65895. void EdgeTable::optimiseTable() throw()
  65896. {
  65897. int maxLineElements = 0;
  65898. for (int i = bounds.getHeight(); --i >= 0;)
  65899. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65900. remapTableForNumEdges (maxLineElements);
  65901. }
  65902. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  65903. {
  65904. jassert (y >= 0 && y < bounds.getHeight());
  65905. int* line = table + lineStrideElements * y;
  65906. const int numPoints = line[0];
  65907. int n = numPoints << 1;
  65908. if (n > 0)
  65909. {
  65910. while (n > 0)
  65911. {
  65912. const int cx = line [n - 1];
  65913. if (cx <= x)
  65914. {
  65915. if (cx == x)
  65916. {
  65917. line [n] += winding;
  65918. return;
  65919. }
  65920. break;
  65921. }
  65922. n -= 2;
  65923. }
  65924. if (numPoints >= maxEdgesPerLine)
  65925. {
  65926. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65927. jassert (numPoints < maxEdgesPerLine);
  65928. line = table + lineStrideElements * y;
  65929. }
  65930. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65931. }
  65932. line [n + 1] = x;
  65933. line [n + 2] = winding;
  65934. line[0]++;
  65935. }
  65936. void EdgeTable::translate (float dx, const int dy) throw()
  65937. {
  65938. bounds.translate ((int) std::floor (dx), dy);
  65939. int* lineStart = table;
  65940. const int intDx = (int) (dx * 256.0f);
  65941. for (int i = bounds.getHeight(); --i >= 0;)
  65942. {
  65943. int* line = lineStart;
  65944. lineStart += lineStrideElements;
  65945. int num = *line++;
  65946. while (--num >= 0)
  65947. {
  65948. *line += intDx;
  65949. line += 2;
  65950. }
  65951. }
  65952. }
  65953. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  65954. {
  65955. jassert (y >= 0 && y < bounds.getHeight());
  65956. int* dest = table + lineStrideElements * y;
  65957. if (dest[0] == 0)
  65958. return;
  65959. int otherNumPoints = *otherLine;
  65960. if (otherNumPoints == 0)
  65961. {
  65962. *dest = 0;
  65963. return;
  65964. }
  65965. const int right = bounds.getRight() << 8;
  65966. // optimise for the common case where our line lies entirely within a
  65967. // single pair of points, as happens when clipping to a simple rect.
  65968. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65969. {
  65970. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65971. return;
  65972. }
  65973. ++otherLine;
  65974. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65975. int* temp = (int*) alloca (lineSizeBytes);
  65976. memcpy (temp, dest, lineSizeBytes);
  65977. const int* src1 = temp;
  65978. int srcNum1 = *src1++;
  65979. int x1 = *src1++;
  65980. const int* src2 = otherLine;
  65981. int srcNum2 = otherNumPoints;
  65982. int x2 = *src2++;
  65983. int destIndex = 0, destTotal = 0;
  65984. int level1 = 0, level2 = 0;
  65985. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65986. while (srcNum1 > 0 && srcNum2 > 0)
  65987. {
  65988. int nextX;
  65989. if (x1 < x2)
  65990. {
  65991. nextX = x1;
  65992. level1 = *src1++;
  65993. x1 = *src1++;
  65994. --srcNum1;
  65995. }
  65996. else if (x1 == x2)
  65997. {
  65998. nextX = x1;
  65999. level1 = *src1++;
  66000. level2 = *src2++;
  66001. x1 = *src1++;
  66002. x2 = *src2++;
  66003. --srcNum1;
  66004. --srcNum2;
  66005. }
  66006. else
  66007. {
  66008. nextX = x2;
  66009. level2 = *src2++;
  66010. x2 = *src2++;
  66011. --srcNum2;
  66012. }
  66013. if (nextX > lastX)
  66014. {
  66015. if (nextX >= right)
  66016. break;
  66017. lastX = nextX;
  66018. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66019. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66020. if (nextLevel != lastLevel)
  66021. {
  66022. if (destTotal >= maxEdgesPerLine)
  66023. {
  66024. dest[0] = destTotal;
  66025. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66026. dest = table + lineStrideElements * y;
  66027. }
  66028. ++destTotal;
  66029. lastLevel = nextLevel;
  66030. dest[++destIndex] = nextX;
  66031. dest[++destIndex] = nextLevel;
  66032. }
  66033. }
  66034. }
  66035. if (lastLevel > 0)
  66036. {
  66037. if (destTotal >= maxEdgesPerLine)
  66038. {
  66039. dest[0] = destTotal;
  66040. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66041. dest = table + lineStrideElements * y;
  66042. }
  66043. ++destTotal;
  66044. dest[++destIndex] = right;
  66045. dest[++destIndex] = 0;
  66046. }
  66047. dest[0] = destTotal;
  66048. #if JUCE_DEBUG
  66049. int last = std::numeric_limits<int>::min();
  66050. for (int i = 0; i < dest[0]; ++i)
  66051. {
  66052. jassert (dest[i * 2 + 1] > last);
  66053. last = dest[i * 2 + 1];
  66054. }
  66055. jassert (dest [dest[0] * 2] == 0);
  66056. #endif
  66057. }
  66058. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66059. {
  66060. int* lastItem = dest + (dest[0] * 2 - 1);
  66061. if (x2 < lastItem[0])
  66062. {
  66063. if (x2 <= dest[1])
  66064. {
  66065. dest[0] = 0;
  66066. return;
  66067. }
  66068. while (x2 < lastItem[-2])
  66069. {
  66070. --(dest[0]);
  66071. lastItem -= 2;
  66072. }
  66073. lastItem[0] = x2;
  66074. lastItem[1] = 0;
  66075. }
  66076. if (x1 > dest[1])
  66077. {
  66078. while (lastItem[0] > x1)
  66079. lastItem -= 2;
  66080. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66081. if (itemsRemoved > 0)
  66082. {
  66083. dest[0] -= itemsRemoved;
  66084. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66085. }
  66086. dest[1] = x1;
  66087. }
  66088. }
  66089. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66090. {
  66091. const Rectangle<int> clipped (r.getIntersection (bounds));
  66092. if (clipped.isEmpty())
  66093. {
  66094. needToCheckEmptinesss = false;
  66095. bounds.setHeight (0);
  66096. }
  66097. else
  66098. {
  66099. const int top = clipped.getY() - bounds.getY();
  66100. const int bottom = clipped.getBottom() - bounds.getY();
  66101. if (bottom < bounds.getHeight())
  66102. bounds.setHeight (bottom);
  66103. if (clipped.getRight() < bounds.getRight())
  66104. bounds.setRight (clipped.getRight());
  66105. for (int i = top; --i >= 0;)
  66106. table [lineStrideElements * i] = 0;
  66107. if (clipped.getX() > bounds.getX())
  66108. {
  66109. const int x1 = clipped.getX() << 8;
  66110. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66111. int* line = table + lineStrideElements * top;
  66112. for (int i = bottom - top; --i >= 0;)
  66113. {
  66114. if (line[0] != 0)
  66115. clipEdgeTableLineToRange (line, x1, x2);
  66116. line += lineStrideElements;
  66117. }
  66118. }
  66119. needToCheckEmptinesss = true;
  66120. }
  66121. }
  66122. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66123. {
  66124. const Rectangle<int> clipped (r.getIntersection (bounds));
  66125. if (! clipped.isEmpty())
  66126. {
  66127. const int top = clipped.getY() - bounds.getY();
  66128. const int bottom = clipped.getBottom() - bounds.getY();
  66129. //XXX optimise here by shortening the table if it fills top or bottom
  66130. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66131. clipped.getX() << 8, 0,
  66132. clipped.getRight() << 8, 255,
  66133. std::numeric_limits<int>::max(), 0 };
  66134. for (int i = top; i < bottom; ++i)
  66135. intersectWithEdgeTableLine (i, rectLine);
  66136. needToCheckEmptinesss = true;
  66137. }
  66138. }
  66139. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66140. {
  66141. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66142. if (clipped.isEmpty())
  66143. {
  66144. needToCheckEmptinesss = false;
  66145. bounds.setHeight (0);
  66146. }
  66147. else
  66148. {
  66149. const int top = clipped.getY() - bounds.getY();
  66150. const int bottom = clipped.getBottom() - bounds.getY();
  66151. if (bottom < bounds.getHeight())
  66152. bounds.setHeight (bottom);
  66153. if (clipped.getRight() < bounds.getRight())
  66154. bounds.setRight (clipped.getRight());
  66155. int i = 0;
  66156. for (i = top; --i >= 0;)
  66157. table [lineStrideElements * i] = 0;
  66158. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66159. for (i = top; i < bottom; ++i)
  66160. {
  66161. intersectWithEdgeTableLine (i, otherLine);
  66162. otherLine += other.lineStrideElements;
  66163. }
  66164. needToCheckEmptinesss = true;
  66165. }
  66166. }
  66167. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66168. {
  66169. y -= bounds.getY();
  66170. if (y < 0 || y >= bounds.getHeight())
  66171. return;
  66172. needToCheckEmptinesss = true;
  66173. if (numPixels <= 0)
  66174. {
  66175. table [lineStrideElements * y] = 0;
  66176. return;
  66177. }
  66178. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  66179. int destIndex = 0, lastLevel = 0;
  66180. while (--numPixels >= 0)
  66181. {
  66182. const int alpha = *mask;
  66183. mask += maskStride;
  66184. if (alpha != lastLevel)
  66185. {
  66186. tempLine[++destIndex] = (x << 8);
  66187. tempLine[++destIndex] = alpha;
  66188. lastLevel = alpha;
  66189. }
  66190. ++x;
  66191. }
  66192. if (lastLevel > 0)
  66193. {
  66194. tempLine[++destIndex] = (x << 8);
  66195. tempLine[++destIndex] = 0;
  66196. }
  66197. tempLine[0] = destIndex >> 1;
  66198. intersectWithEdgeTableLine (y, tempLine);
  66199. }
  66200. bool EdgeTable::isEmpty() throw()
  66201. {
  66202. if (needToCheckEmptinesss)
  66203. {
  66204. needToCheckEmptinesss = false;
  66205. int* t = table;
  66206. for (int i = bounds.getHeight(); --i >= 0;)
  66207. {
  66208. if (t[0] > 1)
  66209. return false;
  66210. t += lineStrideElements;
  66211. }
  66212. bounds.setHeight (0);
  66213. }
  66214. return bounds.getHeight() == 0;
  66215. }
  66216. END_JUCE_NAMESPACE
  66217. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66218. /*** Start of inlined file: juce_FillType.cpp ***/
  66219. BEGIN_JUCE_NAMESPACE
  66220. FillType::FillType() throw()
  66221. : colour (0xff000000), image (0)
  66222. {
  66223. }
  66224. FillType::FillType (const Colour& colour_) throw()
  66225. : colour (colour_), image (0)
  66226. {
  66227. }
  66228. FillType::FillType (const ColourGradient& gradient_)
  66229. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66230. {
  66231. }
  66232. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66233. : colour (0xff000000), image (image_), transform (transform_)
  66234. {
  66235. }
  66236. FillType::FillType (const FillType& other)
  66237. : colour (other.colour),
  66238. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66239. image (other.image), transform (other.transform)
  66240. {
  66241. }
  66242. FillType& FillType::operator= (const FillType& other)
  66243. {
  66244. if (this != &other)
  66245. {
  66246. colour = other.colour;
  66247. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66248. image = other.image;
  66249. transform = other.transform;
  66250. }
  66251. return *this;
  66252. }
  66253. FillType::~FillType() throw()
  66254. {
  66255. }
  66256. bool FillType::operator== (const FillType& other) const
  66257. {
  66258. return colour == other.colour && image == other.image
  66259. && transform == other.transform
  66260. && (gradient == other.gradient
  66261. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66262. }
  66263. bool FillType::operator!= (const FillType& other) const
  66264. {
  66265. return ! operator== (other);
  66266. }
  66267. void FillType::setColour (const Colour& newColour) throw()
  66268. {
  66269. gradient = 0;
  66270. image = Image::null;
  66271. colour = newColour;
  66272. }
  66273. void FillType::setGradient (const ColourGradient& newGradient)
  66274. {
  66275. if (gradient != 0)
  66276. {
  66277. *gradient = newGradient;
  66278. }
  66279. else
  66280. {
  66281. image = Image::null;
  66282. gradient = new ColourGradient (newGradient);
  66283. colour = Colours::black;
  66284. }
  66285. }
  66286. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66287. {
  66288. gradient = 0;
  66289. image = image_;
  66290. transform = transform_;
  66291. colour = Colours::black;
  66292. }
  66293. void FillType::setOpacity (const float newOpacity) throw()
  66294. {
  66295. colour = colour.withAlpha (newOpacity);
  66296. }
  66297. bool FillType::isInvisible() const throw()
  66298. {
  66299. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66300. }
  66301. END_JUCE_NAMESPACE
  66302. /*** End of inlined file: juce_FillType.cpp ***/
  66303. /*** Start of inlined file: juce_Graphics.cpp ***/
  66304. BEGIN_JUCE_NAMESPACE
  66305. template <typename Type>
  66306. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66307. {
  66308. const int maxVal = 0x3fffffff;
  66309. return (int) x >= -maxVal && (int) x <= maxVal
  66310. && (int) y >= -maxVal && (int) y <= maxVal
  66311. && (int) w >= -maxVal && (int) w <= maxVal
  66312. && (int) h >= -maxVal && (int) h <= maxVal;
  66313. }
  66314. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66315. {
  66316. }
  66317. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66318. {
  66319. }
  66320. Graphics::Graphics (const Image& imageToDrawOnto)
  66321. : context (imageToDrawOnto.createLowLevelContext()),
  66322. contextToDelete (context),
  66323. saveStatePending (false)
  66324. {
  66325. }
  66326. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66327. : context (internalContext),
  66328. saveStatePending (false)
  66329. {
  66330. }
  66331. Graphics::~Graphics()
  66332. {
  66333. }
  66334. void Graphics::resetToDefaultState()
  66335. {
  66336. saveStateIfPending();
  66337. context->setFill (FillType());
  66338. context->setFont (Font());
  66339. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66340. }
  66341. bool Graphics::isVectorDevice() const
  66342. {
  66343. return context->isVectorDevice();
  66344. }
  66345. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66346. {
  66347. saveStateIfPending();
  66348. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  66349. }
  66350. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66351. {
  66352. saveStateIfPending();
  66353. return context->clipToRectangleList (clipRegion);
  66354. }
  66355. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66356. {
  66357. saveStateIfPending();
  66358. context->clipToPath (path, transform);
  66359. return ! context->isClipEmpty();
  66360. }
  66361. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66362. {
  66363. saveStateIfPending();
  66364. context->clipToImageAlpha (image, transform);
  66365. return ! context->isClipEmpty();
  66366. }
  66367. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66368. {
  66369. saveStateIfPending();
  66370. context->excludeClipRectangle (rectangleToExclude);
  66371. }
  66372. bool Graphics::isClipEmpty() const
  66373. {
  66374. return context->isClipEmpty();
  66375. }
  66376. const Rectangle<int> Graphics::getClipBounds() const
  66377. {
  66378. return context->getClipBounds();
  66379. }
  66380. void Graphics::saveState()
  66381. {
  66382. saveStateIfPending();
  66383. saveStatePending = true;
  66384. }
  66385. void Graphics::restoreState()
  66386. {
  66387. if (saveStatePending)
  66388. saveStatePending = false;
  66389. else
  66390. context->restoreState();
  66391. }
  66392. void Graphics::saveStateIfPending()
  66393. {
  66394. if (saveStatePending)
  66395. {
  66396. saveStatePending = false;
  66397. context->saveState();
  66398. }
  66399. }
  66400. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66401. {
  66402. saveStateIfPending();
  66403. context->setOrigin (newOriginX, newOriginY);
  66404. }
  66405. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66406. {
  66407. return context->clipRegionIntersects (area);
  66408. }
  66409. void Graphics::setColour (const Colour& newColour)
  66410. {
  66411. saveStateIfPending();
  66412. context->setFill (newColour);
  66413. }
  66414. void Graphics::setOpacity (const float newOpacity)
  66415. {
  66416. saveStateIfPending();
  66417. context->setOpacity (newOpacity);
  66418. }
  66419. void Graphics::setGradientFill (const ColourGradient& gradient)
  66420. {
  66421. setFillType (gradient);
  66422. }
  66423. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66424. {
  66425. saveStateIfPending();
  66426. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66427. context->setOpacity (opacity);
  66428. }
  66429. void Graphics::setFillType (const FillType& newFill)
  66430. {
  66431. saveStateIfPending();
  66432. context->setFill (newFill);
  66433. }
  66434. void Graphics::setFont (const Font& newFont)
  66435. {
  66436. saveStateIfPending();
  66437. context->setFont (newFont);
  66438. }
  66439. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66440. {
  66441. saveStateIfPending();
  66442. Font f (context->getFont());
  66443. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66444. context->setFont (f);
  66445. }
  66446. const Font Graphics::getCurrentFont() const
  66447. {
  66448. return context->getFont();
  66449. }
  66450. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66451. {
  66452. if (text.isNotEmpty()
  66453. && startX < context->getClipBounds().getRight())
  66454. {
  66455. GlyphArrangement arr;
  66456. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66457. arr.draw (*this);
  66458. }
  66459. }
  66460. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66461. {
  66462. if (text.isNotEmpty())
  66463. {
  66464. GlyphArrangement arr;
  66465. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66466. arr.draw (*this, transform);
  66467. }
  66468. }
  66469. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66470. {
  66471. if (text.isNotEmpty()
  66472. && startX < context->getClipBounds().getRight())
  66473. {
  66474. GlyphArrangement arr;
  66475. arr.addJustifiedText (context->getFont(), text,
  66476. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66477. Justification::left);
  66478. arr.draw (*this);
  66479. }
  66480. }
  66481. void Graphics::drawText (const String& text,
  66482. const int x, const int y, const int width, const int height,
  66483. const Justification& justificationType,
  66484. const bool useEllipsesIfTooBig) const
  66485. {
  66486. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66487. {
  66488. GlyphArrangement arr;
  66489. arr.addCurtailedLineOfText (context->getFont(), text,
  66490. 0.0f, 0.0f, (float) width,
  66491. useEllipsesIfTooBig);
  66492. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66493. (float) x, (float) y, (float) width, (float) height,
  66494. justificationType);
  66495. arr.draw (*this);
  66496. }
  66497. }
  66498. void Graphics::drawFittedText (const String& text,
  66499. const int x, const int y, const int width, const int height,
  66500. const Justification& justification,
  66501. const int maximumNumberOfLines,
  66502. const float minimumHorizontalScale) const
  66503. {
  66504. if (text.isNotEmpty()
  66505. && width > 0 && height > 0
  66506. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66507. {
  66508. GlyphArrangement arr;
  66509. arr.addFittedText (context->getFont(), text,
  66510. (float) x, (float) y, (float) width, (float) height,
  66511. justification,
  66512. maximumNumberOfLines,
  66513. minimumHorizontalScale);
  66514. arr.draw (*this);
  66515. }
  66516. }
  66517. void Graphics::fillRect (int x, int y, int width, int height) const
  66518. {
  66519. // passing in a silly number can cause maths problems in rendering!
  66520. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66521. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66522. }
  66523. void Graphics::fillRect (const Rectangle<int>& r) const
  66524. {
  66525. context->fillRect (r, false);
  66526. }
  66527. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66528. {
  66529. // passing in a silly number can cause maths problems in rendering!
  66530. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66531. Path p;
  66532. p.addRectangle (x, y, width, height);
  66533. fillPath (p);
  66534. }
  66535. void Graphics::setPixel (int x, int y) const
  66536. {
  66537. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66538. }
  66539. void Graphics::fillAll() const
  66540. {
  66541. fillRect (context->getClipBounds());
  66542. }
  66543. void Graphics::fillAll (const Colour& colourToUse) const
  66544. {
  66545. if (! colourToUse.isTransparent())
  66546. {
  66547. const Rectangle<int> clip (context->getClipBounds());
  66548. context->saveState();
  66549. context->setFill (colourToUse);
  66550. context->fillRect (clip, false);
  66551. context->restoreState();
  66552. }
  66553. }
  66554. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66555. {
  66556. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66557. context->fillPath (path, transform);
  66558. }
  66559. void Graphics::strokePath (const Path& path,
  66560. const PathStrokeType& strokeType,
  66561. const AffineTransform& transform) const
  66562. {
  66563. Path stroke;
  66564. strokeType.createStrokedPath (stroke, path, transform);
  66565. fillPath (stroke);
  66566. }
  66567. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66568. const int lineThickness) const
  66569. {
  66570. // passing in a silly number can cause maths problems in rendering!
  66571. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66572. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66573. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66574. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66575. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66576. }
  66577. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66578. {
  66579. // passing in a silly number can cause maths problems in rendering!
  66580. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66581. Path p;
  66582. p.addRectangle (x, y, width, lineThickness);
  66583. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66584. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66585. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66586. fillPath (p);
  66587. }
  66588. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66589. {
  66590. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66591. }
  66592. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66593. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66594. const bool useGradient, const bool sharpEdgeOnOutside) const
  66595. {
  66596. // passing in a silly number can cause maths problems in rendering!
  66597. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66598. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66599. {
  66600. context->saveState();
  66601. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66602. const float ramp = oldOpacity / bevelThickness;
  66603. for (int i = bevelThickness; --i >= 0;)
  66604. {
  66605. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66606. : oldOpacity;
  66607. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66608. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66609. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66610. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66611. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66612. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66613. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66614. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66615. }
  66616. context->restoreState();
  66617. }
  66618. }
  66619. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66620. {
  66621. // passing in a silly number can cause maths problems in rendering!
  66622. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66623. Path p;
  66624. p.addEllipse (x, y, width, height);
  66625. fillPath (p);
  66626. }
  66627. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66628. const float lineThickness) const
  66629. {
  66630. // passing in a silly number can cause maths problems in rendering!
  66631. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66632. Path p;
  66633. p.addEllipse (x, y, width, height);
  66634. strokePath (p, PathStrokeType (lineThickness));
  66635. }
  66636. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66637. {
  66638. // passing in a silly number can cause maths problems in rendering!
  66639. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66640. Path p;
  66641. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66642. fillPath (p);
  66643. }
  66644. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66645. {
  66646. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66647. }
  66648. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66649. const float cornerSize, const float lineThickness) const
  66650. {
  66651. // passing in a silly number can cause maths problems in rendering!
  66652. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66653. Path p;
  66654. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66655. strokePath (p, PathStrokeType (lineThickness));
  66656. }
  66657. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66658. {
  66659. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66660. }
  66661. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66662. {
  66663. Path p;
  66664. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66665. fillPath (p);
  66666. }
  66667. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66668. const int checkWidth, const int checkHeight,
  66669. const Colour& colour1, const Colour& colour2) const
  66670. {
  66671. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66672. if (checkWidth > 0 && checkHeight > 0)
  66673. {
  66674. context->saveState();
  66675. if (colour1 == colour2)
  66676. {
  66677. context->setFill (colour1);
  66678. context->fillRect (area, false);
  66679. }
  66680. else
  66681. {
  66682. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66683. if (! clipped.isEmpty())
  66684. {
  66685. context->clipToRectangle (clipped);
  66686. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66687. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66688. const int startX = area.getX() + checkNumX * checkWidth;
  66689. const int startY = area.getY() + checkNumY * checkHeight;
  66690. const int right = clipped.getRight();
  66691. const int bottom = clipped.getBottom();
  66692. for (int i = 0; i < 2; ++i)
  66693. {
  66694. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66695. int cy = i;
  66696. for (int y = startY; y < bottom; y += checkHeight)
  66697. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66698. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66699. }
  66700. }
  66701. }
  66702. context->restoreState();
  66703. }
  66704. }
  66705. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66706. {
  66707. context->drawVerticalLine (x, top, bottom);
  66708. }
  66709. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66710. {
  66711. context->drawHorizontalLine (y, left, right);
  66712. }
  66713. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66714. {
  66715. context->drawLine (Line<float> (x1, y1, x2, y2));
  66716. }
  66717. void Graphics::drawLine (const float startX, const float startY,
  66718. const float endX, const float endY,
  66719. const float lineThickness) const
  66720. {
  66721. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66722. }
  66723. void Graphics::drawLine (const Line<float>& line) const
  66724. {
  66725. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66726. }
  66727. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66728. {
  66729. Path p;
  66730. p.addLineSegment (line, lineThickness);
  66731. fillPath (p);
  66732. }
  66733. void Graphics::drawDashedLine (const float startX, const float startY,
  66734. const float endX, const float endY,
  66735. const float* const dashLengths,
  66736. const int numDashLengths,
  66737. const float lineThickness) const
  66738. {
  66739. const double dx = endX - startX;
  66740. const double dy = endY - startY;
  66741. const double totalLen = juce_hypot (dx, dy);
  66742. if (totalLen >= 0.5)
  66743. {
  66744. const double onePixAlpha = 1.0 / totalLen;
  66745. double alpha = 0.0;
  66746. float x = startX;
  66747. float y = startY;
  66748. int n = 0;
  66749. while (alpha < 1.0f)
  66750. {
  66751. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66752. n = n % numDashLengths;
  66753. const float oldX = x;
  66754. const float oldY = y;
  66755. x = (float) (startX + dx * alpha);
  66756. y = (float) (startY + dy * alpha);
  66757. if ((n & 1) != 0)
  66758. {
  66759. if (lineThickness != 1.0f)
  66760. drawLine (oldX, oldY, x, y, lineThickness);
  66761. else
  66762. drawLine (oldX, oldY, x, y);
  66763. }
  66764. }
  66765. }
  66766. }
  66767. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66768. {
  66769. saveStateIfPending();
  66770. context->setInterpolationQuality (newQuality);
  66771. }
  66772. void Graphics::drawImageAt (const Image& imageToDraw,
  66773. const int topLeftX, const int topLeftY,
  66774. const bool fillAlphaChannelWithCurrentBrush) const
  66775. {
  66776. const int imageW = imageToDraw.getWidth();
  66777. const int imageH = imageToDraw.getHeight();
  66778. drawImage (imageToDraw,
  66779. topLeftX, topLeftY, imageW, imageH,
  66780. 0, 0, imageW, imageH,
  66781. fillAlphaChannelWithCurrentBrush);
  66782. }
  66783. void Graphics::drawImageWithin (const Image& imageToDraw,
  66784. const int destX, const int destY,
  66785. const int destW, const int destH,
  66786. const RectanglePlacement& placementWithinTarget,
  66787. const bool fillAlphaChannelWithCurrentBrush) const
  66788. {
  66789. // passing in a silly number can cause maths problems in rendering!
  66790. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66791. if (imageToDraw.isValid())
  66792. {
  66793. const int imageW = imageToDraw.getWidth();
  66794. const int imageH = imageToDraw.getHeight();
  66795. if (imageW > 0 && imageH > 0)
  66796. {
  66797. double newX = 0.0, newY = 0.0;
  66798. double newW = imageW;
  66799. double newH = imageH;
  66800. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66801. destX, destY, destW, destH);
  66802. if (newW > 0 && newH > 0)
  66803. {
  66804. drawImage (imageToDraw,
  66805. roundToInt (newX), roundToInt (newY),
  66806. roundToInt (newW), roundToInt (newH),
  66807. 0, 0, imageW, imageH,
  66808. fillAlphaChannelWithCurrentBrush);
  66809. }
  66810. }
  66811. }
  66812. }
  66813. void Graphics::drawImage (const Image& imageToDraw,
  66814. int dx, int dy, int dw, int dh,
  66815. int sx, int sy, int sw, int sh,
  66816. const bool fillAlphaChannelWithCurrentBrush) const
  66817. {
  66818. // passing in a silly number can cause maths problems in rendering!
  66819. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66820. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66821. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66822. {
  66823. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66824. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66825. .translated ((float) dx, (float) dy),
  66826. fillAlphaChannelWithCurrentBrush);
  66827. }
  66828. }
  66829. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66830. const AffineTransform& transform,
  66831. const bool fillAlphaChannelWithCurrentBrush) const
  66832. {
  66833. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66834. {
  66835. if (fillAlphaChannelWithCurrentBrush)
  66836. {
  66837. context->saveState();
  66838. context->clipToImageAlpha (imageToDraw, transform);
  66839. fillAll();
  66840. context->restoreState();
  66841. }
  66842. else
  66843. {
  66844. context->drawImage (imageToDraw, transform, false);
  66845. }
  66846. }
  66847. }
  66848. END_JUCE_NAMESPACE
  66849. /*** End of inlined file: juce_Graphics.cpp ***/
  66850. /*** Start of inlined file: juce_Justification.cpp ***/
  66851. BEGIN_JUCE_NAMESPACE
  66852. Justification::Justification (const Justification& other) throw()
  66853. : flags (other.flags)
  66854. {
  66855. }
  66856. Justification& Justification::operator= (const Justification& other) throw()
  66857. {
  66858. flags = other.flags;
  66859. return *this;
  66860. }
  66861. int Justification::getOnlyVerticalFlags() const throw()
  66862. {
  66863. return flags & (top | bottom | verticallyCentred);
  66864. }
  66865. int Justification::getOnlyHorizontalFlags() const throw()
  66866. {
  66867. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66868. }
  66869. void Justification::applyToRectangle (int& x, int& y,
  66870. const int w, const int h,
  66871. const int spaceX, const int spaceY,
  66872. const int spaceW, const int spaceH) const throw()
  66873. {
  66874. if ((flags & horizontallyCentred) != 0)
  66875. x = spaceX + ((spaceW - w) >> 1);
  66876. else if ((flags & right) != 0)
  66877. x = spaceX + spaceW - w;
  66878. else
  66879. x = spaceX;
  66880. if ((flags & verticallyCentred) != 0)
  66881. y = spaceY + ((spaceH - h) >> 1);
  66882. else if ((flags & bottom) != 0)
  66883. y = spaceY + spaceH - h;
  66884. else
  66885. y = spaceY;
  66886. }
  66887. END_JUCE_NAMESPACE
  66888. /*** End of inlined file: juce_Justification.cpp ***/
  66889. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66890. BEGIN_JUCE_NAMESPACE
  66891. // this will throw an assertion if you try to draw something that's not
  66892. // possible in postscript
  66893. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66894. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66895. #define notPossibleInPostscriptAssert jassertfalse
  66896. #else
  66897. #define notPossibleInPostscriptAssert
  66898. #endif
  66899. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66900. const String& documentTitle,
  66901. const int totalWidth_,
  66902. const int totalHeight_)
  66903. : out (resultingPostScript),
  66904. totalWidth (totalWidth_),
  66905. totalHeight (totalHeight_),
  66906. needToClip (true)
  66907. {
  66908. stateStack.add (new SavedState());
  66909. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66910. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66911. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66912. "\n%%BoundingBox: 0 0 600 824"
  66913. "\n%%Pages: 0"
  66914. "\n%%Creator: Raw Material Software JUCE"
  66915. "\n%%Title: " << documentTitle <<
  66916. "\n%%CreationDate: none"
  66917. "\n%%LanguageLevel: 2"
  66918. "\n%%EndComments"
  66919. "\n%%BeginProlog"
  66920. "\n%%BeginResource: JRes"
  66921. "\n/bd {bind def} bind def"
  66922. "\n/c {setrgbcolor} bd"
  66923. "\n/m {moveto} bd"
  66924. "\n/l {lineto} bd"
  66925. "\n/rl {rlineto} bd"
  66926. "\n/ct {curveto} bd"
  66927. "\n/cp {closepath} bd"
  66928. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66929. "\n/doclip {initclip newpath} bd"
  66930. "\n/endclip {clip newpath} bd"
  66931. "\n%%EndResource"
  66932. "\n%%EndProlog"
  66933. "\n%%BeginSetup"
  66934. "\n%%EndSetup"
  66935. "\n%%Page: 1 1"
  66936. "\n%%BeginPageSetup"
  66937. "\n%%EndPageSetup\n\n"
  66938. << "40 800 translate\n"
  66939. << scale << ' ' << scale << " scale\n\n";
  66940. }
  66941. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66942. {
  66943. }
  66944. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66945. {
  66946. return true;
  66947. }
  66948. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66949. {
  66950. if (x != 0 || y != 0)
  66951. {
  66952. stateStack.getLast()->xOffset += x;
  66953. stateStack.getLast()->yOffset += y;
  66954. needToClip = true;
  66955. }
  66956. }
  66957. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66958. {
  66959. needToClip = true;
  66960. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66961. }
  66962. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66963. {
  66964. needToClip = true;
  66965. return stateStack.getLast()->clip.clipTo (clipRegion);
  66966. }
  66967. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66968. {
  66969. needToClip = true;
  66970. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66971. }
  66972. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66973. {
  66974. writeClip();
  66975. Path p (path);
  66976. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66977. writePath (p);
  66978. out << "clip\n";
  66979. }
  66980. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66981. {
  66982. needToClip = true;
  66983. jassertfalse; // xxx
  66984. }
  66985. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66986. {
  66987. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66988. }
  66989. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66990. {
  66991. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66992. -stateStack.getLast()->yOffset);
  66993. }
  66994. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66995. {
  66996. return stateStack.getLast()->clip.isEmpty();
  66997. }
  66998. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66999. : xOffset (0),
  67000. yOffset (0)
  67001. {
  67002. }
  67003. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67004. {
  67005. }
  67006. void LowLevelGraphicsPostScriptRenderer::saveState()
  67007. {
  67008. stateStack.add (new SavedState (*stateStack.getLast()));
  67009. }
  67010. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67011. {
  67012. jassert (stateStack.size() > 0);
  67013. if (stateStack.size() > 0)
  67014. stateStack.removeLast();
  67015. }
  67016. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67017. {
  67018. if (needToClip)
  67019. {
  67020. needToClip = false;
  67021. out << "doclip ";
  67022. int itemsOnLine = 0;
  67023. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67024. {
  67025. if (++itemsOnLine == 6)
  67026. {
  67027. itemsOnLine = 0;
  67028. out << '\n';
  67029. }
  67030. const Rectangle<int>& r = *i.getRectangle();
  67031. out << r.getX() << ' ' << -r.getY() << ' '
  67032. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67033. }
  67034. out << "endclip\n";
  67035. }
  67036. }
  67037. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67038. {
  67039. Colour c (Colours::white.overlaidWith (colour));
  67040. if (lastColour != c)
  67041. {
  67042. lastColour = c;
  67043. out << String (c.getFloatRed(), 3) << ' '
  67044. << String (c.getFloatGreen(), 3) << ' '
  67045. << String (c.getFloatBlue(), 3) << " c\n";
  67046. }
  67047. }
  67048. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67049. {
  67050. out << String (x, 2) << ' '
  67051. << String (-y, 2) << ' ';
  67052. }
  67053. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67054. {
  67055. out << "newpath ";
  67056. float lastX = 0.0f;
  67057. float lastY = 0.0f;
  67058. int itemsOnLine = 0;
  67059. Path::Iterator i (path);
  67060. while (i.next())
  67061. {
  67062. if (++itemsOnLine == 4)
  67063. {
  67064. itemsOnLine = 0;
  67065. out << '\n';
  67066. }
  67067. switch (i.elementType)
  67068. {
  67069. case Path::Iterator::startNewSubPath:
  67070. writeXY (i.x1, i.y1);
  67071. lastX = i.x1;
  67072. lastY = i.y1;
  67073. out << "m ";
  67074. break;
  67075. case Path::Iterator::lineTo:
  67076. writeXY (i.x1, i.y1);
  67077. lastX = i.x1;
  67078. lastY = i.y1;
  67079. out << "l ";
  67080. break;
  67081. case Path::Iterator::quadraticTo:
  67082. {
  67083. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67084. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67085. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67086. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67087. writeXY (cp1x, cp1y);
  67088. writeXY (cp2x, cp2y);
  67089. writeXY (i.x2, i.y2);
  67090. out << "ct ";
  67091. lastX = i.x2;
  67092. lastY = i.y2;
  67093. }
  67094. break;
  67095. case Path::Iterator::cubicTo:
  67096. writeXY (i.x1, i.y1);
  67097. writeXY (i.x2, i.y2);
  67098. writeXY (i.x3, i.y3);
  67099. out << "ct ";
  67100. lastX = i.x3;
  67101. lastY = i.y3;
  67102. break;
  67103. case Path::Iterator::closePath:
  67104. out << "cp ";
  67105. break;
  67106. default:
  67107. jassertfalse;
  67108. break;
  67109. }
  67110. }
  67111. out << '\n';
  67112. }
  67113. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67114. {
  67115. out << "[ "
  67116. << trans.mat00 << ' '
  67117. << trans.mat10 << ' '
  67118. << trans.mat01 << ' '
  67119. << trans.mat11 << ' '
  67120. << trans.mat02 << ' '
  67121. << trans.mat12 << " ] concat ";
  67122. }
  67123. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67124. {
  67125. stateStack.getLast()->fillType = fillType;
  67126. }
  67127. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67128. {
  67129. }
  67130. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67131. {
  67132. }
  67133. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67134. {
  67135. if (stateStack.getLast()->fillType.isColour())
  67136. {
  67137. writeClip();
  67138. writeColour (stateStack.getLast()->fillType.colour);
  67139. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67140. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67141. }
  67142. else
  67143. {
  67144. Path p;
  67145. p.addRectangle (r);
  67146. fillPath (p, AffineTransform::identity);
  67147. }
  67148. }
  67149. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67150. {
  67151. if (stateStack.getLast()->fillType.isColour())
  67152. {
  67153. writeClip();
  67154. Path p (path);
  67155. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67156. (float) stateStack.getLast()->yOffset));
  67157. writePath (p);
  67158. writeColour (stateStack.getLast()->fillType.colour);
  67159. out << "fill\n";
  67160. }
  67161. else if (stateStack.getLast()->fillType.isGradient())
  67162. {
  67163. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67164. // postscript can't do semi-transparent ones.
  67165. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67166. writeClip();
  67167. out << "gsave ";
  67168. {
  67169. Path p (path);
  67170. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67171. writePath (p);
  67172. out << "clip\n";
  67173. }
  67174. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67175. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67176. // time-being, this just fills it with the average colour..
  67177. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67178. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67179. out << "grestore\n";
  67180. }
  67181. }
  67182. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67183. const int sx, const int sy,
  67184. const int maxW, const int maxH) const
  67185. {
  67186. out << "{<\n";
  67187. const int w = jmin (maxW, im.getWidth());
  67188. const int h = jmin (maxH, im.getHeight());
  67189. int charsOnLine = 0;
  67190. const Image::BitmapData srcData (im, 0, 0, w, h);
  67191. Colour pixel;
  67192. for (int y = h; --y >= 0;)
  67193. {
  67194. for (int x = 0; x < w; ++x)
  67195. {
  67196. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67197. if (x >= sx && y >= sy)
  67198. {
  67199. if (im.isARGB())
  67200. {
  67201. PixelARGB p (*(const PixelARGB*) pixelData);
  67202. p.unpremultiply();
  67203. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67204. }
  67205. else if (im.isRGB())
  67206. {
  67207. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67208. }
  67209. else
  67210. {
  67211. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67212. }
  67213. }
  67214. else
  67215. {
  67216. pixel = Colours::transparentWhite;
  67217. }
  67218. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67219. out << String::toHexString (pixelValues, 3, 0);
  67220. charsOnLine += 3;
  67221. if (charsOnLine > 100)
  67222. {
  67223. out << '\n';
  67224. charsOnLine = 0;
  67225. }
  67226. }
  67227. }
  67228. out << "\n>}\n";
  67229. }
  67230. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67231. {
  67232. const int w = sourceImage.getWidth();
  67233. const int h = sourceImage.getHeight();
  67234. writeClip();
  67235. out << "gsave ";
  67236. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67237. .scaled (1.0f, -1.0f));
  67238. RectangleList imageClip;
  67239. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67240. out << "newpath ";
  67241. int itemsOnLine = 0;
  67242. for (RectangleList::Iterator i (imageClip); i.next();)
  67243. {
  67244. if (++itemsOnLine == 6)
  67245. {
  67246. out << '\n';
  67247. itemsOnLine = 0;
  67248. }
  67249. const Rectangle<int>& r = *i.getRectangle();
  67250. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67251. }
  67252. out << " clip newpath\n";
  67253. out << w << ' ' << h << " scale\n";
  67254. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67255. writeImage (sourceImage, 0, 0, w, h);
  67256. out << "false 3 colorimage grestore\n";
  67257. needToClip = true;
  67258. }
  67259. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67260. {
  67261. Path p;
  67262. p.addLineSegment (line, 1.0f);
  67263. fillPath (p, AffineTransform::identity);
  67264. }
  67265. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67266. {
  67267. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67268. }
  67269. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67270. {
  67271. drawLine (Line<float> (left, (float) y, right, (float) y));
  67272. }
  67273. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67274. {
  67275. stateStack.getLast()->font = newFont;
  67276. }
  67277. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67278. {
  67279. return stateStack.getLast()->font;
  67280. }
  67281. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67282. {
  67283. Path p;
  67284. Font& font = stateStack.getLast()->font;
  67285. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67286. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67287. }
  67288. END_JUCE_NAMESPACE
  67289. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67290. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67291. BEGIN_JUCE_NAMESPACE
  67292. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67293. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67294. #endif
  67295. #if JUCE_MSVC
  67296. #pragma warning (push)
  67297. #pragma warning (disable: 4127) // "expression is constant" warning
  67298. #if JUCE_DEBUG
  67299. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67300. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67301. #endif
  67302. #endif
  67303. namespace SoftwareRendererClasses
  67304. {
  67305. template <class PixelType, bool replaceExisting = false>
  67306. class SolidColourEdgeTableRenderer
  67307. {
  67308. public:
  67309. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67310. : data (data_),
  67311. sourceColour (colour)
  67312. {
  67313. if (sizeof (PixelType) == 3)
  67314. {
  67315. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67316. && sourceColour.getGreen() == sourceColour.getBlue();
  67317. filler[0].set (sourceColour);
  67318. filler[1].set (sourceColour);
  67319. filler[2].set (sourceColour);
  67320. filler[3].set (sourceColour);
  67321. }
  67322. }
  67323. forcedinline void setEdgeTableYPos (const int y) throw()
  67324. {
  67325. linePixels = (PixelType*) data.getLinePointer (y);
  67326. }
  67327. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67328. {
  67329. if (replaceExisting)
  67330. linePixels[x].set (sourceColour);
  67331. else
  67332. linePixels[x].blend (sourceColour, alphaLevel);
  67333. }
  67334. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67335. {
  67336. if (replaceExisting)
  67337. linePixels[x].set (sourceColour);
  67338. else
  67339. linePixels[x].blend (sourceColour);
  67340. }
  67341. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67342. {
  67343. PixelARGB p (sourceColour);
  67344. p.multiplyAlpha (alphaLevel);
  67345. PixelType* dest = linePixels + x;
  67346. if (replaceExisting || p.getAlpha() >= 0xff)
  67347. replaceLine (dest, p, width);
  67348. else
  67349. blendLine (dest, p, width);
  67350. }
  67351. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67352. {
  67353. PixelType* dest = linePixels + x;
  67354. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67355. replaceLine (dest, sourceColour, width);
  67356. else
  67357. blendLine (dest, sourceColour, width);
  67358. }
  67359. private:
  67360. const Image::BitmapData& data;
  67361. PixelType* linePixels;
  67362. PixelARGB sourceColour;
  67363. PixelRGB filler [4];
  67364. bool areRGBComponentsEqual;
  67365. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67366. {
  67367. do
  67368. {
  67369. dest->blend (colour);
  67370. ++dest;
  67371. } while (--width > 0);
  67372. }
  67373. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67374. {
  67375. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67376. {
  67377. memset (dest, colour.getRed(), width * 3);
  67378. }
  67379. else
  67380. {
  67381. if (width >> 5)
  67382. {
  67383. const int* const intFiller = (const int*) filler;
  67384. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67385. {
  67386. dest->set (colour);
  67387. ++dest;
  67388. --width;
  67389. }
  67390. while (width > 4)
  67391. {
  67392. ((int*) dest) [0] = intFiller[0];
  67393. ((int*) dest) [1] = intFiller[1];
  67394. ((int*) dest) [2] = intFiller[2];
  67395. dest = (PixelRGB*) (((uint8*) dest) + 12);
  67396. width -= 4;
  67397. }
  67398. }
  67399. while (--width >= 0)
  67400. {
  67401. dest->set (colour);
  67402. ++dest;
  67403. }
  67404. }
  67405. }
  67406. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67407. {
  67408. memset (dest, colour.getAlpha(), width);
  67409. }
  67410. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67411. {
  67412. do
  67413. {
  67414. dest->set (colour);
  67415. ++dest;
  67416. } while (--width > 0);
  67417. }
  67418. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67419. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67420. };
  67421. class LinearGradientPixelGenerator
  67422. {
  67423. public:
  67424. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67425. : lookupTable (lookupTable_), numEntries (numEntries_)
  67426. {
  67427. jassert (numEntries_ >= 0);
  67428. Point<float> p1 (gradient.point1);
  67429. Point<float> p2 (gradient.point2);
  67430. if (! transform.isIdentity())
  67431. {
  67432. const Line<float> l (p2, p1);
  67433. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67434. p1.applyTransform (transform);
  67435. p2.applyTransform (transform);
  67436. p3.applyTransform (transform);
  67437. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67438. }
  67439. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67440. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67441. if (vertical)
  67442. {
  67443. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67444. start = roundToInt (p1.getY() * scale);
  67445. }
  67446. else if (horizontal)
  67447. {
  67448. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67449. start = roundToInt (p1.getX() * scale);
  67450. }
  67451. else
  67452. {
  67453. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67454. yTerm = p1.getY() - p1.getX() / grad;
  67455. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67456. grad *= scale;
  67457. }
  67458. }
  67459. forcedinline void setY (const int y) throw()
  67460. {
  67461. if (vertical)
  67462. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67463. else if (! horizontal)
  67464. start = roundToInt ((y - yTerm) * grad);
  67465. }
  67466. inline const PixelARGB getPixel (const int x) const throw()
  67467. {
  67468. return vertical ? linePix
  67469. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67470. }
  67471. private:
  67472. const PixelARGB* const lookupTable;
  67473. const int numEntries;
  67474. PixelARGB linePix;
  67475. int start, scale;
  67476. double grad, yTerm;
  67477. bool vertical, horizontal;
  67478. enum { numScaleBits = 12 };
  67479. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67480. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67481. };
  67482. class RadialGradientPixelGenerator
  67483. {
  67484. public:
  67485. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67486. const PixelARGB* const lookupTable_, const int numEntries_)
  67487. : lookupTable (lookupTable_),
  67488. numEntries (numEntries_),
  67489. gx1 (gradient.point1.getX()),
  67490. gy1 (gradient.point1.getY())
  67491. {
  67492. jassert (numEntries_ >= 0);
  67493. const Point<float> diff (gradient.point1 - gradient.point2);
  67494. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67495. invScale = numEntries / std::sqrt (maxDist);
  67496. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67497. }
  67498. forcedinline void setY (const int y) throw()
  67499. {
  67500. dy = y - gy1;
  67501. dy *= dy;
  67502. }
  67503. inline const PixelARGB getPixel (const int px) const throw()
  67504. {
  67505. double x = px - gx1;
  67506. x *= x;
  67507. x += dy;
  67508. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67509. }
  67510. protected:
  67511. const PixelARGB* const lookupTable;
  67512. const int numEntries;
  67513. const double gx1, gy1;
  67514. double maxDist, invScale, dy;
  67515. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67516. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67517. };
  67518. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67519. {
  67520. public:
  67521. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67522. const PixelARGB* const lookupTable_, const int numEntries_)
  67523. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67524. inverseTransform (transform.inverted())
  67525. {
  67526. tM10 = inverseTransform.mat10;
  67527. tM00 = inverseTransform.mat00;
  67528. }
  67529. forcedinline void setY (const int y) throw()
  67530. {
  67531. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67532. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67533. }
  67534. inline const PixelARGB getPixel (const int px) const throw()
  67535. {
  67536. double x = px;
  67537. const double y = tM10 * x + lineYM11;
  67538. x = tM00 * x + lineYM01;
  67539. x *= x;
  67540. x += y * y;
  67541. if (x >= maxDist)
  67542. return lookupTable [numEntries];
  67543. else
  67544. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67545. }
  67546. private:
  67547. double tM10, tM00, lineYM01, lineYM11;
  67548. const AffineTransform inverseTransform;
  67549. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67550. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67551. };
  67552. template <class PixelType, class GradientType>
  67553. class GradientEdgeTableRenderer : public GradientType
  67554. {
  67555. public:
  67556. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67557. const PixelARGB* const lookupTable_, const int numEntries_)
  67558. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67559. destData (destData_)
  67560. {
  67561. }
  67562. forcedinline void setEdgeTableYPos (const int y) throw()
  67563. {
  67564. linePixels = (PixelType*) destData.getLinePointer (y);
  67565. GradientType::setY (y);
  67566. }
  67567. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67568. {
  67569. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67570. }
  67571. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67572. {
  67573. linePixels[x].blend (GradientType::getPixel (x));
  67574. }
  67575. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67576. {
  67577. PixelType* dest = linePixels + x;
  67578. if (alphaLevel < 0xff)
  67579. {
  67580. do
  67581. {
  67582. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67583. } while (--width > 0);
  67584. }
  67585. else
  67586. {
  67587. do
  67588. {
  67589. (dest++)->blend (GradientType::getPixel (x++));
  67590. } while (--width > 0);
  67591. }
  67592. }
  67593. void handleEdgeTableLineFull (int x, int width) const throw()
  67594. {
  67595. PixelType* dest = linePixels + x;
  67596. do
  67597. {
  67598. (dest++)->blend (GradientType::getPixel (x++));
  67599. } while (--width > 0);
  67600. }
  67601. private:
  67602. const Image::BitmapData& destData;
  67603. PixelType* linePixels;
  67604. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67605. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67606. };
  67607. static forcedinline int safeModulo (int n, const int divisor) throw()
  67608. {
  67609. jassert (divisor > 0);
  67610. n %= divisor;
  67611. return (n < 0) ? (n + divisor) : n;
  67612. }
  67613. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67614. class ImageFillEdgeTableRenderer
  67615. {
  67616. public:
  67617. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67618. const Image::BitmapData& srcData_,
  67619. const int extraAlpha_,
  67620. const int x, const int y)
  67621. : destData (destData_),
  67622. srcData (srcData_),
  67623. extraAlpha (extraAlpha_ + 1),
  67624. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67625. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67626. {
  67627. }
  67628. forcedinline void setEdgeTableYPos (int y) throw()
  67629. {
  67630. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67631. y -= yOffset;
  67632. if (repeatPattern)
  67633. {
  67634. jassert (y >= 0);
  67635. y %= srcData.height;
  67636. }
  67637. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67638. }
  67639. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67640. {
  67641. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67642. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67643. }
  67644. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67645. {
  67646. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67647. }
  67648. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67649. {
  67650. DestPixelType* dest = linePixels + x;
  67651. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67652. x -= xOffset;
  67653. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67654. if (alphaLevel < 0xfe)
  67655. {
  67656. do
  67657. {
  67658. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67659. } while (--width > 0);
  67660. }
  67661. else
  67662. {
  67663. if (repeatPattern)
  67664. {
  67665. do
  67666. {
  67667. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67668. } while (--width > 0);
  67669. }
  67670. else
  67671. {
  67672. copyRow (dest, sourceLineStart + x, width);
  67673. }
  67674. }
  67675. }
  67676. void handleEdgeTableLineFull (int x, int width) const throw()
  67677. {
  67678. DestPixelType* dest = linePixels + x;
  67679. x -= xOffset;
  67680. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67681. if (extraAlpha < 0xfe)
  67682. {
  67683. do
  67684. {
  67685. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67686. } while (--width > 0);
  67687. }
  67688. else
  67689. {
  67690. if (repeatPattern)
  67691. {
  67692. do
  67693. {
  67694. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67695. } while (--width > 0);
  67696. }
  67697. else
  67698. {
  67699. copyRow (dest, sourceLineStart + x, width);
  67700. }
  67701. }
  67702. }
  67703. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67704. {
  67705. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67706. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67707. uint8* mask = (uint8*) (s + x - xOffset);
  67708. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67709. mask += PixelARGB::indexA;
  67710. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67711. }
  67712. private:
  67713. const Image::BitmapData& destData;
  67714. const Image::BitmapData& srcData;
  67715. const int extraAlpha, xOffset, yOffset;
  67716. DestPixelType* linePixels;
  67717. SrcPixelType* sourceLineStart;
  67718. template <class PixelType1, class PixelType2>
  67719. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67720. {
  67721. do
  67722. {
  67723. dest++ ->blend (*src++);
  67724. } while (--width > 0);
  67725. }
  67726. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67727. {
  67728. memcpy (dest, src, width * sizeof (PixelRGB));
  67729. }
  67730. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67731. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67732. };
  67733. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67734. class TransformedImageFillEdgeTableRenderer
  67735. {
  67736. public:
  67737. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67738. const Image::BitmapData& srcData_,
  67739. const AffineTransform& transform,
  67740. const int extraAlpha_,
  67741. const bool betterQuality_)
  67742. : interpolator (transform),
  67743. destData (destData_),
  67744. srcData (srcData_),
  67745. extraAlpha (extraAlpha_ + 1),
  67746. betterQuality (betterQuality_),
  67747. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67748. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67749. maxX (srcData_.width - 1),
  67750. maxY (srcData_.height - 1),
  67751. scratchSize (2048)
  67752. {
  67753. scratchBuffer.malloc (scratchSize);
  67754. }
  67755. ~TransformedImageFillEdgeTableRenderer()
  67756. {
  67757. }
  67758. forcedinline void setEdgeTableYPos (const int newY) throw()
  67759. {
  67760. y = newY;
  67761. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67762. }
  67763. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67764. {
  67765. alphaLevel *= extraAlpha;
  67766. alphaLevel >>= 8;
  67767. SrcPixelType p;
  67768. generate (&p, x, 1);
  67769. linePixels[x].blend (p, alphaLevel);
  67770. }
  67771. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67772. {
  67773. SrcPixelType p;
  67774. generate (&p, x, 1);
  67775. linePixels[x].blend (p, extraAlpha);
  67776. }
  67777. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67778. {
  67779. if (width > scratchSize)
  67780. {
  67781. scratchSize = width;
  67782. scratchBuffer.malloc (scratchSize);
  67783. }
  67784. SrcPixelType* span = scratchBuffer;
  67785. generate (span, x, width);
  67786. DestPixelType* dest = linePixels + x;
  67787. alphaLevel *= extraAlpha;
  67788. alphaLevel >>= 8;
  67789. if (alphaLevel < 0xfe)
  67790. {
  67791. do
  67792. {
  67793. dest++ ->blend (*span++, alphaLevel);
  67794. } while (--width > 0);
  67795. }
  67796. else
  67797. {
  67798. do
  67799. {
  67800. dest++ ->blend (*span++);
  67801. } while (--width > 0);
  67802. }
  67803. }
  67804. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67805. {
  67806. handleEdgeTableLine (x, width, 255);
  67807. }
  67808. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67809. {
  67810. if (width > scratchSize)
  67811. {
  67812. scratchSize = width;
  67813. scratchBuffer.malloc (scratchSize);
  67814. }
  67815. y = y_;
  67816. generate (scratchBuffer, x, width);
  67817. et.clipLineToMask (x, y_,
  67818. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67819. sizeof (SrcPixelType), width);
  67820. }
  67821. private:
  67822. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67823. {
  67824. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67825. do
  67826. {
  67827. int hiResX, hiResY;
  67828. this->interpolator.next (hiResX, hiResY);
  67829. hiResX += pixelOffsetInt;
  67830. hiResY += pixelOffsetInt;
  67831. int loResX = hiResX >> 8;
  67832. int loResY = hiResY >> 8;
  67833. if (repeatPattern)
  67834. {
  67835. loResX = safeModulo (loResX, srcData.width);
  67836. loResY = safeModulo (loResY, srcData.height);
  67837. }
  67838. if (betterQuality
  67839. && ((unsigned int) loResX) < (unsigned int) maxX
  67840. && ((unsigned int) loResY) < (unsigned int) maxY)
  67841. {
  67842. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67843. hiResX &= 255;
  67844. hiResY &= 255;
  67845. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67846. uint32 weight = (256 - hiResX) * (256 - hiResY);
  67847. c[0] += weight * src[0];
  67848. c[1] += weight * src[1];
  67849. c[2] += weight * src[2];
  67850. c[3] += weight * src[3];
  67851. weight = hiResX * (256 - hiResY);
  67852. c[0] += weight * src[4];
  67853. c[1] += weight * src[5];
  67854. c[2] += weight * src[6];
  67855. c[3] += weight * src[7];
  67856. src += this->srcData.lineStride;
  67857. weight = (256 - hiResX) * hiResY;
  67858. c[0] += weight * src[0];
  67859. c[1] += weight * src[1];
  67860. c[2] += weight * src[2];
  67861. c[3] += weight * src[3];
  67862. weight = hiResX * hiResY;
  67863. c[0] += weight * src[4];
  67864. c[1] += weight * src[5];
  67865. c[2] += weight * src[6];
  67866. c[3] += weight * src[7];
  67867. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67868. (uint8) (c[PixelARGB::indexR] >> 16),
  67869. (uint8) (c[PixelARGB::indexG] >> 16),
  67870. (uint8) (c[PixelARGB::indexB] >> 16));
  67871. }
  67872. else
  67873. {
  67874. if (! repeatPattern)
  67875. {
  67876. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67877. if (loResX < 0) loResX = 0;
  67878. if (loResY < 0) loResY = 0;
  67879. if (loResX > maxX) loResX = maxX;
  67880. if (loResY > maxY) loResY = maxY;
  67881. }
  67882. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  67883. }
  67884. ++dest;
  67885. } while (--numPixels > 0);
  67886. }
  67887. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  67888. {
  67889. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67890. do
  67891. {
  67892. int hiResX, hiResY;
  67893. this->interpolator.next (hiResX, hiResY);
  67894. hiResX += pixelOffsetInt;
  67895. hiResY += pixelOffsetInt;
  67896. int loResX = hiResX >> 8;
  67897. int loResY = hiResY >> 8;
  67898. if (repeatPattern)
  67899. {
  67900. loResX = safeModulo (loResX, srcData.width);
  67901. loResY = safeModulo (loResY, srcData.height);
  67902. }
  67903. if (betterQuality
  67904. && ((unsigned int) loResX) < (unsigned int) maxX
  67905. && ((unsigned int) loResY) < (unsigned int) maxY)
  67906. {
  67907. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67908. hiResX &= 255;
  67909. hiResY &= 255;
  67910. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67911. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  67912. c[0] += weight * src[0];
  67913. c[1] += weight * src[1];
  67914. c[2] += weight * src[2];
  67915. weight = hiResX * (256 - hiResY);
  67916. c[0] += weight * src[3];
  67917. c[1] += weight * src[4];
  67918. c[2] += weight * src[5];
  67919. src += this->srcData.lineStride;
  67920. weight = (256 - hiResX) * hiResY;
  67921. c[0] += weight * src[0];
  67922. c[1] += weight * src[1];
  67923. c[2] += weight * src[2];
  67924. weight = hiResX * hiResY;
  67925. c[0] += weight * src[3];
  67926. c[1] += weight * src[4];
  67927. c[2] += weight * src[5];
  67928. dest->setARGB ((uint8) 255,
  67929. (uint8) (c[PixelRGB::indexR] >> 16),
  67930. (uint8) (c[PixelRGB::indexG] >> 16),
  67931. (uint8) (c[PixelRGB::indexB] >> 16));
  67932. }
  67933. else
  67934. {
  67935. if (! repeatPattern)
  67936. {
  67937. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67938. if (loResX < 0) loResX = 0;
  67939. if (loResY < 0) loResY = 0;
  67940. if (loResX > maxX) loResX = maxX;
  67941. if (loResY > maxY) loResY = maxY;
  67942. }
  67943. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  67944. }
  67945. ++dest;
  67946. } while (--numPixels > 0);
  67947. }
  67948. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  67949. {
  67950. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67951. do
  67952. {
  67953. int hiResX, hiResY;
  67954. this->interpolator.next (hiResX, hiResY);
  67955. hiResX += pixelOffsetInt;
  67956. hiResY += pixelOffsetInt;
  67957. int loResX = hiResX >> 8;
  67958. int loResY = hiResY >> 8;
  67959. if (repeatPattern)
  67960. {
  67961. loResX = safeModulo (loResX, srcData.width);
  67962. loResY = safeModulo (loResY, srcData.height);
  67963. }
  67964. if (betterQuality
  67965. && ((unsigned int) loResX) < (unsigned int) maxX
  67966. && ((unsigned int) loResY) < (unsigned int) maxY)
  67967. {
  67968. hiResX &= 255;
  67969. hiResY &= 255;
  67970. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67971. uint32 c = 256 * 128;
  67972. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  67973. c += src[1] * (hiResX * (256 - hiResY));
  67974. src += this->srcData.lineStride;
  67975. c += src[0] * ((256 - hiResX) * hiResY);
  67976. c += src[1] * (hiResX * hiResY);
  67977. *((uint8*) dest) = (uint8) c;
  67978. }
  67979. else
  67980. {
  67981. if (! repeatPattern)
  67982. {
  67983. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67984. if (loResX < 0) loResX = 0;
  67985. if (loResY < 0) loResY = 0;
  67986. if (loResX > maxX) loResX = maxX;
  67987. if (loResY > maxY) loResY = maxY;
  67988. }
  67989. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  67990. }
  67991. ++dest;
  67992. } while (--numPixels > 0);
  67993. }
  67994. class TransformedImageSpanInterpolator
  67995. {
  67996. public:
  67997. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  67998. : inverseTransform (transform.inverted())
  67999. {}
  68000. void setStartOfLine (float x, float y, const int numPixels) throw()
  68001. {
  68002. float x1 = x, y1 = y;
  68003. x += numPixels;
  68004. inverseTransform.transformPoints (x1, y1, x, y);
  68005. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68006. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68007. }
  68008. void next (int& x, int& y) throw()
  68009. {
  68010. x = xBresenham.n;
  68011. xBresenham.stepToNext();
  68012. y = yBresenham.n;
  68013. yBresenham.stepToNext();
  68014. }
  68015. private:
  68016. class BresenhamInterpolator
  68017. {
  68018. public:
  68019. BresenhamInterpolator() throw() {}
  68020. void set (const int n1, const int n2, const int numSteps_) throw()
  68021. {
  68022. numSteps = jmax (1, numSteps_);
  68023. step = (n2 - n1) / numSteps;
  68024. remainder = modulo = (n2 - n1) % numSteps;
  68025. n = n1;
  68026. if (modulo <= 0)
  68027. {
  68028. modulo += numSteps;
  68029. remainder += numSteps;
  68030. --step;
  68031. }
  68032. modulo -= numSteps;
  68033. }
  68034. forcedinline void stepToNext() throw()
  68035. {
  68036. modulo += remainder;
  68037. n += step;
  68038. if (modulo > 0)
  68039. {
  68040. modulo -= numSteps;
  68041. ++n;
  68042. }
  68043. }
  68044. int n;
  68045. private:
  68046. int numSteps, step, modulo, remainder;
  68047. };
  68048. const AffineTransform inverseTransform;
  68049. BresenhamInterpolator xBresenham, yBresenham;
  68050. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68051. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68052. };
  68053. TransformedImageSpanInterpolator interpolator;
  68054. const Image::BitmapData& destData;
  68055. const Image::BitmapData& srcData;
  68056. const int extraAlpha;
  68057. const bool betterQuality;
  68058. const float pixelOffset;
  68059. const int pixelOffsetInt, maxX, maxY;
  68060. int y;
  68061. DestPixelType* linePixels;
  68062. HeapBlock <SrcPixelType> scratchBuffer;
  68063. int scratchSize;
  68064. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68065. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68066. };
  68067. class ClipRegionBase : public ReferenceCountedObject
  68068. {
  68069. public:
  68070. ClipRegionBase() {}
  68071. virtual ~ClipRegionBase() {}
  68072. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68073. virtual const Ptr clone() const = 0;
  68074. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68075. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68076. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68077. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68078. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68079. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68080. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68081. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68082. virtual const Rectangle<int> getClipBounds() const = 0;
  68083. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68084. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68085. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68086. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68087. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68088. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68089. protected:
  68090. template <class Iterator>
  68091. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68092. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68093. {
  68094. switch (destData.pixelFormat)
  68095. {
  68096. case Image::ARGB:
  68097. switch (srcData.pixelFormat)
  68098. {
  68099. case Image::ARGB:
  68100. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68101. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68102. break;
  68103. case Image::RGB:
  68104. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68105. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68106. break;
  68107. default:
  68108. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68109. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68110. break;
  68111. }
  68112. break;
  68113. case Image::RGB:
  68114. switch (srcData.pixelFormat)
  68115. {
  68116. case Image::ARGB:
  68117. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68118. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68119. break;
  68120. case Image::RGB:
  68121. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68122. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68123. break;
  68124. default:
  68125. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68126. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68127. break;
  68128. }
  68129. break;
  68130. default:
  68131. switch (srcData.pixelFormat)
  68132. {
  68133. case Image::ARGB:
  68134. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68135. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68136. break;
  68137. case Image::RGB:
  68138. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68139. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68140. break;
  68141. default:
  68142. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68143. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68144. break;
  68145. }
  68146. break;
  68147. }
  68148. }
  68149. template <class Iterator>
  68150. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68151. {
  68152. switch (destData.pixelFormat)
  68153. {
  68154. case Image::ARGB:
  68155. switch (srcData.pixelFormat)
  68156. {
  68157. case Image::ARGB:
  68158. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68159. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68160. break;
  68161. case Image::RGB:
  68162. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68163. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68164. break;
  68165. default:
  68166. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68167. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68168. break;
  68169. }
  68170. break;
  68171. case Image::RGB:
  68172. switch (srcData.pixelFormat)
  68173. {
  68174. case Image::ARGB:
  68175. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68176. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68177. break;
  68178. case Image::RGB:
  68179. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68180. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68181. break;
  68182. default:
  68183. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68184. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68185. break;
  68186. }
  68187. break;
  68188. default:
  68189. switch (srcData.pixelFormat)
  68190. {
  68191. case Image::ARGB:
  68192. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68193. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68194. break;
  68195. case Image::RGB:
  68196. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68197. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68198. break;
  68199. default:
  68200. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68201. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68202. break;
  68203. }
  68204. break;
  68205. }
  68206. }
  68207. template <class Iterator, class DestPixelType>
  68208. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68209. {
  68210. jassert (destData.pixelStride == sizeof (DestPixelType));
  68211. if (replaceContents)
  68212. {
  68213. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68214. iter.iterate (r);
  68215. }
  68216. else
  68217. {
  68218. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68219. iter.iterate (r);
  68220. }
  68221. }
  68222. template <class Iterator, class DestPixelType>
  68223. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68224. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68225. {
  68226. jassert (destData.pixelStride == sizeof (DestPixelType));
  68227. if (g.isRadial)
  68228. {
  68229. if (isIdentity)
  68230. {
  68231. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68232. iter.iterate (renderer);
  68233. }
  68234. else
  68235. {
  68236. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68237. iter.iterate (renderer);
  68238. }
  68239. }
  68240. else
  68241. {
  68242. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68243. iter.iterate (renderer);
  68244. }
  68245. }
  68246. };
  68247. class ClipRegion_EdgeTable : public ClipRegionBase
  68248. {
  68249. public:
  68250. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68251. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68252. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68253. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68254. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68255. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68256. ~ClipRegion_EdgeTable() {}
  68257. const Ptr clone() const
  68258. {
  68259. return new ClipRegion_EdgeTable (*this);
  68260. }
  68261. const Ptr applyClipTo (const Ptr& target) const
  68262. {
  68263. return target->clipToEdgeTable (edgeTable);
  68264. }
  68265. const Ptr clipToRectangle (const Rectangle<int>& r)
  68266. {
  68267. edgeTable.clipToRectangle (r);
  68268. return edgeTable.isEmpty() ? 0 : this;
  68269. }
  68270. const Ptr clipToRectangleList (const RectangleList& r)
  68271. {
  68272. RectangleList inverse (edgeTable.getMaximumBounds());
  68273. if (inverse.subtract (r))
  68274. for (RectangleList::Iterator iter (inverse); iter.next();)
  68275. edgeTable.excludeRectangle (*iter.getRectangle());
  68276. return edgeTable.isEmpty() ? 0 : this;
  68277. }
  68278. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68279. {
  68280. edgeTable.excludeRectangle (r);
  68281. return edgeTable.isEmpty() ? 0 : this;
  68282. }
  68283. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68284. {
  68285. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68286. edgeTable.clipToEdgeTable (et);
  68287. return edgeTable.isEmpty() ? 0 : this;
  68288. }
  68289. const Ptr clipToEdgeTable (const EdgeTable& et)
  68290. {
  68291. edgeTable.clipToEdgeTable (et);
  68292. return edgeTable.isEmpty() ? 0 : this;
  68293. }
  68294. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68295. {
  68296. const Image::BitmapData srcData (image, false);
  68297. if (transform.isOnlyTranslation())
  68298. {
  68299. // If our translation doesn't involve any distortion, just use a simple blit..
  68300. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68301. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68302. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68303. {
  68304. const int imageX = ((tx + 128) >> 8);
  68305. const int imageY = ((ty + 128) >> 8);
  68306. if (image.getFormat() == Image::ARGB)
  68307. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68308. else
  68309. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68310. return edgeTable.isEmpty() ? 0 : this;
  68311. }
  68312. }
  68313. if (transform.isSingularity())
  68314. return 0;
  68315. {
  68316. Path p;
  68317. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68318. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68319. edgeTable.clipToEdgeTable (et2);
  68320. }
  68321. if (! edgeTable.isEmpty())
  68322. {
  68323. if (image.getFormat() == Image::ARGB)
  68324. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68325. else
  68326. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68327. }
  68328. return edgeTable.isEmpty() ? 0 : this;
  68329. }
  68330. bool clipRegionIntersects (const Rectangle<int>& r) const
  68331. {
  68332. return edgeTable.getMaximumBounds().intersects (r);
  68333. }
  68334. const Rectangle<int> getClipBounds() const
  68335. {
  68336. return edgeTable.getMaximumBounds();
  68337. }
  68338. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68339. {
  68340. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68341. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68342. if (! clipped.isEmpty())
  68343. {
  68344. ClipRegion_EdgeTable et (clipped);
  68345. et.edgeTable.clipToEdgeTable (edgeTable);
  68346. et.fillAllWithColour (destData, colour, replaceContents);
  68347. }
  68348. }
  68349. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68350. {
  68351. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68352. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68353. if (! clipped.isEmpty())
  68354. {
  68355. ClipRegion_EdgeTable et (clipped);
  68356. et.edgeTable.clipToEdgeTable (edgeTable);
  68357. et.fillAllWithColour (destData, colour, false);
  68358. }
  68359. }
  68360. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68361. {
  68362. switch (destData.pixelFormat)
  68363. {
  68364. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68365. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68366. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68367. }
  68368. }
  68369. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68370. {
  68371. HeapBlock <PixelARGB> lookupTable;
  68372. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68373. jassert (numLookupEntries > 0);
  68374. switch (destData.pixelFormat)
  68375. {
  68376. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68377. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68378. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68379. }
  68380. }
  68381. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68382. {
  68383. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68384. }
  68385. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68386. {
  68387. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68388. }
  68389. EdgeTable edgeTable;
  68390. private:
  68391. template <class SrcPixelType>
  68392. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68393. {
  68394. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68395. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68396. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68397. edgeTable.getMaximumBounds().getWidth());
  68398. }
  68399. template <class SrcPixelType>
  68400. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68401. {
  68402. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68403. edgeTable.clipToRectangle (r);
  68404. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68405. for (int y = 0; y < r.getHeight(); ++y)
  68406. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68407. }
  68408. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68409. };
  68410. class ClipRegion_RectangleList : public ClipRegionBase
  68411. {
  68412. public:
  68413. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68414. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68415. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68416. ~ClipRegion_RectangleList() {}
  68417. const Ptr clone() const
  68418. {
  68419. return new ClipRegion_RectangleList (*this);
  68420. }
  68421. const Ptr applyClipTo (const Ptr& target) const
  68422. {
  68423. return target->clipToRectangleList (clip);
  68424. }
  68425. const Ptr clipToRectangle (const Rectangle<int>& r)
  68426. {
  68427. clip.clipTo (r);
  68428. return clip.isEmpty() ? 0 : this;
  68429. }
  68430. const Ptr clipToRectangleList (const RectangleList& r)
  68431. {
  68432. clip.clipTo (r);
  68433. return clip.isEmpty() ? 0 : this;
  68434. }
  68435. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68436. {
  68437. clip.subtract (r);
  68438. return clip.isEmpty() ? 0 : this;
  68439. }
  68440. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68441. {
  68442. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68443. }
  68444. const Ptr clipToEdgeTable (const EdgeTable& et)
  68445. {
  68446. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68447. }
  68448. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68449. {
  68450. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68451. }
  68452. bool clipRegionIntersects (const Rectangle<int>& r) const
  68453. {
  68454. return clip.intersects (r);
  68455. }
  68456. const Rectangle<int> getClipBounds() const
  68457. {
  68458. return clip.getBounds();
  68459. }
  68460. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68461. {
  68462. SubRectangleIterator iter (clip, area);
  68463. switch (destData.pixelFormat)
  68464. {
  68465. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68466. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68467. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68468. }
  68469. }
  68470. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68471. {
  68472. SubRectangleIteratorFloat iter (clip, area);
  68473. switch (destData.pixelFormat)
  68474. {
  68475. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68476. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68477. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68478. }
  68479. }
  68480. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68481. {
  68482. switch (destData.pixelFormat)
  68483. {
  68484. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68485. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68486. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68487. }
  68488. }
  68489. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68490. {
  68491. HeapBlock <PixelARGB> lookupTable;
  68492. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68493. jassert (numLookupEntries > 0);
  68494. switch (destData.pixelFormat)
  68495. {
  68496. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68497. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68498. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68499. }
  68500. }
  68501. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68502. {
  68503. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68504. }
  68505. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68506. {
  68507. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68508. }
  68509. RectangleList clip;
  68510. template <class Renderer>
  68511. void iterate (Renderer& r) const throw()
  68512. {
  68513. RectangleList::Iterator iter (clip);
  68514. while (iter.next())
  68515. {
  68516. const Rectangle<int> rect (*iter.getRectangle());
  68517. const int x = rect.getX();
  68518. const int w = rect.getWidth();
  68519. jassert (w > 0);
  68520. const int bottom = rect.getBottom();
  68521. for (int y = rect.getY(); y < bottom; ++y)
  68522. {
  68523. r.setEdgeTableYPos (y);
  68524. r.handleEdgeTableLineFull (x, w);
  68525. }
  68526. }
  68527. }
  68528. private:
  68529. class SubRectangleIterator
  68530. {
  68531. public:
  68532. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68533. : clip (clip_), area (area_)
  68534. {
  68535. }
  68536. template <class Renderer>
  68537. void iterate (Renderer& r) const throw()
  68538. {
  68539. RectangleList::Iterator iter (clip);
  68540. while (iter.next())
  68541. {
  68542. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68543. if (! rect.isEmpty())
  68544. {
  68545. const int x = rect.getX();
  68546. const int w = rect.getWidth();
  68547. const int bottom = rect.getBottom();
  68548. for (int y = rect.getY(); y < bottom; ++y)
  68549. {
  68550. r.setEdgeTableYPos (y);
  68551. r.handleEdgeTableLineFull (x, w);
  68552. }
  68553. }
  68554. }
  68555. }
  68556. private:
  68557. const RectangleList& clip;
  68558. const Rectangle<int> area;
  68559. SubRectangleIterator (const SubRectangleIterator&);
  68560. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68561. };
  68562. class SubRectangleIteratorFloat
  68563. {
  68564. public:
  68565. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68566. : clip (clip_), area (area_)
  68567. {
  68568. }
  68569. template <class Renderer>
  68570. void iterate (Renderer& r) const throw()
  68571. {
  68572. int left = roundToInt (area.getX() * 256.0f);
  68573. int top = roundToInt (area.getY() * 256.0f);
  68574. int right = roundToInt (area.getRight() * 256.0f);
  68575. int bottom = roundToInt (area.getBottom() * 256.0f);
  68576. int totalTop, totalLeft, totalBottom, totalRight;
  68577. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68578. if ((top >> 8) == (bottom >> 8))
  68579. {
  68580. topAlpha = bottom - top;
  68581. bottomAlpha = 0;
  68582. totalTop = top >> 8;
  68583. totalBottom = bottom = top = totalTop + 1;
  68584. }
  68585. else
  68586. {
  68587. if ((top & 255) == 0)
  68588. {
  68589. topAlpha = 0;
  68590. top = totalTop = (top >> 8);
  68591. }
  68592. else
  68593. {
  68594. topAlpha = 255 - (top & 255);
  68595. totalTop = (top >> 8);
  68596. top = totalTop + 1;
  68597. }
  68598. bottomAlpha = bottom & 255;
  68599. bottom >>= 8;
  68600. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68601. }
  68602. if ((left >> 8) == (right >> 8))
  68603. {
  68604. leftAlpha = right - left;
  68605. rightAlpha = 0;
  68606. totalLeft = (left >> 8);
  68607. totalRight = right = left = totalLeft + 1;
  68608. }
  68609. else
  68610. {
  68611. if ((left & 255) == 0)
  68612. {
  68613. leftAlpha = 0;
  68614. left = totalLeft = (left >> 8);
  68615. }
  68616. else
  68617. {
  68618. leftAlpha = 255 - (left & 255);
  68619. totalLeft = (left >> 8);
  68620. left = totalLeft + 1;
  68621. }
  68622. rightAlpha = right & 255;
  68623. right >>= 8;
  68624. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68625. }
  68626. RectangleList::Iterator iter (clip);
  68627. while (iter.next())
  68628. {
  68629. const int clipLeft = iter.getRectangle()->getX();
  68630. const int clipRight = iter.getRectangle()->getRight();
  68631. const int clipTop = iter.getRectangle()->getY();
  68632. const int clipBottom = iter.getRectangle()->getBottom();
  68633. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68634. {
  68635. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68636. {
  68637. if (topAlpha != 0 && totalTop >= clipTop)
  68638. {
  68639. r.setEdgeTableYPos (totalTop);
  68640. r.handleEdgeTablePixel (left, topAlpha);
  68641. }
  68642. const int endY = jmin (bottom, clipBottom);
  68643. for (int y = jmax (clipTop, top); y < endY; ++y)
  68644. {
  68645. r.setEdgeTableYPos (y);
  68646. r.handleEdgeTablePixelFull (left);
  68647. }
  68648. if (bottomAlpha != 0 && bottom < clipBottom)
  68649. {
  68650. r.setEdgeTableYPos (bottom);
  68651. r.handleEdgeTablePixel (left, bottomAlpha);
  68652. }
  68653. }
  68654. else
  68655. {
  68656. const int clippedLeft = jmax (left, clipLeft);
  68657. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68658. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68659. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68660. if (topAlpha != 0 && totalTop >= clipTop)
  68661. {
  68662. r.setEdgeTableYPos (totalTop);
  68663. if (doLeftAlpha)
  68664. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68665. if (clippedWidth > 0)
  68666. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68667. if (doRightAlpha)
  68668. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68669. }
  68670. const int endY = jmin (bottom, clipBottom);
  68671. for (int y = jmax (clipTop, top); y < endY; ++y)
  68672. {
  68673. r.setEdgeTableYPos (y);
  68674. if (doLeftAlpha)
  68675. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68676. if (clippedWidth > 0)
  68677. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68678. if (doRightAlpha)
  68679. r.handleEdgeTablePixel (right, rightAlpha);
  68680. }
  68681. if (bottomAlpha != 0 && bottom < clipBottom)
  68682. {
  68683. r.setEdgeTableYPos (bottom);
  68684. if (doLeftAlpha)
  68685. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68686. if (clippedWidth > 0)
  68687. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68688. if (doRightAlpha)
  68689. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68690. }
  68691. }
  68692. }
  68693. }
  68694. }
  68695. private:
  68696. const RectangleList& clip;
  68697. const Rectangle<float>& area;
  68698. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68699. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68700. };
  68701. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68702. };
  68703. }
  68704. class LowLevelGraphicsSoftwareRenderer::SavedState
  68705. {
  68706. public:
  68707. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68708. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68709. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68710. {
  68711. }
  68712. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68713. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68714. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68715. {
  68716. }
  68717. SavedState (const SavedState& other)
  68718. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68719. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68720. {
  68721. }
  68722. ~SavedState()
  68723. {
  68724. }
  68725. void setOrigin (const int x, const int y) throw()
  68726. {
  68727. xOffset += x;
  68728. yOffset += y;
  68729. }
  68730. bool clipToRectangle (const Rectangle<int>& r)
  68731. {
  68732. if (clip != 0)
  68733. {
  68734. cloneClipIfMultiplyReferenced();
  68735. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68736. }
  68737. return clip != 0;
  68738. }
  68739. bool clipToRectangleList (const RectangleList& r)
  68740. {
  68741. if (clip != 0)
  68742. {
  68743. cloneClipIfMultiplyReferenced();
  68744. RectangleList offsetList (r);
  68745. offsetList.offsetAll (xOffset, yOffset);
  68746. clip = clip->clipToRectangleList (offsetList);
  68747. }
  68748. return clip != 0;
  68749. }
  68750. bool excludeClipRectangle (const Rectangle<int>& r)
  68751. {
  68752. if (clip != 0)
  68753. {
  68754. cloneClipIfMultiplyReferenced();
  68755. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68756. }
  68757. return clip != 0;
  68758. }
  68759. void clipToPath (const Path& p, const AffineTransform& transform)
  68760. {
  68761. if (clip != 0)
  68762. {
  68763. cloneClipIfMultiplyReferenced();
  68764. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68765. }
  68766. }
  68767. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68768. {
  68769. if (clip != 0)
  68770. {
  68771. if (image.hasAlphaChannel())
  68772. {
  68773. cloneClipIfMultiplyReferenced();
  68774. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68775. interpolationQuality != Graphics::lowResamplingQuality);
  68776. }
  68777. else
  68778. {
  68779. Path p;
  68780. p.addRectangle (image.getBounds());
  68781. clipToPath (p, t);
  68782. }
  68783. }
  68784. }
  68785. bool clipRegionIntersects (const Rectangle<int>& r) const
  68786. {
  68787. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68788. }
  68789. const Rectangle<int> getClipBounds() const
  68790. {
  68791. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68792. }
  68793. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68794. {
  68795. if (clip != 0)
  68796. {
  68797. if (fillType.isColour())
  68798. {
  68799. Image::BitmapData destData (image, true);
  68800. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68801. }
  68802. else
  68803. {
  68804. const Rectangle<int> totalClip (clip->getClipBounds());
  68805. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68806. if (! clipped.isEmpty())
  68807. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68808. }
  68809. }
  68810. }
  68811. void fillRect (Image& image, const Rectangle<float>& r)
  68812. {
  68813. if (clip != 0)
  68814. {
  68815. if (fillType.isColour())
  68816. {
  68817. Image::BitmapData destData (image, true);
  68818. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68819. }
  68820. else
  68821. {
  68822. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68823. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68824. if (! clipped.isEmpty())
  68825. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68826. }
  68827. }
  68828. }
  68829. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68830. {
  68831. if (clip != 0)
  68832. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  68833. }
  68834. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68835. {
  68836. if (clip != 0)
  68837. {
  68838. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68839. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68840. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68841. fillShape (image, shapeToFill, false);
  68842. }
  68843. }
  68844. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68845. {
  68846. jassert (clip != 0);
  68847. shapeToFill = clip->applyClipTo (shapeToFill);
  68848. if (shapeToFill != 0)
  68849. {
  68850. Image::BitmapData destData (image, true);
  68851. if (fillType.isGradient())
  68852. {
  68853. jassert (! replaceContents); // that option is just for solid colours
  68854. ColourGradient g2 (*(fillType.gradient));
  68855. g2.multiplyOpacity (fillType.getOpacity());
  68856. g2.point1.addXY (-0.5f, -0.5f);
  68857. g2.point2.addXY (-0.5f, -0.5f);
  68858. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  68859. const bool isIdentity = transform.isOnlyTranslation();
  68860. if (isIdentity)
  68861. {
  68862. // If our translation doesn't involve any distortion, we can speed it up..
  68863. g2.point1.applyTransform (transform);
  68864. g2.point2.applyTransform (transform);
  68865. transform = AffineTransform::identity;
  68866. }
  68867. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68868. }
  68869. else if (fillType.isTiledImage())
  68870. {
  68871. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68872. }
  68873. else
  68874. {
  68875. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68876. }
  68877. }
  68878. }
  68879. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68880. {
  68881. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  68882. const Image::BitmapData destData (destImage, true);
  68883. const Image::BitmapData srcData (sourceImage, false);
  68884. const int alpha = fillType.colour.getAlpha();
  68885. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68886. if (transform.isOnlyTranslation())
  68887. {
  68888. // If our translation doesn't involve any distortion, just use a simple blit..
  68889. int tx = (int) (transform.getTranslationX() * 256.0f);
  68890. int ty = (int) (transform.getTranslationY() * 256.0f);
  68891. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68892. {
  68893. tx = ((tx + 128) >> 8);
  68894. ty = ((ty + 128) >> 8);
  68895. if (tiledFillClipRegion != 0)
  68896. {
  68897. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68898. }
  68899. else
  68900. {
  68901. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  68902. c = clip->applyClipTo (c);
  68903. if (c != 0)
  68904. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68905. }
  68906. return;
  68907. }
  68908. }
  68909. if (transform.isSingularity())
  68910. return;
  68911. if (tiledFillClipRegion != 0)
  68912. {
  68913. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68914. }
  68915. else
  68916. {
  68917. Path p;
  68918. p.addRectangle (sourceImage.getBounds());
  68919. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68920. c = c->clipToPath (p, transform);
  68921. if (c != 0)
  68922. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68923. }
  68924. }
  68925. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68926. int xOffset, yOffset;
  68927. Font font;
  68928. FillType fillType;
  68929. Graphics::ResamplingQuality interpolationQuality;
  68930. private:
  68931. void cloneClipIfMultiplyReferenced()
  68932. {
  68933. if (clip->getReferenceCount() > 1)
  68934. clip = clip->clone();
  68935. }
  68936. SavedState& operator= (const SavedState&);
  68937. };
  68938. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68939. : image (image_)
  68940. {
  68941. currentState = new SavedState (image_.getBounds(), 0, 0);
  68942. }
  68943. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68944. const RectangleList& initialClip)
  68945. : image (image_)
  68946. {
  68947. currentState = new SavedState (initialClip, xOffset, yOffset);
  68948. }
  68949. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68950. {
  68951. }
  68952. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68953. {
  68954. return false;
  68955. }
  68956. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68957. {
  68958. currentState->setOrigin (x, y);
  68959. }
  68960. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68961. {
  68962. return currentState->clipToRectangle (r);
  68963. }
  68964. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68965. {
  68966. return currentState->clipToRectangleList (clipRegion);
  68967. }
  68968. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68969. {
  68970. currentState->excludeClipRectangle (r);
  68971. }
  68972. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68973. {
  68974. currentState->clipToPath (path, transform);
  68975. }
  68976. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  68977. {
  68978. currentState->clipToImageAlpha (sourceImage, transform);
  68979. }
  68980. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  68981. {
  68982. return currentState->clipRegionIntersects (r);
  68983. }
  68984. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  68985. {
  68986. return currentState->getClipBounds();
  68987. }
  68988. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  68989. {
  68990. return currentState->clip == 0;
  68991. }
  68992. void LowLevelGraphicsSoftwareRenderer::saveState()
  68993. {
  68994. stateStack.add (new SavedState (*currentState));
  68995. }
  68996. void LowLevelGraphicsSoftwareRenderer::restoreState()
  68997. {
  68998. SavedState* const top = stateStack.getLast();
  68999. if (top != 0)
  69000. {
  69001. currentState = top;
  69002. stateStack.removeLast (1, false);
  69003. }
  69004. else
  69005. {
  69006. jassertfalse; // trying to pop with an empty stack!
  69007. }
  69008. }
  69009. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69010. {
  69011. currentState->fillType = fillType;
  69012. }
  69013. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69014. {
  69015. currentState->fillType.setOpacity (newOpacity);
  69016. }
  69017. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69018. {
  69019. currentState->interpolationQuality = quality;
  69020. }
  69021. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69022. {
  69023. currentState->fillRect (image, r, replaceExistingContents);
  69024. }
  69025. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69026. {
  69027. currentState->fillPath (image, path, transform);
  69028. }
  69029. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69030. {
  69031. currentState->renderImage (image, sourceImage, transform,
  69032. fillEntireClipAsTiles ? currentState->clip : 0);
  69033. }
  69034. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69035. {
  69036. Path p;
  69037. p.addLineSegment (line, 1.0f);
  69038. fillPath (p, AffineTransform::identity);
  69039. }
  69040. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69041. {
  69042. if (bottom > top)
  69043. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69044. }
  69045. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69046. {
  69047. if (right > left)
  69048. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69049. }
  69050. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69051. {
  69052. public:
  69053. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69054. ~CachedGlyph() {}
  69055. void draw (SavedState& state, Image& image, const float x, const float y) const
  69056. {
  69057. if (edgeTable != 0)
  69058. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69059. }
  69060. void generate (const Font& newFont, const int glyphNumber)
  69061. {
  69062. font = newFont;
  69063. glyph = glyphNumber;
  69064. edgeTable = 0;
  69065. Path glyphPath;
  69066. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69067. if (! glyphPath.isEmpty())
  69068. {
  69069. const float fontHeight = font.getHeight();
  69070. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69071. #if JUCE_MAC || JUCE_IOS
  69072. .translated (0.0f, -0.5f)
  69073. #endif
  69074. );
  69075. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69076. glyphPath, transform);
  69077. }
  69078. }
  69079. int glyph, lastAccessCount;
  69080. Font font;
  69081. juce_UseDebuggingNewOperator
  69082. private:
  69083. ScopedPointer <EdgeTable> edgeTable;
  69084. CachedGlyph (const CachedGlyph&);
  69085. CachedGlyph& operator= (const CachedGlyph&);
  69086. };
  69087. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69088. {
  69089. public:
  69090. GlyphCache()
  69091. : accessCounter (0), hits (0), misses (0)
  69092. {
  69093. for (int i = 120; --i >= 0;)
  69094. glyphs.add (new CachedGlyph());
  69095. }
  69096. ~GlyphCache()
  69097. {
  69098. clearSingletonInstance();
  69099. }
  69100. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69101. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69102. {
  69103. ++accessCounter;
  69104. int oldestCounter = std::numeric_limits<int>::max();
  69105. CachedGlyph* oldest = 0;
  69106. for (int i = glyphs.size(); --i >= 0;)
  69107. {
  69108. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69109. if (glyph->glyph == glyphNumber && glyph->font == font)
  69110. {
  69111. ++hits;
  69112. glyph->lastAccessCount = accessCounter;
  69113. glyph->draw (state, image, x, y);
  69114. return;
  69115. }
  69116. if (glyph->lastAccessCount <= oldestCounter)
  69117. {
  69118. oldestCounter = glyph->lastAccessCount;
  69119. oldest = glyph;
  69120. }
  69121. }
  69122. if (hits + ++misses > (glyphs.size() << 4))
  69123. {
  69124. if (misses * 2 > hits)
  69125. {
  69126. for (int i = 32; --i >= 0;)
  69127. glyphs.add (new CachedGlyph());
  69128. }
  69129. hits = misses = 0;
  69130. oldest = glyphs.getLast();
  69131. }
  69132. jassert (oldest != 0);
  69133. oldest->lastAccessCount = accessCounter;
  69134. oldest->generate (font, glyphNumber);
  69135. oldest->draw (state, image, x, y);
  69136. }
  69137. juce_UseDebuggingNewOperator
  69138. private:
  69139. friend class OwnedArray <CachedGlyph>;
  69140. OwnedArray <CachedGlyph> glyphs;
  69141. int accessCounter, hits, misses;
  69142. GlyphCache (const GlyphCache&);
  69143. GlyphCache& operator= (const GlyphCache&);
  69144. };
  69145. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69146. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69147. {
  69148. currentState->font = newFont;
  69149. }
  69150. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69151. {
  69152. return currentState->font;
  69153. }
  69154. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69155. {
  69156. Font& f = currentState->font;
  69157. if (transform.isOnlyTranslation())
  69158. {
  69159. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69160. transform.getTranslationX(),
  69161. transform.getTranslationY());
  69162. }
  69163. else
  69164. {
  69165. Path p;
  69166. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69167. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69168. }
  69169. }
  69170. #if JUCE_MSVC
  69171. #pragma warning (pop)
  69172. #if JUCE_DEBUG
  69173. #pragma optimize ("", on) // resets optimisations to the project defaults
  69174. #endif
  69175. #endif
  69176. END_JUCE_NAMESPACE
  69177. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69178. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69179. BEGIN_JUCE_NAMESPACE
  69180. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69181. : flags (other.flags)
  69182. {
  69183. }
  69184. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69185. {
  69186. flags = other.flags;
  69187. return *this;
  69188. }
  69189. void RectanglePlacement::applyTo (double& x, double& y,
  69190. double& w, double& h,
  69191. const double dx, const double dy,
  69192. const double dw, const double dh) const throw()
  69193. {
  69194. if (w == 0 || h == 0)
  69195. return;
  69196. if ((flags & stretchToFit) != 0)
  69197. {
  69198. x = dx;
  69199. y = dy;
  69200. w = dw;
  69201. h = dh;
  69202. }
  69203. else
  69204. {
  69205. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69206. : jmin (dw / w, dh / h);
  69207. if ((flags & onlyReduceInSize) != 0)
  69208. scale = jmin (scale, 1.0);
  69209. if ((flags & onlyIncreaseInSize) != 0)
  69210. scale = jmax (scale, 1.0);
  69211. w *= scale;
  69212. h *= scale;
  69213. if ((flags & xLeft) != 0)
  69214. x = dx;
  69215. else if ((flags & xRight) != 0)
  69216. x = dx + dw - w;
  69217. else
  69218. x = dx + (dw - w) * 0.5;
  69219. if ((flags & yTop) != 0)
  69220. y = dy;
  69221. else if ((flags & yBottom) != 0)
  69222. y = dy + dh - h;
  69223. else
  69224. y = dy + (dh - h) * 0.5;
  69225. }
  69226. }
  69227. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  69228. float w, float h,
  69229. const float dx, const float dy,
  69230. const float dw, const float dh) const throw()
  69231. {
  69232. if (w == 0 || h == 0)
  69233. return AffineTransform::identity;
  69234. const float scaleX = dw / w;
  69235. const float scaleY = dh / h;
  69236. if ((flags & stretchToFit) != 0)
  69237. return AffineTransform::translation (-x, -y)
  69238. .scaled (scaleX, scaleY)
  69239. .translated (dx, dy);
  69240. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69241. : jmin (scaleX, scaleY);
  69242. if ((flags & onlyReduceInSize) != 0)
  69243. scale = jmin (scale, 1.0f);
  69244. if ((flags & onlyIncreaseInSize) != 0)
  69245. scale = jmax (scale, 1.0f);
  69246. w *= scale;
  69247. h *= scale;
  69248. float newX = dx;
  69249. if ((flags & xRight) != 0)
  69250. newX += dw - w; // right
  69251. else if ((flags & xLeft) == 0)
  69252. newX += (dw - w) / 2.0f; // centre
  69253. float newY = dy;
  69254. if ((flags & yBottom) != 0)
  69255. newY += dh - h; // bottom
  69256. else if ((flags & yTop) == 0)
  69257. newY += (dh - h) / 2.0f; // centre
  69258. return AffineTransform::translation (-x, -y)
  69259. .scaled (scale, scale)
  69260. .translated (newX, newY);
  69261. }
  69262. END_JUCE_NAMESPACE
  69263. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69264. /*** Start of inlined file: juce_Drawable.cpp ***/
  69265. BEGIN_JUCE_NAMESPACE
  69266. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69267. const AffineTransform& transform_,
  69268. const float opacity_) throw()
  69269. : g (g_),
  69270. transform (transform_),
  69271. opacity (opacity_)
  69272. {
  69273. }
  69274. Drawable::Drawable()
  69275. : parent (0)
  69276. {
  69277. }
  69278. Drawable::~Drawable()
  69279. {
  69280. }
  69281. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69282. {
  69283. render (RenderingContext (g, transform, opacity));
  69284. }
  69285. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69286. {
  69287. draw (g, opacity, AffineTransform::translation (x, y));
  69288. }
  69289. void Drawable::drawWithin (Graphics& g,
  69290. const int destX,
  69291. const int destY,
  69292. const int destW,
  69293. const int destH,
  69294. const RectanglePlacement& placement,
  69295. const float opacity) const
  69296. {
  69297. if (destW > 0 && destH > 0)
  69298. {
  69299. Rectangle<float> bounds (getBounds());
  69300. draw (g, opacity,
  69301. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  69302. (float) destX, (float) destY,
  69303. (float) destW, (float) destH));
  69304. }
  69305. }
  69306. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69307. {
  69308. Drawable* result = 0;
  69309. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69310. if (image.isValid())
  69311. {
  69312. DrawableImage* const di = new DrawableImage();
  69313. di->setImage (image);
  69314. result = di;
  69315. }
  69316. else
  69317. {
  69318. const String asString (String::createStringFromData (data, (int) numBytes));
  69319. XmlDocument doc (asString);
  69320. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69321. if (outer != 0 && outer->hasTagName ("svg"))
  69322. {
  69323. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69324. if (svg != 0)
  69325. result = Drawable::createFromSVG (*svg);
  69326. }
  69327. }
  69328. return result;
  69329. }
  69330. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69331. {
  69332. MemoryOutputStream mo;
  69333. mo.writeFromInputStream (dataSource, -1);
  69334. return createFromImageData (mo.getData(), mo.getDataSize());
  69335. }
  69336. Drawable* Drawable::createFromImageFile (const File& file)
  69337. {
  69338. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69339. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69340. }
  69341. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69342. {
  69343. return createChildFromValueTree (0, tree, imageProvider);
  69344. }
  69345. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69346. {
  69347. const Identifier type (tree.getType());
  69348. Drawable* d = 0;
  69349. if (type == DrawablePath::valueTreeType)
  69350. d = new DrawablePath();
  69351. else if (type == DrawableComposite::valueTreeType)
  69352. d = new DrawableComposite();
  69353. else if (type == DrawableImage::valueTreeType)
  69354. d = new DrawableImage();
  69355. else if (type == DrawableText::valueTreeType)
  69356. d = new DrawableText();
  69357. if (d != 0)
  69358. {
  69359. d->parent = parent;
  69360. d->refreshFromValueTree (tree, imageProvider);
  69361. }
  69362. return d;
  69363. }
  69364. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69365. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  69366. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  69367. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  69368. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  69369. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  69370. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  69371. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  69372. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  69373. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  69374. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69375. : state (state_)
  69376. {
  69377. }
  69378. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69379. {
  69380. }
  69381. const String Drawable::ValueTreeWrapperBase::getID() const
  69382. {
  69383. return state [idProperty];
  69384. }
  69385. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69386. {
  69387. if (newID.isEmpty())
  69388. state.removeProperty (idProperty, undoManager);
  69389. else
  69390. state.setProperty (idProperty, newID, undoManager);
  69391. }
  69392. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69393. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69394. {
  69395. const String newType (v[type].toString());
  69396. if (newType == "solid")
  69397. {
  69398. const String colourString (v [colour].toString());
  69399. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69400. : (uint32) colourString.getHexValue32()));
  69401. }
  69402. else if (newType == "gradient")
  69403. {
  69404. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69405. ColourGradient g;
  69406. if (gp1 != 0) *gp1 = p1;
  69407. if (gp2 != 0) *gp2 = p2;
  69408. if (gp3 != 0) *gp3 = p3;
  69409. g.point1 = p1.resolve (nameFinder);
  69410. g.point2 = p2.resolve (nameFinder);
  69411. g.isRadial = v[radial];
  69412. StringArray colourSteps;
  69413. colourSteps.addTokens (v[colours].toString(), false);
  69414. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69415. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69416. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69417. FillType fillType (g);
  69418. if (g.isRadial)
  69419. {
  69420. const Point<float> point3 (p3.resolve (nameFinder));
  69421. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69422. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69423. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69424. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69425. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69426. }
  69427. return fillType;
  69428. }
  69429. else if (newType == "image")
  69430. {
  69431. Image im;
  69432. if (imageProvider != 0)
  69433. im = imageProvider->getImageForIdentifier (v[imageId]);
  69434. FillType f (im, AffineTransform::identity);
  69435. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69436. return f;
  69437. }
  69438. jassertfalse;
  69439. return FillType();
  69440. }
  69441. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69442. {
  69443. const ColourGradient& g = *fillType.gradient;
  69444. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69445. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69446. return point3Source.transformedBy (fillType.transform);
  69447. }
  69448. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  69449. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69450. ImageProvider* imageProvider, UndoManager* const undoManager)
  69451. {
  69452. if (fillType.isColour())
  69453. {
  69454. v.setProperty (type, "solid", undoManager);
  69455. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69456. }
  69457. else if (fillType.isGradient())
  69458. {
  69459. v.setProperty (type, "gradient", undoManager);
  69460. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69461. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69462. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  69463. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69464. String s;
  69465. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69466. s << ' ' << fillType.gradient->getColourPosition (i)
  69467. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69468. v.setProperty (colours, s.trimStart(), undoManager);
  69469. }
  69470. else if (fillType.isTiledImage())
  69471. {
  69472. v.setProperty (type, "image", undoManager);
  69473. if (imageProvider != 0)
  69474. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69475. if (fillType.getOpacity() < 1.0f)
  69476. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69477. else
  69478. v.removeProperty (imageOpacity, undoManager);
  69479. }
  69480. else
  69481. {
  69482. jassertfalse;
  69483. }
  69484. }
  69485. END_JUCE_NAMESPACE
  69486. /*** End of inlined file: juce_Drawable.cpp ***/
  69487. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69488. BEGIN_JUCE_NAMESPACE
  69489. DrawableComposite::DrawableComposite()
  69490. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69491. {
  69492. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69493. RelativeCoordinate (100.0),
  69494. RelativeCoordinate (0.0),
  69495. RelativeCoordinate (100.0)));
  69496. }
  69497. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69498. {
  69499. bounds = other.bounds;
  69500. for (int i = 0; i < other.drawables.size(); ++i)
  69501. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69502. markersX.addCopiesOf (other.markersX);
  69503. markersY.addCopiesOf (other.markersY);
  69504. }
  69505. DrawableComposite::~DrawableComposite()
  69506. {
  69507. }
  69508. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69509. {
  69510. if (drawable != 0)
  69511. {
  69512. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69513. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69514. drawables.insert (index, drawable);
  69515. drawable->parent = this;
  69516. }
  69517. }
  69518. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69519. {
  69520. insertDrawable (drawable.createCopy(), index);
  69521. }
  69522. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69523. {
  69524. drawables.remove (index, deleteDrawable);
  69525. }
  69526. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69527. {
  69528. for (int i = drawables.size(); --i >= 0;)
  69529. if (drawables.getUnchecked(i)->getName() == name)
  69530. return drawables.getUnchecked(i);
  69531. return 0;
  69532. }
  69533. void DrawableComposite::bringToFront (const int index)
  69534. {
  69535. if (index >= 0 && index < drawables.size() - 1)
  69536. drawables.move (index, -1);
  69537. }
  69538. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69539. {
  69540. bounds = newBoundingBox;
  69541. }
  69542. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69543. : name (other.name), position (other.position)
  69544. {
  69545. }
  69546. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69547. : name (name_), position (position_)
  69548. {
  69549. }
  69550. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69551. {
  69552. return name != other.name || position != other.position;
  69553. }
  69554. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69555. const char* const DrawableComposite::contentRightMarkerName ("right");
  69556. const char* const DrawableComposite::contentTopMarkerName ("top");
  69557. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69558. const RelativeRectangle DrawableComposite::getContentArea() const
  69559. {
  69560. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69561. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69562. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69563. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69564. }
  69565. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69566. {
  69567. setMarker (contentLeftMarkerName, true, newArea.left);
  69568. setMarker (contentRightMarkerName, true, newArea.right);
  69569. setMarker (contentTopMarkerName, false, newArea.top);
  69570. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69571. }
  69572. void DrawableComposite::resetBoundingBoxToContentArea()
  69573. {
  69574. const RelativeRectangle content (getContentArea());
  69575. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69576. RelativePoint (content.right, content.top),
  69577. RelativePoint (content.left, content.bottom)));
  69578. }
  69579. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69580. {
  69581. const Rectangle<float> bounds (getUntransformedBounds (false));
  69582. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69583. RelativeCoordinate (bounds.getRight()),
  69584. RelativeCoordinate (bounds.getY()),
  69585. RelativeCoordinate (bounds.getBottom())));
  69586. resetBoundingBoxToContentArea();
  69587. }
  69588. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69589. {
  69590. return (xAxis ? markersX : markersY).size();
  69591. }
  69592. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69593. {
  69594. return (xAxis ? markersX : markersY) [index];
  69595. }
  69596. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69597. {
  69598. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69599. for (int i = 0; i < markers.size(); ++i)
  69600. {
  69601. Marker* const m = markers.getUnchecked(i);
  69602. if (m->name == name)
  69603. {
  69604. if (m->position != position)
  69605. {
  69606. m->position = position;
  69607. invalidatePoints();
  69608. }
  69609. return;
  69610. }
  69611. }
  69612. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69613. invalidatePoints();
  69614. }
  69615. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69616. {
  69617. jassert (index >= 2);
  69618. if (index >= 2)
  69619. (xAxis ? markersX : markersY).remove (index);
  69620. }
  69621. const AffineTransform DrawableComposite::calculateTransform() const
  69622. {
  69623. Point<float> resolved[3];
  69624. bounds.resolveThreePoints (resolved, parent);
  69625. const Rectangle<float> content (getContentArea().resolve (parent));
  69626. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69627. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69628. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69629. }
  69630. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69631. {
  69632. if (drawables.size() > 0 && context.opacity > 0)
  69633. {
  69634. if (context.opacity >= 1.0f || drawables.size() == 1)
  69635. {
  69636. Drawable::RenderingContext contextCopy (context);
  69637. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69638. for (int i = 0; i < drawables.size(); ++i)
  69639. drawables.getUnchecked(i)->render (contextCopy);
  69640. }
  69641. else
  69642. {
  69643. // To correctly render a whole composite layer with an overall transparency,
  69644. // we need to render everything opaquely into a temp buffer, then blend that
  69645. // with the target opacity...
  69646. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69647. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69648. {
  69649. Graphics tempG (tempImage);
  69650. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69651. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69652. render (tempContext);
  69653. }
  69654. context.g.setOpacity (context.opacity);
  69655. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69656. }
  69657. }
  69658. }
  69659. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69660. {
  69661. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69662. int i;
  69663. for (i = 0; i < markersX.size(); ++i)
  69664. {
  69665. Marker* const m = markersX.getUnchecked(i);
  69666. if (m->name == symbol)
  69667. return m->position.getExpression();
  69668. }
  69669. for (i = 0; i < markersY.size(); ++i)
  69670. {
  69671. Marker* const m = markersY.getUnchecked(i);
  69672. if (m->name == symbol)
  69673. return m->position.getExpression();
  69674. }
  69675. return Expression::EvaluationContext::getSymbolValue (symbol, member);
  69676. }
  69677. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69678. {
  69679. Rectangle<float> bounds;
  69680. int i;
  69681. for (i = 0; i < drawables.size(); ++i)
  69682. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69683. if (includeMarkers)
  69684. {
  69685. if (markersX.size() > 0)
  69686. {
  69687. float minX = std::numeric_limits<float>::max();
  69688. float maxX = std::numeric_limits<float>::min();
  69689. for (i = markersX.size(); --i >= 0;)
  69690. {
  69691. const Marker* m = markersX.getUnchecked(i);
  69692. const float pos = (float) m->position.resolve (this);
  69693. minX = jmin (minX, pos);
  69694. maxX = jmax (maxX, pos);
  69695. }
  69696. if (minX <= maxX)
  69697. {
  69698. if (bounds.getHeight() > 0)
  69699. {
  69700. minX = jmin (minX, bounds.getX());
  69701. maxX = jmax (maxX, bounds.getRight());
  69702. }
  69703. bounds.setLeft (minX);
  69704. bounds.setWidth (maxX - minX);
  69705. }
  69706. }
  69707. if (markersY.size() > 0)
  69708. {
  69709. float minY = std::numeric_limits<float>::max();
  69710. float maxY = std::numeric_limits<float>::min();
  69711. for (i = markersY.size(); --i >= 0;)
  69712. {
  69713. const Marker* m = markersY.getUnchecked(i);
  69714. const float pos = (float) m->position.resolve (this);
  69715. minY = jmin (minY, pos);
  69716. maxY = jmax (maxY, pos);
  69717. }
  69718. if (minY <= maxY)
  69719. {
  69720. if (bounds.getHeight() > 0)
  69721. {
  69722. minY = jmin (minY, bounds.getY());
  69723. maxY = jmax (maxY, bounds.getBottom());
  69724. }
  69725. bounds.setTop (minY);
  69726. bounds.setHeight (maxY - minY);
  69727. }
  69728. }
  69729. }
  69730. return bounds;
  69731. }
  69732. const Rectangle<float> DrawableComposite::getBounds() const
  69733. {
  69734. return getUntransformedBounds (true).transformed (calculateTransform());
  69735. }
  69736. bool DrawableComposite::hitTest (float x, float y) const
  69737. {
  69738. calculateTransform().inverted().transformPoint (x, y);
  69739. for (int i = 0; i < drawables.size(); ++i)
  69740. if (drawables.getUnchecked(i)->hitTest (x, y))
  69741. return true;
  69742. return false;
  69743. }
  69744. Drawable* DrawableComposite::createCopy() const
  69745. {
  69746. return new DrawableComposite (*this);
  69747. }
  69748. void DrawableComposite::invalidatePoints()
  69749. {
  69750. for (int i = 0; i < drawables.size(); ++i)
  69751. drawables.getUnchecked(i)->invalidatePoints();
  69752. }
  69753. const Identifier DrawableComposite::valueTreeType ("Group");
  69754. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69755. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69756. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69757. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69758. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69759. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69760. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69761. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69762. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69763. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69764. : ValueTreeWrapperBase (state_)
  69765. {
  69766. jassert (state.hasType (valueTreeType));
  69767. }
  69768. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69769. {
  69770. return state.getChildWithName (childGroupTag);
  69771. }
  69772. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69773. {
  69774. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69775. }
  69776. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69777. {
  69778. return getChildList().getNumChildren();
  69779. }
  69780. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69781. {
  69782. return getChildList().getChild (index);
  69783. }
  69784. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69785. {
  69786. if (getID() == objectId)
  69787. return state;
  69788. if (! recursive)
  69789. {
  69790. return getChildList().getChildWithProperty (idProperty, objectId);
  69791. }
  69792. else
  69793. {
  69794. const ValueTree childList (getChildList());
  69795. for (int i = getNumDrawables(); --i >= 0;)
  69796. {
  69797. const ValueTree& child = childList.getChild (i);
  69798. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69799. return child;
  69800. if (child.hasType (DrawableComposite::valueTreeType))
  69801. {
  69802. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69803. if (v.isValid())
  69804. return v;
  69805. }
  69806. }
  69807. return ValueTree::invalid;
  69808. }
  69809. }
  69810. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69811. {
  69812. return getChildList().indexOf (item);
  69813. }
  69814. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69815. {
  69816. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69817. }
  69818. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69819. {
  69820. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69821. }
  69822. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69823. {
  69824. getChildList().removeChild (child, undoManager);
  69825. }
  69826. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69827. {
  69828. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69829. state.getProperty (topRight, "100, 0"),
  69830. state.getProperty (bottomLeft, "0, 100"));
  69831. }
  69832. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69833. {
  69834. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69835. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69836. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69837. }
  69838. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69839. {
  69840. const RelativeRectangle content (getContentArea());
  69841. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69842. RelativePoint (content.right, content.top),
  69843. RelativePoint (content.left, content.bottom)), undoManager);
  69844. }
  69845. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69846. {
  69847. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69848. getMarker (true, getMarkerState (true, 1)).position,
  69849. getMarker (false, getMarkerState (false, 0)).position,
  69850. getMarker (false, getMarkerState (false, 1)).position);
  69851. }
  69852. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69853. {
  69854. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69855. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69856. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69857. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69858. }
  69859. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69860. {
  69861. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69862. }
  69863. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  69864. {
  69865. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  69866. }
  69867. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  69868. {
  69869. return getMarkerList (xAxis).getNumChildren();
  69870. }
  69871. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  69872. {
  69873. return getMarkerList (xAxis).getChild (index);
  69874. }
  69875. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  69876. {
  69877. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  69878. }
  69879. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  69880. {
  69881. return state.isAChildOf (getMarkerList (xAxis));
  69882. }
  69883. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  69884. {
  69885. jassert (containsMarker (xAxis, state));
  69886. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  69887. }
  69888. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  69889. {
  69890. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  69891. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  69892. if (marker.isValid())
  69893. {
  69894. marker.setProperty (posProperty, m.position.toString(), undoManager);
  69895. }
  69896. else
  69897. {
  69898. marker = ValueTree (markerTag);
  69899. marker.setProperty (nameProperty, m.name, 0);
  69900. marker.setProperty (posProperty, m.position.toString(), 0);
  69901. markerList.addChild (marker, -1, undoManager);
  69902. }
  69903. }
  69904. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  69905. {
  69906. if (state [nameProperty].toString() != contentLeftMarkerName
  69907. && state [nameProperty].toString() != contentRightMarkerName
  69908. && state [nameProperty].toString() != contentTopMarkerName
  69909. && state [nameProperty].toString() != contentBottomMarkerName)
  69910. return getMarkerList (xAxis).removeChild (state, undoManager);
  69911. }
  69912. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69913. {
  69914. const ValueTreeWrapper wrapper (tree);
  69915. setName (wrapper.getID());
  69916. Rectangle<float> damage;
  69917. bool redrawAll = false;
  69918. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  69919. if (bounds != newBounds)
  69920. {
  69921. redrawAll = true;
  69922. damage = getBounds();
  69923. bounds = newBounds;
  69924. }
  69925. const int numMarkersX = wrapper.getNumMarkers (true);
  69926. const int numMarkersY = wrapper.getNumMarkers (false);
  69927. // Remove deleted markers...
  69928. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  69929. {
  69930. if (! redrawAll)
  69931. {
  69932. redrawAll = true;
  69933. damage = getBounds();
  69934. }
  69935. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  69936. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  69937. }
  69938. // Update markers and add new ones..
  69939. int i;
  69940. for (i = 0; i < numMarkersX; ++i)
  69941. {
  69942. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  69943. Marker* m = markersX[i];
  69944. if (m == 0 || newMarker != *m)
  69945. {
  69946. if (! redrawAll)
  69947. {
  69948. redrawAll = true;
  69949. damage = getBounds();
  69950. }
  69951. if (m == 0)
  69952. markersX.add (new Marker (newMarker));
  69953. else
  69954. *m = newMarker;
  69955. }
  69956. }
  69957. for (i = 0; i < numMarkersY; ++i)
  69958. {
  69959. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  69960. Marker* m = markersY[i];
  69961. if (m == 0 || newMarker != *m)
  69962. {
  69963. if (! redrawAll)
  69964. {
  69965. redrawAll = true;
  69966. damage = getBounds();
  69967. }
  69968. if (m == 0)
  69969. markersY.add (new Marker (newMarker));
  69970. else
  69971. *m = newMarker;
  69972. }
  69973. }
  69974. // Remove deleted drawables..
  69975. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  69976. {
  69977. Drawable* const d = drawables.getUnchecked(i);
  69978. if (! redrawAll)
  69979. damage = damage.getUnion (d->getBounds());
  69980. d->parent = 0;
  69981. drawables.remove (i);
  69982. }
  69983. // Update drawables and add new ones..
  69984. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  69985. {
  69986. const ValueTree newDrawable (wrapper.getDrawableState (i));
  69987. Drawable* d = drawables[i];
  69988. if (d != 0)
  69989. {
  69990. if (newDrawable.hasType (d->getValueTreeType()))
  69991. {
  69992. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  69993. if (! redrawAll)
  69994. damage = damage.getUnion (area);
  69995. }
  69996. else
  69997. {
  69998. if (! redrawAll)
  69999. damage = damage.getUnion (d->getBounds());
  70000. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70001. drawables.set (i, d);
  70002. if (! redrawAll)
  70003. damage = damage.getUnion (d->getBounds());
  70004. }
  70005. }
  70006. else
  70007. {
  70008. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70009. drawables.set (i, d);
  70010. if (! redrawAll)
  70011. damage = damage.getUnion (d->getBounds());
  70012. }
  70013. }
  70014. if (redrawAll)
  70015. damage = damage.getUnion (getBounds());
  70016. else if (! damage.isEmpty())
  70017. damage = damage.transformed (calculateTransform());
  70018. return damage;
  70019. }
  70020. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70021. {
  70022. ValueTree tree (valueTreeType);
  70023. ValueTreeWrapper v (tree);
  70024. v.setID (getName(), 0);
  70025. v.setBoundingBox (bounds, 0);
  70026. int i;
  70027. for (i = 0; i < drawables.size(); ++i)
  70028. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70029. for (i = 0; i < markersX.size(); ++i)
  70030. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70031. for (i = 0; i < markersY.size(); ++i)
  70032. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70033. return tree;
  70034. }
  70035. END_JUCE_NAMESPACE
  70036. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70037. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70038. BEGIN_JUCE_NAMESPACE
  70039. DrawableImage::DrawableImage()
  70040. : image (0),
  70041. opacity (1.0f),
  70042. overlayColour (0x00000000)
  70043. {
  70044. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70045. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70046. }
  70047. DrawableImage::DrawableImage (const DrawableImage& other)
  70048. : image (other.image),
  70049. opacity (other.opacity),
  70050. overlayColour (other.overlayColour),
  70051. bounds (other.bounds)
  70052. {
  70053. }
  70054. DrawableImage::~DrawableImage()
  70055. {
  70056. }
  70057. void DrawableImage::setImage (const Image& imageToUse)
  70058. {
  70059. image = imageToUse;
  70060. if (image.isValid())
  70061. {
  70062. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70063. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70064. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70065. }
  70066. }
  70067. void DrawableImage::setOpacity (const float newOpacity)
  70068. {
  70069. opacity = newOpacity;
  70070. }
  70071. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70072. {
  70073. overlayColour = newOverlayColour;
  70074. }
  70075. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70076. {
  70077. bounds = newBounds;
  70078. }
  70079. const AffineTransform DrawableImage::calculateTransform() const
  70080. {
  70081. if (image.isNull())
  70082. return AffineTransform::identity;
  70083. Point<float> resolved[3];
  70084. bounds.resolveThreePoints (resolved, parent);
  70085. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70086. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70087. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70088. tr.getX(), tr.getY(),
  70089. bl.getX(), bl.getY());
  70090. }
  70091. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70092. {
  70093. if (image.isValid())
  70094. {
  70095. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70096. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70097. {
  70098. context.g.setOpacity (context.opacity * opacity);
  70099. context.g.drawImageTransformed (image, t, false);
  70100. }
  70101. if (! overlayColour.isTransparent())
  70102. {
  70103. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70104. context.g.drawImageTransformed (image, t, true);
  70105. }
  70106. }
  70107. }
  70108. const Rectangle<float> DrawableImage::getBounds() const
  70109. {
  70110. if (image.isNull())
  70111. return Rectangle<float>();
  70112. return bounds.getBounds (parent);
  70113. }
  70114. bool DrawableImage::hitTest (float x, float y) const
  70115. {
  70116. if (image.isNull())
  70117. return false;
  70118. calculateTransform().inverted().transformPoint (x, y);
  70119. const int ix = roundToInt (x);
  70120. const int iy = roundToInt (y);
  70121. return ix >= 0
  70122. && iy >= 0
  70123. && ix < image.getWidth()
  70124. && iy < image.getHeight()
  70125. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70126. }
  70127. Drawable* DrawableImage::createCopy() const
  70128. {
  70129. return new DrawableImage (*this);
  70130. }
  70131. void DrawableImage::invalidatePoints()
  70132. {
  70133. }
  70134. const Identifier DrawableImage::valueTreeType ("Image");
  70135. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70136. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70137. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70138. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70139. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70140. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70141. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70142. : ValueTreeWrapperBase (state_)
  70143. {
  70144. jassert (state.hasType (valueTreeType));
  70145. }
  70146. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70147. {
  70148. return state [image];
  70149. }
  70150. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70151. {
  70152. return state.getPropertyAsValue (image, undoManager);
  70153. }
  70154. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70155. {
  70156. state.setProperty (image, newIdentifier, undoManager);
  70157. }
  70158. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70159. {
  70160. return (float) state.getProperty (opacity, 1.0);
  70161. }
  70162. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70163. {
  70164. if (! state.hasProperty (opacity))
  70165. state.setProperty (opacity, 1.0, undoManager);
  70166. return state.getPropertyAsValue (opacity, undoManager);
  70167. }
  70168. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70169. {
  70170. state.setProperty (opacity, newOpacity, undoManager);
  70171. }
  70172. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70173. {
  70174. return Colour (state [overlay].toString().getHexValue32());
  70175. }
  70176. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70177. {
  70178. if (newColour.isTransparent())
  70179. state.removeProperty (overlay, undoManager);
  70180. else
  70181. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70182. }
  70183. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70184. {
  70185. return state.getPropertyAsValue (overlay, undoManager);
  70186. }
  70187. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70188. {
  70189. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70190. state.getProperty (topRight, "100, 0"),
  70191. state.getProperty (bottomLeft, "0, 100"));
  70192. }
  70193. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70194. {
  70195. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70196. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70197. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70198. }
  70199. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70200. {
  70201. const ValueTreeWrapper controller (tree);
  70202. setName (controller.getID());
  70203. const float newOpacity = controller.getOpacity();
  70204. const Colour newOverlayColour (controller.getOverlayColour());
  70205. Image newImage;
  70206. const var imageIdentifier (controller.getImageIdentifier());
  70207. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70208. if (imageProvider != 0)
  70209. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70210. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70211. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70212. {
  70213. const Rectangle<float> damage (getBounds());
  70214. opacity = newOpacity;
  70215. overlayColour = newOverlayColour;
  70216. bounds = newBounds;
  70217. image = newImage;
  70218. return damage.getUnion (getBounds());
  70219. }
  70220. return Rectangle<float>();
  70221. }
  70222. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70223. {
  70224. ValueTree tree (valueTreeType);
  70225. ValueTreeWrapper v (tree);
  70226. v.setID (getName(), 0);
  70227. v.setOpacity (opacity, 0);
  70228. v.setOverlayColour (overlayColour, 0);
  70229. v.setBoundingBox (bounds, 0);
  70230. if (image.isValid())
  70231. {
  70232. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70233. if (imageProvider != 0)
  70234. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70235. }
  70236. return tree;
  70237. }
  70238. END_JUCE_NAMESPACE
  70239. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70240. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70241. BEGIN_JUCE_NAMESPACE
  70242. DrawablePath::DrawablePath()
  70243. : mainFill (Colours::black),
  70244. strokeFill (Colours::black),
  70245. strokeType (0.0f),
  70246. pathNeedsUpdating (true),
  70247. strokeNeedsUpdating (true)
  70248. {
  70249. }
  70250. DrawablePath::DrawablePath (const DrawablePath& other)
  70251. : mainFill (other.mainFill),
  70252. strokeFill (other.strokeFill),
  70253. strokeType (other.strokeType),
  70254. pathNeedsUpdating (true),
  70255. strokeNeedsUpdating (true)
  70256. {
  70257. if (other.relativePath != 0)
  70258. relativePath = new RelativePointPath (*other.relativePath);
  70259. else
  70260. path = other.path;
  70261. }
  70262. DrawablePath::~DrawablePath()
  70263. {
  70264. }
  70265. void DrawablePath::setPath (const Path& newPath)
  70266. {
  70267. path = newPath;
  70268. strokeNeedsUpdating = true;
  70269. }
  70270. void DrawablePath::setFill (const FillType& newFill)
  70271. {
  70272. mainFill = newFill;
  70273. }
  70274. void DrawablePath::setStrokeFill (const FillType& newFill)
  70275. {
  70276. strokeFill = newFill;
  70277. }
  70278. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  70279. {
  70280. strokeType = newStrokeType;
  70281. strokeNeedsUpdating = true;
  70282. }
  70283. void DrawablePath::setStrokeThickness (const float newThickness)
  70284. {
  70285. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70286. }
  70287. void DrawablePath::updatePath() const
  70288. {
  70289. if (pathNeedsUpdating)
  70290. {
  70291. pathNeedsUpdating = false;
  70292. if (relativePath != 0)
  70293. {
  70294. path.clear();
  70295. relativePath->createPath (path, parent);
  70296. strokeNeedsUpdating = true;
  70297. }
  70298. }
  70299. }
  70300. void DrawablePath::updateStroke() const
  70301. {
  70302. if (strokeNeedsUpdating)
  70303. {
  70304. strokeNeedsUpdating = false;
  70305. updatePath();
  70306. stroke.clear();
  70307. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  70308. }
  70309. }
  70310. const Path& DrawablePath::getPath() const
  70311. {
  70312. updatePath();
  70313. return path;
  70314. }
  70315. const Path& DrawablePath::getStrokePath() const
  70316. {
  70317. updateStroke();
  70318. return stroke;
  70319. }
  70320. bool DrawablePath::isStrokeVisible() const throw()
  70321. {
  70322. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  70323. }
  70324. void DrawablePath::invalidatePoints()
  70325. {
  70326. pathNeedsUpdating = true;
  70327. strokeNeedsUpdating = true;
  70328. }
  70329. void DrawablePath::render (const Drawable::RenderingContext& context) const
  70330. {
  70331. {
  70332. FillType f (mainFill);
  70333. if (f.isGradient())
  70334. f.gradient->multiplyOpacity (context.opacity);
  70335. else
  70336. f.setOpacity (f.getOpacity() * context.opacity);
  70337. f.transform = f.transform.followedBy (context.transform);
  70338. context.g.setFillType (f);
  70339. context.g.fillPath (getPath(), context.transform);
  70340. }
  70341. if (isStrokeVisible())
  70342. {
  70343. FillType f (strokeFill);
  70344. if (f.isGradient())
  70345. f.gradient->multiplyOpacity (context.opacity);
  70346. else
  70347. f.setOpacity (f.getOpacity() * context.opacity);
  70348. f.transform = f.transform.followedBy (context.transform);
  70349. context.g.setFillType (f);
  70350. context.g.fillPath (getStrokePath(), context.transform);
  70351. }
  70352. }
  70353. const Rectangle<float> DrawablePath::getBounds() const
  70354. {
  70355. if (isStrokeVisible())
  70356. return getStrokePath().getBounds();
  70357. else
  70358. return getPath().getBounds();
  70359. }
  70360. bool DrawablePath::hitTest (float x, float y) const
  70361. {
  70362. return getPath().contains (x, y)
  70363. || (isStrokeVisible() && getStrokePath().contains (x, y));
  70364. }
  70365. Drawable* DrawablePath::createCopy() const
  70366. {
  70367. return new DrawablePath (*this);
  70368. }
  70369. const Identifier DrawablePath::valueTreeType ("Path");
  70370. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  70371. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  70372. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  70373. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  70374. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  70375. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  70376. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70377. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70378. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70379. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70380. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70381. : ValueTreeWrapperBase (state_)
  70382. {
  70383. jassert (state.hasType (valueTreeType));
  70384. }
  70385. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70386. {
  70387. return state.getOrCreateChildWithName (path, 0);
  70388. }
  70389. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  70390. {
  70391. ValueTree v (state.getChildWithName (fill));
  70392. if (v.isValid())
  70393. return v;
  70394. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  70395. return getMainFillState();
  70396. }
  70397. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  70398. {
  70399. ValueTree v (state.getChildWithName (stroke));
  70400. if (v.isValid())
  70401. return v;
  70402. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  70403. return getStrokeFillState();
  70404. }
  70405. const FillType DrawablePath::ValueTreeWrapper::getMainFill (Expression::EvaluationContext* nameFinder,
  70406. ImageProvider* imageProvider) const
  70407. {
  70408. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  70409. }
  70410. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  70411. const RelativePoint* gp2, const RelativePoint* gp3,
  70412. ImageProvider* imageProvider, UndoManager* undoManager)
  70413. {
  70414. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  70415. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70416. }
  70417. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (Expression::EvaluationContext* nameFinder,
  70418. ImageProvider* imageProvider) const
  70419. {
  70420. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  70421. }
  70422. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  70423. const RelativePoint* gp2, const RelativePoint* gp3,
  70424. ImageProvider* imageProvider, UndoManager* undoManager)
  70425. {
  70426. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  70427. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70428. }
  70429. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  70430. {
  70431. const String jointStyleString (state [jointStyle].toString());
  70432. const String capStyleString (state [capStyle].toString());
  70433. return PathStrokeType (state [strokeWidth],
  70434. jointStyleString == "curved" ? PathStrokeType::curved
  70435. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70436. : PathStrokeType::mitered),
  70437. capStyleString == "square" ? PathStrokeType::square
  70438. : (capStyleString == "round" ? PathStrokeType::rounded
  70439. : PathStrokeType::butt));
  70440. }
  70441. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70442. {
  70443. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70444. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70445. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70446. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70447. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70448. }
  70449. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70450. {
  70451. return state [nonZeroWinding];
  70452. }
  70453. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70454. {
  70455. state.setProperty (nonZeroWinding, b, undoManager);
  70456. }
  70457. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70458. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70459. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70460. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70461. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70462. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70463. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70464. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70465. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70466. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70467. : state (state_)
  70468. {
  70469. }
  70470. DrawablePath::ValueTreeWrapper::Element::~Element()
  70471. {
  70472. }
  70473. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70474. {
  70475. return ValueTreeWrapper (state.getParent().getParent());
  70476. }
  70477. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70478. {
  70479. return Element (state.getSibling (-1));
  70480. }
  70481. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70482. {
  70483. const Identifier i (state.getType());
  70484. if (i == startSubPathElement || i == lineToElement) return 1;
  70485. if (i == quadraticToElement) return 2;
  70486. if (i == cubicToElement) return 3;
  70487. return 0;
  70488. }
  70489. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70490. {
  70491. jassert (index >= 0 && index < getNumControlPoints());
  70492. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70493. }
  70494. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70495. {
  70496. jassert (index >= 0 && index < getNumControlPoints());
  70497. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70498. }
  70499. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70500. {
  70501. jassert (index >= 0 && index < getNumControlPoints());
  70502. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70503. }
  70504. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70505. {
  70506. const Identifier i (state.getType());
  70507. if (i == startSubPathElement)
  70508. return getControlPoint (0);
  70509. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70510. return getPreviousElement().getEndPoint();
  70511. }
  70512. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70513. {
  70514. const Identifier i (state.getType());
  70515. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70516. if (i == quadraticToElement) return getControlPoint (1);
  70517. if (i == cubicToElement) return getControlPoint (2);
  70518. jassert (i == closeSubPathElement);
  70519. return RelativePoint();
  70520. }
  70521. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70522. {
  70523. const Identifier i (state.getType());
  70524. if (i == lineToElement || i == closeSubPathElement)
  70525. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70526. if (i == cubicToElement)
  70527. {
  70528. Path p;
  70529. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70530. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70531. return p.getLength();
  70532. }
  70533. if (i == quadraticToElement)
  70534. {
  70535. Path p;
  70536. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70537. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70538. return p.getLength();
  70539. }
  70540. jassert (i == startSubPathElement);
  70541. return 0;
  70542. }
  70543. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70544. {
  70545. return state [mode].toString();
  70546. }
  70547. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70548. {
  70549. if (state.hasType (cubicToElement))
  70550. state.setProperty (mode, newMode, undoManager);
  70551. }
  70552. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70553. {
  70554. const Identifier i (state.getType());
  70555. if (i == quadraticToElement || i == cubicToElement)
  70556. {
  70557. ValueTree newState (lineToElement);
  70558. Element e (newState);
  70559. e.setControlPoint (0, getEndPoint(), undoManager);
  70560. state = newState;
  70561. }
  70562. }
  70563. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70564. {
  70565. const Identifier i (state.getType());
  70566. if (i == lineToElement || i == quadraticToElement)
  70567. {
  70568. ValueTree newState (cubicToElement);
  70569. Element e (newState);
  70570. const RelativePoint start (getStartPoint());
  70571. const RelativePoint end (getEndPoint());
  70572. const Point<float> startResolved (start.resolve (nameFinder));
  70573. const Point<float> endResolved (end.resolve (nameFinder));
  70574. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70575. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70576. e.setControlPoint (2, end, undoManager);
  70577. state = newState;
  70578. }
  70579. }
  70580. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70581. {
  70582. const Identifier i (state.getType());
  70583. if (i != startSubPathElement)
  70584. {
  70585. ValueTree newState (startSubPathElement);
  70586. Element e (newState);
  70587. e.setControlPoint (0, getEndPoint(), undoManager);
  70588. state = newState;
  70589. }
  70590. }
  70591. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70592. {
  70593. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70594. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70595. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70596. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70597. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70598. return newCp1 + (newCp2 - newCp1) * proportion;
  70599. }
  70600. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70601. {
  70602. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70603. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70604. return mid1 + (mid2 - mid1) * proportion;
  70605. }
  70606. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70607. {
  70608. const Identifier i (state.getType());
  70609. float bestProp = 0;
  70610. if (i == cubicToElement)
  70611. {
  70612. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70613. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70614. float bestDistance = std::numeric_limits<float>::max();
  70615. for (int i = 110; --i >= 0;)
  70616. {
  70617. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70618. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70619. const float distance = centre.getDistanceFrom (targetPoint);
  70620. if (distance < bestDistance)
  70621. {
  70622. bestProp = prop;
  70623. bestDistance = distance;
  70624. }
  70625. }
  70626. }
  70627. else if (i == quadraticToElement)
  70628. {
  70629. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70630. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70631. float bestDistance = std::numeric_limits<float>::max();
  70632. for (int i = 110; --i >= 0;)
  70633. {
  70634. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70635. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70636. const float distance = centre.getDistanceFrom (targetPoint);
  70637. if (distance < bestDistance)
  70638. {
  70639. bestProp = prop;
  70640. bestDistance = distance;
  70641. }
  70642. }
  70643. }
  70644. else if (i == lineToElement)
  70645. {
  70646. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70647. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70648. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70649. }
  70650. return bestProp;
  70651. }
  70652. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70653. {
  70654. ValueTree newTree;
  70655. const Identifier i (state.getType());
  70656. if (i == cubicToElement)
  70657. {
  70658. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70659. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70660. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70661. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70662. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70663. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70664. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70665. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70666. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70667. setControlPoint (0, mid1, undoManager);
  70668. setControlPoint (1, newCp1, undoManager);
  70669. setControlPoint (2, newCentre, undoManager);
  70670. setModeOfEndPoint (roundedMode, undoManager);
  70671. Element newElement (newTree = ValueTree (cubicToElement));
  70672. newElement.setControlPoint (0, newCp2, 0);
  70673. newElement.setControlPoint (1, mid3, 0);
  70674. newElement.setControlPoint (2, rp4, 0);
  70675. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70676. }
  70677. else if (i == quadraticToElement)
  70678. {
  70679. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70680. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70681. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70682. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70683. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70684. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70685. setControlPoint (0, mid1, undoManager);
  70686. setControlPoint (1, newCentre, undoManager);
  70687. setModeOfEndPoint (roundedMode, undoManager);
  70688. Element newElement (newTree = ValueTree (quadraticToElement));
  70689. newElement.setControlPoint (0, mid2, 0);
  70690. newElement.setControlPoint (1, rp3, 0);
  70691. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70692. }
  70693. else if (i == lineToElement)
  70694. {
  70695. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70696. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70697. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70698. setControlPoint (0, newPoint, undoManager);
  70699. Element newElement (newTree = ValueTree (lineToElement));
  70700. newElement.setControlPoint (0, rp2, 0);
  70701. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70702. }
  70703. else if (i == closeSubPathElement)
  70704. {
  70705. }
  70706. return newTree;
  70707. }
  70708. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70709. {
  70710. state.getParent().removeChild (state, undoManager);
  70711. }
  70712. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70713. {
  70714. Rectangle<float> damageRect;
  70715. ValueTreeWrapper v (tree);
  70716. setName (v.getID());
  70717. bool needsRedraw = false;
  70718. const FillType newFill (v.getMainFill (parent, imageProvider));
  70719. if (mainFill != newFill)
  70720. {
  70721. needsRedraw = true;
  70722. mainFill = newFill;
  70723. }
  70724. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  70725. if (strokeFill != newStrokeFill)
  70726. {
  70727. needsRedraw = true;
  70728. strokeFill = newStrokeFill;
  70729. }
  70730. const PathStrokeType newStroke (v.getStrokeType());
  70731. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70732. Path newPath;
  70733. newRelativePath->createPath (newPath, parent);
  70734. if (! newRelativePath->containsAnyDynamicPoints())
  70735. newRelativePath = 0;
  70736. if (strokeType != newStroke || path != newPath)
  70737. {
  70738. damageRect = getBounds();
  70739. path.swapWithPath (newPath);
  70740. strokeNeedsUpdating = true;
  70741. strokeType = newStroke;
  70742. needsRedraw = true;
  70743. }
  70744. relativePath = newRelativePath;
  70745. if (needsRedraw)
  70746. damageRect = damageRect.getUnion (getBounds());
  70747. return damageRect;
  70748. }
  70749. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70750. {
  70751. ValueTree tree (valueTreeType);
  70752. ValueTreeWrapper v (tree);
  70753. v.setID (getName(), 0);
  70754. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  70755. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  70756. v.setStrokeType (strokeType, 0);
  70757. if (relativePath != 0)
  70758. {
  70759. relativePath->writeTo (tree, 0);
  70760. }
  70761. else
  70762. {
  70763. RelativePointPath rp (path);
  70764. rp.writeTo (tree, 0);
  70765. }
  70766. return tree;
  70767. }
  70768. END_JUCE_NAMESPACE
  70769. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70770. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70771. BEGIN_JUCE_NAMESPACE
  70772. DrawableText::DrawableText()
  70773. : colour (Colours::black),
  70774. justification (Justification::centredLeft)
  70775. {
  70776. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70777. RelativePoint (50.0f, 0.0f),
  70778. RelativePoint (0.0f, 20.0f)));
  70779. setFont (Font (15.0f), true);
  70780. }
  70781. DrawableText::DrawableText (const DrawableText& other)
  70782. : text (other.text),
  70783. font (other.font),
  70784. colour (other.colour),
  70785. justification (other.justification),
  70786. bounds (other.bounds),
  70787. fontSizeControlPoint (other.fontSizeControlPoint)
  70788. {
  70789. }
  70790. DrawableText::~DrawableText()
  70791. {
  70792. }
  70793. void DrawableText::setText (const String& newText)
  70794. {
  70795. text = newText;
  70796. }
  70797. void DrawableText::setColour (const Colour& newColour)
  70798. {
  70799. colour = newColour;
  70800. }
  70801. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70802. {
  70803. font = newFont;
  70804. if (applySizeAndScale)
  70805. {
  70806. Point<float> corners[3];
  70807. bounds.resolveThreePoints (corners, parent);
  70808. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70809. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70810. }
  70811. }
  70812. void DrawableText::setJustification (const Justification& newJustification)
  70813. {
  70814. justification = newJustification;
  70815. }
  70816. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70817. {
  70818. bounds = newBounds;
  70819. }
  70820. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70821. {
  70822. fontSizeControlPoint = newPoint;
  70823. }
  70824. void DrawableText::render (const Drawable::RenderingContext& context) const
  70825. {
  70826. Point<float> points[3];
  70827. bounds.resolveThreePoints (points, parent);
  70828. const float w = Line<float> (points[0], points[1]).getLength();
  70829. const float h = Line<float> (points[0], points[2]).getLength();
  70830. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70831. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  70832. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  70833. Font f (font);
  70834. f.setHeight (fontHeight);
  70835. f.setHorizontalScale (fontWidth / fontHeight);
  70836. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70837. GlyphArrangement ga;
  70838. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70839. ga.draw (context.g,
  70840. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70841. w, 0, points[1].getX(), points[1].getY(),
  70842. 0, h, points[2].getX(), points[2].getY())
  70843. .followedBy (context.transform));
  70844. }
  70845. const Rectangle<float> DrawableText::getBounds() const
  70846. {
  70847. return bounds.getBounds (parent);
  70848. }
  70849. bool DrawableText::hitTest (float x, float y) const
  70850. {
  70851. Path p;
  70852. bounds.getPath (p, parent);
  70853. return p.contains (x, y);
  70854. }
  70855. Drawable* DrawableText::createCopy() const
  70856. {
  70857. return new DrawableText (*this);
  70858. }
  70859. void DrawableText::invalidatePoints()
  70860. {
  70861. }
  70862. const Identifier DrawableText::valueTreeType ("Text");
  70863. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70864. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70865. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70866. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70867. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70868. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70869. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70870. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70871. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70872. : ValueTreeWrapperBase (state_)
  70873. {
  70874. jassert (state.hasType (valueTreeType));
  70875. }
  70876. const String DrawableText::ValueTreeWrapper::getText() const
  70877. {
  70878. return state [text].toString();
  70879. }
  70880. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70881. {
  70882. state.setProperty (text, newText, undoManager);
  70883. }
  70884. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70885. {
  70886. return state.getPropertyAsValue (text, undoManager);
  70887. }
  70888. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70889. {
  70890. return Colour::fromString (state [colour].toString());
  70891. }
  70892. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70893. {
  70894. state.setProperty (colour, newColour.toString(), undoManager);
  70895. }
  70896. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70897. {
  70898. return Justification ((int) state [justification]);
  70899. }
  70900. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  70901. {
  70902. state.setProperty (justification, newJustification.getFlags(), undoManager);
  70903. }
  70904. const Font DrawableText::ValueTreeWrapper::getFont() const
  70905. {
  70906. return Font::fromString (state [font]);
  70907. }
  70908. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  70909. {
  70910. state.setProperty (font, newFont.toString(), undoManager);
  70911. }
  70912. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  70913. {
  70914. return state.getPropertyAsValue (font, undoManager);
  70915. }
  70916. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  70917. {
  70918. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  70919. }
  70920. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70921. {
  70922. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70923. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70924. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70925. }
  70926. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  70927. {
  70928. return state [fontSizeAnchor].toString();
  70929. }
  70930. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  70931. {
  70932. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  70933. }
  70934. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  70935. {
  70936. ValueTreeWrapper v (tree);
  70937. setName (v.getID());
  70938. const RelativeParallelogram newBounds (v.getBoundingBox());
  70939. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  70940. const Colour newColour (v.getColour());
  70941. const Justification newJustification (v.getJustification());
  70942. const String newText (v.getText());
  70943. const Font newFont (v.getFont());
  70944. if (text != newText || font != newFont || justification != newJustification
  70945. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  70946. {
  70947. const Rectangle<float> damage (getBounds());
  70948. setBoundingBox (newBounds);
  70949. setFontSizeControlPoint (newFontPoint);
  70950. setColour (newColour);
  70951. setFont (newFont, false);
  70952. setJustification (newJustification);
  70953. setText (newText);
  70954. return damage.getUnion (getBounds());
  70955. }
  70956. return Rectangle<float>();
  70957. }
  70958. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  70959. {
  70960. ValueTree tree (valueTreeType);
  70961. ValueTreeWrapper v (tree);
  70962. v.setID (getName(), 0);
  70963. v.setText (text, 0);
  70964. v.setFont (font, 0);
  70965. v.setJustification (justification, 0);
  70966. v.setColour (colour, 0);
  70967. v.setBoundingBox (bounds, 0);
  70968. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  70969. return tree;
  70970. }
  70971. END_JUCE_NAMESPACE
  70972. /*** End of inlined file: juce_DrawableText.cpp ***/
  70973. /*** Start of inlined file: juce_SVGParser.cpp ***/
  70974. BEGIN_JUCE_NAMESPACE
  70975. class SVGState
  70976. {
  70977. public:
  70978. SVGState (const XmlElement* const topLevel)
  70979. : topLevelXml (topLevel),
  70980. elementX (0), elementY (0),
  70981. width (512), height (512),
  70982. viewBoxW (0), viewBoxH (0)
  70983. {
  70984. }
  70985. ~SVGState()
  70986. {
  70987. }
  70988. Drawable* parseSVGElement (const XmlElement& xml)
  70989. {
  70990. if (! xml.hasTagName ("svg"))
  70991. return 0;
  70992. DrawableComposite* const drawable = new DrawableComposite();
  70993. drawable->setName (xml.getStringAttribute ("id"));
  70994. SVGState newState (*this);
  70995. if (xml.hasAttribute ("transform"))
  70996. newState.addTransform (xml);
  70997. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  70998. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  70999. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71000. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71001. if (xml.hasAttribute ("viewBox"))
  71002. {
  71003. const String viewParams (xml.getStringAttribute ("viewBox"));
  71004. int i = 0;
  71005. float vx, vy, vw, vh;
  71006. if (parseCoords (viewParams, vx, vy, i, true)
  71007. && parseCoords (viewParams, vw, vh, i, true)
  71008. && vw > 0
  71009. && vh > 0)
  71010. {
  71011. newState.viewBoxW = vw;
  71012. newState.viewBoxH = vh;
  71013. int placementFlags = 0;
  71014. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71015. if (aspect.containsIgnoreCase ("none"))
  71016. {
  71017. placementFlags = RectanglePlacement::stretchToFit;
  71018. }
  71019. else
  71020. {
  71021. if (aspect.containsIgnoreCase ("slice"))
  71022. placementFlags |= RectanglePlacement::fillDestination;
  71023. if (aspect.containsIgnoreCase ("xMin"))
  71024. placementFlags |= RectanglePlacement::xLeft;
  71025. else if (aspect.containsIgnoreCase ("xMax"))
  71026. placementFlags |= RectanglePlacement::xRight;
  71027. else
  71028. placementFlags |= RectanglePlacement::xMid;
  71029. if (aspect.containsIgnoreCase ("yMin"))
  71030. placementFlags |= RectanglePlacement::yTop;
  71031. else if (aspect.containsIgnoreCase ("yMax"))
  71032. placementFlags |= RectanglePlacement::yBottom;
  71033. else
  71034. placementFlags |= RectanglePlacement::yMid;
  71035. }
  71036. const RectanglePlacement placement (placementFlags);
  71037. newState.transform
  71038. = placement.getTransformToFit (vx, vy, vw, vh,
  71039. 0.0f, 0.0f, newState.width, newState.height)
  71040. .followedBy (newState.transform);
  71041. }
  71042. }
  71043. else
  71044. {
  71045. if (viewBoxW == 0)
  71046. newState.viewBoxW = newState.width;
  71047. if (viewBoxH == 0)
  71048. newState.viewBoxH = newState.height;
  71049. }
  71050. newState.parseSubElements (xml, drawable);
  71051. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71052. return drawable;
  71053. }
  71054. private:
  71055. const XmlElement* const topLevelXml;
  71056. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71057. AffineTransform transform;
  71058. String cssStyleText;
  71059. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71060. {
  71061. forEachXmlChildElement (xml, e)
  71062. {
  71063. Drawable* d = 0;
  71064. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71065. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71066. else if (e->hasTagName ("path")) d = parsePath (*e);
  71067. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71068. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71069. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71070. else if (e->hasTagName ("line")) d = parseLine (*e);
  71071. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71072. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71073. else if (e->hasTagName ("text")) d = parseText (*e);
  71074. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71075. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71076. parentDrawable->insertDrawable (d);
  71077. }
  71078. }
  71079. DrawableComposite* parseSwitch (const XmlElement& xml)
  71080. {
  71081. const XmlElement* const group = xml.getChildByName ("g");
  71082. if (group != 0)
  71083. return parseGroupElement (*group);
  71084. return 0;
  71085. }
  71086. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71087. {
  71088. DrawableComposite* const drawable = new DrawableComposite();
  71089. drawable->setName (xml.getStringAttribute ("id"));
  71090. if (xml.hasAttribute ("transform"))
  71091. {
  71092. SVGState newState (*this);
  71093. newState.addTransform (xml);
  71094. newState.parseSubElements (xml, drawable);
  71095. }
  71096. else
  71097. {
  71098. parseSubElements (xml, drawable);
  71099. }
  71100. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71101. return drawable;
  71102. }
  71103. Drawable* parsePath (const XmlElement& xml) const
  71104. {
  71105. const String d (xml.getStringAttribute ("d").trimStart());
  71106. Path path;
  71107. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71108. path.setUsingNonZeroWinding (false);
  71109. int index = 0;
  71110. float lastX = 0, lastY = 0;
  71111. float lastX2 = 0, lastY2 = 0;
  71112. juce_wchar lastCommandChar = 0;
  71113. bool isRelative = true;
  71114. bool carryOn = true;
  71115. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71116. while (d[index] != 0)
  71117. {
  71118. float x, y, x2, y2, x3, y3;
  71119. if (validCommandChars.containsChar (d[index]))
  71120. {
  71121. lastCommandChar = d [index++];
  71122. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71123. }
  71124. switch (lastCommandChar)
  71125. {
  71126. case 'M':
  71127. case 'm':
  71128. case 'L':
  71129. case 'l':
  71130. if (parseCoords (d, x, y, index, false))
  71131. {
  71132. if (isRelative)
  71133. {
  71134. x += lastX;
  71135. y += lastY;
  71136. }
  71137. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71138. {
  71139. path.startNewSubPath (x, y);
  71140. lastCommandChar = 'l';
  71141. }
  71142. else
  71143. path.lineTo (x, y);
  71144. lastX2 = lastX;
  71145. lastY2 = lastY;
  71146. lastX = x;
  71147. lastY = y;
  71148. }
  71149. else
  71150. {
  71151. ++index;
  71152. }
  71153. break;
  71154. case 'H':
  71155. case 'h':
  71156. if (parseCoord (d, x, index, false, true))
  71157. {
  71158. if (isRelative)
  71159. x += lastX;
  71160. path.lineTo (x, lastY);
  71161. lastX2 = lastX;
  71162. lastX = x;
  71163. }
  71164. else
  71165. {
  71166. ++index;
  71167. }
  71168. break;
  71169. case 'V':
  71170. case 'v':
  71171. if (parseCoord (d, y, index, false, false))
  71172. {
  71173. if (isRelative)
  71174. y += lastY;
  71175. path.lineTo (lastX, y);
  71176. lastY2 = lastY;
  71177. lastY = y;
  71178. }
  71179. else
  71180. {
  71181. ++index;
  71182. }
  71183. break;
  71184. case 'C':
  71185. case 'c':
  71186. if (parseCoords (d, x, y, index, false)
  71187. && parseCoords (d, x2, y2, index, false)
  71188. && parseCoords (d, x3, y3, index, false))
  71189. {
  71190. if (isRelative)
  71191. {
  71192. x += lastX;
  71193. y += lastY;
  71194. x2 += lastX;
  71195. y2 += lastY;
  71196. x3 += lastX;
  71197. y3 += lastY;
  71198. }
  71199. path.cubicTo (x, y, x2, y2, x3, y3);
  71200. lastX2 = x2;
  71201. lastY2 = y2;
  71202. lastX = x3;
  71203. lastY = y3;
  71204. }
  71205. else
  71206. {
  71207. ++index;
  71208. }
  71209. break;
  71210. case 'S':
  71211. case 's':
  71212. if (parseCoords (d, x, y, index, false)
  71213. && parseCoords (d, x3, y3, index, false))
  71214. {
  71215. if (isRelative)
  71216. {
  71217. x += lastX;
  71218. y += lastY;
  71219. x3 += lastX;
  71220. y3 += lastY;
  71221. }
  71222. x2 = lastX + (lastX - lastX2);
  71223. y2 = lastY + (lastY - lastY2);
  71224. path.cubicTo (x2, y2, x, y, x3, y3);
  71225. lastX2 = x;
  71226. lastY2 = y;
  71227. lastX = x3;
  71228. lastY = y3;
  71229. }
  71230. else
  71231. {
  71232. ++index;
  71233. }
  71234. break;
  71235. case 'Q':
  71236. case 'q':
  71237. if (parseCoords (d, x, y, index, false)
  71238. && parseCoords (d, x2, y2, index, false))
  71239. {
  71240. if (isRelative)
  71241. {
  71242. x += lastX;
  71243. y += lastY;
  71244. x2 += lastX;
  71245. y2 += lastY;
  71246. }
  71247. path.quadraticTo (x, y, x2, y2);
  71248. lastX2 = x;
  71249. lastY2 = y;
  71250. lastX = x2;
  71251. lastY = y2;
  71252. }
  71253. else
  71254. {
  71255. ++index;
  71256. }
  71257. break;
  71258. case 'T':
  71259. case 't':
  71260. if (parseCoords (d, x, y, index, false))
  71261. {
  71262. if (isRelative)
  71263. {
  71264. x += lastX;
  71265. y += lastY;
  71266. }
  71267. x2 = lastX + (lastX - lastX2);
  71268. y2 = lastY + (lastY - lastY2);
  71269. path.quadraticTo (x2, y2, x, y);
  71270. lastX2 = x2;
  71271. lastY2 = y2;
  71272. lastX = x;
  71273. lastY = y;
  71274. }
  71275. else
  71276. {
  71277. ++index;
  71278. }
  71279. break;
  71280. case 'A':
  71281. case 'a':
  71282. if (parseCoords (d, x, y, index, false))
  71283. {
  71284. String num;
  71285. if (parseNextNumber (d, num, index, false))
  71286. {
  71287. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71288. if (parseNextNumber (d, num, index, false))
  71289. {
  71290. const bool largeArc = num.getIntValue() != 0;
  71291. if (parseNextNumber (d, num, index, false))
  71292. {
  71293. const bool sweep = num.getIntValue() != 0;
  71294. if (parseCoords (d, x2, y2, index, false))
  71295. {
  71296. if (isRelative)
  71297. {
  71298. x2 += lastX;
  71299. y2 += lastY;
  71300. }
  71301. if (lastX != x2 || lastY != y2)
  71302. {
  71303. double centreX, centreY, startAngle, deltaAngle;
  71304. double rx = x, ry = y;
  71305. endpointToCentreParameters (lastX, lastY, x2, y2,
  71306. angle, largeArc, sweep,
  71307. rx, ry, centreX, centreY,
  71308. startAngle, deltaAngle);
  71309. path.addCentredArc ((float) centreX, (float) centreY,
  71310. (float) rx, (float) ry,
  71311. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71312. false);
  71313. path.lineTo (x2, y2);
  71314. }
  71315. lastX2 = lastX;
  71316. lastY2 = lastY;
  71317. lastX = x2;
  71318. lastY = y2;
  71319. }
  71320. }
  71321. }
  71322. }
  71323. }
  71324. else
  71325. {
  71326. ++index;
  71327. }
  71328. break;
  71329. case 'Z':
  71330. case 'z':
  71331. path.closeSubPath();
  71332. while (CharacterFunctions::isWhitespace (d [index]))
  71333. ++index;
  71334. break;
  71335. default:
  71336. carryOn = false;
  71337. break;
  71338. }
  71339. if (! carryOn)
  71340. break;
  71341. }
  71342. return parseShape (xml, path);
  71343. }
  71344. Drawable* parseRect (const XmlElement& xml) const
  71345. {
  71346. Path rect;
  71347. const bool hasRX = xml.hasAttribute ("rx");
  71348. const bool hasRY = xml.hasAttribute ("ry");
  71349. if (hasRX || hasRY)
  71350. {
  71351. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71352. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71353. if (! hasRX)
  71354. rx = ry;
  71355. else if (! hasRY)
  71356. ry = rx;
  71357. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71358. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71359. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71360. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71361. rx, ry);
  71362. }
  71363. else
  71364. {
  71365. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71366. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71367. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71368. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71369. }
  71370. return parseShape (xml, rect);
  71371. }
  71372. Drawable* parseCircle (const XmlElement& xml) const
  71373. {
  71374. Path circle;
  71375. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71376. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71377. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71378. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71379. return parseShape (xml, circle);
  71380. }
  71381. Drawable* parseEllipse (const XmlElement& xml) const
  71382. {
  71383. Path ellipse;
  71384. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71385. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71386. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71387. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71388. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71389. return parseShape (xml, ellipse);
  71390. }
  71391. Drawable* parseLine (const XmlElement& xml) const
  71392. {
  71393. Path line;
  71394. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71395. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71396. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71397. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71398. line.startNewSubPath (x1, y1);
  71399. line.lineTo (x2, y2);
  71400. return parseShape (xml, line);
  71401. }
  71402. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71403. {
  71404. const String points (xml.getStringAttribute ("points"));
  71405. Path path;
  71406. int index = 0;
  71407. float x, y;
  71408. if (parseCoords (points, x, y, index, true))
  71409. {
  71410. float firstX = x;
  71411. float firstY = y;
  71412. float lastX = 0, lastY = 0;
  71413. path.startNewSubPath (x, y);
  71414. while (parseCoords (points, x, y, index, true))
  71415. {
  71416. lastX = x;
  71417. lastY = y;
  71418. path.lineTo (x, y);
  71419. }
  71420. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71421. path.closeSubPath();
  71422. }
  71423. return parseShape (xml, path);
  71424. }
  71425. Drawable* parseShape (const XmlElement& xml, Path& path,
  71426. const bool shouldParseTransform = true) const
  71427. {
  71428. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71429. {
  71430. SVGState newState (*this);
  71431. newState.addTransform (xml);
  71432. return newState.parseShape (xml, path, false);
  71433. }
  71434. DrawablePath* dp = new DrawablePath();
  71435. dp->setName (xml.getStringAttribute ("id"));
  71436. dp->setFill (Colours::transparentBlack);
  71437. path.applyTransform (transform);
  71438. dp->setPath (path);
  71439. Path::Iterator iter (path);
  71440. bool containsClosedSubPath = false;
  71441. while (iter.next())
  71442. {
  71443. if (iter.elementType == Path::Iterator::closePath)
  71444. {
  71445. containsClosedSubPath = true;
  71446. break;
  71447. }
  71448. }
  71449. dp->setFill (getPathFillType (path,
  71450. getStyleAttribute (&xml, "fill"),
  71451. getStyleAttribute (&xml, "fill-opacity"),
  71452. getStyleAttribute (&xml, "opacity"),
  71453. containsClosedSubPath ? Colours::black
  71454. : Colours::transparentBlack));
  71455. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71456. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71457. {
  71458. dp->setStrokeFill (getPathFillType (path, strokeType,
  71459. getStyleAttribute (&xml, "stroke-opacity"),
  71460. getStyleAttribute (&xml, "opacity"),
  71461. Colours::transparentBlack));
  71462. dp->setStrokeType (getStrokeFor (&xml));
  71463. }
  71464. return dp;
  71465. }
  71466. const XmlElement* findLinkedElement (const XmlElement* e) const
  71467. {
  71468. const String id (e->getStringAttribute ("xlink:href"));
  71469. if (! id.startsWithChar ('#'))
  71470. return 0;
  71471. return findElementForId (topLevelXml, id.substring (1));
  71472. }
  71473. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71474. {
  71475. if (fillXml == 0)
  71476. return;
  71477. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71478. {
  71479. int index = 0;
  71480. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71481. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71482. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71483. double offset = e->getDoubleAttribute ("offset");
  71484. if (e->getStringAttribute ("offset").containsChar ('%'))
  71485. offset *= 0.01;
  71486. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71487. }
  71488. }
  71489. const FillType getPathFillType (const Path& path,
  71490. const String& fill,
  71491. const String& fillOpacity,
  71492. const String& overallOpacity,
  71493. const Colour& defaultColour) const
  71494. {
  71495. float opacity = 1.0f;
  71496. if (overallOpacity.isNotEmpty())
  71497. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71498. if (fillOpacity.isNotEmpty())
  71499. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71500. if (fill.startsWithIgnoreCase ("url"))
  71501. {
  71502. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71503. .upToLastOccurrenceOf (")", false, false).trim());
  71504. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71505. if (fillXml != 0
  71506. && (fillXml->hasTagName ("linearGradient")
  71507. || fillXml->hasTagName ("radialGradient")))
  71508. {
  71509. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71510. ColourGradient gradient;
  71511. addGradientStopsIn (gradient, inheritedFrom);
  71512. addGradientStopsIn (gradient, fillXml);
  71513. if (gradient.getNumColours() > 0)
  71514. {
  71515. gradient.addColour (0.0, gradient.getColour (0));
  71516. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71517. }
  71518. else
  71519. {
  71520. gradient.addColour (0.0, Colours::black);
  71521. gradient.addColour (1.0, Colours::black);
  71522. }
  71523. if (overallOpacity.isNotEmpty())
  71524. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71525. jassert (gradient.getNumColours() > 0);
  71526. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71527. float gradientWidth = viewBoxW;
  71528. float gradientHeight = viewBoxH;
  71529. float dx = 0.0f;
  71530. float dy = 0.0f;
  71531. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71532. if (! userSpace)
  71533. {
  71534. const Rectangle<float> bounds (path.getBounds());
  71535. dx = bounds.getX();
  71536. dy = bounds.getY();
  71537. gradientWidth = bounds.getWidth();
  71538. gradientHeight = bounds.getHeight();
  71539. }
  71540. if (gradient.isRadial)
  71541. {
  71542. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71543. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71544. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71545. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71546. //xxx (the fx, fy focal point isn't handled properly here..)
  71547. }
  71548. else
  71549. {
  71550. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71551. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71552. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71553. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71554. if (gradient.point1 == gradient.point2)
  71555. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71556. }
  71557. FillType type (gradient);
  71558. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71559. .followedBy (transform);
  71560. return type;
  71561. }
  71562. }
  71563. if (fill.equalsIgnoreCase ("none"))
  71564. return Colours::transparentBlack;
  71565. int i = 0;
  71566. const Colour colour (parseColour (fill, i, defaultColour));
  71567. return colour.withMultipliedAlpha (opacity);
  71568. }
  71569. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71570. {
  71571. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71572. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71573. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71574. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71575. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71576. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71577. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71578. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71579. if (join.equalsIgnoreCase ("round"))
  71580. joinStyle = PathStrokeType::curved;
  71581. else if (join.equalsIgnoreCase ("bevel"))
  71582. joinStyle = PathStrokeType::beveled;
  71583. if (cap.equalsIgnoreCase ("round"))
  71584. capStyle = PathStrokeType::rounded;
  71585. else if (cap.equalsIgnoreCase ("square"))
  71586. capStyle = PathStrokeType::square;
  71587. float ox = 0.0f, oy = 0.0f;
  71588. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71589. transform.transformPoints (ox, oy, x, y);
  71590. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71591. joinStyle, capStyle);
  71592. }
  71593. Drawable* parseText (const XmlElement& xml)
  71594. {
  71595. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71596. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71597. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71598. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71599. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71600. //xxx not done text yet!
  71601. forEachXmlChildElement (xml, e)
  71602. {
  71603. if (e->isTextElement())
  71604. {
  71605. const String text (e->getText());
  71606. Path path;
  71607. Drawable* s = parseShape (*e, path);
  71608. delete s; // xxx not finished!
  71609. }
  71610. else if (e->hasTagName ("tspan"))
  71611. {
  71612. Drawable* s = parseText (*e);
  71613. delete s; // xxx not finished!
  71614. }
  71615. }
  71616. return 0;
  71617. }
  71618. void addTransform (const XmlElement& xml)
  71619. {
  71620. transform = parseTransform (xml.getStringAttribute ("transform"))
  71621. .followedBy (transform);
  71622. }
  71623. bool parseCoord (const String& s, float& value, int& index,
  71624. const bool allowUnits, const bool isX) const
  71625. {
  71626. String number;
  71627. if (! parseNextNumber (s, number, index, allowUnits))
  71628. {
  71629. value = 0;
  71630. return false;
  71631. }
  71632. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71633. return true;
  71634. }
  71635. bool parseCoords (const String& s, float& x, float& y,
  71636. int& index, const bool allowUnits) const
  71637. {
  71638. return parseCoord (s, x, index, allowUnits, true)
  71639. && parseCoord (s, y, index, allowUnits, false);
  71640. }
  71641. float getCoordLength (const String& s, const float sizeForProportions) const
  71642. {
  71643. float n = s.getFloatValue();
  71644. const int len = s.length();
  71645. if (len > 2)
  71646. {
  71647. const float dpi = 96.0f;
  71648. const juce_wchar n1 = s [len - 2];
  71649. const juce_wchar n2 = s [len - 1];
  71650. if (n1 == 'i' && n2 == 'n')
  71651. n *= dpi;
  71652. else if (n1 == 'm' && n2 == 'm')
  71653. n *= dpi / 25.4f;
  71654. else if (n1 == 'c' && n2 == 'm')
  71655. n *= dpi / 2.54f;
  71656. else if (n1 == 'p' && n2 == 'c')
  71657. n *= 15.0f;
  71658. else if (n2 == '%')
  71659. n *= 0.01f * sizeForProportions;
  71660. }
  71661. return n;
  71662. }
  71663. void getCoordList (Array <float>& coords, const String& list,
  71664. const bool allowUnits, const bool isX) const
  71665. {
  71666. int index = 0;
  71667. float value;
  71668. while (parseCoord (list, value, index, allowUnits, isX))
  71669. coords.add (value);
  71670. }
  71671. void parseCSSStyle (const XmlElement& xml)
  71672. {
  71673. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71674. }
  71675. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71676. const String& defaultValue = String::empty) const
  71677. {
  71678. if (xml->hasAttribute (attributeName))
  71679. return xml->getStringAttribute (attributeName, defaultValue);
  71680. const String styleAtt (xml->getStringAttribute ("style"));
  71681. if (styleAtt.isNotEmpty())
  71682. {
  71683. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71684. if (value.isNotEmpty())
  71685. return value;
  71686. }
  71687. else if (xml->hasAttribute ("class"))
  71688. {
  71689. const String className ("." + xml->getStringAttribute ("class"));
  71690. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71691. if (index < 0)
  71692. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71693. if (index >= 0)
  71694. {
  71695. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71696. if (openBracket > index)
  71697. {
  71698. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71699. if (closeBracket > openBracket)
  71700. {
  71701. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71702. if (value.isNotEmpty())
  71703. return value;
  71704. }
  71705. }
  71706. }
  71707. }
  71708. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71709. if (xml != 0)
  71710. return getStyleAttribute (xml, attributeName, defaultValue);
  71711. return defaultValue;
  71712. }
  71713. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71714. {
  71715. if (xml->hasAttribute (attributeName))
  71716. return xml->getStringAttribute (attributeName);
  71717. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71718. if (xml != 0)
  71719. return getInheritedAttribute (xml, attributeName);
  71720. return String::empty;
  71721. }
  71722. static bool isIdentifierChar (const juce_wchar c)
  71723. {
  71724. return CharacterFunctions::isLetter (c) || c == '-';
  71725. }
  71726. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71727. {
  71728. int i = 0;
  71729. for (;;)
  71730. {
  71731. i = list.indexOf (i, attributeName);
  71732. if (i < 0)
  71733. break;
  71734. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71735. && ! isIdentifierChar (list [i + attributeName.length()]))
  71736. {
  71737. i = list.indexOfChar (i, ':');
  71738. if (i < 0)
  71739. break;
  71740. int end = list.indexOfChar (i, ';');
  71741. if (end < 0)
  71742. end = 0x7ffff;
  71743. return list.substring (i + 1, end).trim();
  71744. }
  71745. ++i;
  71746. }
  71747. return defaultValue;
  71748. }
  71749. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71750. {
  71751. const juce_wchar* const s = source;
  71752. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71753. ++index;
  71754. int start = index;
  71755. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71756. ++index;
  71757. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71758. ++index;
  71759. if ((s[index] == 'e' || s[index] == 'E')
  71760. && (CharacterFunctions::isDigit (s[index + 1])
  71761. || s[index + 1] == '-'
  71762. || s[index + 1] == '+'))
  71763. {
  71764. index += 2;
  71765. while (CharacterFunctions::isDigit (s[index]))
  71766. ++index;
  71767. }
  71768. if (allowUnits)
  71769. {
  71770. while (CharacterFunctions::isLetter (s[index]))
  71771. ++index;
  71772. }
  71773. if (index == start)
  71774. return false;
  71775. value = String (s + start, index - start);
  71776. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71777. ++index;
  71778. return true;
  71779. }
  71780. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71781. {
  71782. if (s [index] == '#')
  71783. {
  71784. uint32 hex [6];
  71785. zeromem (hex, sizeof (hex));
  71786. int numChars = 0;
  71787. for (int i = 6; --i >= 0;)
  71788. {
  71789. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71790. if (hexValue >= 0)
  71791. hex [numChars++] = hexValue;
  71792. else
  71793. break;
  71794. }
  71795. if (numChars <= 3)
  71796. return Colour ((uint8) (hex [0] * 0x11),
  71797. (uint8) (hex [1] * 0x11),
  71798. (uint8) (hex [2] * 0x11));
  71799. else
  71800. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71801. (uint8) ((hex [2] << 4) + hex [3]),
  71802. (uint8) ((hex [4] << 4) + hex [5]));
  71803. }
  71804. else if (s [index] == 'r'
  71805. && s [index + 1] == 'g'
  71806. && s [index + 2] == 'b')
  71807. {
  71808. const int openBracket = s.indexOfChar (index, '(');
  71809. const int closeBracket = s.indexOfChar (openBracket, ')');
  71810. if (openBracket >= 3 && closeBracket > openBracket)
  71811. {
  71812. index = closeBracket;
  71813. StringArray tokens;
  71814. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71815. tokens.trim();
  71816. tokens.removeEmptyStrings();
  71817. if (tokens[0].containsChar ('%'))
  71818. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71819. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71820. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71821. else
  71822. return Colour ((uint8) tokens[0].getIntValue(),
  71823. (uint8) tokens[1].getIntValue(),
  71824. (uint8) tokens[2].getIntValue());
  71825. }
  71826. }
  71827. return Colours::findColourForName (s, defaultColour);
  71828. }
  71829. static const AffineTransform parseTransform (String t)
  71830. {
  71831. AffineTransform result;
  71832. while (t.isNotEmpty())
  71833. {
  71834. StringArray tokens;
  71835. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71836. .upToFirstOccurrenceOf (")", false, false),
  71837. ", ", String::empty);
  71838. tokens.removeEmptyStrings (true);
  71839. float numbers [6];
  71840. for (int i = 0; i < 6; ++i)
  71841. numbers[i] = tokens[i].getFloatValue();
  71842. AffineTransform trans;
  71843. if (t.startsWithIgnoreCase ("matrix"))
  71844. {
  71845. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71846. numbers[1], numbers[3], numbers[5]);
  71847. }
  71848. else if (t.startsWithIgnoreCase ("translate"))
  71849. {
  71850. jassert (tokens.size() == 2);
  71851. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71852. }
  71853. else if (t.startsWithIgnoreCase ("scale"))
  71854. {
  71855. if (tokens.size() == 1)
  71856. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71857. else
  71858. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71859. }
  71860. else if (t.startsWithIgnoreCase ("rotate"))
  71861. {
  71862. if (tokens.size() != 3)
  71863. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71864. else
  71865. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71866. numbers[1], numbers[2]);
  71867. }
  71868. else if (t.startsWithIgnoreCase ("skewX"))
  71869. {
  71870. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71871. 0.0f, 1.0f, 0.0f);
  71872. }
  71873. else if (t.startsWithIgnoreCase ("skewY"))
  71874. {
  71875. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71876. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71877. }
  71878. result = trans.followedBy (result);
  71879. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71880. }
  71881. return result;
  71882. }
  71883. static void endpointToCentreParameters (const double x1, const double y1,
  71884. const double x2, const double y2,
  71885. const double angle,
  71886. const bool largeArc, const bool sweep,
  71887. double& rx, double& ry,
  71888. double& centreX, double& centreY,
  71889. double& startAngle, double& deltaAngle)
  71890. {
  71891. const double midX = (x1 - x2) * 0.5;
  71892. const double midY = (y1 - y2) * 0.5;
  71893. const double cosAngle = cos (angle);
  71894. const double sinAngle = sin (angle);
  71895. const double xp = cosAngle * midX + sinAngle * midY;
  71896. const double yp = cosAngle * midY - sinAngle * midX;
  71897. const double xp2 = xp * xp;
  71898. const double yp2 = yp * yp;
  71899. double rx2 = rx * rx;
  71900. double ry2 = ry * ry;
  71901. const double s = (xp2 / rx2) + (yp2 / ry2);
  71902. double c;
  71903. if (s <= 1.0)
  71904. {
  71905. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  71906. / (( rx2 * yp2) + (ry2 * xp2))));
  71907. if (largeArc == sweep)
  71908. c = -c;
  71909. }
  71910. else
  71911. {
  71912. const double s2 = std::sqrt (s);
  71913. rx *= s2;
  71914. ry *= s2;
  71915. rx2 = rx * rx;
  71916. ry2 = ry * ry;
  71917. c = 0;
  71918. }
  71919. const double cpx = ((rx * yp) / ry) * c;
  71920. const double cpy = ((-ry * xp) / rx) * c;
  71921. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  71922. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  71923. const double ux = (xp - cpx) / rx;
  71924. const double uy = (yp - cpy) / ry;
  71925. const double vx = (-xp - cpx) / rx;
  71926. const double vy = (-yp - cpy) / ry;
  71927. const double length = juce_hypot (ux, uy);
  71928. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  71929. if (uy < 0)
  71930. startAngle = -startAngle;
  71931. startAngle += double_Pi * 0.5;
  71932. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  71933. / (length * juce_hypot (vx, vy))));
  71934. if ((ux * vy) - (uy * vx) < 0)
  71935. deltaAngle = -deltaAngle;
  71936. if (sweep)
  71937. {
  71938. if (deltaAngle < 0)
  71939. deltaAngle += double_Pi * 2.0;
  71940. }
  71941. else
  71942. {
  71943. if (deltaAngle > 0)
  71944. deltaAngle -= double_Pi * 2.0;
  71945. }
  71946. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  71947. }
  71948. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  71949. {
  71950. forEachXmlChildElement (*parent, e)
  71951. {
  71952. if (e->compareAttribute ("id", id))
  71953. return e;
  71954. const XmlElement* const found = findElementForId (e, id);
  71955. if (found != 0)
  71956. return found;
  71957. }
  71958. return 0;
  71959. }
  71960. SVGState& operator= (const SVGState&);
  71961. };
  71962. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  71963. {
  71964. SVGState state (&svgDocument);
  71965. return state.parseSVGElement (svgDocument);
  71966. }
  71967. END_JUCE_NAMESPACE
  71968. /*** End of inlined file: juce_SVGParser.cpp ***/
  71969. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  71970. BEGIN_JUCE_NAMESPACE
  71971. #if JUCE_MSVC && JUCE_DEBUG
  71972. #pragma optimize ("t", on)
  71973. #endif
  71974. DropShadowEffect::DropShadowEffect()
  71975. : offsetX (0),
  71976. offsetY (0),
  71977. radius (4),
  71978. opacity (0.6f)
  71979. {
  71980. }
  71981. DropShadowEffect::~DropShadowEffect()
  71982. {
  71983. }
  71984. void DropShadowEffect::setShadowProperties (const float newRadius,
  71985. const float newOpacity,
  71986. const int newShadowOffsetX,
  71987. const int newShadowOffsetY)
  71988. {
  71989. radius = jmax (1.1f, newRadius);
  71990. offsetX = newShadowOffsetX;
  71991. offsetY = newShadowOffsetY;
  71992. opacity = newOpacity;
  71993. }
  71994. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  71995. {
  71996. const int w = image.getWidth();
  71997. const int h = image.getHeight();
  71998. Image shadowImage (Image::SingleChannel, w, h, false);
  71999. const Image::BitmapData srcData (image, false);
  72000. const Image::BitmapData destData (shadowImage, true);
  72001. const int filter = roundToInt (63.0f / radius);
  72002. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72003. for (int x = w; --x >= 0;)
  72004. {
  72005. int shadowAlpha = 0;
  72006. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72007. uint8* shadowPix = destData.data + x;
  72008. for (int y = h; --y >= 0;)
  72009. {
  72010. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72011. *shadowPix = (uint8) shadowAlpha;
  72012. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72013. shadowPix += destData.lineStride;
  72014. }
  72015. }
  72016. for (int y = h; --y >= 0;)
  72017. {
  72018. int shadowAlpha = 0;
  72019. uint8* shadowPix = destData.getLinePointer (y);
  72020. for (int x = w; --x >= 0;)
  72021. {
  72022. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72023. *shadowPix++ = (uint8) shadowAlpha;
  72024. }
  72025. }
  72026. g.setColour (Colours::black.withAlpha (opacity));
  72027. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72028. g.setOpacity (1.0f);
  72029. g.drawImageAt (image, 0, 0);
  72030. }
  72031. #if JUCE_MSVC && JUCE_DEBUG
  72032. #pragma optimize ("", on) // resets optimisations to the project defaults
  72033. #endif
  72034. END_JUCE_NAMESPACE
  72035. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72036. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72037. BEGIN_JUCE_NAMESPACE
  72038. GlowEffect::GlowEffect()
  72039. : radius (2.0f),
  72040. colour (Colours::white)
  72041. {
  72042. }
  72043. GlowEffect::~GlowEffect()
  72044. {
  72045. }
  72046. void GlowEffect::setGlowProperties (const float newRadius,
  72047. const Colour& newColour)
  72048. {
  72049. radius = newRadius;
  72050. colour = newColour;
  72051. }
  72052. void GlowEffect::applyEffect (Image& image, Graphics& g)
  72053. {
  72054. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72055. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72056. blurKernel.createGaussianBlur (radius);
  72057. blurKernel.rescaleAllValues (radius);
  72058. blurKernel.applyToImage (temp, image, image.getBounds());
  72059. g.setColour (colour);
  72060. g.drawImageAt (temp, 0, 0, true);
  72061. g.setOpacity (1.0f);
  72062. g.drawImageAt (image, 0, 0, false);
  72063. }
  72064. END_JUCE_NAMESPACE
  72065. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72066. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72067. BEGIN_JUCE_NAMESPACE
  72068. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  72069. : opacity (opacity_)
  72070. {
  72071. }
  72072. ReduceOpacityEffect::~ReduceOpacityEffect()
  72073. {
  72074. }
  72075. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  72076. {
  72077. opacity = jlimit (0.0f, 1.0f, newOpacity);
  72078. }
  72079. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  72080. {
  72081. g.setOpacity (opacity);
  72082. g.drawImageAt (image, 0, 0);
  72083. }
  72084. END_JUCE_NAMESPACE
  72085. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72086. /*** Start of inlined file: juce_Font.cpp ***/
  72087. BEGIN_JUCE_NAMESPACE
  72088. namespace FontValues
  72089. {
  72090. static float limitFontHeight (const float height) throw()
  72091. {
  72092. return jlimit (0.1f, 10000.0f, height);
  72093. }
  72094. static const float defaultFontHeight = 14.0f;
  72095. static String fallbackFont;
  72096. }
  72097. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72098. const float kerning_, const float ascent_, const int styleFlags_,
  72099. Typeface* const typeface_) throw()
  72100. : typefaceName (typefaceName_),
  72101. height (height_),
  72102. horizontalScale (horizontalScale_),
  72103. kerning (kerning_),
  72104. ascent (ascent_),
  72105. styleFlags (styleFlags_),
  72106. typeface (typeface_)
  72107. {
  72108. }
  72109. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72110. : typefaceName (other.typefaceName),
  72111. height (other.height),
  72112. horizontalScale (other.horizontalScale),
  72113. kerning (other.kerning),
  72114. ascent (other.ascent),
  72115. styleFlags (other.styleFlags),
  72116. typeface (other.typeface)
  72117. {
  72118. }
  72119. Font::Font() throw()
  72120. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72121. 1.0f, 0, 0, Font::plain, 0))
  72122. {
  72123. }
  72124. Font::Font (const float fontHeight, const int styleFlags_) throw()
  72125. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72126. 1.0f, 0, 0, styleFlags_, 0))
  72127. {
  72128. }
  72129. Font::Font (const String& typefaceName_,
  72130. const float fontHeight,
  72131. const int styleFlags_) throw()
  72132. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72133. 1.0f, 0, 0, styleFlags_, 0))
  72134. {
  72135. }
  72136. Font::Font (const Font& other) throw()
  72137. : font (other.font)
  72138. {
  72139. }
  72140. Font& Font::operator= (const Font& other) throw()
  72141. {
  72142. font = other.font;
  72143. return *this;
  72144. }
  72145. Font::~Font() throw()
  72146. {
  72147. }
  72148. Font::Font (const Typeface::Ptr& typeface) throw()
  72149. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72150. 1.0f, 0, 0, Font::plain, typeface))
  72151. {
  72152. }
  72153. bool Font::operator== (const Font& other) const throw()
  72154. {
  72155. return font == other.font
  72156. || (font->height == other.font->height
  72157. && font->styleFlags == other.font->styleFlags
  72158. && font->horizontalScale == other.font->horizontalScale
  72159. && font->kerning == other.font->kerning
  72160. && font->typefaceName == other.font->typefaceName);
  72161. }
  72162. bool Font::operator!= (const Font& other) const throw()
  72163. {
  72164. return ! operator== (other);
  72165. }
  72166. void Font::dupeInternalIfShared() throw()
  72167. {
  72168. if (font->getReferenceCount() > 1)
  72169. font = new SharedFontInternal (*font);
  72170. }
  72171. const String Font::getDefaultSansSerifFontName() throw()
  72172. {
  72173. static const String name ("<Sans-Serif>");
  72174. return name;
  72175. }
  72176. const String Font::getDefaultSerifFontName() throw()
  72177. {
  72178. static const String name ("<Serif>");
  72179. return name;
  72180. }
  72181. const String Font::getDefaultMonospacedFontName() throw()
  72182. {
  72183. static const String name ("<Monospaced>");
  72184. return name;
  72185. }
  72186. void Font::setTypefaceName (const String& faceName) throw()
  72187. {
  72188. if (faceName != font->typefaceName)
  72189. {
  72190. dupeInternalIfShared();
  72191. font->typefaceName = faceName;
  72192. font->typeface = 0;
  72193. font->ascent = 0;
  72194. }
  72195. }
  72196. const String Font::getFallbackFontName() throw()
  72197. {
  72198. return FontValues::fallbackFont;
  72199. }
  72200. void Font::setFallbackFontName (const String& name) throw()
  72201. {
  72202. FontValues::fallbackFont = name;
  72203. }
  72204. void Font::setHeight (float newHeight) throw()
  72205. {
  72206. newHeight = FontValues::limitFontHeight (newHeight);
  72207. if (font->height != newHeight)
  72208. {
  72209. dupeInternalIfShared();
  72210. font->height = newHeight;
  72211. }
  72212. }
  72213. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  72214. {
  72215. newHeight = FontValues::limitFontHeight (newHeight);
  72216. if (font->height != newHeight)
  72217. {
  72218. dupeInternalIfShared();
  72219. font->horizontalScale *= (font->height / newHeight);
  72220. font->height = newHeight;
  72221. }
  72222. }
  72223. void Font::setStyleFlags (const int newFlags) throw()
  72224. {
  72225. if (font->styleFlags != newFlags)
  72226. {
  72227. dupeInternalIfShared();
  72228. font->styleFlags = newFlags;
  72229. font->typeface = 0;
  72230. font->ascent = 0;
  72231. }
  72232. }
  72233. void Font::setSizeAndStyle (float newHeight,
  72234. const int newStyleFlags,
  72235. const float newHorizontalScale,
  72236. const float newKerningAmount) throw()
  72237. {
  72238. newHeight = FontValues::limitFontHeight (newHeight);
  72239. if (font->height != newHeight
  72240. || font->horizontalScale != newHorizontalScale
  72241. || font->kerning != newKerningAmount)
  72242. {
  72243. dupeInternalIfShared();
  72244. font->height = newHeight;
  72245. font->horizontalScale = newHorizontalScale;
  72246. font->kerning = newKerningAmount;
  72247. }
  72248. setStyleFlags (newStyleFlags);
  72249. }
  72250. void Font::setHorizontalScale (const float scaleFactor) throw()
  72251. {
  72252. dupeInternalIfShared();
  72253. font->horizontalScale = scaleFactor;
  72254. }
  72255. void Font::setExtraKerningFactor (const float extraKerning) throw()
  72256. {
  72257. dupeInternalIfShared();
  72258. font->kerning = extraKerning;
  72259. }
  72260. void Font::setBold (const bool shouldBeBold) throw()
  72261. {
  72262. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72263. : (font->styleFlags & ~bold));
  72264. }
  72265. bool Font::isBold() const throw()
  72266. {
  72267. return (font->styleFlags & bold) != 0;
  72268. }
  72269. void Font::setItalic (const bool shouldBeItalic) throw()
  72270. {
  72271. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72272. : (font->styleFlags & ~italic));
  72273. }
  72274. bool Font::isItalic() const throw()
  72275. {
  72276. return (font->styleFlags & italic) != 0;
  72277. }
  72278. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  72279. {
  72280. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72281. : (font->styleFlags & ~underlined));
  72282. }
  72283. bool Font::isUnderlined() const throw()
  72284. {
  72285. return (font->styleFlags & underlined) != 0;
  72286. }
  72287. float Font::getAscent() const throw()
  72288. {
  72289. if (font->ascent == 0)
  72290. font->ascent = getTypeface()->getAscent();
  72291. return font->height * font->ascent;
  72292. }
  72293. float Font::getDescent() const throw()
  72294. {
  72295. return font->height - getAscent();
  72296. }
  72297. int Font::getStringWidth (const String& text) const throw()
  72298. {
  72299. return roundToInt (getStringWidthFloat (text));
  72300. }
  72301. float Font::getStringWidthFloat (const String& text) const throw()
  72302. {
  72303. float w = getTypeface()->getStringWidth (text);
  72304. if (font->kerning != 0)
  72305. w += font->kerning * text.length();
  72306. return w * font->height * font->horizontalScale;
  72307. }
  72308. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  72309. {
  72310. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72311. const float scale = font->height * font->horizontalScale;
  72312. const int num = xOffsets.size();
  72313. if (num > 0)
  72314. {
  72315. float* const x = &(xOffsets.getReference(0));
  72316. if (font->kerning != 0)
  72317. {
  72318. for (int i = 0; i < num; ++i)
  72319. x[i] = (x[i] + i * font->kerning) * scale;
  72320. }
  72321. else
  72322. {
  72323. for (int i = 0; i < num; ++i)
  72324. x[i] *= scale;
  72325. }
  72326. }
  72327. }
  72328. void Font::findFonts (Array<Font>& destArray) throw()
  72329. {
  72330. const StringArray names (findAllTypefaceNames());
  72331. for (int i = 0; i < names.size(); ++i)
  72332. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72333. }
  72334. const String Font::toString() const
  72335. {
  72336. String s (getTypefaceName());
  72337. if (s == getDefaultSansSerifFontName())
  72338. s = String::empty;
  72339. else
  72340. s += "; ";
  72341. s += String (getHeight(), 1);
  72342. if (isBold())
  72343. s += " bold";
  72344. if (isItalic())
  72345. s += " italic";
  72346. return s;
  72347. }
  72348. const Font Font::fromString (const String& fontDescription)
  72349. {
  72350. String name;
  72351. const int separator = fontDescription.indexOfChar (';');
  72352. if (separator > 0)
  72353. name = fontDescription.substring (0, separator).trim();
  72354. if (name.isEmpty())
  72355. name = getDefaultSansSerifFontName();
  72356. String sizeAndStyle (fontDescription.substring (separator + 1));
  72357. float height = sizeAndStyle.getFloatValue();
  72358. if (height <= 0)
  72359. height = 10.0f;
  72360. int flags = Font::plain;
  72361. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72362. flags |= Font::bold;
  72363. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72364. flags |= Font::italic;
  72365. return Font (name, height, flags);
  72366. }
  72367. class TypefaceCache : public DeletedAtShutdown
  72368. {
  72369. public:
  72370. TypefaceCache (int numToCache = 10) throw()
  72371. : counter (1)
  72372. {
  72373. while (--numToCache >= 0)
  72374. faces.add (new CachedFace());
  72375. }
  72376. ~TypefaceCache()
  72377. {
  72378. clearSingletonInstance();
  72379. }
  72380. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72381. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  72382. {
  72383. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72384. const String faceName (font.getTypefaceName());
  72385. int i;
  72386. for (i = faces.size(); --i >= 0;)
  72387. {
  72388. CachedFace* const face = faces.getUnchecked(i);
  72389. if (face->flags == flags
  72390. && face->typefaceName == faceName)
  72391. {
  72392. face->lastUsageCount = ++counter;
  72393. return face->typeFace;
  72394. }
  72395. }
  72396. int replaceIndex = 0;
  72397. int bestLastUsageCount = std::numeric_limits<int>::max();
  72398. for (i = faces.size(); --i >= 0;)
  72399. {
  72400. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72401. if (bestLastUsageCount > lu)
  72402. {
  72403. bestLastUsageCount = lu;
  72404. replaceIndex = i;
  72405. }
  72406. }
  72407. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72408. face->typefaceName = faceName;
  72409. face->flags = flags;
  72410. face->lastUsageCount = ++counter;
  72411. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72412. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72413. return face->typeFace;
  72414. }
  72415. juce_UseDebuggingNewOperator
  72416. private:
  72417. struct CachedFace
  72418. {
  72419. CachedFace() throw()
  72420. : lastUsageCount (0), flags (-1)
  72421. {
  72422. }
  72423. String typefaceName;
  72424. int lastUsageCount;
  72425. int flags;
  72426. Typeface::Ptr typeFace;
  72427. };
  72428. int counter;
  72429. OwnedArray <CachedFace> faces;
  72430. TypefaceCache (const TypefaceCache&);
  72431. TypefaceCache& operator= (const TypefaceCache&);
  72432. };
  72433. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72434. Typeface* Font::getTypeface() const throw()
  72435. {
  72436. if (font->typeface == 0)
  72437. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72438. return font->typeface;
  72439. }
  72440. END_JUCE_NAMESPACE
  72441. /*** End of inlined file: juce_Font.cpp ***/
  72442. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72443. BEGIN_JUCE_NAMESPACE
  72444. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72445. const juce_wchar character_, const int glyph_)
  72446. : x (x_),
  72447. y (y_),
  72448. w (w_),
  72449. font (font_),
  72450. character (character_),
  72451. glyph (glyph_)
  72452. {
  72453. }
  72454. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72455. : x (other.x),
  72456. y (other.y),
  72457. w (other.w),
  72458. font (other.font),
  72459. character (other.character),
  72460. glyph (other.glyph)
  72461. {
  72462. }
  72463. void PositionedGlyph::draw (const Graphics& g) const
  72464. {
  72465. if (! isWhitespace())
  72466. {
  72467. g.getInternalContext()->setFont (font);
  72468. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72469. }
  72470. }
  72471. void PositionedGlyph::draw (const Graphics& g,
  72472. const AffineTransform& transform) const
  72473. {
  72474. if (! isWhitespace())
  72475. {
  72476. g.getInternalContext()->setFont (font);
  72477. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72478. .followedBy (transform));
  72479. }
  72480. }
  72481. void PositionedGlyph::createPath (Path& path) const
  72482. {
  72483. if (! isWhitespace())
  72484. {
  72485. Typeface* const t = font.getTypeface();
  72486. if (t != 0)
  72487. {
  72488. Path p;
  72489. t->getOutlineForGlyph (glyph, p);
  72490. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72491. .translated (x, y));
  72492. }
  72493. }
  72494. }
  72495. bool PositionedGlyph::hitTest (float px, float py) const
  72496. {
  72497. if (getBounds().contains (px, py) && ! isWhitespace())
  72498. {
  72499. Typeface* const t = font.getTypeface();
  72500. if (t != 0)
  72501. {
  72502. Path p;
  72503. t->getOutlineForGlyph (glyph, p);
  72504. AffineTransform::translation (-x, -y)
  72505. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72506. .transformPoint (px, py);
  72507. return p.contains (px, py);
  72508. }
  72509. }
  72510. return false;
  72511. }
  72512. void PositionedGlyph::moveBy (const float deltaX,
  72513. const float deltaY)
  72514. {
  72515. x += deltaX;
  72516. y += deltaY;
  72517. }
  72518. GlyphArrangement::GlyphArrangement()
  72519. {
  72520. glyphs.ensureStorageAllocated (128);
  72521. }
  72522. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72523. {
  72524. addGlyphArrangement (other);
  72525. }
  72526. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72527. {
  72528. if (this != &other)
  72529. {
  72530. clear();
  72531. addGlyphArrangement (other);
  72532. }
  72533. return *this;
  72534. }
  72535. GlyphArrangement::~GlyphArrangement()
  72536. {
  72537. }
  72538. void GlyphArrangement::clear()
  72539. {
  72540. glyphs.clear();
  72541. }
  72542. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72543. {
  72544. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72545. return *glyphs [index];
  72546. }
  72547. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72548. {
  72549. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72550. glyphs.addCopiesOf (other.glyphs);
  72551. }
  72552. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72553. {
  72554. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72555. }
  72556. void GlyphArrangement::addLineOfText (const Font& font,
  72557. const String& text,
  72558. const float xOffset,
  72559. const float yOffset)
  72560. {
  72561. addCurtailedLineOfText (font, text,
  72562. xOffset, yOffset,
  72563. 1.0e10f, false);
  72564. }
  72565. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72566. const String& text,
  72567. float xOffset,
  72568. const float yOffset,
  72569. const float maxWidthPixels,
  72570. const bool useEllipsis)
  72571. {
  72572. if (text.isNotEmpty())
  72573. {
  72574. Array <int> newGlyphs;
  72575. Array <float> xOffsets;
  72576. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72577. const int textLen = newGlyphs.size();
  72578. const juce_wchar* const unicodeText = text;
  72579. for (int i = 0; i < textLen; ++i)
  72580. {
  72581. const float thisX = xOffsets.getUnchecked (i);
  72582. const float nextX = xOffsets.getUnchecked (i + 1);
  72583. if (nextX > maxWidthPixels + 1.0f)
  72584. {
  72585. // curtail the string if it's too wide..
  72586. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72587. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72588. break;
  72589. }
  72590. else
  72591. {
  72592. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72593. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72594. }
  72595. }
  72596. }
  72597. }
  72598. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72599. const int startIndex, int endIndex)
  72600. {
  72601. int numDeleted = 0;
  72602. if (glyphs.size() > 0)
  72603. {
  72604. Array<int> dotGlyphs;
  72605. Array<float> dotXs;
  72606. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72607. const float dx = dotXs[1];
  72608. float xOffset = 0.0f, yOffset = 0.0f;
  72609. while (endIndex > startIndex)
  72610. {
  72611. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72612. xOffset = pg->x;
  72613. yOffset = pg->y;
  72614. glyphs.remove (endIndex);
  72615. ++numDeleted;
  72616. if (xOffset + dx * 3 <= maxXPos)
  72617. break;
  72618. }
  72619. for (int i = 3; --i >= 0;)
  72620. {
  72621. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72622. font, '.', dotGlyphs.getFirst()));
  72623. --numDeleted;
  72624. xOffset += dx;
  72625. if (xOffset > maxXPos)
  72626. break;
  72627. }
  72628. }
  72629. return numDeleted;
  72630. }
  72631. void GlyphArrangement::addJustifiedText (const Font& font,
  72632. const String& text,
  72633. float x, float y,
  72634. const float maxLineWidth,
  72635. const Justification& horizontalLayout)
  72636. {
  72637. int lineStartIndex = glyphs.size();
  72638. addLineOfText (font, text, x, y);
  72639. const float originalY = y;
  72640. while (lineStartIndex < glyphs.size())
  72641. {
  72642. int i = lineStartIndex;
  72643. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72644. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72645. ++i;
  72646. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72647. int lastWordBreakIndex = -1;
  72648. while (i < glyphs.size())
  72649. {
  72650. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72651. const juce_wchar c = pg->getCharacter();
  72652. if (c == '\r' || c == '\n')
  72653. {
  72654. ++i;
  72655. if (c == '\r' && i < glyphs.size()
  72656. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72657. ++i;
  72658. break;
  72659. }
  72660. else if (pg->isWhitespace())
  72661. {
  72662. lastWordBreakIndex = i + 1;
  72663. }
  72664. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72665. {
  72666. if (lastWordBreakIndex >= 0)
  72667. i = lastWordBreakIndex;
  72668. break;
  72669. }
  72670. ++i;
  72671. }
  72672. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72673. float currentLineEndX = currentLineStartX;
  72674. for (int j = i; --j >= lineStartIndex;)
  72675. {
  72676. if (! glyphs.getUnchecked (j)->isWhitespace())
  72677. {
  72678. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72679. break;
  72680. }
  72681. }
  72682. float deltaX = 0.0f;
  72683. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72684. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72685. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72686. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72687. else if (horizontalLayout.testFlags (Justification::right))
  72688. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72689. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72690. x + deltaX - currentLineStartX, y - originalY);
  72691. lineStartIndex = i;
  72692. y += font.getHeight();
  72693. }
  72694. }
  72695. void GlyphArrangement::addFittedText (const Font& f,
  72696. const String& text,
  72697. const float x, const float y,
  72698. const float width, const float height,
  72699. const Justification& layout,
  72700. int maximumLines,
  72701. const float minimumHorizontalScale)
  72702. {
  72703. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72704. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72705. if (text.containsAnyOf ("\r\n"))
  72706. {
  72707. GlyphArrangement ga;
  72708. ga.addJustifiedText (f, text, x, y, width, layout);
  72709. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72710. float dy = y - bb.getY();
  72711. if (layout.testFlags (Justification::verticallyCentred))
  72712. dy += (height - bb.getHeight()) * 0.5f;
  72713. else if (layout.testFlags (Justification::bottom))
  72714. dy += height - bb.getHeight();
  72715. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72716. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72717. for (int i = 0; i < ga.glyphs.size(); ++i)
  72718. glyphs.add (ga.glyphs.getUnchecked (i));
  72719. ga.glyphs.clear (false);
  72720. return;
  72721. }
  72722. int startIndex = glyphs.size();
  72723. addLineOfText (f, text.trim(), x, y);
  72724. if (glyphs.size() > startIndex)
  72725. {
  72726. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72727. - glyphs.getUnchecked (startIndex)->getLeft();
  72728. if (lineWidth <= 0)
  72729. return;
  72730. if (lineWidth * minimumHorizontalScale < width)
  72731. {
  72732. if (lineWidth > width)
  72733. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72734. width / lineWidth);
  72735. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72736. x, y, width, height, layout);
  72737. }
  72738. else if (maximumLines <= 1)
  72739. {
  72740. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72741. x, y, width, height, f, layout, minimumHorizontalScale);
  72742. }
  72743. else
  72744. {
  72745. Font font (f);
  72746. String txt (text.trim());
  72747. const int length = txt.length();
  72748. const int originalStartIndex = startIndex;
  72749. int numLines = 1;
  72750. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72751. maximumLines = 1;
  72752. maximumLines = jmin (maximumLines, length);
  72753. while (numLines < maximumLines)
  72754. {
  72755. ++numLines;
  72756. const float newFontHeight = height / (float) numLines;
  72757. if (newFontHeight < font.getHeight())
  72758. {
  72759. font.setHeight (jmax (8.0f, newFontHeight));
  72760. removeRangeOfGlyphs (startIndex, -1);
  72761. addLineOfText (font, txt, x, y);
  72762. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72763. - glyphs.getUnchecked (startIndex)->getLeft();
  72764. }
  72765. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72766. break;
  72767. }
  72768. if (numLines < 1)
  72769. numLines = 1;
  72770. float lineY = y;
  72771. float widthPerLine = lineWidth / numLines;
  72772. int lastLineStartIndex = 0;
  72773. for (int line = 0; line < numLines; ++line)
  72774. {
  72775. int i = startIndex;
  72776. lastLineStartIndex = i;
  72777. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72778. if (line == numLines - 1)
  72779. {
  72780. widthPerLine = width;
  72781. i = glyphs.size();
  72782. }
  72783. else
  72784. {
  72785. while (i < glyphs.size())
  72786. {
  72787. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72788. if (lineWidth > widthPerLine)
  72789. {
  72790. // got to a point where the line's too long, so skip forward to find a
  72791. // good place to break it..
  72792. const int searchStartIndex = i;
  72793. while (i < glyphs.size())
  72794. {
  72795. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72796. {
  72797. if (glyphs.getUnchecked (i)->isWhitespace()
  72798. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72799. {
  72800. ++i;
  72801. break;
  72802. }
  72803. }
  72804. else
  72805. {
  72806. // can't find a suitable break, so try looking backwards..
  72807. i = searchStartIndex;
  72808. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72809. {
  72810. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72811. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72812. {
  72813. i -= back - 1;
  72814. break;
  72815. }
  72816. }
  72817. break;
  72818. }
  72819. ++i;
  72820. }
  72821. break;
  72822. }
  72823. ++i;
  72824. }
  72825. int wsStart = i;
  72826. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72827. --wsStart;
  72828. int wsEnd = i;
  72829. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72830. ++wsEnd;
  72831. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72832. i = jmax (wsStart, startIndex + 1);
  72833. }
  72834. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72835. x, lineY, width, font.getHeight(), font,
  72836. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72837. minimumHorizontalScale);
  72838. startIndex = i;
  72839. lineY += font.getHeight();
  72840. if (startIndex >= glyphs.size())
  72841. break;
  72842. }
  72843. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72844. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72845. }
  72846. }
  72847. }
  72848. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72849. const float dx, const float dy)
  72850. {
  72851. jassert (startIndex >= 0);
  72852. if (dx != 0.0f || dy != 0.0f)
  72853. {
  72854. if (num < 0 || startIndex + num > glyphs.size())
  72855. num = glyphs.size() - startIndex;
  72856. while (--num >= 0)
  72857. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72858. }
  72859. }
  72860. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72861. const Justification& justification, float minimumHorizontalScale)
  72862. {
  72863. int numDeleted = 0;
  72864. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72865. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72866. if (lineWidth > w)
  72867. {
  72868. if (minimumHorizontalScale < 1.0f)
  72869. {
  72870. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72871. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72872. }
  72873. if (lineWidth > w)
  72874. {
  72875. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72876. numGlyphs -= numDeleted;
  72877. }
  72878. }
  72879. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72880. return numDeleted;
  72881. }
  72882. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  72883. const float horizontalScaleFactor)
  72884. {
  72885. jassert (startIndex >= 0);
  72886. if (num < 0 || startIndex + num > glyphs.size())
  72887. num = glyphs.size() - startIndex;
  72888. if (num > 0)
  72889. {
  72890. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  72891. while (--num >= 0)
  72892. {
  72893. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72894. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  72895. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  72896. pg->w *= horizontalScaleFactor;
  72897. }
  72898. }
  72899. }
  72900. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  72901. {
  72902. jassert (startIndex >= 0);
  72903. if (num < 0 || startIndex + num > glyphs.size())
  72904. num = glyphs.size() - startIndex;
  72905. Rectangle<float> result;
  72906. while (--num >= 0)
  72907. {
  72908. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72909. if (includeWhitespace || ! pg->isWhitespace())
  72910. result = result.getUnion (pg->getBounds());
  72911. }
  72912. return result;
  72913. }
  72914. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  72915. const float x, const float y, const float width, const float height,
  72916. const Justification& justification)
  72917. {
  72918. jassert (num >= 0 && startIndex >= 0);
  72919. if (glyphs.size() > 0 && num > 0)
  72920. {
  72921. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  72922. | Justification::horizontallyCentred)));
  72923. float deltaX = 0.0f;
  72924. if (justification.testFlags (Justification::horizontallyJustified))
  72925. deltaX = x - bb.getX();
  72926. else if (justification.testFlags (Justification::horizontallyCentred))
  72927. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  72928. else if (justification.testFlags (Justification::right))
  72929. deltaX = (x + width) - bb.getRight();
  72930. else
  72931. deltaX = x - bb.getX();
  72932. float deltaY = 0.0f;
  72933. if (justification.testFlags (Justification::top))
  72934. deltaY = y - bb.getY();
  72935. else if (justification.testFlags (Justification::bottom))
  72936. deltaY = (y + height) - bb.getBottom();
  72937. else
  72938. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  72939. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  72940. if (justification.testFlags (Justification::horizontallyJustified))
  72941. {
  72942. int lineStart = 0;
  72943. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  72944. int i;
  72945. for (i = 0; i < num; ++i)
  72946. {
  72947. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  72948. if (glyphY != baseY)
  72949. {
  72950. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72951. lineStart = i;
  72952. baseY = glyphY;
  72953. }
  72954. }
  72955. if (i > lineStart)
  72956. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72957. }
  72958. }
  72959. }
  72960. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  72961. {
  72962. if (start + num < glyphs.size()
  72963. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  72964. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  72965. {
  72966. int numSpaces = 0;
  72967. int spacesAtEnd = 0;
  72968. for (int i = 0; i < num; ++i)
  72969. {
  72970. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72971. {
  72972. ++spacesAtEnd;
  72973. ++numSpaces;
  72974. }
  72975. else
  72976. {
  72977. spacesAtEnd = 0;
  72978. }
  72979. }
  72980. numSpaces -= spacesAtEnd;
  72981. if (numSpaces > 0)
  72982. {
  72983. const float startX = glyphs.getUnchecked (start)->getLeft();
  72984. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  72985. const float extraPaddingBetweenWords
  72986. = (targetWidth - (endX - startX)) / (float) numSpaces;
  72987. float deltaX = 0.0f;
  72988. for (int i = 0; i < num; ++i)
  72989. {
  72990. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  72991. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72992. deltaX += extraPaddingBetweenWords;
  72993. }
  72994. }
  72995. }
  72996. }
  72997. void GlyphArrangement::draw (const Graphics& g) const
  72998. {
  72999. for (int i = 0; i < glyphs.size(); ++i)
  73000. {
  73001. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73002. if (pg->font.isUnderlined())
  73003. {
  73004. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73005. float nextX = pg->x + pg->w;
  73006. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73007. nextX = glyphs.getUnchecked (i + 1)->x;
  73008. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73009. nextX - pg->x, lineThickness);
  73010. }
  73011. pg->draw (g);
  73012. }
  73013. }
  73014. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73015. {
  73016. for (int i = 0; i < glyphs.size(); ++i)
  73017. {
  73018. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73019. if (pg->font.isUnderlined())
  73020. {
  73021. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73022. float nextX = pg->x + pg->w;
  73023. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73024. nextX = glyphs.getUnchecked (i + 1)->x;
  73025. Path p;
  73026. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73027. nextX, pg->y + lineThickness * 2.0f),
  73028. lineThickness);
  73029. g.fillPath (p, transform);
  73030. }
  73031. pg->draw (g, transform);
  73032. }
  73033. }
  73034. void GlyphArrangement::createPath (Path& path) const
  73035. {
  73036. for (int i = 0; i < glyphs.size(); ++i)
  73037. glyphs.getUnchecked (i)->createPath (path);
  73038. }
  73039. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73040. {
  73041. for (int i = 0; i < glyphs.size(); ++i)
  73042. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73043. return i;
  73044. return -1;
  73045. }
  73046. END_JUCE_NAMESPACE
  73047. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73048. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73049. BEGIN_JUCE_NAMESPACE
  73050. class TextLayout::Token
  73051. {
  73052. public:
  73053. String text;
  73054. Font font;
  73055. int x, y, w, h;
  73056. int line, lineHeight;
  73057. bool isWhitespace, isNewLine;
  73058. Token (const String& t,
  73059. const Font& f,
  73060. const bool isWhitespace_)
  73061. : text (t),
  73062. font (f),
  73063. x(0),
  73064. y(0),
  73065. isWhitespace (isWhitespace_)
  73066. {
  73067. w = font.getStringWidth (t);
  73068. h = roundToInt (f.getHeight());
  73069. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73070. }
  73071. Token (const Token& other)
  73072. : text (other.text),
  73073. font (other.font),
  73074. x (other.x),
  73075. y (other.y),
  73076. w (other.w),
  73077. h (other.h),
  73078. line (other.line),
  73079. lineHeight (other.lineHeight),
  73080. isWhitespace (other.isWhitespace),
  73081. isNewLine (other.isNewLine)
  73082. {
  73083. }
  73084. ~Token()
  73085. {
  73086. }
  73087. void draw (Graphics& g,
  73088. const int xOffset,
  73089. const int yOffset)
  73090. {
  73091. if (! isWhitespace)
  73092. {
  73093. g.setFont (font);
  73094. g.drawSingleLineText (text.trimEnd(),
  73095. xOffset + x,
  73096. yOffset + y + (lineHeight - h)
  73097. + roundToInt (font.getAscent()));
  73098. }
  73099. }
  73100. juce_UseDebuggingNewOperator
  73101. };
  73102. TextLayout::TextLayout()
  73103. : totalLines (0)
  73104. {
  73105. tokens.ensureStorageAllocated (64);
  73106. }
  73107. TextLayout::TextLayout (const String& text, const Font& font)
  73108. : totalLines (0)
  73109. {
  73110. tokens.ensureStorageAllocated (64);
  73111. appendText (text, font);
  73112. }
  73113. TextLayout::TextLayout (const TextLayout& other)
  73114. : totalLines (0)
  73115. {
  73116. *this = other;
  73117. }
  73118. TextLayout& TextLayout::operator= (const TextLayout& other)
  73119. {
  73120. if (this != &other)
  73121. {
  73122. clear();
  73123. totalLines = other.totalLines;
  73124. tokens.addCopiesOf (other.tokens);
  73125. }
  73126. return *this;
  73127. }
  73128. TextLayout::~TextLayout()
  73129. {
  73130. clear();
  73131. }
  73132. void TextLayout::clear()
  73133. {
  73134. tokens.clear();
  73135. totalLines = 0;
  73136. }
  73137. void TextLayout::appendText (const String& text, const Font& font)
  73138. {
  73139. const juce_wchar* t = text;
  73140. String currentString;
  73141. int lastCharType = 0;
  73142. for (;;)
  73143. {
  73144. const juce_wchar c = *t++;
  73145. if (c == 0)
  73146. break;
  73147. int charType;
  73148. if (c == '\r' || c == '\n')
  73149. {
  73150. charType = 0;
  73151. }
  73152. else if (CharacterFunctions::isWhitespace (c))
  73153. {
  73154. charType = 2;
  73155. }
  73156. else
  73157. {
  73158. charType = 1;
  73159. }
  73160. if (charType == 0 || charType != lastCharType)
  73161. {
  73162. if (currentString.isNotEmpty())
  73163. {
  73164. tokens.add (new Token (currentString, font,
  73165. lastCharType == 2 || lastCharType == 0));
  73166. }
  73167. currentString = String::charToString (c);
  73168. if (c == '\r' && *t == '\n')
  73169. currentString += *t++;
  73170. }
  73171. else
  73172. {
  73173. currentString += c;
  73174. }
  73175. lastCharType = charType;
  73176. }
  73177. if (currentString.isNotEmpty())
  73178. tokens.add (new Token (currentString, font, lastCharType == 2));
  73179. }
  73180. void TextLayout::setText (const String& text, const Font& font)
  73181. {
  73182. clear();
  73183. appendText (text, font);
  73184. }
  73185. void TextLayout::layout (int maxWidth,
  73186. const Justification& justification,
  73187. const bool attemptToBalanceLineLengths)
  73188. {
  73189. if (attemptToBalanceLineLengths)
  73190. {
  73191. const int originalW = maxWidth;
  73192. int bestWidth = maxWidth;
  73193. float bestLineProportion = 0.0f;
  73194. while (maxWidth > originalW / 2)
  73195. {
  73196. layout (maxWidth, justification, false);
  73197. if (getNumLines() <= 1)
  73198. return;
  73199. const int lastLineW = getLineWidth (getNumLines() - 1);
  73200. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73201. const float prop = lastLineW / (float) lastButOneLineW;
  73202. if (prop > 0.9f)
  73203. return;
  73204. if (prop > bestLineProportion)
  73205. {
  73206. bestLineProportion = prop;
  73207. bestWidth = maxWidth;
  73208. }
  73209. maxWidth -= 10;
  73210. }
  73211. layout (bestWidth, justification, false);
  73212. }
  73213. else
  73214. {
  73215. int x = 0;
  73216. int y = 0;
  73217. int h = 0;
  73218. totalLines = 0;
  73219. int i;
  73220. for (i = 0; i < tokens.size(); ++i)
  73221. {
  73222. Token* const t = tokens.getUnchecked(i);
  73223. t->x = x;
  73224. t->y = y;
  73225. t->line = totalLines;
  73226. x += t->w;
  73227. h = jmax (h, t->h);
  73228. const Token* nextTok = tokens [i + 1];
  73229. if (nextTok == 0)
  73230. break;
  73231. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73232. {
  73233. // finished a line, so go back and update the heights of the things on it
  73234. for (int j = i; j >= 0; --j)
  73235. {
  73236. Token* const tok = tokens.getUnchecked(j);
  73237. if (tok->line == totalLines)
  73238. tok->lineHeight = h;
  73239. else
  73240. break;
  73241. }
  73242. x = 0;
  73243. y += h;
  73244. h = 0;
  73245. ++totalLines;
  73246. }
  73247. }
  73248. // finished a line, so go back and update the heights of the things on it
  73249. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73250. {
  73251. Token* const t = tokens.getUnchecked(j);
  73252. if (t->line == totalLines)
  73253. t->lineHeight = h;
  73254. else
  73255. break;
  73256. }
  73257. ++totalLines;
  73258. if (! justification.testFlags (Justification::left))
  73259. {
  73260. int totalW = getWidth();
  73261. for (i = totalLines; --i >= 0;)
  73262. {
  73263. const int lineW = getLineWidth (i);
  73264. int dx = 0;
  73265. if (justification.testFlags (Justification::horizontallyCentred))
  73266. dx = (totalW - lineW) / 2;
  73267. else if (justification.testFlags (Justification::right))
  73268. dx = totalW - lineW;
  73269. for (int j = tokens.size(); --j >= 0;)
  73270. {
  73271. Token* const t = tokens.getUnchecked(j);
  73272. if (t->line == i)
  73273. t->x += dx;
  73274. }
  73275. }
  73276. }
  73277. }
  73278. }
  73279. int TextLayout::getLineWidth (const int lineNumber) const
  73280. {
  73281. int maxW = 0;
  73282. for (int i = tokens.size(); --i >= 0;)
  73283. {
  73284. const Token* const t = tokens.getUnchecked(i);
  73285. if (t->line == lineNumber && ! t->isWhitespace)
  73286. maxW = jmax (maxW, t->x + t->w);
  73287. }
  73288. return maxW;
  73289. }
  73290. int TextLayout::getWidth() const
  73291. {
  73292. int maxW = 0;
  73293. for (int i = tokens.size(); --i >= 0;)
  73294. {
  73295. const Token* const t = tokens.getUnchecked(i);
  73296. if (! t->isWhitespace)
  73297. maxW = jmax (maxW, t->x + t->w);
  73298. }
  73299. return maxW;
  73300. }
  73301. int TextLayout::getHeight() const
  73302. {
  73303. int maxH = 0;
  73304. for (int i = tokens.size(); --i >= 0;)
  73305. {
  73306. const Token* const t = tokens.getUnchecked(i);
  73307. if (! t->isWhitespace)
  73308. maxH = jmax (maxH, t->y + t->h);
  73309. }
  73310. return maxH;
  73311. }
  73312. void TextLayout::draw (Graphics& g,
  73313. const int xOffset,
  73314. const int yOffset) const
  73315. {
  73316. for (int i = tokens.size(); --i >= 0;)
  73317. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73318. }
  73319. void TextLayout::drawWithin (Graphics& g,
  73320. int x, int y, int w, int h,
  73321. const Justification& justification) const
  73322. {
  73323. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73324. x, y, w, h);
  73325. draw (g, x, y);
  73326. }
  73327. END_JUCE_NAMESPACE
  73328. /*** End of inlined file: juce_TextLayout.cpp ***/
  73329. /*** Start of inlined file: juce_Typeface.cpp ***/
  73330. BEGIN_JUCE_NAMESPACE
  73331. Typeface::Typeface (const String& name_) throw()
  73332. : name (name_)
  73333. {
  73334. }
  73335. Typeface::~Typeface()
  73336. {
  73337. }
  73338. class CustomTypeface::GlyphInfo
  73339. {
  73340. public:
  73341. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73342. : character (character_), path (path_), width (width_)
  73343. {
  73344. }
  73345. ~GlyphInfo() throw()
  73346. {
  73347. }
  73348. struct KerningPair
  73349. {
  73350. juce_wchar character2;
  73351. float kerningAmount;
  73352. };
  73353. void addKerningPair (const juce_wchar subsequentCharacter,
  73354. const float extraKerningAmount) throw()
  73355. {
  73356. KerningPair kp;
  73357. kp.character2 = subsequentCharacter;
  73358. kp.kerningAmount = extraKerningAmount;
  73359. kerningPairs.add (kp);
  73360. }
  73361. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73362. {
  73363. if (subsequentCharacter != 0)
  73364. {
  73365. for (int i = kerningPairs.size(); --i >= 0;)
  73366. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73367. return width + kerningPairs.getReference(i).kerningAmount;
  73368. }
  73369. return width;
  73370. }
  73371. const juce_wchar character;
  73372. const Path path;
  73373. float width;
  73374. Array <KerningPair> kerningPairs;
  73375. juce_UseDebuggingNewOperator
  73376. private:
  73377. GlyphInfo (const GlyphInfo&);
  73378. GlyphInfo& operator= (const GlyphInfo&);
  73379. };
  73380. CustomTypeface::CustomTypeface()
  73381. : Typeface (String::empty)
  73382. {
  73383. clear();
  73384. }
  73385. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73386. : Typeface (String::empty)
  73387. {
  73388. clear();
  73389. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  73390. BufferedInputStream in (&gzin, 32768, false);
  73391. name = in.readString();
  73392. isBold = in.readBool();
  73393. isItalic = in.readBool();
  73394. ascent = in.readFloat();
  73395. defaultCharacter = (juce_wchar) in.readShort();
  73396. int i, numChars = in.readInt();
  73397. for (i = 0; i < numChars; ++i)
  73398. {
  73399. const juce_wchar c = (juce_wchar) in.readShort();
  73400. const float width = in.readFloat();
  73401. Path p;
  73402. p.loadPathFromStream (in);
  73403. addGlyph (c, p, width);
  73404. }
  73405. const int numKerningPairs = in.readInt();
  73406. for (i = 0; i < numKerningPairs; ++i)
  73407. {
  73408. const juce_wchar char1 = (juce_wchar) in.readShort();
  73409. const juce_wchar char2 = (juce_wchar) in.readShort();
  73410. addKerningPair (char1, char2, in.readFloat());
  73411. }
  73412. }
  73413. CustomTypeface::~CustomTypeface()
  73414. {
  73415. }
  73416. void CustomTypeface::clear()
  73417. {
  73418. defaultCharacter = 0;
  73419. ascent = 1.0f;
  73420. isBold = isItalic = false;
  73421. zeromem (lookupTable, sizeof (lookupTable));
  73422. glyphs.clear();
  73423. }
  73424. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73425. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73426. {
  73427. name = name_;
  73428. defaultCharacter = defaultCharacter_;
  73429. ascent = ascent_;
  73430. isBold = isBold_;
  73431. isItalic = isItalic_;
  73432. }
  73433. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73434. {
  73435. // Check that you're not trying to add the same character twice..
  73436. jassert (findGlyph (character, false) == 0);
  73437. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73438. lookupTable [character] = (short) glyphs.size();
  73439. glyphs.add (new GlyphInfo (character, path, width));
  73440. }
  73441. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73442. {
  73443. if (extraAmount != 0)
  73444. {
  73445. GlyphInfo* const g = findGlyph (char1, true);
  73446. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73447. if (g != 0)
  73448. g->addKerningPair (char2, extraAmount);
  73449. }
  73450. }
  73451. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73452. {
  73453. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73454. return glyphs [(int) lookupTable [(int) character]];
  73455. for (int i = 0; i < glyphs.size(); ++i)
  73456. {
  73457. GlyphInfo* const g = glyphs.getUnchecked(i);
  73458. if (g->character == character)
  73459. return g;
  73460. }
  73461. if (loadIfNeeded && loadGlyphIfPossible (character))
  73462. return findGlyph (character, false);
  73463. return 0;
  73464. }
  73465. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73466. {
  73467. GlyphInfo* glyph = findGlyph (character, true);
  73468. if (glyph == 0)
  73469. {
  73470. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73471. glyph = findGlyph (L' ', true);
  73472. if (glyph == 0)
  73473. {
  73474. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73475. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73476. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73477. {
  73478. //xxx
  73479. }
  73480. if (glyph == 0)
  73481. glyph = findGlyph (defaultCharacter, true);
  73482. }
  73483. }
  73484. return glyph;
  73485. }
  73486. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73487. {
  73488. return false;
  73489. }
  73490. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73491. {
  73492. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73493. for (int i = 0; i < numCharacters; ++i)
  73494. {
  73495. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73496. Array <int> glyphIndexes;
  73497. Array <float> offsets;
  73498. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73499. const int glyphIndex = glyphIndexes.getFirst();
  73500. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73501. {
  73502. const float glyphWidth = offsets[1];
  73503. Path p;
  73504. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73505. addGlyph (c, p, glyphWidth);
  73506. for (int j = glyphs.size() - 1; --j >= 0;)
  73507. {
  73508. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73509. glyphIndexes.clearQuick();
  73510. offsets.clearQuick();
  73511. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73512. if (offsets.size() > 1)
  73513. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73514. }
  73515. }
  73516. }
  73517. }
  73518. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73519. {
  73520. GZIPCompressorOutputStream out (&outputStream);
  73521. out.writeString (name);
  73522. out.writeBool (isBold);
  73523. out.writeBool (isItalic);
  73524. out.writeFloat (ascent);
  73525. out.writeShort ((short) (unsigned short) defaultCharacter);
  73526. out.writeInt (glyphs.size());
  73527. int i, numKerningPairs = 0;
  73528. for (i = 0; i < glyphs.size(); ++i)
  73529. {
  73530. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73531. out.writeShort ((short) (unsigned short) g->character);
  73532. out.writeFloat (g->width);
  73533. g->path.writePathToStream (out);
  73534. numKerningPairs += g->kerningPairs.size();
  73535. }
  73536. out.writeInt (numKerningPairs);
  73537. for (i = 0; i < glyphs.size(); ++i)
  73538. {
  73539. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73540. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73541. {
  73542. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73543. out.writeShort ((short) (unsigned short) g->character);
  73544. out.writeShort ((short) (unsigned short) p.character2);
  73545. out.writeFloat (p.kerningAmount);
  73546. }
  73547. }
  73548. return true;
  73549. }
  73550. float CustomTypeface::getAscent() const
  73551. {
  73552. return ascent;
  73553. }
  73554. float CustomTypeface::getDescent() const
  73555. {
  73556. return 1.0f - ascent;
  73557. }
  73558. float CustomTypeface::getStringWidth (const String& text)
  73559. {
  73560. float x = 0;
  73561. const juce_wchar* t = text;
  73562. while (*t != 0)
  73563. {
  73564. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73565. if (glyph != 0)
  73566. x += glyph->getHorizontalSpacing (*t);
  73567. }
  73568. return x;
  73569. }
  73570. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73571. {
  73572. xOffsets.add (0);
  73573. float x = 0;
  73574. const juce_wchar* t = text;
  73575. while (*t != 0)
  73576. {
  73577. const juce_wchar c = *t++;
  73578. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73579. if (glyph != 0)
  73580. {
  73581. x += glyph->getHorizontalSpacing (*t);
  73582. resultGlyphs.add ((int) glyph->character);
  73583. xOffsets.add (x);
  73584. }
  73585. }
  73586. }
  73587. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73588. {
  73589. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73590. if (glyph != 0)
  73591. {
  73592. path = glyph->path;
  73593. return true;
  73594. }
  73595. return false;
  73596. }
  73597. END_JUCE_NAMESPACE
  73598. /*** End of inlined file: juce_Typeface.cpp ***/
  73599. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73600. BEGIN_JUCE_NAMESPACE
  73601. AffineTransform::AffineTransform() throw()
  73602. : mat00 (1.0f),
  73603. mat01 (0),
  73604. mat02 (0),
  73605. mat10 (0),
  73606. mat11 (1.0f),
  73607. mat12 (0)
  73608. {
  73609. }
  73610. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73611. : mat00 (other.mat00),
  73612. mat01 (other.mat01),
  73613. mat02 (other.mat02),
  73614. mat10 (other.mat10),
  73615. mat11 (other.mat11),
  73616. mat12 (other.mat12)
  73617. {
  73618. }
  73619. AffineTransform::AffineTransform (const float mat00_,
  73620. const float mat01_,
  73621. const float mat02_,
  73622. const float mat10_,
  73623. const float mat11_,
  73624. const float mat12_) throw()
  73625. : mat00 (mat00_),
  73626. mat01 (mat01_),
  73627. mat02 (mat02_),
  73628. mat10 (mat10_),
  73629. mat11 (mat11_),
  73630. mat12 (mat12_)
  73631. {
  73632. }
  73633. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73634. {
  73635. mat00 = other.mat00;
  73636. mat01 = other.mat01;
  73637. mat02 = other.mat02;
  73638. mat10 = other.mat10;
  73639. mat11 = other.mat11;
  73640. mat12 = other.mat12;
  73641. return *this;
  73642. }
  73643. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73644. {
  73645. return mat00 == other.mat00
  73646. && mat01 == other.mat01
  73647. && mat02 == other.mat02
  73648. && mat10 == other.mat10
  73649. && mat11 == other.mat11
  73650. && mat12 == other.mat12;
  73651. }
  73652. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73653. {
  73654. return ! operator== (other);
  73655. }
  73656. bool AffineTransform::isIdentity() const throw()
  73657. {
  73658. return (mat01 == 0)
  73659. && (mat02 == 0)
  73660. && (mat10 == 0)
  73661. && (mat12 == 0)
  73662. && (mat00 == 1.0f)
  73663. && (mat11 == 1.0f);
  73664. }
  73665. const AffineTransform AffineTransform::identity;
  73666. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73667. {
  73668. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73669. other.mat00 * mat01 + other.mat01 * mat11,
  73670. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73671. other.mat10 * mat00 + other.mat11 * mat10,
  73672. other.mat10 * mat01 + other.mat11 * mat11,
  73673. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73674. }
  73675. const AffineTransform AffineTransform::followedBy (const float omat00,
  73676. const float omat01,
  73677. const float omat02,
  73678. const float omat10,
  73679. const float omat11,
  73680. const float omat12) const throw()
  73681. {
  73682. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73683. omat00 * mat01 + omat01 * mat11,
  73684. omat00 * mat02 + omat01 * mat12 + omat02,
  73685. omat10 * mat00 + omat11 * mat10,
  73686. omat10 * mat01 + omat11 * mat11,
  73687. omat10 * mat02 + omat11 * mat12 + omat12);
  73688. }
  73689. const AffineTransform AffineTransform::translated (const float dx,
  73690. const float dy) const throw()
  73691. {
  73692. return AffineTransform (mat00, mat01, mat02 + dx,
  73693. mat10, mat11, mat12 + dy);
  73694. }
  73695. const AffineTransform AffineTransform::translation (const float dx,
  73696. const float dy) throw()
  73697. {
  73698. return AffineTransform (1.0f, 0, dx,
  73699. 0, 1.0f, dy);
  73700. }
  73701. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73702. {
  73703. const float cosRad = std::cos (rad);
  73704. const float sinRad = std::sin (rad);
  73705. return followedBy (cosRad, -sinRad, 0,
  73706. sinRad, cosRad, 0);
  73707. }
  73708. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73709. {
  73710. const float cosRad = std::cos (rad);
  73711. const float sinRad = std::sin (rad);
  73712. return AffineTransform (cosRad, -sinRad, 0,
  73713. sinRad, cosRad, 0);
  73714. }
  73715. const AffineTransform AffineTransform::rotated (const float angle,
  73716. const float pivotX,
  73717. const float pivotY) const throw()
  73718. {
  73719. return translated (-pivotX, -pivotY)
  73720. .rotated (angle)
  73721. .translated (pivotX, pivotY);
  73722. }
  73723. const AffineTransform AffineTransform::rotation (const float angle,
  73724. const float pivotX,
  73725. const float pivotY) throw()
  73726. {
  73727. return translation (-pivotX, -pivotY)
  73728. .rotated (angle)
  73729. .translated (pivotX, pivotY);
  73730. }
  73731. const AffineTransform AffineTransform::scaled (const float factorX,
  73732. const float factorY) const throw()
  73733. {
  73734. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73735. factorY * mat10, factorY * mat11, factorY * mat12);
  73736. }
  73737. const AffineTransform AffineTransform::scale (const float factorX,
  73738. const float factorY) throw()
  73739. {
  73740. return AffineTransform (factorX, 0, 0,
  73741. 0, factorY, 0);
  73742. }
  73743. const AffineTransform AffineTransform::sheared (const float shearX,
  73744. const float shearY) const throw()
  73745. {
  73746. return followedBy (1.0f, shearX, 0,
  73747. shearY, 1.0f, 0);
  73748. }
  73749. const AffineTransform AffineTransform::inverted() const throw()
  73750. {
  73751. double determinant = (mat00 * mat11 - mat10 * mat01);
  73752. if (determinant != 0.0)
  73753. {
  73754. determinant = 1.0 / determinant;
  73755. const float dst00 = (float) (mat11 * determinant);
  73756. const float dst10 = (float) (-mat10 * determinant);
  73757. const float dst01 = (float) (-mat01 * determinant);
  73758. const float dst11 = (float) (mat00 * determinant);
  73759. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73760. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73761. }
  73762. else
  73763. {
  73764. // singularity..
  73765. return *this;
  73766. }
  73767. }
  73768. bool AffineTransform::isSingularity() const throw()
  73769. {
  73770. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73771. }
  73772. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73773. const float x10, const float y10,
  73774. const float x01, const float y01) throw()
  73775. {
  73776. return AffineTransform (x10 - x00, x01 - x00, x00,
  73777. y10 - y00, y01 - y00, y00);
  73778. }
  73779. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73780. const float sx2, const float sy2, const float tx2, const float ty2,
  73781. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73782. {
  73783. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73784. .inverted()
  73785. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73786. }
  73787. bool AffineTransform::isOnlyTranslation() const throw()
  73788. {
  73789. return (mat01 == 0)
  73790. && (mat10 == 0)
  73791. && (mat00 == 1.0f)
  73792. && (mat11 == 1.0f);
  73793. }
  73794. END_JUCE_NAMESPACE
  73795. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73796. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73797. BEGIN_JUCE_NAMESPACE
  73798. BorderSize::BorderSize() throw()
  73799. : top (0),
  73800. left (0),
  73801. bottom (0),
  73802. right (0)
  73803. {
  73804. }
  73805. BorderSize::BorderSize (const BorderSize& other) throw()
  73806. : top (other.top),
  73807. left (other.left),
  73808. bottom (other.bottom),
  73809. right (other.right)
  73810. {
  73811. }
  73812. BorderSize::BorderSize (const int topGap,
  73813. const int leftGap,
  73814. const int bottomGap,
  73815. const int rightGap) throw()
  73816. : top (topGap),
  73817. left (leftGap),
  73818. bottom (bottomGap),
  73819. right (rightGap)
  73820. {
  73821. }
  73822. BorderSize::BorderSize (const int allGaps) throw()
  73823. : top (allGaps),
  73824. left (allGaps),
  73825. bottom (allGaps),
  73826. right (allGaps)
  73827. {
  73828. }
  73829. BorderSize::~BorderSize() throw()
  73830. {
  73831. }
  73832. void BorderSize::setTop (const int newTopGap) throw()
  73833. {
  73834. top = newTopGap;
  73835. }
  73836. void BorderSize::setLeft (const int newLeftGap) throw()
  73837. {
  73838. left = newLeftGap;
  73839. }
  73840. void BorderSize::setBottom (const int newBottomGap) throw()
  73841. {
  73842. bottom = newBottomGap;
  73843. }
  73844. void BorderSize::setRight (const int newRightGap) throw()
  73845. {
  73846. right = newRightGap;
  73847. }
  73848. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73849. {
  73850. return Rectangle<int> (r.getX() + left,
  73851. r.getY() + top,
  73852. r.getWidth() - (left + right),
  73853. r.getHeight() - (top + bottom));
  73854. }
  73855. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73856. {
  73857. r.setBounds (r.getX() + left,
  73858. r.getY() + top,
  73859. r.getWidth() - (left + right),
  73860. r.getHeight() - (top + bottom));
  73861. }
  73862. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73863. {
  73864. return Rectangle<int> (r.getX() - left,
  73865. r.getY() - top,
  73866. r.getWidth() + (left + right),
  73867. r.getHeight() + (top + bottom));
  73868. }
  73869. void BorderSize::addTo (Rectangle<int>& r) const throw()
  73870. {
  73871. r.setBounds (r.getX() - left,
  73872. r.getY() - top,
  73873. r.getWidth() + (left + right),
  73874. r.getHeight() + (top + bottom));
  73875. }
  73876. bool BorderSize::operator== (const BorderSize& other) const throw()
  73877. {
  73878. return top == other.top
  73879. && left == other.left
  73880. && bottom == other.bottom
  73881. && right == other.right;
  73882. }
  73883. bool BorderSize::operator!= (const BorderSize& other) const throw()
  73884. {
  73885. return ! operator== (other);
  73886. }
  73887. END_JUCE_NAMESPACE
  73888. /*** End of inlined file: juce_BorderSize.cpp ***/
  73889. /*** Start of inlined file: juce_Path.cpp ***/
  73890. BEGIN_JUCE_NAMESPACE
  73891. // tests that some co-ords aren't NaNs
  73892. #define CHECK_COORDS_ARE_VALID(x, y) \
  73893. jassert (x == x && y == y);
  73894. namespace PathHelpers
  73895. {
  73896. static const float ellipseAngularIncrement = 0.05f;
  73897. static const String nextToken (const juce_wchar*& t)
  73898. {
  73899. while (CharacterFunctions::isWhitespace (*t))
  73900. ++t;
  73901. const juce_wchar* const start = t;
  73902. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  73903. ++t;
  73904. return String (start, (int) (t - start));
  73905. }
  73906. }
  73907. const float Path::lineMarker = 100001.0f;
  73908. const float Path::moveMarker = 100002.0f;
  73909. const float Path::quadMarker = 100003.0f;
  73910. const float Path::cubicMarker = 100004.0f;
  73911. const float Path::closeSubPathMarker = 100005.0f;
  73912. Path::Path()
  73913. : numElements (0),
  73914. pathXMin (0),
  73915. pathXMax (0),
  73916. pathYMin (0),
  73917. pathYMax (0),
  73918. useNonZeroWinding (true)
  73919. {
  73920. }
  73921. Path::~Path()
  73922. {
  73923. }
  73924. Path::Path (const Path& other)
  73925. : numElements (other.numElements),
  73926. pathXMin (other.pathXMin),
  73927. pathXMax (other.pathXMax),
  73928. pathYMin (other.pathYMin),
  73929. pathYMax (other.pathYMax),
  73930. useNonZeroWinding (other.useNonZeroWinding)
  73931. {
  73932. if (numElements > 0)
  73933. {
  73934. data.setAllocatedSize ((int) numElements);
  73935. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73936. }
  73937. }
  73938. Path& Path::operator= (const Path& other)
  73939. {
  73940. if (this != &other)
  73941. {
  73942. data.ensureAllocatedSize ((int) other.numElements);
  73943. numElements = other.numElements;
  73944. pathXMin = other.pathXMin;
  73945. pathXMax = other.pathXMax;
  73946. pathYMin = other.pathYMin;
  73947. pathYMax = other.pathYMax;
  73948. useNonZeroWinding = other.useNonZeroWinding;
  73949. if (numElements > 0)
  73950. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73951. }
  73952. return *this;
  73953. }
  73954. bool Path::operator== (const Path& other) const throw()
  73955. {
  73956. return ! operator!= (other);
  73957. }
  73958. bool Path::operator!= (const Path& other) const throw()
  73959. {
  73960. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  73961. return true;
  73962. for (size_t i = 0; i < numElements; ++i)
  73963. if (data.elements[i] != other.data.elements[i])
  73964. return true;
  73965. return false;
  73966. }
  73967. void Path::clear() throw()
  73968. {
  73969. numElements = 0;
  73970. pathXMin = 0;
  73971. pathYMin = 0;
  73972. pathYMax = 0;
  73973. pathXMax = 0;
  73974. }
  73975. void Path::swapWithPath (Path& other) throw()
  73976. {
  73977. data.swapWith (other.data);
  73978. swapVariables <size_t> (numElements, other.numElements);
  73979. swapVariables <float> (pathXMin, other.pathXMin);
  73980. swapVariables <float> (pathXMax, other.pathXMax);
  73981. swapVariables <float> (pathYMin, other.pathYMin);
  73982. swapVariables <float> (pathYMax, other.pathYMax);
  73983. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  73984. }
  73985. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  73986. {
  73987. useNonZeroWinding = isNonZero;
  73988. }
  73989. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  73990. const bool preserveProportions) throw()
  73991. {
  73992. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  73993. }
  73994. bool Path::isEmpty() const throw()
  73995. {
  73996. size_t i = 0;
  73997. while (i < numElements)
  73998. {
  73999. const float type = data.elements [i++];
  74000. if (type == moveMarker)
  74001. {
  74002. i += 2;
  74003. }
  74004. else if (type == lineMarker
  74005. || type == quadMarker
  74006. || type == cubicMarker)
  74007. {
  74008. return false;
  74009. }
  74010. }
  74011. return true;
  74012. }
  74013. const Rectangle<float> Path::getBounds() const throw()
  74014. {
  74015. return Rectangle<float> (pathXMin, pathYMin,
  74016. pathXMax - pathXMin,
  74017. pathYMax - pathYMin);
  74018. }
  74019. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74020. {
  74021. return getBounds().transformed (transform);
  74022. }
  74023. void Path::startNewSubPath (const float x, const float y)
  74024. {
  74025. CHECK_COORDS_ARE_VALID (x, y);
  74026. if (numElements == 0)
  74027. {
  74028. pathXMin = pathXMax = x;
  74029. pathYMin = pathYMax = y;
  74030. }
  74031. else
  74032. {
  74033. pathXMin = jmin (pathXMin, x);
  74034. pathXMax = jmax (pathXMax, x);
  74035. pathYMin = jmin (pathYMin, y);
  74036. pathYMax = jmax (pathYMax, y);
  74037. }
  74038. data.ensureAllocatedSize ((int) numElements + 3);
  74039. data.elements [numElements++] = moveMarker;
  74040. data.elements [numElements++] = x;
  74041. data.elements [numElements++] = y;
  74042. }
  74043. void Path::startNewSubPath (const Point<float>& start)
  74044. {
  74045. startNewSubPath (start.getX(), start.getY());
  74046. }
  74047. void Path::lineTo (const float x, const float y)
  74048. {
  74049. CHECK_COORDS_ARE_VALID (x, y);
  74050. if (numElements == 0)
  74051. startNewSubPath (0, 0);
  74052. data.ensureAllocatedSize ((int) numElements + 3);
  74053. data.elements [numElements++] = lineMarker;
  74054. data.elements [numElements++] = x;
  74055. data.elements [numElements++] = y;
  74056. pathXMin = jmin (pathXMin, x);
  74057. pathXMax = jmax (pathXMax, x);
  74058. pathYMin = jmin (pathYMin, y);
  74059. pathYMax = jmax (pathYMax, y);
  74060. }
  74061. void Path::lineTo (const Point<float>& end)
  74062. {
  74063. lineTo (end.getX(), end.getY());
  74064. }
  74065. void Path::quadraticTo (const float x1, const float y1,
  74066. const float x2, const float y2)
  74067. {
  74068. CHECK_COORDS_ARE_VALID (x1, y1);
  74069. CHECK_COORDS_ARE_VALID (x2, y2);
  74070. if (numElements == 0)
  74071. startNewSubPath (0, 0);
  74072. data.ensureAllocatedSize ((int) numElements + 5);
  74073. data.elements [numElements++] = quadMarker;
  74074. data.elements [numElements++] = x1;
  74075. data.elements [numElements++] = y1;
  74076. data.elements [numElements++] = x2;
  74077. data.elements [numElements++] = y2;
  74078. pathXMin = jmin (pathXMin, x1, x2);
  74079. pathXMax = jmax (pathXMax, x1, x2);
  74080. pathYMin = jmin (pathYMin, y1, y2);
  74081. pathYMax = jmax (pathYMax, y1, y2);
  74082. }
  74083. void Path::quadraticTo (const Point<float>& controlPoint,
  74084. const Point<float>& endPoint)
  74085. {
  74086. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74087. endPoint.getX(), endPoint.getY());
  74088. }
  74089. void Path::cubicTo (const float x1, const float y1,
  74090. const float x2, const float y2,
  74091. const float x3, const float y3)
  74092. {
  74093. CHECK_COORDS_ARE_VALID (x1, y1);
  74094. CHECK_COORDS_ARE_VALID (x2, y2);
  74095. CHECK_COORDS_ARE_VALID (x3, y3);
  74096. if (numElements == 0)
  74097. startNewSubPath (0, 0);
  74098. data.ensureAllocatedSize ((int) numElements + 7);
  74099. data.elements [numElements++] = cubicMarker;
  74100. data.elements [numElements++] = x1;
  74101. data.elements [numElements++] = y1;
  74102. data.elements [numElements++] = x2;
  74103. data.elements [numElements++] = y2;
  74104. data.elements [numElements++] = x3;
  74105. data.elements [numElements++] = y3;
  74106. pathXMin = jmin (pathXMin, x1, x2, x3);
  74107. pathXMax = jmax (pathXMax, x1, x2, x3);
  74108. pathYMin = jmin (pathYMin, y1, y2, y3);
  74109. pathYMax = jmax (pathYMax, y1, y2, y3);
  74110. }
  74111. void Path::cubicTo (const Point<float>& controlPoint1,
  74112. const Point<float>& controlPoint2,
  74113. const Point<float>& endPoint)
  74114. {
  74115. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74116. controlPoint2.getX(), controlPoint2.getY(),
  74117. endPoint.getX(), endPoint.getY());
  74118. }
  74119. void Path::closeSubPath()
  74120. {
  74121. if (numElements > 0
  74122. && data.elements [numElements - 1] != closeSubPathMarker)
  74123. {
  74124. data.ensureAllocatedSize ((int) numElements + 1);
  74125. data.elements [numElements++] = closeSubPathMarker;
  74126. }
  74127. }
  74128. const Point<float> Path::getCurrentPosition() const
  74129. {
  74130. size_t i = numElements - 1;
  74131. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74132. {
  74133. while (i >= 0)
  74134. {
  74135. if (data.elements[i] == moveMarker)
  74136. {
  74137. i += 2;
  74138. break;
  74139. }
  74140. --i;
  74141. }
  74142. }
  74143. if (i > 0)
  74144. return Point<float> (data.elements [i - 1], data.elements [i]);
  74145. return Point<float>();
  74146. }
  74147. void Path::addRectangle (const float x, const float y,
  74148. const float w, const float h)
  74149. {
  74150. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74151. if (w < 0)
  74152. swapVariables (x1, x2);
  74153. if (h < 0)
  74154. swapVariables (y1, y2);
  74155. data.ensureAllocatedSize ((int) numElements + 13);
  74156. if (numElements == 0)
  74157. {
  74158. pathXMin = x1;
  74159. pathXMax = x2;
  74160. pathYMin = y1;
  74161. pathYMax = y2;
  74162. }
  74163. else
  74164. {
  74165. pathXMin = jmin (pathXMin, x1);
  74166. pathXMax = jmax (pathXMax, x2);
  74167. pathYMin = jmin (pathYMin, y1);
  74168. pathYMax = jmax (pathYMax, y2);
  74169. }
  74170. data.elements [numElements++] = moveMarker;
  74171. data.elements [numElements++] = x1;
  74172. data.elements [numElements++] = y2;
  74173. data.elements [numElements++] = lineMarker;
  74174. data.elements [numElements++] = x1;
  74175. data.elements [numElements++] = y1;
  74176. data.elements [numElements++] = lineMarker;
  74177. data.elements [numElements++] = x2;
  74178. data.elements [numElements++] = y1;
  74179. data.elements [numElements++] = lineMarker;
  74180. data.elements [numElements++] = x2;
  74181. data.elements [numElements++] = y2;
  74182. data.elements [numElements++] = closeSubPathMarker;
  74183. }
  74184. void Path::addRectangle (const Rectangle<int>& rectangle)
  74185. {
  74186. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  74187. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  74188. }
  74189. void Path::addRoundedRectangle (const float x, const float y,
  74190. const float w, const float h,
  74191. float csx,
  74192. float csy)
  74193. {
  74194. csx = jmin (csx, w * 0.5f);
  74195. csy = jmin (csy, h * 0.5f);
  74196. const float cs45x = csx * 0.45f;
  74197. const float cs45y = csy * 0.45f;
  74198. const float x2 = x + w;
  74199. const float y2 = y + h;
  74200. startNewSubPath (x + csx, y);
  74201. lineTo (x2 - csx, y);
  74202. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74203. lineTo (x2, y2 - csy);
  74204. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74205. lineTo (x + csx, y2);
  74206. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74207. lineTo (x, y + csy);
  74208. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74209. closeSubPath();
  74210. }
  74211. void Path::addRoundedRectangle (const float x, const float y,
  74212. const float w, const float h,
  74213. float cs)
  74214. {
  74215. addRoundedRectangle (x, y, w, h, cs, cs);
  74216. }
  74217. void Path::addTriangle (const float x1, const float y1,
  74218. const float x2, const float y2,
  74219. const float x3, const float y3)
  74220. {
  74221. startNewSubPath (x1, y1);
  74222. lineTo (x2, y2);
  74223. lineTo (x3, y3);
  74224. closeSubPath();
  74225. }
  74226. void Path::addQuadrilateral (const float x1, const float y1,
  74227. const float x2, const float y2,
  74228. const float x3, const float y3,
  74229. const float x4, const float y4)
  74230. {
  74231. startNewSubPath (x1, y1);
  74232. lineTo (x2, y2);
  74233. lineTo (x3, y3);
  74234. lineTo (x4, y4);
  74235. closeSubPath();
  74236. }
  74237. void Path::addEllipse (const float x, const float y,
  74238. const float w, const float h)
  74239. {
  74240. const float hw = w * 0.5f;
  74241. const float hw55 = hw * 0.55f;
  74242. const float hh = h * 0.5f;
  74243. const float hh45 = hh * 0.55f;
  74244. const float cx = x + hw;
  74245. const float cy = y + hh;
  74246. startNewSubPath (cx, cy - hh);
  74247. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  74248. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  74249. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  74250. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  74251. closeSubPath();
  74252. }
  74253. void Path::addArc (const float x, const float y,
  74254. const float w, const float h,
  74255. const float fromRadians,
  74256. const float toRadians,
  74257. const bool startAsNewSubPath)
  74258. {
  74259. const float radiusX = w / 2.0f;
  74260. const float radiusY = h / 2.0f;
  74261. addCentredArc (x + radiusX,
  74262. y + radiusY,
  74263. radiusX, radiusY,
  74264. 0.0f,
  74265. fromRadians, toRadians,
  74266. startAsNewSubPath);
  74267. }
  74268. void Path::addCentredArc (const float centreX, const float centreY,
  74269. const float radiusX, const float radiusY,
  74270. const float rotationOfEllipse,
  74271. const float fromRadians,
  74272. const float toRadians,
  74273. const bool startAsNewSubPath)
  74274. {
  74275. if (radiusX > 0.0f && radiusY > 0.0f)
  74276. {
  74277. const Point<float> centre (centreX, centreY);
  74278. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74279. float angle = fromRadians;
  74280. if (startAsNewSubPath)
  74281. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74282. if (fromRadians < toRadians)
  74283. {
  74284. if (startAsNewSubPath)
  74285. angle += PathHelpers::ellipseAngularIncrement;
  74286. while (angle < toRadians)
  74287. {
  74288. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74289. angle += PathHelpers::ellipseAngularIncrement;
  74290. }
  74291. }
  74292. else
  74293. {
  74294. if (startAsNewSubPath)
  74295. angle -= PathHelpers::ellipseAngularIncrement;
  74296. while (angle > toRadians)
  74297. {
  74298. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74299. angle -= PathHelpers::ellipseAngularIncrement;
  74300. }
  74301. }
  74302. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74303. }
  74304. }
  74305. void Path::addPieSegment (const float x, const float y,
  74306. const float width, const float height,
  74307. const float fromRadians,
  74308. const float toRadians,
  74309. const float innerCircleProportionalSize)
  74310. {
  74311. float radiusX = width * 0.5f;
  74312. float radiusY = height * 0.5f;
  74313. const Point<float> centre (x + radiusX, y + radiusY);
  74314. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74315. addArc (x, y, width, height, fromRadians, toRadians);
  74316. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74317. {
  74318. closeSubPath();
  74319. if (innerCircleProportionalSize > 0)
  74320. {
  74321. radiusX *= innerCircleProportionalSize;
  74322. radiusY *= innerCircleProportionalSize;
  74323. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74324. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74325. }
  74326. }
  74327. else
  74328. {
  74329. if (innerCircleProportionalSize > 0)
  74330. {
  74331. radiusX *= innerCircleProportionalSize;
  74332. radiusY *= innerCircleProportionalSize;
  74333. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74334. }
  74335. else
  74336. {
  74337. lineTo (centre);
  74338. }
  74339. }
  74340. closeSubPath();
  74341. }
  74342. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74343. {
  74344. const Line<float> reversed (line.reversed());
  74345. lineThickness *= 0.5f;
  74346. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74347. lineTo (line.getPointAlongLine (0, -lineThickness));
  74348. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74349. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74350. closeSubPath();
  74351. }
  74352. void Path::addArrow (const Line<float>& line, float lineThickness,
  74353. float arrowheadWidth, float arrowheadLength)
  74354. {
  74355. const Line<float> reversed (line.reversed());
  74356. lineThickness *= 0.5f;
  74357. arrowheadWidth *= 0.5f;
  74358. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74359. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74360. lineTo (line.getPointAlongLine (0, -lineThickness));
  74361. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74362. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74363. lineTo (line.getEnd());
  74364. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74365. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74366. closeSubPath();
  74367. }
  74368. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74369. const float radius, const float startAngle)
  74370. {
  74371. jassert (numberOfSides > 1); // this would be silly.
  74372. if (numberOfSides > 1)
  74373. {
  74374. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74375. for (int i = 0; i < numberOfSides; ++i)
  74376. {
  74377. const float angle = startAngle + i * angleBetweenPoints;
  74378. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74379. if (i == 0)
  74380. startNewSubPath (p);
  74381. else
  74382. lineTo (p);
  74383. }
  74384. closeSubPath();
  74385. }
  74386. }
  74387. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74388. const float innerRadius, const float outerRadius, const float startAngle)
  74389. {
  74390. jassert (numberOfPoints > 1); // this would be silly.
  74391. if (numberOfPoints > 1)
  74392. {
  74393. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74394. for (int i = 0; i < numberOfPoints; ++i)
  74395. {
  74396. const float angle = startAngle + i * angleBetweenPoints;
  74397. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74398. if (i == 0)
  74399. startNewSubPath (p);
  74400. else
  74401. lineTo (p);
  74402. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74403. }
  74404. closeSubPath();
  74405. }
  74406. }
  74407. void Path::addBubble (float x, float y,
  74408. float w, float h,
  74409. float cs,
  74410. float tipX,
  74411. float tipY,
  74412. int whichSide,
  74413. float arrowPos,
  74414. float arrowWidth)
  74415. {
  74416. if (w > 1.0f && h > 1.0f)
  74417. {
  74418. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74419. const float cs2 = 2.0f * cs;
  74420. startNewSubPath (x + cs, y);
  74421. if (whichSide == 0)
  74422. {
  74423. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74424. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74425. lineTo (arrowX1, y);
  74426. lineTo (tipX, tipY);
  74427. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74428. }
  74429. lineTo (x + w - cs, y);
  74430. if (cs > 0.0f)
  74431. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74432. if (whichSide == 3)
  74433. {
  74434. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74435. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74436. lineTo (x + w, arrowY1);
  74437. lineTo (tipX, tipY);
  74438. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74439. }
  74440. lineTo (x + w, y + h - cs);
  74441. if (cs > 0.0f)
  74442. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74443. if (whichSide == 2)
  74444. {
  74445. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74446. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74447. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74448. lineTo (tipX, tipY);
  74449. lineTo (arrowX1, y + h);
  74450. }
  74451. lineTo (x + cs, y + h);
  74452. if (cs > 0.0f)
  74453. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74454. if (whichSide == 1)
  74455. {
  74456. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74457. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74458. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74459. lineTo (tipX, tipY);
  74460. lineTo (x, arrowY1);
  74461. }
  74462. lineTo (x, y + cs);
  74463. if (cs > 0.0f)
  74464. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74465. closeSubPath();
  74466. }
  74467. }
  74468. void Path::addPath (const Path& other)
  74469. {
  74470. size_t i = 0;
  74471. while (i < other.numElements)
  74472. {
  74473. const float type = other.data.elements [i++];
  74474. if (type == moveMarker)
  74475. {
  74476. startNewSubPath (other.data.elements [i],
  74477. other.data.elements [i + 1]);
  74478. i += 2;
  74479. }
  74480. else if (type == lineMarker)
  74481. {
  74482. lineTo (other.data.elements [i],
  74483. other.data.elements [i + 1]);
  74484. i += 2;
  74485. }
  74486. else if (type == quadMarker)
  74487. {
  74488. quadraticTo (other.data.elements [i],
  74489. other.data.elements [i + 1],
  74490. other.data.elements [i + 2],
  74491. other.data.elements [i + 3]);
  74492. i += 4;
  74493. }
  74494. else if (type == cubicMarker)
  74495. {
  74496. cubicTo (other.data.elements [i],
  74497. other.data.elements [i + 1],
  74498. other.data.elements [i + 2],
  74499. other.data.elements [i + 3],
  74500. other.data.elements [i + 4],
  74501. other.data.elements [i + 5]);
  74502. i += 6;
  74503. }
  74504. else if (type == closeSubPathMarker)
  74505. {
  74506. closeSubPath();
  74507. }
  74508. else
  74509. {
  74510. // something's gone wrong with the element list!
  74511. jassertfalse;
  74512. }
  74513. }
  74514. }
  74515. void Path::addPath (const Path& other,
  74516. const AffineTransform& transformToApply)
  74517. {
  74518. size_t i = 0;
  74519. while (i < other.numElements)
  74520. {
  74521. const float type = other.data.elements [i++];
  74522. if (type == closeSubPathMarker)
  74523. {
  74524. closeSubPath();
  74525. }
  74526. else
  74527. {
  74528. float x = other.data.elements [i++];
  74529. float y = other.data.elements [i++];
  74530. transformToApply.transformPoint (x, y);
  74531. if (type == moveMarker)
  74532. {
  74533. startNewSubPath (x, y);
  74534. }
  74535. else if (type == lineMarker)
  74536. {
  74537. lineTo (x, y);
  74538. }
  74539. else if (type == quadMarker)
  74540. {
  74541. float x2 = other.data.elements [i++];
  74542. float y2 = other.data.elements [i++];
  74543. transformToApply.transformPoint (x2, y2);
  74544. quadraticTo (x, y, x2, y2);
  74545. }
  74546. else if (type == cubicMarker)
  74547. {
  74548. float x2 = other.data.elements [i++];
  74549. float y2 = other.data.elements [i++];
  74550. float x3 = other.data.elements [i++];
  74551. float y3 = other.data.elements [i++];
  74552. transformToApply.transformPoints (x2, y2, x3, y3);
  74553. cubicTo (x, y, x2, y2, x3, y3);
  74554. }
  74555. else
  74556. {
  74557. // something's gone wrong with the element list!
  74558. jassertfalse;
  74559. }
  74560. }
  74561. }
  74562. }
  74563. void Path::applyTransform (const AffineTransform& transform) throw()
  74564. {
  74565. size_t i = 0;
  74566. pathYMin = pathXMin = 0;
  74567. pathYMax = pathXMax = 0;
  74568. bool setMaxMin = false;
  74569. while (i < numElements)
  74570. {
  74571. const float type = data.elements [i++];
  74572. if (type == moveMarker)
  74573. {
  74574. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74575. if (setMaxMin)
  74576. {
  74577. pathXMin = jmin (pathXMin, data.elements [i]);
  74578. pathXMax = jmax (pathXMax, data.elements [i]);
  74579. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74580. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74581. }
  74582. else
  74583. {
  74584. pathXMin = pathXMax = data.elements [i];
  74585. pathYMin = pathYMax = data.elements [i + 1];
  74586. setMaxMin = true;
  74587. }
  74588. i += 2;
  74589. }
  74590. else if (type == lineMarker)
  74591. {
  74592. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74593. pathXMin = jmin (pathXMin, data.elements [i]);
  74594. pathXMax = jmax (pathXMax, data.elements [i]);
  74595. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74596. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74597. i += 2;
  74598. }
  74599. else if (type == quadMarker)
  74600. {
  74601. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74602. data.elements [i + 2], data.elements [i + 3]);
  74603. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74604. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74605. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74606. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74607. i += 4;
  74608. }
  74609. else if (type == cubicMarker)
  74610. {
  74611. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74612. data.elements [i + 2], data.elements [i + 3],
  74613. data.elements [i + 4], data.elements [i + 5]);
  74614. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74615. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74616. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74617. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74618. i += 6;
  74619. }
  74620. }
  74621. }
  74622. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74623. const float w, const float h,
  74624. const bool preserveProportions,
  74625. const Justification& justification) const
  74626. {
  74627. Rectangle<float> bounds (getBounds());
  74628. if (preserveProportions)
  74629. {
  74630. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74631. return AffineTransform::identity;
  74632. float newW, newH;
  74633. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74634. if (srcRatio > h / w)
  74635. {
  74636. newW = h / srcRatio;
  74637. newH = h;
  74638. }
  74639. else
  74640. {
  74641. newW = w;
  74642. newH = w * srcRatio;
  74643. }
  74644. float newXCentre = x;
  74645. float newYCentre = y;
  74646. if (justification.testFlags (Justification::left))
  74647. newXCentre += newW * 0.5f;
  74648. else if (justification.testFlags (Justification::right))
  74649. newXCentre += w - newW * 0.5f;
  74650. else
  74651. newXCentre += w * 0.5f;
  74652. if (justification.testFlags (Justification::top))
  74653. newYCentre += newH * 0.5f;
  74654. else if (justification.testFlags (Justification::bottom))
  74655. newYCentre += h - newH * 0.5f;
  74656. else
  74657. newYCentre += h * 0.5f;
  74658. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74659. bounds.getHeight() * -0.5f - bounds.getY())
  74660. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74661. .translated (newXCentre, newYCentre);
  74662. }
  74663. else
  74664. {
  74665. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74666. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74667. .translated (x, y);
  74668. }
  74669. }
  74670. bool Path::contains (const float x, const float y, const float tolerence) const
  74671. {
  74672. if (x <= pathXMin || x >= pathXMax
  74673. || y <= pathYMin || y >= pathYMax)
  74674. return false;
  74675. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74676. int positiveCrossings = 0;
  74677. int negativeCrossings = 0;
  74678. while (i.next())
  74679. {
  74680. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74681. {
  74682. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74683. if (intersectX <= x)
  74684. {
  74685. if (i.y1 < i.y2)
  74686. ++positiveCrossings;
  74687. else
  74688. ++negativeCrossings;
  74689. }
  74690. }
  74691. }
  74692. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74693. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74694. }
  74695. bool Path::contains (const Point<float>& point, const float tolerence) const
  74696. {
  74697. return contains (point.getX(), point.getY(), tolerence);
  74698. }
  74699. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74700. {
  74701. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74702. Point<float> intersection;
  74703. while (i.next())
  74704. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74705. return true;
  74706. return false;
  74707. }
  74708. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74709. {
  74710. Line<float> result (line);
  74711. const bool startInside = contains (line.getStart());
  74712. const bool endInside = contains (line.getEnd());
  74713. if (startInside == endInside)
  74714. {
  74715. if (keepSectionOutsidePath == startInside)
  74716. result = Line<float>();
  74717. }
  74718. else
  74719. {
  74720. PathFlatteningIterator i (*this, AffineTransform::identity);
  74721. Point<float> intersection;
  74722. while (i.next())
  74723. {
  74724. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74725. {
  74726. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74727. result.setStart (intersection);
  74728. else
  74729. result.setEnd (intersection);
  74730. }
  74731. }
  74732. }
  74733. return result;
  74734. }
  74735. float Path::getLength (const AffineTransform& transform) const
  74736. {
  74737. float length = 0;
  74738. PathFlatteningIterator i (*this, transform);
  74739. while (i.next())
  74740. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74741. return length;
  74742. }
  74743. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74744. {
  74745. PathFlatteningIterator i (*this, transform);
  74746. while (i.next())
  74747. {
  74748. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74749. const float lineLength = line.getLength();
  74750. if (distanceFromStart <= lineLength)
  74751. return line.getPointAlongLine (distanceFromStart);
  74752. distanceFromStart -= lineLength;
  74753. }
  74754. return Point<float> (i.x2, i.y2);
  74755. }
  74756. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74757. const AffineTransform& transform) const
  74758. {
  74759. PathFlatteningIterator i (*this, transform);
  74760. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74761. float length = 0;
  74762. Point<float> pointOnLine;
  74763. while (i.next())
  74764. {
  74765. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74766. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74767. if (distance < bestDistance)
  74768. {
  74769. bestDistance = distance;
  74770. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74771. pointOnPath = pointOnLine;
  74772. }
  74773. length += line.getLength();
  74774. }
  74775. return bestPosition;
  74776. }
  74777. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74778. {
  74779. if (cornerRadius <= 0.01f)
  74780. return *this;
  74781. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74782. size_t n = 0;
  74783. bool lastWasLine = false, firstWasLine = false;
  74784. Path p;
  74785. while (n < numElements)
  74786. {
  74787. const float type = data.elements [n++];
  74788. if (type == moveMarker)
  74789. {
  74790. indexOfPathStart = p.numElements;
  74791. indexOfPathStartThis = n - 1;
  74792. const float x = data.elements [n++];
  74793. const float y = data.elements [n++];
  74794. p.startNewSubPath (x, y);
  74795. lastWasLine = false;
  74796. firstWasLine = (data.elements [n] == lineMarker);
  74797. }
  74798. else if (type == lineMarker || type == closeSubPathMarker)
  74799. {
  74800. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74801. if (type == lineMarker)
  74802. {
  74803. endX = data.elements [n++];
  74804. endY = data.elements [n++];
  74805. if (n > 8)
  74806. {
  74807. startX = data.elements [n - 8];
  74808. startY = data.elements [n - 7];
  74809. joinX = data.elements [n - 5];
  74810. joinY = data.elements [n - 4];
  74811. }
  74812. }
  74813. else
  74814. {
  74815. endX = data.elements [indexOfPathStartThis + 1];
  74816. endY = data.elements [indexOfPathStartThis + 2];
  74817. if (n > 6)
  74818. {
  74819. startX = data.elements [n - 6];
  74820. startY = data.elements [n - 5];
  74821. joinX = data.elements [n - 3];
  74822. joinY = data.elements [n - 2];
  74823. }
  74824. }
  74825. if (lastWasLine)
  74826. {
  74827. const double len1 = juce_hypot (startX - joinX,
  74828. startY - joinY);
  74829. if (len1 > 0)
  74830. {
  74831. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74832. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74833. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74834. }
  74835. const double len2 = juce_hypot (endX - joinX,
  74836. endY - joinY);
  74837. if (len2 > 0)
  74838. {
  74839. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74840. p.quadraticTo (joinX, joinY,
  74841. (float) (joinX + (endX - joinX) * propNeeded),
  74842. (float) (joinY + (endY - joinY) * propNeeded));
  74843. }
  74844. p.lineTo (endX, endY);
  74845. }
  74846. else if (type == lineMarker)
  74847. {
  74848. p.lineTo (endX, endY);
  74849. lastWasLine = true;
  74850. }
  74851. if (type == closeSubPathMarker)
  74852. {
  74853. if (firstWasLine)
  74854. {
  74855. startX = data.elements [n - 3];
  74856. startY = data.elements [n - 2];
  74857. joinX = endX;
  74858. joinY = endY;
  74859. endX = data.elements [indexOfPathStartThis + 4];
  74860. endY = data.elements [indexOfPathStartThis + 5];
  74861. const double len1 = juce_hypot (startX - joinX,
  74862. startY - joinY);
  74863. if (len1 > 0)
  74864. {
  74865. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74866. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74867. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74868. }
  74869. const double len2 = juce_hypot (endX - joinX,
  74870. endY - joinY);
  74871. if (len2 > 0)
  74872. {
  74873. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74874. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74875. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74876. p.quadraticTo (joinX, joinY, endX, endY);
  74877. p.data.elements [indexOfPathStart + 1] = endX;
  74878. p.data.elements [indexOfPathStart + 2] = endY;
  74879. }
  74880. }
  74881. p.closeSubPath();
  74882. }
  74883. }
  74884. else if (type == quadMarker)
  74885. {
  74886. lastWasLine = false;
  74887. const float x1 = data.elements [n++];
  74888. const float y1 = data.elements [n++];
  74889. const float x2 = data.elements [n++];
  74890. const float y2 = data.elements [n++];
  74891. p.quadraticTo (x1, y1, x2, y2);
  74892. }
  74893. else if (type == cubicMarker)
  74894. {
  74895. lastWasLine = false;
  74896. const float x1 = data.elements [n++];
  74897. const float y1 = data.elements [n++];
  74898. const float x2 = data.elements [n++];
  74899. const float y2 = data.elements [n++];
  74900. const float x3 = data.elements [n++];
  74901. const float y3 = data.elements [n++];
  74902. p.cubicTo (x1, y1, x2, y2, x3, y3);
  74903. }
  74904. }
  74905. return p;
  74906. }
  74907. void Path::loadPathFromStream (InputStream& source)
  74908. {
  74909. while (! source.isExhausted())
  74910. {
  74911. switch (source.readByte())
  74912. {
  74913. case 'm':
  74914. {
  74915. const float x = source.readFloat();
  74916. const float y = source.readFloat();
  74917. startNewSubPath (x, y);
  74918. break;
  74919. }
  74920. case 'l':
  74921. {
  74922. const float x = source.readFloat();
  74923. const float y = source.readFloat();
  74924. lineTo (x, y);
  74925. break;
  74926. }
  74927. case 'q':
  74928. {
  74929. const float x1 = source.readFloat();
  74930. const float y1 = source.readFloat();
  74931. const float x2 = source.readFloat();
  74932. const float y2 = source.readFloat();
  74933. quadraticTo (x1, y1, x2, y2);
  74934. break;
  74935. }
  74936. case 'b':
  74937. {
  74938. const float x1 = source.readFloat();
  74939. const float y1 = source.readFloat();
  74940. const float x2 = source.readFloat();
  74941. const float y2 = source.readFloat();
  74942. const float x3 = source.readFloat();
  74943. const float y3 = source.readFloat();
  74944. cubicTo (x1, y1, x2, y2, x3, y3);
  74945. break;
  74946. }
  74947. case 'c':
  74948. closeSubPath();
  74949. break;
  74950. case 'n':
  74951. useNonZeroWinding = true;
  74952. break;
  74953. case 'z':
  74954. useNonZeroWinding = false;
  74955. break;
  74956. case 'e':
  74957. return; // end of path marker
  74958. default:
  74959. jassertfalse; // illegal char in the stream
  74960. break;
  74961. }
  74962. }
  74963. }
  74964. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  74965. {
  74966. MemoryInputStream in (pathData, numberOfBytes, false);
  74967. loadPathFromStream (in);
  74968. }
  74969. void Path::writePathToStream (OutputStream& dest) const
  74970. {
  74971. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  74972. size_t i = 0;
  74973. while (i < numElements)
  74974. {
  74975. const float type = data.elements [i++];
  74976. if (type == moveMarker)
  74977. {
  74978. dest.writeByte ('m');
  74979. dest.writeFloat (data.elements [i++]);
  74980. dest.writeFloat (data.elements [i++]);
  74981. }
  74982. else if (type == lineMarker)
  74983. {
  74984. dest.writeByte ('l');
  74985. dest.writeFloat (data.elements [i++]);
  74986. dest.writeFloat (data.elements [i++]);
  74987. }
  74988. else if (type == quadMarker)
  74989. {
  74990. dest.writeByte ('q');
  74991. dest.writeFloat (data.elements [i++]);
  74992. dest.writeFloat (data.elements [i++]);
  74993. dest.writeFloat (data.elements [i++]);
  74994. dest.writeFloat (data.elements [i++]);
  74995. }
  74996. else if (type == cubicMarker)
  74997. {
  74998. dest.writeByte ('b');
  74999. dest.writeFloat (data.elements [i++]);
  75000. dest.writeFloat (data.elements [i++]);
  75001. dest.writeFloat (data.elements [i++]);
  75002. dest.writeFloat (data.elements [i++]);
  75003. dest.writeFloat (data.elements [i++]);
  75004. dest.writeFloat (data.elements [i++]);
  75005. }
  75006. else if (type == closeSubPathMarker)
  75007. {
  75008. dest.writeByte ('c');
  75009. }
  75010. }
  75011. dest.writeByte ('e'); // marks the end-of-path
  75012. }
  75013. const String Path::toString() const
  75014. {
  75015. MemoryOutputStream s (2048);
  75016. if (! useNonZeroWinding)
  75017. s << 'a';
  75018. size_t i = 0;
  75019. float lastMarker = 0.0f;
  75020. while (i < numElements)
  75021. {
  75022. const float marker = data.elements [i++];
  75023. char markerChar = 0;
  75024. int numCoords = 0;
  75025. if (marker == moveMarker)
  75026. {
  75027. markerChar = 'm';
  75028. numCoords = 2;
  75029. }
  75030. else if (marker == lineMarker)
  75031. {
  75032. markerChar = 'l';
  75033. numCoords = 2;
  75034. }
  75035. else if (marker == quadMarker)
  75036. {
  75037. markerChar = 'q';
  75038. numCoords = 4;
  75039. }
  75040. else if (marker == cubicMarker)
  75041. {
  75042. markerChar = 'c';
  75043. numCoords = 6;
  75044. }
  75045. else
  75046. {
  75047. jassert (marker == closeSubPathMarker);
  75048. markerChar = 'z';
  75049. }
  75050. if (marker != lastMarker)
  75051. {
  75052. if (s.getDataSize() != 0)
  75053. s << ' ';
  75054. s << markerChar;
  75055. lastMarker = marker;
  75056. }
  75057. while (--numCoords >= 0 && i < numElements)
  75058. {
  75059. String coord (data.elements [i++], 3);
  75060. while (coord.endsWithChar ('0') && coord != "0")
  75061. coord = coord.dropLastCharacters (1);
  75062. if (coord.endsWithChar ('.'))
  75063. coord = coord.dropLastCharacters (1);
  75064. if (s.getDataSize() != 0)
  75065. s << ' ';
  75066. s << coord;
  75067. }
  75068. }
  75069. return s.toUTF8();
  75070. }
  75071. void Path::restoreFromString (const String& stringVersion)
  75072. {
  75073. clear();
  75074. setUsingNonZeroWinding (true);
  75075. const juce_wchar* t = stringVersion;
  75076. juce_wchar marker = 'm';
  75077. int numValues = 2;
  75078. float values [6];
  75079. for (;;)
  75080. {
  75081. const String token (PathHelpers::nextToken (t));
  75082. const juce_wchar firstChar = token[0];
  75083. int startNum = 0;
  75084. if (firstChar == 0)
  75085. break;
  75086. if (firstChar == 'm' || firstChar == 'l')
  75087. {
  75088. marker = firstChar;
  75089. numValues = 2;
  75090. }
  75091. else if (firstChar == 'q')
  75092. {
  75093. marker = firstChar;
  75094. numValues = 4;
  75095. }
  75096. else if (firstChar == 'c')
  75097. {
  75098. marker = firstChar;
  75099. numValues = 6;
  75100. }
  75101. else if (firstChar == 'z')
  75102. {
  75103. marker = firstChar;
  75104. numValues = 0;
  75105. }
  75106. else if (firstChar == 'a')
  75107. {
  75108. setUsingNonZeroWinding (false);
  75109. continue;
  75110. }
  75111. else
  75112. {
  75113. ++startNum;
  75114. values [0] = token.getFloatValue();
  75115. }
  75116. for (int i = startNum; i < numValues; ++i)
  75117. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75118. switch (marker)
  75119. {
  75120. case 'm':
  75121. startNewSubPath (values[0], values[1]);
  75122. break;
  75123. case 'l':
  75124. lineTo (values[0], values[1]);
  75125. break;
  75126. case 'q':
  75127. quadraticTo (values[0], values[1],
  75128. values[2], values[3]);
  75129. break;
  75130. case 'c':
  75131. cubicTo (values[0], values[1],
  75132. values[2], values[3],
  75133. values[4], values[5]);
  75134. break;
  75135. case 'z':
  75136. closeSubPath();
  75137. break;
  75138. default:
  75139. jassertfalse; // illegal string format?
  75140. break;
  75141. }
  75142. }
  75143. }
  75144. Path::Iterator::Iterator (const Path& path_)
  75145. : path (path_),
  75146. index (0)
  75147. {
  75148. }
  75149. Path::Iterator::~Iterator()
  75150. {
  75151. }
  75152. bool Path::Iterator::next()
  75153. {
  75154. const float* const elements = path.data.elements;
  75155. if (index < path.numElements)
  75156. {
  75157. const float type = elements [index++];
  75158. if (type == moveMarker)
  75159. {
  75160. elementType = startNewSubPath;
  75161. x1 = elements [index++];
  75162. y1 = elements [index++];
  75163. }
  75164. else if (type == lineMarker)
  75165. {
  75166. elementType = lineTo;
  75167. x1 = elements [index++];
  75168. y1 = elements [index++];
  75169. }
  75170. else if (type == quadMarker)
  75171. {
  75172. elementType = quadraticTo;
  75173. x1 = elements [index++];
  75174. y1 = elements [index++];
  75175. x2 = elements [index++];
  75176. y2 = elements [index++];
  75177. }
  75178. else if (type == cubicMarker)
  75179. {
  75180. elementType = cubicTo;
  75181. x1 = elements [index++];
  75182. y1 = elements [index++];
  75183. x2 = elements [index++];
  75184. y2 = elements [index++];
  75185. x3 = elements [index++];
  75186. y3 = elements [index++];
  75187. }
  75188. else if (type == closeSubPathMarker)
  75189. {
  75190. elementType = closePath;
  75191. }
  75192. return true;
  75193. }
  75194. return false;
  75195. }
  75196. END_JUCE_NAMESPACE
  75197. /*** End of inlined file: juce_Path.cpp ***/
  75198. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75199. BEGIN_JUCE_NAMESPACE
  75200. #if JUCE_MSVC && JUCE_DEBUG
  75201. #pragma optimize ("t", on)
  75202. #endif
  75203. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75204. const AffineTransform& transform_,
  75205. float tolerence_)
  75206. : x2 (0),
  75207. y2 (0),
  75208. closesSubPath (false),
  75209. subPathIndex (-1),
  75210. path (path_),
  75211. transform (transform_),
  75212. points (path_.data.elements),
  75213. tolerence (tolerence_ * tolerence_),
  75214. subPathCloseX (0),
  75215. subPathCloseY (0),
  75216. isIdentityTransform (transform_.isIdentity()),
  75217. stackBase (32),
  75218. index (0),
  75219. stackSize (32)
  75220. {
  75221. stackPos = stackBase;
  75222. }
  75223. PathFlatteningIterator::~PathFlatteningIterator()
  75224. {
  75225. }
  75226. bool PathFlatteningIterator::next()
  75227. {
  75228. x1 = x2;
  75229. y1 = y2;
  75230. float x3 = 0;
  75231. float y3 = 0;
  75232. float x4 = 0;
  75233. float y4 = 0;
  75234. float type;
  75235. for (;;)
  75236. {
  75237. if (stackPos == stackBase)
  75238. {
  75239. if (index >= path.numElements)
  75240. {
  75241. return false;
  75242. }
  75243. else
  75244. {
  75245. type = points [index++];
  75246. if (type != Path::closeSubPathMarker)
  75247. {
  75248. x2 = points [index++];
  75249. y2 = points [index++];
  75250. if (type == Path::quadMarker)
  75251. {
  75252. x3 = points [index++];
  75253. y3 = points [index++];
  75254. if (! isIdentityTransform)
  75255. transform.transformPoints (x2, y2, x3, y3);
  75256. }
  75257. else if (type == Path::cubicMarker)
  75258. {
  75259. x3 = points [index++];
  75260. y3 = points [index++];
  75261. x4 = points [index++];
  75262. y4 = points [index++];
  75263. if (! isIdentityTransform)
  75264. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75265. }
  75266. else
  75267. {
  75268. if (! isIdentityTransform)
  75269. transform.transformPoint (x2, y2);
  75270. }
  75271. }
  75272. }
  75273. }
  75274. else
  75275. {
  75276. type = *--stackPos;
  75277. if (type != Path::closeSubPathMarker)
  75278. {
  75279. x2 = *--stackPos;
  75280. y2 = *--stackPos;
  75281. if (type == Path::quadMarker)
  75282. {
  75283. x3 = *--stackPos;
  75284. y3 = *--stackPos;
  75285. }
  75286. else if (type == Path::cubicMarker)
  75287. {
  75288. x3 = *--stackPos;
  75289. y3 = *--stackPos;
  75290. x4 = *--stackPos;
  75291. y4 = *--stackPos;
  75292. }
  75293. }
  75294. }
  75295. if (type == Path::lineMarker)
  75296. {
  75297. ++subPathIndex;
  75298. closesSubPath = (stackPos == stackBase)
  75299. && (index < path.numElements)
  75300. && (points [index] == Path::closeSubPathMarker)
  75301. && x2 == subPathCloseX
  75302. && y2 == subPathCloseY;
  75303. return true;
  75304. }
  75305. else if (type == Path::quadMarker)
  75306. {
  75307. const size_t offset = (size_t) (stackPos - stackBase);
  75308. if (offset >= stackSize - 10)
  75309. {
  75310. stackSize <<= 1;
  75311. stackBase.realloc (stackSize);
  75312. stackPos = stackBase + offset;
  75313. }
  75314. const float dx1 = x1 - x2;
  75315. const float dy1 = y1 - y2;
  75316. const float dx2 = x2 - x3;
  75317. const float dy2 = y2 - y3;
  75318. const float m1x = (x1 + x2) * 0.5f;
  75319. const float m1y = (y1 + y2) * 0.5f;
  75320. const float m2x = (x2 + x3) * 0.5f;
  75321. const float m2y = (y2 + y3) * 0.5f;
  75322. const float m3x = (m1x + m2x) * 0.5f;
  75323. const float m3y = (m1y + m2y) * 0.5f;
  75324. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75325. {
  75326. *stackPos++ = y3;
  75327. *stackPos++ = x3;
  75328. *stackPos++ = m2y;
  75329. *stackPos++ = m2x;
  75330. *stackPos++ = Path::quadMarker;
  75331. *stackPos++ = m3y;
  75332. *stackPos++ = m3x;
  75333. *stackPos++ = m1y;
  75334. *stackPos++ = m1x;
  75335. *stackPos++ = Path::quadMarker;
  75336. }
  75337. else
  75338. {
  75339. *stackPos++ = y3;
  75340. *stackPos++ = x3;
  75341. *stackPos++ = Path::lineMarker;
  75342. *stackPos++ = m3y;
  75343. *stackPos++ = m3x;
  75344. *stackPos++ = Path::lineMarker;
  75345. }
  75346. jassert (stackPos < stackBase + stackSize);
  75347. }
  75348. else if (type == Path::cubicMarker)
  75349. {
  75350. const size_t offset = (size_t) (stackPos - stackBase);
  75351. if (offset >= stackSize - 16)
  75352. {
  75353. stackSize <<= 1;
  75354. stackBase.realloc (stackSize);
  75355. stackPos = stackBase + offset;
  75356. }
  75357. const float dx1 = x1 - x2;
  75358. const float dy1 = y1 - y2;
  75359. const float dx2 = x2 - x3;
  75360. const float dy2 = y2 - y3;
  75361. const float dx3 = x3 - x4;
  75362. const float dy3 = y3 - y4;
  75363. const float m1x = (x1 + x2) * 0.5f;
  75364. const float m1y = (y1 + y2) * 0.5f;
  75365. const float m2x = (x3 + x2) * 0.5f;
  75366. const float m2y = (y3 + y2) * 0.5f;
  75367. const float m3x = (x3 + x4) * 0.5f;
  75368. const float m3y = (y3 + y4) * 0.5f;
  75369. const float m4x = (m1x + m2x) * 0.5f;
  75370. const float m4y = (m1y + m2y) * 0.5f;
  75371. const float m5x = (m3x + m2x) * 0.5f;
  75372. const float m5y = (m3y + m2y) * 0.5f;
  75373. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75374. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75375. {
  75376. *stackPos++ = y4;
  75377. *stackPos++ = x4;
  75378. *stackPos++ = m3y;
  75379. *stackPos++ = m3x;
  75380. *stackPos++ = m5y;
  75381. *stackPos++ = m5x;
  75382. *stackPos++ = Path::cubicMarker;
  75383. *stackPos++ = (m4y + m5y) * 0.5f;
  75384. *stackPos++ = (m4x + m5x) * 0.5f;
  75385. *stackPos++ = m4y;
  75386. *stackPos++ = m4x;
  75387. *stackPos++ = m1y;
  75388. *stackPos++ = m1x;
  75389. *stackPos++ = Path::cubicMarker;
  75390. }
  75391. else
  75392. {
  75393. *stackPos++ = y4;
  75394. *stackPos++ = x4;
  75395. *stackPos++ = Path::lineMarker;
  75396. *stackPos++ = m5y;
  75397. *stackPos++ = m5x;
  75398. *stackPos++ = Path::lineMarker;
  75399. *stackPos++ = m4y;
  75400. *stackPos++ = m4x;
  75401. *stackPos++ = Path::lineMarker;
  75402. }
  75403. }
  75404. else if (type == Path::closeSubPathMarker)
  75405. {
  75406. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75407. {
  75408. x1 = x2;
  75409. y1 = y2;
  75410. x2 = subPathCloseX;
  75411. y2 = subPathCloseY;
  75412. closesSubPath = true;
  75413. return true;
  75414. }
  75415. }
  75416. else
  75417. {
  75418. jassert (type == Path::moveMarker);
  75419. subPathIndex = -1;
  75420. subPathCloseX = x1 = x2;
  75421. subPathCloseY = y1 = y2;
  75422. }
  75423. }
  75424. }
  75425. #if JUCE_MSVC && JUCE_DEBUG
  75426. #pragma optimize ("", on) // resets optimisations to the project defaults
  75427. #endif
  75428. END_JUCE_NAMESPACE
  75429. /*** End of inlined file: juce_PathIterator.cpp ***/
  75430. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75431. BEGIN_JUCE_NAMESPACE
  75432. PathStrokeType::PathStrokeType (const float strokeThickness,
  75433. const JointStyle jointStyle_,
  75434. const EndCapStyle endStyle_) throw()
  75435. : thickness (strokeThickness),
  75436. jointStyle (jointStyle_),
  75437. endStyle (endStyle_)
  75438. {
  75439. }
  75440. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75441. : thickness (other.thickness),
  75442. jointStyle (other.jointStyle),
  75443. endStyle (other.endStyle)
  75444. {
  75445. }
  75446. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75447. {
  75448. thickness = other.thickness;
  75449. jointStyle = other.jointStyle;
  75450. endStyle = other.endStyle;
  75451. return *this;
  75452. }
  75453. PathStrokeType::~PathStrokeType() throw()
  75454. {
  75455. }
  75456. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75457. {
  75458. return thickness == other.thickness
  75459. && jointStyle == other.jointStyle
  75460. && endStyle == other.endStyle;
  75461. }
  75462. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75463. {
  75464. return ! operator== (other);
  75465. }
  75466. namespace PathStrokeHelpers
  75467. {
  75468. static bool lineIntersection (const float x1, const float y1,
  75469. const float x2, const float y2,
  75470. const float x3, const float y3,
  75471. const float x4, const float y4,
  75472. float& intersectionX,
  75473. float& intersectionY,
  75474. float& distanceBeyondLine1EndSquared) throw()
  75475. {
  75476. if (x2 != x3 || y2 != y3)
  75477. {
  75478. const float dx1 = x2 - x1;
  75479. const float dy1 = y2 - y1;
  75480. const float dx2 = x4 - x3;
  75481. const float dy2 = y4 - y3;
  75482. const float divisor = dx1 * dy2 - dx2 * dy1;
  75483. if (divisor == 0)
  75484. {
  75485. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75486. {
  75487. if (dy1 == 0 && dy2 != 0)
  75488. {
  75489. const float along = (y1 - y3) / dy2;
  75490. intersectionX = x3 + along * dx2;
  75491. intersectionY = y1;
  75492. distanceBeyondLine1EndSquared = intersectionX - x2;
  75493. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75494. if ((x2 > x1) == (intersectionX < x2))
  75495. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75496. return along >= 0 && along <= 1.0f;
  75497. }
  75498. else if (dy2 == 0 && dy1 != 0)
  75499. {
  75500. const float along = (y3 - y1) / dy1;
  75501. intersectionX = x1 + along * dx1;
  75502. intersectionY = y3;
  75503. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75504. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75505. if (along < 1.0f)
  75506. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75507. return along >= 0 && along <= 1.0f;
  75508. }
  75509. else if (dx1 == 0 && dx2 != 0)
  75510. {
  75511. const float along = (x1 - x3) / dx2;
  75512. intersectionX = x1;
  75513. intersectionY = y3 + along * dy2;
  75514. distanceBeyondLine1EndSquared = intersectionY - y2;
  75515. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75516. if ((y2 > y1) == (intersectionY < y2))
  75517. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75518. return along >= 0 && along <= 1.0f;
  75519. }
  75520. else if (dx2 == 0 && dx1 != 0)
  75521. {
  75522. const float along = (x3 - x1) / dx1;
  75523. intersectionX = x3;
  75524. intersectionY = y1 + along * dy1;
  75525. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75526. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75527. if (along < 1.0f)
  75528. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75529. return along >= 0 && along <= 1.0f;
  75530. }
  75531. }
  75532. intersectionX = 0.5f * (x2 + x3);
  75533. intersectionY = 0.5f * (y2 + y3);
  75534. distanceBeyondLine1EndSquared = 0.0f;
  75535. return false;
  75536. }
  75537. else
  75538. {
  75539. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75540. intersectionX = x1 + along1 * dx1;
  75541. intersectionY = y1 + along1 * dy1;
  75542. if (along1 >= 0 && along1 <= 1.0f)
  75543. {
  75544. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75545. if (along2 >= 0 && along2 <= divisor)
  75546. {
  75547. distanceBeyondLine1EndSquared = 0.0f;
  75548. return true;
  75549. }
  75550. }
  75551. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75552. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75553. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75554. if (along1 < 1.0f)
  75555. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75556. return false;
  75557. }
  75558. }
  75559. intersectionX = x2;
  75560. intersectionY = y2;
  75561. distanceBeyondLine1EndSquared = 0.0f;
  75562. return true;
  75563. }
  75564. static void addEdgeAndJoint (Path& destPath,
  75565. const PathStrokeType::JointStyle style,
  75566. const float maxMiterExtensionSquared, const float width,
  75567. const float x1, const float y1,
  75568. const float x2, const float y2,
  75569. const float x3, const float y3,
  75570. const float x4, const float y4,
  75571. const float midX, const float midY)
  75572. {
  75573. if (style == PathStrokeType::beveled
  75574. || (x3 == x4 && y3 == y4)
  75575. || (x1 == x2 && y1 == y2))
  75576. {
  75577. destPath.lineTo (x2, y2);
  75578. destPath.lineTo (x3, y3);
  75579. }
  75580. else
  75581. {
  75582. float jx, jy, distanceBeyondLine1EndSquared;
  75583. // if they intersect, use this point..
  75584. if (lineIntersection (x1, y1, x2, y2,
  75585. x3, y3, x4, y4,
  75586. jx, jy, distanceBeyondLine1EndSquared))
  75587. {
  75588. destPath.lineTo (jx, jy);
  75589. }
  75590. else
  75591. {
  75592. if (style == PathStrokeType::mitered)
  75593. {
  75594. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75595. && distanceBeyondLine1EndSquared > 0.0f)
  75596. {
  75597. destPath.lineTo (jx, jy);
  75598. }
  75599. else
  75600. {
  75601. // the end sticks out too far, so just use a blunt joint
  75602. destPath.lineTo (x2, y2);
  75603. destPath.lineTo (x3, y3);
  75604. }
  75605. }
  75606. else
  75607. {
  75608. // curved joints
  75609. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75610. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75611. const float angleIncrement = 0.1f;
  75612. destPath.lineTo (x2, y2);
  75613. if (std::abs (angle1 - angle2) > angleIncrement)
  75614. {
  75615. if (angle2 > angle1 + float_Pi
  75616. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75617. {
  75618. if (angle2 > angle1)
  75619. angle2 -= float_Pi * 2.0f;
  75620. jassert (angle1 <= angle2 + float_Pi);
  75621. angle1 -= angleIncrement;
  75622. while (angle1 > angle2)
  75623. {
  75624. destPath.lineTo (midX + width * std::sin (angle1),
  75625. midY + width * std::cos (angle1));
  75626. angle1 -= angleIncrement;
  75627. }
  75628. }
  75629. else
  75630. {
  75631. if (angle1 > angle2)
  75632. angle1 -= float_Pi * 2.0f;
  75633. jassert (angle1 >= angle2 - float_Pi);
  75634. angle1 += angleIncrement;
  75635. while (angle1 < angle2)
  75636. {
  75637. destPath.lineTo (midX + width * std::sin (angle1),
  75638. midY + width * std::cos (angle1));
  75639. angle1 += angleIncrement;
  75640. }
  75641. }
  75642. }
  75643. destPath.lineTo (x3, y3);
  75644. }
  75645. }
  75646. }
  75647. }
  75648. static void addLineEnd (Path& destPath,
  75649. const PathStrokeType::EndCapStyle style,
  75650. const float x1, const float y1,
  75651. const float x2, const float y2,
  75652. const float width)
  75653. {
  75654. if (style == PathStrokeType::butt)
  75655. {
  75656. destPath.lineTo (x2, y2);
  75657. }
  75658. else
  75659. {
  75660. float offx1, offy1, offx2, offy2;
  75661. float dx = x2 - x1;
  75662. float dy = y2 - y1;
  75663. const float len = juce_hypotf (dx, dy);
  75664. if (len == 0)
  75665. {
  75666. offx1 = offx2 = x1;
  75667. offy1 = offy2 = y1;
  75668. }
  75669. else
  75670. {
  75671. const float offset = width / len;
  75672. dx *= offset;
  75673. dy *= offset;
  75674. offx1 = x1 + dy;
  75675. offy1 = y1 - dx;
  75676. offx2 = x2 + dy;
  75677. offy2 = y2 - dx;
  75678. }
  75679. if (style == PathStrokeType::square)
  75680. {
  75681. // sqaure ends
  75682. destPath.lineTo (offx1, offy1);
  75683. destPath.lineTo (offx2, offy2);
  75684. destPath.lineTo (x2, y2);
  75685. }
  75686. else
  75687. {
  75688. // rounded ends
  75689. const float midx = (offx1 + offx2) * 0.5f;
  75690. const float midy = (offy1 + offy2) * 0.5f;
  75691. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75692. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75693. midx, midy);
  75694. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75695. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75696. x2, y2);
  75697. }
  75698. }
  75699. }
  75700. struct Arrowhead
  75701. {
  75702. float startWidth, startLength;
  75703. float endWidth, endLength;
  75704. };
  75705. static void addArrowhead (Path& destPath,
  75706. const float x1, const float y1,
  75707. const float x2, const float y2,
  75708. const float tipX, const float tipY,
  75709. const float width,
  75710. const float arrowheadWidth)
  75711. {
  75712. Line<float> line (x1, y1, x2, y2);
  75713. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75714. destPath.lineTo (tipX, tipY);
  75715. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75716. destPath.lineTo (x2, y2);
  75717. }
  75718. struct LineSection
  75719. {
  75720. float x1, y1, x2, y2; // original line
  75721. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75722. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75723. };
  75724. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75725. {
  75726. while (amountAtEnd > 0 && subPath.size() > 0)
  75727. {
  75728. LineSection& l = subPath.getReference (subPath.size() - 1);
  75729. float dx = l.rx2 - l.rx1;
  75730. float dy = l.ry2 - l.ry1;
  75731. const float len = juce_hypotf (dx, dy);
  75732. if (len <= amountAtEnd && subPath.size() > 1)
  75733. {
  75734. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75735. prev.x2 = l.x2;
  75736. prev.y2 = l.y2;
  75737. subPath.removeLast();
  75738. amountAtEnd -= len;
  75739. }
  75740. else
  75741. {
  75742. const float prop = jmin (0.9999f, amountAtEnd / len);
  75743. dx *= prop;
  75744. dy *= prop;
  75745. l.rx1 += dx;
  75746. l.ry1 += dy;
  75747. l.lx2 += dx;
  75748. l.ly2 += dy;
  75749. break;
  75750. }
  75751. }
  75752. while (amountAtStart > 0 && subPath.size() > 0)
  75753. {
  75754. LineSection& l = subPath.getReference (0);
  75755. float dx = l.rx2 - l.rx1;
  75756. float dy = l.ry2 - l.ry1;
  75757. const float len = juce_hypotf (dx, dy);
  75758. if (len <= amountAtStart && subPath.size() > 1)
  75759. {
  75760. LineSection& next = subPath.getReference (1);
  75761. next.x1 = l.x1;
  75762. next.y1 = l.y1;
  75763. subPath.remove (0);
  75764. amountAtStart -= len;
  75765. }
  75766. else
  75767. {
  75768. const float prop = jmin (0.9999f, amountAtStart / len);
  75769. dx *= prop;
  75770. dy *= prop;
  75771. l.rx2 -= dx;
  75772. l.ry2 -= dy;
  75773. l.lx1 -= dx;
  75774. l.ly1 -= dy;
  75775. break;
  75776. }
  75777. }
  75778. }
  75779. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75780. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75781. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75782. const Arrowhead* const arrowhead)
  75783. {
  75784. jassert (subPath.size() > 0);
  75785. if (arrowhead != 0)
  75786. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75787. const LineSection& firstLine = subPath.getReference (0);
  75788. float lastX1 = firstLine.lx1;
  75789. float lastY1 = firstLine.ly1;
  75790. float lastX2 = firstLine.lx2;
  75791. float lastY2 = firstLine.ly2;
  75792. if (isClosed)
  75793. {
  75794. destPath.startNewSubPath (lastX1, lastY1);
  75795. }
  75796. else
  75797. {
  75798. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75799. if (arrowhead != 0)
  75800. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75801. width, arrowhead->startWidth);
  75802. else
  75803. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75804. }
  75805. int i;
  75806. for (i = 1; i < subPath.size(); ++i)
  75807. {
  75808. const LineSection& l = subPath.getReference (i);
  75809. addEdgeAndJoint (destPath, jointStyle,
  75810. maxMiterExtensionSquared, width,
  75811. lastX1, lastY1, lastX2, lastY2,
  75812. l.lx1, l.ly1, l.lx2, l.ly2,
  75813. l.x1, l.y1);
  75814. lastX1 = l.lx1;
  75815. lastY1 = l.ly1;
  75816. lastX2 = l.lx2;
  75817. lastY2 = l.ly2;
  75818. }
  75819. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75820. if (isClosed)
  75821. {
  75822. const LineSection& l = subPath.getReference (0);
  75823. addEdgeAndJoint (destPath, jointStyle,
  75824. maxMiterExtensionSquared, width,
  75825. lastX1, lastY1, lastX2, lastY2,
  75826. l.lx1, l.ly1, l.lx2, l.ly2,
  75827. l.x1, l.y1);
  75828. destPath.closeSubPath();
  75829. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75830. }
  75831. else
  75832. {
  75833. destPath.lineTo (lastX2, lastY2);
  75834. if (arrowhead != 0)
  75835. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75836. width, arrowhead->endWidth);
  75837. else
  75838. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75839. }
  75840. lastX1 = lastLine.rx1;
  75841. lastY1 = lastLine.ry1;
  75842. lastX2 = lastLine.rx2;
  75843. lastY2 = lastLine.ry2;
  75844. for (i = subPath.size() - 1; --i >= 0;)
  75845. {
  75846. const LineSection& l = subPath.getReference (i);
  75847. addEdgeAndJoint (destPath, jointStyle,
  75848. maxMiterExtensionSquared, width,
  75849. lastX1, lastY1, lastX2, lastY2,
  75850. l.rx1, l.ry1, l.rx2, l.ry2,
  75851. l.x2, l.y2);
  75852. lastX1 = l.rx1;
  75853. lastY1 = l.ry1;
  75854. lastX2 = l.rx2;
  75855. lastY2 = l.ry2;
  75856. }
  75857. if (isClosed)
  75858. {
  75859. addEdgeAndJoint (destPath, jointStyle,
  75860. maxMiterExtensionSquared, width,
  75861. lastX1, lastY1, lastX2, lastY2,
  75862. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75863. lastLine.x2, lastLine.y2);
  75864. }
  75865. else
  75866. {
  75867. // do the last line
  75868. destPath.lineTo (lastX2, lastY2);
  75869. }
  75870. destPath.closeSubPath();
  75871. }
  75872. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75873. const PathStrokeType::EndCapStyle endStyle,
  75874. Path& destPath, const Path& source,
  75875. const AffineTransform& transform,
  75876. const float extraAccuracy, const Arrowhead* const arrowhead)
  75877. {
  75878. if (thickness <= 0)
  75879. {
  75880. destPath.clear();
  75881. return;
  75882. }
  75883. const Path* sourcePath = &source;
  75884. Path temp;
  75885. if (sourcePath == &destPath)
  75886. {
  75887. destPath.swapWithPath (temp);
  75888. sourcePath = &temp;
  75889. }
  75890. else
  75891. {
  75892. destPath.clear();
  75893. }
  75894. destPath.setUsingNonZeroWinding (true);
  75895. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75896. const float width = 0.5f * thickness;
  75897. // Iterate the path, creating a list of the
  75898. // left/right-hand lines along either side of it...
  75899. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  75900. Array <LineSection> subPath;
  75901. subPath.ensureStorageAllocated (512);
  75902. LineSection l;
  75903. l.x1 = 0;
  75904. l.y1 = 0;
  75905. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  75906. while (it.next())
  75907. {
  75908. if (it.subPathIndex == 0)
  75909. {
  75910. if (subPath.size() > 0)
  75911. {
  75912. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75913. subPath.clearQuick();
  75914. }
  75915. l.x1 = it.x1;
  75916. l.y1 = it.y1;
  75917. }
  75918. l.x2 = it.x2;
  75919. l.y2 = it.y2;
  75920. float dx = l.x2 - l.x1;
  75921. float dy = l.y2 - l.y1;
  75922. const float hypotSquared = dx*dx + dy*dy;
  75923. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  75924. {
  75925. const float len = std::sqrt (hypotSquared);
  75926. if (len == 0)
  75927. {
  75928. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  75929. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  75930. }
  75931. else
  75932. {
  75933. const float offset = width / len;
  75934. dx *= offset;
  75935. dy *= offset;
  75936. l.rx2 = l.x1 - dy;
  75937. l.ry2 = l.y1 + dx;
  75938. l.lx1 = l.x1 + dy;
  75939. l.ly1 = l.y1 - dx;
  75940. l.lx2 = l.x2 + dy;
  75941. l.ly2 = l.y2 - dx;
  75942. l.rx1 = l.x2 - dy;
  75943. l.ry1 = l.y2 + dx;
  75944. }
  75945. subPath.add (l);
  75946. if (it.closesSubPath)
  75947. {
  75948. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75949. subPath.clearQuick();
  75950. }
  75951. else
  75952. {
  75953. l.x1 = it.x2;
  75954. l.y1 = it.y2;
  75955. }
  75956. }
  75957. }
  75958. if (subPath.size() > 0)
  75959. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75960. }
  75961. }
  75962. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  75963. const AffineTransform& transform, const float extraAccuracy) const
  75964. {
  75965. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  75966. transform, extraAccuracy, 0);
  75967. }
  75968. void PathStrokeType::createDashedStroke (Path& destPath,
  75969. const Path& sourcePath,
  75970. const float* dashLengths,
  75971. int numDashLengths,
  75972. const AffineTransform& transform,
  75973. const float extraAccuracy) const
  75974. {
  75975. if (thickness <= 0)
  75976. return;
  75977. // this should really be an even number..
  75978. jassert ((numDashLengths & 1) == 0);
  75979. Path newDestPath;
  75980. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  75981. bool first = true;
  75982. int dashNum = 0;
  75983. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  75984. float dx = 0.0f, dy = 0.0f;
  75985. for (;;)
  75986. {
  75987. const bool isSolid = ((dashNum & 1) == 0);
  75988. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  75989. jassert (dashLen > 0); // must be a positive increment!
  75990. if (dashLen <= 0)
  75991. break;
  75992. pos += dashLen;
  75993. while (pos > lineEndPos)
  75994. {
  75995. if (! it.next())
  75996. {
  75997. if (isSolid && ! first)
  75998. newDestPath.lineTo (it.x2, it.y2);
  75999. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76000. return;
  76001. }
  76002. if (isSolid && ! first)
  76003. newDestPath.lineTo (it.x1, it.y1);
  76004. else
  76005. newDestPath.startNewSubPath (it.x1, it.y1);
  76006. dx = it.x2 - it.x1;
  76007. dy = it.y2 - it.y1;
  76008. lineLen = juce_hypotf (dx, dy);
  76009. lineEndPos += lineLen;
  76010. first = it.closesSubPath;
  76011. }
  76012. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76013. if (isSolid)
  76014. newDestPath.lineTo (it.x1 + dx * alpha,
  76015. it.y1 + dy * alpha);
  76016. else
  76017. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76018. it.y1 + dy * alpha);
  76019. }
  76020. }
  76021. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76022. const Path& sourcePath,
  76023. const float arrowheadStartWidth, const float arrowheadStartLength,
  76024. const float arrowheadEndWidth, const float arrowheadEndLength,
  76025. const AffineTransform& transform,
  76026. const float extraAccuracy) const
  76027. {
  76028. PathStrokeHelpers::Arrowhead head;
  76029. head.startWidth = arrowheadStartWidth;
  76030. head.startLength = arrowheadStartLength;
  76031. head.endWidth = arrowheadEndWidth;
  76032. head.endLength = arrowheadEndLength;
  76033. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76034. destPath, sourcePath, transform, extraAccuracy, &head);
  76035. }
  76036. END_JUCE_NAMESPACE
  76037. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76038. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76039. BEGIN_JUCE_NAMESPACE
  76040. PositionedRectangle::PositionedRectangle() throw()
  76041. : x (0.0),
  76042. y (0.0),
  76043. w (0.0),
  76044. h (0.0),
  76045. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76046. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76047. wMode (absoluteSize),
  76048. hMode (absoluteSize)
  76049. {
  76050. }
  76051. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76052. : x (other.x),
  76053. y (other.y),
  76054. w (other.w),
  76055. h (other.h),
  76056. xMode (other.xMode),
  76057. yMode (other.yMode),
  76058. wMode (other.wMode),
  76059. hMode (other.hMode)
  76060. {
  76061. }
  76062. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76063. {
  76064. x = other.x;
  76065. y = other.y;
  76066. w = other.w;
  76067. h = other.h;
  76068. xMode = other.xMode;
  76069. yMode = other.yMode;
  76070. wMode = other.wMode;
  76071. hMode = other.hMode;
  76072. return *this;
  76073. }
  76074. PositionedRectangle::~PositionedRectangle() throw()
  76075. {
  76076. }
  76077. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76078. {
  76079. return x == other.x
  76080. && y == other.y
  76081. && w == other.w
  76082. && h == other.h
  76083. && xMode == other.xMode
  76084. && yMode == other.yMode
  76085. && wMode == other.wMode
  76086. && hMode == other.hMode;
  76087. }
  76088. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76089. {
  76090. return ! operator== (other);
  76091. }
  76092. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76093. {
  76094. StringArray tokens;
  76095. tokens.addTokens (stringVersion, false);
  76096. decodePosString (tokens [0], xMode, x);
  76097. decodePosString (tokens [1], yMode, y);
  76098. decodeSizeString (tokens [2], wMode, w);
  76099. decodeSizeString (tokens [3], hMode, h);
  76100. }
  76101. const String PositionedRectangle::toString() const throw()
  76102. {
  76103. String s;
  76104. s.preallocateStorage (12);
  76105. addPosDescription (s, xMode, x);
  76106. s << ' ';
  76107. addPosDescription (s, yMode, y);
  76108. s << ' ';
  76109. addSizeDescription (s, wMode, w);
  76110. s << ' ';
  76111. addSizeDescription (s, hMode, h);
  76112. return s;
  76113. }
  76114. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76115. {
  76116. jassert (! target.isEmpty());
  76117. double x_, y_, w_, h_;
  76118. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76119. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76120. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76121. roundToInt (w_), roundToInt (h_));
  76122. }
  76123. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76124. double& x_, double& y_,
  76125. double& w_, double& h_) const throw()
  76126. {
  76127. jassert (! target.isEmpty());
  76128. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76129. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76130. }
  76131. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76132. {
  76133. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76134. }
  76135. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76136. const Rectangle<int>& target) throw()
  76137. {
  76138. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76139. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76140. }
  76141. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76142. const double newW, const double newH,
  76143. const Rectangle<int>& target) throw()
  76144. {
  76145. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76146. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76147. }
  76148. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76149. {
  76150. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76151. updateFrom (comp.getBounds(), Rectangle<int>());
  76152. else
  76153. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76154. }
  76155. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76156. {
  76157. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76158. }
  76159. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76160. {
  76161. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76162. | absoluteFromParentBottomRight
  76163. | absoluteFromParentCentre
  76164. | proportionOfParentSize));
  76165. }
  76166. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76167. {
  76168. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76169. }
  76170. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76171. {
  76172. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76173. | absoluteFromParentBottomRight
  76174. | absoluteFromParentCentre
  76175. | proportionOfParentSize));
  76176. }
  76177. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76178. {
  76179. return (SizeMode) wMode;
  76180. }
  76181. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76182. {
  76183. return (SizeMode) hMode;
  76184. }
  76185. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76186. const PositionMode xMode_,
  76187. const AnchorPoint yAnchor,
  76188. const PositionMode yMode_,
  76189. const SizeMode widthMode,
  76190. const SizeMode heightMode,
  76191. const Rectangle<int>& target) throw()
  76192. {
  76193. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76194. {
  76195. double tx, tw;
  76196. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76197. xMode = (uint8) (xAnchor | xMode_);
  76198. wMode = (uint8) widthMode;
  76199. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76200. }
  76201. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76202. {
  76203. double ty, th;
  76204. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76205. yMode = (uint8) (yAnchor | yMode_);
  76206. hMode = (uint8) heightMode;
  76207. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76208. }
  76209. }
  76210. bool PositionedRectangle::isPositionAbsolute() const throw()
  76211. {
  76212. return xMode == absoluteFromParentTopLeft
  76213. && yMode == absoluteFromParentTopLeft
  76214. && wMode == absoluteSize
  76215. && hMode == absoluteSize;
  76216. }
  76217. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76218. {
  76219. if ((mode & proportionOfParentSize) != 0)
  76220. {
  76221. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76222. }
  76223. else
  76224. {
  76225. s << (roundToInt (value * 100.0) / 100.0);
  76226. if ((mode & absoluteFromParentBottomRight) != 0)
  76227. s << 'R';
  76228. else if ((mode & absoluteFromParentCentre) != 0)
  76229. s << 'C';
  76230. }
  76231. if ((mode & anchorAtRightOrBottom) != 0)
  76232. s << 'r';
  76233. else if ((mode & anchorAtCentre) != 0)
  76234. s << 'c';
  76235. }
  76236. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76237. {
  76238. if (mode == proportionalSize)
  76239. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76240. else if (mode == parentSizeMinusAbsolute)
  76241. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76242. else
  76243. s << (roundToInt (value * 100.0) / 100.0);
  76244. }
  76245. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76246. {
  76247. if (s.containsChar ('r'))
  76248. mode = anchorAtRightOrBottom;
  76249. else if (s.containsChar ('c'))
  76250. mode = anchorAtCentre;
  76251. else
  76252. mode = anchorAtLeftOrTop;
  76253. if (s.containsChar ('%'))
  76254. {
  76255. mode |= proportionOfParentSize;
  76256. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76257. }
  76258. else
  76259. {
  76260. if (s.containsChar ('R'))
  76261. mode |= absoluteFromParentBottomRight;
  76262. else if (s.containsChar ('C'))
  76263. mode |= absoluteFromParentCentre;
  76264. else
  76265. mode |= absoluteFromParentTopLeft;
  76266. value = s.removeCharacters ("rcRC").getDoubleValue();
  76267. }
  76268. }
  76269. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76270. {
  76271. if (s.containsChar ('%'))
  76272. {
  76273. mode = proportionalSize;
  76274. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76275. }
  76276. else if (s.containsChar ('M'))
  76277. {
  76278. mode = parentSizeMinusAbsolute;
  76279. value = s.getDoubleValue();
  76280. }
  76281. else
  76282. {
  76283. mode = absoluteSize;
  76284. value = s.getDoubleValue();
  76285. }
  76286. }
  76287. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76288. const double x_, const double w_,
  76289. const uint8 xMode_, const uint8 wMode_,
  76290. const int parentPos,
  76291. const int parentSize) const throw()
  76292. {
  76293. if (wMode_ == proportionalSize)
  76294. wOut = roundToInt (w_ * parentSize);
  76295. else if (wMode_ == parentSizeMinusAbsolute)
  76296. wOut = jmax (0, parentSize - roundToInt (w_));
  76297. else
  76298. wOut = roundToInt (w_);
  76299. if ((xMode_ & proportionOfParentSize) != 0)
  76300. xOut = parentPos + x_ * parentSize;
  76301. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76302. xOut = (parentPos + parentSize) - x_;
  76303. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76304. xOut = x_ + (parentPos + parentSize / 2);
  76305. else
  76306. xOut = x_ + parentPos;
  76307. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76308. xOut -= wOut;
  76309. else if ((xMode_ & anchorAtCentre) != 0)
  76310. xOut -= wOut / 2;
  76311. }
  76312. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76313. double x_, const double w_,
  76314. const uint8 xMode_, const uint8 wMode_,
  76315. const int parentPos,
  76316. const int parentSize) const throw()
  76317. {
  76318. if (wMode_ == proportionalSize)
  76319. {
  76320. if (parentSize > 0)
  76321. wOut = w_ / parentSize;
  76322. }
  76323. else if (wMode_ == parentSizeMinusAbsolute)
  76324. wOut = parentSize - w_;
  76325. else
  76326. wOut = w_;
  76327. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76328. x_ += w_;
  76329. else if ((xMode_ & anchorAtCentre) != 0)
  76330. x_ += w_ / 2;
  76331. if ((xMode_ & proportionOfParentSize) != 0)
  76332. {
  76333. if (parentSize > 0)
  76334. xOut = (x_ - parentPos) / parentSize;
  76335. }
  76336. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76337. xOut = (parentPos + parentSize) - x_;
  76338. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76339. xOut = x_ - (parentPos + parentSize / 2);
  76340. else
  76341. xOut = x_ - parentPos;
  76342. }
  76343. END_JUCE_NAMESPACE
  76344. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76345. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76346. BEGIN_JUCE_NAMESPACE
  76347. RectangleList::RectangleList() throw()
  76348. {
  76349. }
  76350. RectangleList::RectangleList (const Rectangle<int>& rect)
  76351. {
  76352. if (! rect.isEmpty())
  76353. rects.add (rect);
  76354. }
  76355. RectangleList::RectangleList (const RectangleList& other)
  76356. : rects (other.rects)
  76357. {
  76358. }
  76359. RectangleList& RectangleList::operator= (const RectangleList& other)
  76360. {
  76361. rects = other.rects;
  76362. return *this;
  76363. }
  76364. RectangleList::~RectangleList()
  76365. {
  76366. }
  76367. void RectangleList::clear()
  76368. {
  76369. rects.clearQuick();
  76370. }
  76371. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76372. {
  76373. if (((unsigned int) index) < (unsigned int) rects.size())
  76374. return rects.getReference (index);
  76375. return Rectangle<int>();
  76376. }
  76377. bool RectangleList::isEmpty() const throw()
  76378. {
  76379. return rects.size() == 0;
  76380. }
  76381. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76382. : current (0),
  76383. owner (list),
  76384. index (list.rects.size())
  76385. {
  76386. }
  76387. RectangleList::Iterator::~Iterator()
  76388. {
  76389. }
  76390. bool RectangleList::Iterator::next() throw()
  76391. {
  76392. if (--index >= 0)
  76393. {
  76394. current = & (owner.rects.getReference (index));
  76395. return true;
  76396. }
  76397. return false;
  76398. }
  76399. void RectangleList::add (const Rectangle<int>& rect)
  76400. {
  76401. if (! rect.isEmpty())
  76402. {
  76403. if (rects.size() == 0)
  76404. {
  76405. rects.add (rect);
  76406. }
  76407. else
  76408. {
  76409. bool anyOverlaps = false;
  76410. int i;
  76411. for (i = rects.size(); --i >= 0;)
  76412. {
  76413. Rectangle<int>& ourRect = rects.getReference (i);
  76414. if (rect.intersects (ourRect))
  76415. {
  76416. if (rect.contains (ourRect))
  76417. rects.remove (i);
  76418. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76419. anyOverlaps = true;
  76420. }
  76421. }
  76422. if (anyOverlaps && rects.size() > 0)
  76423. {
  76424. RectangleList r (rect);
  76425. for (i = rects.size(); --i >= 0;)
  76426. {
  76427. const Rectangle<int>& ourRect = rects.getReference (i);
  76428. if (rect.intersects (ourRect))
  76429. {
  76430. r.subtract (ourRect);
  76431. if (r.rects.size() == 0)
  76432. return;
  76433. }
  76434. }
  76435. for (i = r.getNumRectangles(); --i >= 0;)
  76436. rects.add (r.rects.getReference (i));
  76437. }
  76438. else
  76439. {
  76440. rects.add (rect);
  76441. }
  76442. }
  76443. }
  76444. }
  76445. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76446. {
  76447. if (! rect.isEmpty())
  76448. rects.add (rect);
  76449. }
  76450. void RectangleList::add (const int x, const int y, const int w, const int h)
  76451. {
  76452. if (rects.size() == 0)
  76453. {
  76454. if (w > 0 && h > 0)
  76455. rects.add (Rectangle<int> (x, y, w, h));
  76456. }
  76457. else
  76458. {
  76459. add (Rectangle<int> (x, y, w, h));
  76460. }
  76461. }
  76462. void RectangleList::add (const RectangleList& other)
  76463. {
  76464. for (int i = 0; i < other.rects.size(); ++i)
  76465. add (other.rects.getReference (i));
  76466. }
  76467. void RectangleList::subtract (const Rectangle<int>& rect)
  76468. {
  76469. const int originalNumRects = rects.size();
  76470. if (originalNumRects > 0)
  76471. {
  76472. const int x1 = rect.x;
  76473. const int y1 = rect.y;
  76474. const int x2 = x1 + rect.w;
  76475. const int y2 = y1 + rect.h;
  76476. for (int i = getNumRectangles(); --i >= 0;)
  76477. {
  76478. Rectangle<int>& r = rects.getReference (i);
  76479. const int rx1 = r.x;
  76480. const int ry1 = r.y;
  76481. const int rx2 = rx1 + r.w;
  76482. const int ry2 = ry1 + r.h;
  76483. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76484. {
  76485. if (x1 > rx1 && x1 < rx2)
  76486. {
  76487. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76488. {
  76489. r.w = x1 - rx1;
  76490. }
  76491. else
  76492. {
  76493. r.x = x1;
  76494. r.w = rx2 - x1;
  76495. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76496. i += 2;
  76497. }
  76498. }
  76499. else if (x2 > rx1 && x2 < rx2)
  76500. {
  76501. r.x = x2;
  76502. r.w = rx2 - x2;
  76503. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76504. {
  76505. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76506. i += 2;
  76507. }
  76508. }
  76509. else if (y1 > ry1 && y1 < ry2)
  76510. {
  76511. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76512. {
  76513. r.h = y1 - ry1;
  76514. }
  76515. else
  76516. {
  76517. r.y = y1;
  76518. r.h = ry2 - y1;
  76519. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76520. i += 2;
  76521. }
  76522. }
  76523. else if (y2 > ry1 && y2 < ry2)
  76524. {
  76525. r.y = y2;
  76526. r.h = ry2 - y2;
  76527. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76528. {
  76529. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76530. i += 2;
  76531. }
  76532. }
  76533. else
  76534. {
  76535. rects.remove (i);
  76536. }
  76537. }
  76538. }
  76539. }
  76540. }
  76541. bool RectangleList::subtract (const RectangleList& otherList)
  76542. {
  76543. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76544. subtract (otherList.rects.getReference (i));
  76545. return rects.size() > 0;
  76546. }
  76547. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76548. {
  76549. bool notEmpty = false;
  76550. if (rect.isEmpty())
  76551. {
  76552. clear();
  76553. }
  76554. else
  76555. {
  76556. for (int i = rects.size(); --i >= 0;)
  76557. {
  76558. Rectangle<int>& r = rects.getReference (i);
  76559. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76560. rects.remove (i);
  76561. else
  76562. notEmpty = true;
  76563. }
  76564. }
  76565. return notEmpty;
  76566. }
  76567. bool RectangleList::clipTo (const RectangleList& other)
  76568. {
  76569. if (rects.size() == 0)
  76570. return false;
  76571. RectangleList result;
  76572. for (int j = 0; j < rects.size(); ++j)
  76573. {
  76574. const Rectangle<int>& rect = rects.getReference (j);
  76575. for (int i = other.rects.size(); --i >= 0;)
  76576. {
  76577. Rectangle<int> r (other.rects.getReference (i));
  76578. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76579. result.rects.add (r);
  76580. }
  76581. }
  76582. swapWith (result);
  76583. return ! isEmpty();
  76584. }
  76585. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76586. {
  76587. destRegion.clear();
  76588. if (! rect.isEmpty())
  76589. {
  76590. for (int i = rects.size(); --i >= 0;)
  76591. {
  76592. Rectangle<int> r (rects.getReference (i));
  76593. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76594. destRegion.rects.add (r);
  76595. }
  76596. }
  76597. return destRegion.rects.size() > 0;
  76598. }
  76599. void RectangleList::swapWith (RectangleList& otherList) throw()
  76600. {
  76601. rects.swapWithArray (otherList.rects);
  76602. }
  76603. void RectangleList::consolidate()
  76604. {
  76605. int i;
  76606. for (i = 0; i < getNumRectangles() - 1; ++i)
  76607. {
  76608. Rectangle<int>& r = rects.getReference (i);
  76609. const int rx1 = r.x;
  76610. const int ry1 = r.y;
  76611. const int rx2 = rx1 + r.w;
  76612. const int ry2 = ry1 + r.h;
  76613. for (int j = rects.size(); --j > i;)
  76614. {
  76615. Rectangle<int>& r2 = rects.getReference (j);
  76616. const int jrx1 = r2.x;
  76617. const int jry1 = r2.y;
  76618. const int jrx2 = jrx1 + r2.w;
  76619. const int jry2 = jry1 + r2.h;
  76620. // if the vertical edges of any blocks are touching and their horizontals don't
  76621. // line up, split them horizontally..
  76622. if (jrx1 == rx2 || jrx2 == rx1)
  76623. {
  76624. if (jry1 > ry1 && jry1 < ry2)
  76625. {
  76626. r.h = jry1 - ry1;
  76627. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76628. i = -1;
  76629. break;
  76630. }
  76631. if (jry2 > ry1 && jry2 < ry2)
  76632. {
  76633. r.h = jry2 - ry1;
  76634. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76635. i = -1;
  76636. break;
  76637. }
  76638. else if (ry1 > jry1 && ry1 < jry2)
  76639. {
  76640. r2.h = ry1 - jry1;
  76641. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76642. i = -1;
  76643. break;
  76644. }
  76645. else if (ry2 > jry1 && ry2 < jry2)
  76646. {
  76647. r2.h = ry2 - jry1;
  76648. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76649. i = -1;
  76650. break;
  76651. }
  76652. }
  76653. }
  76654. }
  76655. for (i = 0; i < rects.size() - 1; ++i)
  76656. {
  76657. Rectangle<int>& r = rects.getReference (i);
  76658. for (int j = rects.size(); --j > i;)
  76659. {
  76660. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76661. {
  76662. rects.remove (j);
  76663. i = -1;
  76664. break;
  76665. }
  76666. }
  76667. }
  76668. }
  76669. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76670. {
  76671. for (int i = getNumRectangles(); --i >= 0;)
  76672. if (rects.getReference (i).contains (x, y))
  76673. return true;
  76674. return false;
  76675. }
  76676. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76677. {
  76678. if (rects.size() > 1)
  76679. {
  76680. RectangleList r (rectangleToCheck);
  76681. for (int i = rects.size(); --i >= 0;)
  76682. {
  76683. r.subtract (rects.getReference (i));
  76684. if (r.rects.size() == 0)
  76685. return true;
  76686. }
  76687. }
  76688. else if (rects.size() > 0)
  76689. {
  76690. return rects.getReference (0).contains (rectangleToCheck);
  76691. }
  76692. return false;
  76693. }
  76694. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76695. {
  76696. for (int i = rects.size(); --i >= 0;)
  76697. if (rects.getReference (i).intersects (rectangleToCheck))
  76698. return true;
  76699. return false;
  76700. }
  76701. bool RectangleList::intersects (const RectangleList& other) const throw()
  76702. {
  76703. for (int i = rects.size(); --i >= 0;)
  76704. if (other.intersectsRectangle (rects.getReference (i)))
  76705. return true;
  76706. return false;
  76707. }
  76708. const Rectangle<int> RectangleList::getBounds() const throw()
  76709. {
  76710. if (rects.size() <= 1)
  76711. {
  76712. if (rects.size() == 0)
  76713. return Rectangle<int>();
  76714. else
  76715. return rects.getReference (0);
  76716. }
  76717. else
  76718. {
  76719. const Rectangle<int>& r = rects.getReference (0);
  76720. int minX = r.x;
  76721. int minY = r.y;
  76722. int maxX = minX + r.w;
  76723. int maxY = minY + r.h;
  76724. for (int i = rects.size(); --i > 0;)
  76725. {
  76726. const Rectangle<int>& r2 = rects.getReference (i);
  76727. minX = jmin (minX, r2.x);
  76728. minY = jmin (minY, r2.y);
  76729. maxX = jmax (maxX, r2.getRight());
  76730. maxY = jmax (maxY, r2.getBottom());
  76731. }
  76732. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76733. }
  76734. }
  76735. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76736. {
  76737. for (int i = rects.size(); --i >= 0;)
  76738. {
  76739. Rectangle<int>& r = rects.getReference (i);
  76740. r.x += dx;
  76741. r.y += dy;
  76742. }
  76743. }
  76744. const Path RectangleList::toPath() const
  76745. {
  76746. Path p;
  76747. for (int i = rects.size(); --i >= 0;)
  76748. {
  76749. const Rectangle<int>& r = rects.getReference (i);
  76750. p.addRectangle ((float) r.x,
  76751. (float) r.y,
  76752. (float) r.w,
  76753. (float) r.h);
  76754. }
  76755. return p;
  76756. }
  76757. END_JUCE_NAMESPACE
  76758. /*** End of inlined file: juce_RectangleList.cpp ***/
  76759. /*** Start of inlined file: juce_Image.cpp ***/
  76760. BEGIN_JUCE_NAMESPACE
  76761. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76762. : format (format_), width (width_), height (height_)
  76763. {
  76764. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76765. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76766. }
  76767. Image::SharedImage::~SharedImage()
  76768. {
  76769. }
  76770. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76771. {
  76772. return imageData + lineStride * y + pixelStride * x;
  76773. }
  76774. class SoftwareSharedImage : public Image::SharedImage
  76775. {
  76776. public:
  76777. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76778. : Image::SharedImage (format_, width_, height_)
  76779. {
  76780. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76781. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76782. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76783. imageData = imageDataAllocated;
  76784. }
  76785. ~SoftwareSharedImage()
  76786. {
  76787. }
  76788. Image::ImageType getType() const
  76789. {
  76790. return Image::SoftwareImage;
  76791. }
  76792. LowLevelGraphicsContext* createLowLevelContext()
  76793. {
  76794. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76795. }
  76796. SharedImage* clone()
  76797. {
  76798. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76799. memcpy (s->imageData, imageData, lineStride * height);
  76800. return s;
  76801. }
  76802. private:
  76803. HeapBlock<uint8> imageDataAllocated;
  76804. };
  76805. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76806. {
  76807. return new SoftwareSharedImage (format, width, height, clearImage);
  76808. }
  76809. class SubsectionSharedImage : public Image::SharedImage
  76810. {
  76811. public:
  76812. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76813. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76814. image (image_), area (area_)
  76815. {
  76816. pixelStride = image_->getPixelStride();
  76817. lineStride = image_->getLineStride();
  76818. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76819. }
  76820. ~SubsectionSharedImage() {}
  76821. Image::ImageType getType() const
  76822. {
  76823. return Image::SoftwareImage;
  76824. }
  76825. LowLevelGraphicsContext* createLowLevelContext()
  76826. {
  76827. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76828. g->clipToRectangle (area);
  76829. g->setOrigin (area.getX(), area.getY());
  76830. return g;
  76831. }
  76832. SharedImage* clone()
  76833. {
  76834. return new SubsectionSharedImage (image->clone(), area);
  76835. }
  76836. private:
  76837. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76838. const Rectangle<int> area;
  76839. SubsectionSharedImage (const SubsectionSharedImage&);
  76840. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76841. };
  76842. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76843. {
  76844. if (area.contains (getBounds()))
  76845. return *this;
  76846. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76847. if (validArea.isEmpty())
  76848. return Image::null;
  76849. return Image (new SubsectionSharedImage (image, validArea));
  76850. }
  76851. Image::Image()
  76852. {
  76853. }
  76854. Image::Image (SharedImage* const instance)
  76855. : image (instance)
  76856. {
  76857. }
  76858. Image::Image (const PixelFormat format,
  76859. const int width, const int height,
  76860. const bool clearImage, const ImageType type)
  76861. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76862. : new SoftwareSharedImage (format, width, height, clearImage))
  76863. {
  76864. }
  76865. Image::Image (const Image& other)
  76866. : image (other.image)
  76867. {
  76868. }
  76869. Image& Image::operator= (const Image& other)
  76870. {
  76871. image = other.image;
  76872. return *this;
  76873. }
  76874. Image::~Image()
  76875. {
  76876. }
  76877. const Image Image::null;
  76878. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76879. {
  76880. return image == 0 ? 0 : image->createLowLevelContext();
  76881. }
  76882. void Image::duplicateIfShared()
  76883. {
  76884. if (image != 0 && image->getReferenceCount() > 1)
  76885. image = image->clone();
  76886. }
  76887. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76888. {
  76889. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76890. return *this;
  76891. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76892. Graphics g (newImage);
  76893. g.setImageResamplingQuality (quality);
  76894. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76895. return newImage;
  76896. }
  76897. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76898. {
  76899. if (image == 0 || newFormat == image->format)
  76900. return *this;
  76901. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76902. if (newFormat == SingleChannel)
  76903. {
  76904. if (! hasAlphaChannel())
  76905. {
  76906. newImage.clear (getBounds(), Colours::black);
  76907. }
  76908. else
  76909. {
  76910. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76911. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76912. for (int y = 0; y < image->height; ++y)
  76913. {
  76914. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76915. uint8* dst = destData.getLinePointer (y);
  76916. for (int x = image->width; --x >= 0;)
  76917. {
  76918. *dst++ = src->getAlpha();
  76919. ++src;
  76920. }
  76921. }
  76922. }
  76923. }
  76924. else
  76925. {
  76926. if (hasAlphaChannel())
  76927. newImage.clear (getBounds());
  76928. Graphics g (newImage);
  76929. g.drawImageAt (*this, 0, 0);
  76930. }
  76931. return newImage;
  76932. }
  76933. const var Image::getTag() const
  76934. {
  76935. return image == 0 ? var::null : image->userTag;
  76936. }
  76937. void Image::setTag (const var& newTag)
  76938. {
  76939. if (image != 0)
  76940. image->userTag = newTag;
  76941. }
  76942. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76943. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76944. pixelFormat (image.getFormat()),
  76945. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76946. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76947. width (w),
  76948. height (h)
  76949. {
  76950. jassert (data != 0);
  76951. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76952. }
  76953. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76954. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76955. pixelFormat (image.getFormat()),
  76956. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76957. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76958. width (w),
  76959. height (h)
  76960. {
  76961. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76962. }
  76963. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76964. : data (image.image == 0 ? 0 : image.image->imageData),
  76965. pixelFormat (image.getFormat()),
  76966. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76967. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76968. width (image.getWidth()),
  76969. height (image.getHeight())
  76970. {
  76971. }
  76972. Image::BitmapData::~BitmapData()
  76973. {
  76974. }
  76975. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76976. {
  76977. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76978. const uint8* const pixel = getPixelPointer (x, y);
  76979. switch (pixelFormat)
  76980. {
  76981. case Image::ARGB:
  76982. {
  76983. PixelARGB p (*(const PixelARGB*) pixel);
  76984. p.unpremultiply();
  76985. return Colour (p.getARGB());
  76986. }
  76987. case Image::RGB:
  76988. return Colour (((const PixelRGB*) pixel)->getARGB());
  76989. case Image::SingleChannel:
  76990. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76991. default:
  76992. jassertfalse;
  76993. break;
  76994. }
  76995. return Colour();
  76996. }
  76997. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76998. {
  76999. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77000. uint8* const pixel = getPixelPointer (x, y);
  77001. const PixelARGB col (colour.getPixelARGB());
  77002. switch (pixelFormat)
  77003. {
  77004. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77005. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77006. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77007. default: jassertfalse; break;
  77008. }
  77009. }
  77010. void Image::setPixelData (int x, int y, int w, int h,
  77011. const uint8* const sourcePixelData, const int sourceLineStride)
  77012. {
  77013. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77014. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77015. {
  77016. const BitmapData dest (*this, x, y, w, h, true);
  77017. for (int i = 0; i < h; ++i)
  77018. {
  77019. memcpy (dest.getLinePointer(i),
  77020. sourcePixelData + sourceLineStride * i,
  77021. w * dest.pixelStride);
  77022. }
  77023. }
  77024. }
  77025. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77026. {
  77027. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77028. if (! clipped.isEmpty())
  77029. {
  77030. const PixelARGB col (colourToClearTo.getPixelARGB());
  77031. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77032. uint8* dest = destData.data;
  77033. int dh = clipped.getHeight();
  77034. while (--dh >= 0)
  77035. {
  77036. uint8* line = dest;
  77037. dest += destData.lineStride;
  77038. if (isARGB())
  77039. {
  77040. for (int x = clipped.getWidth(); --x >= 0;)
  77041. {
  77042. ((PixelARGB*) line)->set (col);
  77043. line += destData.pixelStride;
  77044. }
  77045. }
  77046. else if (isRGB())
  77047. {
  77048. for (int x = clipped.getWidth(); --x >= 0;)
  77049. {
  77050. ((PixelRGB*) line)->set (col);
  77051. line += destData.pixelStride;
  77052. }
  77053. }
  77054. else
  77055. {
  77056. for (int x = clipped.getWidth(); --x >= 0;)
  77057. {
  77058. *line = col.getAlpha();
  77059. line += destData.pixelStride;
  77060. }
  77061. }
  77062. }
  77063. }
  77064. }
  77065. const Colour Image::getPixelAt (const int x, const int y) const
  77066. {
  77067. if (((unsigned int) x) < (unsigned int) getWidth()
  77068. && ((unsigned int) y) < (unsigned int) getHeight())
  77069. {
  77070. const BitmapData srcData (*this, x, y, 1, 1);
  77071. return srcData.getPixelColour (0, 0);
  77072. }
  77073. return Colour();
  77074. }
  77075. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77076. {
  77077. if (((unsigned int) x) < (unsigned int) getWidth()
  77078. && ((unsigned int) y) < (unsigned int) getHeight())
  77079. {
  77080. const BitmapData destData (*this, x, y, 1, 1, true);
  77081. destData.setPixelColour (0, 0, colour);
  77082. }
  77083. }
  77084. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77085. {
  77086. if (((unsigned int) x) < (unsigned int) getWidth()
  77087. && ((unsigned int) y) < (unsigned int) getHeight()
  77088. && hasAlphaChannel())
  77089. {
  77090. const BitmapData destData (*this, x, y, 1, 1, true);
  77091. if (isARGB())
  77092. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77093. else
  77094. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77095. }
  77096. }
  77097. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77098. {
  77099. if (hasAlphaChannel())
  77100. {
  77101. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77102. if (isARGB())
  77103. {
  77104. for (int y = 0; y < destData.height; ++y)
  77105. {
  77106. uint8* p = destData.getLinePointer (y);
  77107. for (int x = 0; x < destData.width; ++x)
  77108. {
  77109. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77110. p += destData.pixelStride;
  77111. }
  77112. }
  77113. }
  77114. else
  77115. {
  77116. for (int y = 0; y < destData.height; ++y)
  77117. {
  77118. uint8* p = destData.getLinePointer (y);
  77119. for (int x = 0; x < destData.width; ++x)
  77120. {
  77121. *p = (uint8) (*p * amountToMultiplyBy);
  77122. p += destData.pixelStride;
  77123. }
  77124. }
  77125. }
  77126. }
  77127. else
  77128. {
  77129. jassertfalse; // can't do this without an alpha-channel!
  77130. }
  77131. }
  77132. void Image::desaturate()
  77133. {
  77134. if (isARGB() || isRGB())
  77135. {
  77136. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77137. if (isARGB())
  77138. {
  77139. for (int y = 0; y < destData.height; ++y)
  77140. {
  77141. uint8* p = destData.getLinePointer (y);
  77142. for (int x = 0; x < destData.width; ++x)
  77143. {
  77144. ((PixelARGB*) p)->desaturate();
  77145. p += destData.pixelStride;
  77146. }
  77147. }
  77148. }
  77149. else
  77150. {
  77151. for (int y = 0; y < destData.height; ++y)
  77152. {
  77153. uint8* p = destData.getLinePointer (y);
  77154. for (int x = 0; x < destData.width; ++x)
  77155. {
  77156. ((PixelRGB*) p)->desaturate();
  77157. p += destData.pixelStride;
  77158. }
  77159. }
  77160. }
  77161. }
  77162. }
  77163. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77164. {
  77165. if (hasAlphaChannel())
  77166. {
  77167. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77168. SparseSet<int> pixelsOnRow;
  77169. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77170. for (int y = 0; y < srcData.height; ++y)
  77171. {
  77172. pixelsOnRow.clear();
  77173. const uint8* lineData = srcData.getLinePointer (y);
  77174. if (isARGB())
  77175. {
  77176. for (int x = 0; x < srcData.width; ++x)
  77177. {
  77178. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77179. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77180. lineData += srcData.pixelStride;
  77181. }
  77182. }
  77183. else
  77184. {
  77185. for (int x = 0; x < srcData.width; ++x)
  77186. {
  77187. if (*lineData >= threshold)
  77188. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77189. lineData += srcData.pixelStride;
  77190. }
  77191. }
  77192. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77193. {
  77194. const Range<int> range (pixelsOnRow.getRange (i));
  77195. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77196. }
  77197. result.consolidate();
  77198. }
  77199. }
  77200. else
  77201. {
  77202. result.add (0, 0, getWidth(), getHeight());
  77203. }
  77204. }
  77205. void Image::moveImageSection (int dx, int dy,
  77206. int sx, int sy,
  77207. int w, int h)
  77208. {
  77209. if (dx < 0)
  77210. {
  77211. w += dx;
  77212. sx -= dx;
  77213. dx = 0;
  77214. }
  77215. if (dy < 0)
  77216. {
  77217. h += dy;
  77218. sy -= dy;
  77219. dy = 0;
  77220. }
  77221. if (sx < 0)
  77222. {
  77223. w += sx;
  77224. dx -= sx;
  77225. sx = 0;
  77226. }
  77227. if (sy < 0)
  77228. {
  77229. h += sy;
  77230. dy -= sy;
  77231. sy = 0;
  77232. }
  77233. const int minX = jmin (dx, sx);
  77234. const int minY = jmin (dy, sy);
  77235. w = jmin (w, getWidth() - jmax (sx, dx));
  77236. h = jmin (h, getHeight() - jmax (sy, dy));
  77237. if (w > 0 && h > 0)
  77238. {
  77239. const int maxX = jmax (dx, sx) + w;
  77240. const int maxY = jmax (dy, sy) + h;
  77241. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77242. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77243. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77244. const int lineSize = destData.pixelStride * w;
  77245. if (dy > sy)
  77246. {
  77247. while (--h >= 0)
  77248. {
  77249. const int offset = h * destData.lineStride;
  77250. memmove (dst + offset, src + offset, lineSize);
  77251. }
  77252. }
  77253. else if (dst != src)
  77254. {
  77255. while (--h >= 0)
  77256. {
  77257. memmove (dst, src, lineSize);
  77258. dst += destData.lineStride;
  77259. src += destData.lineStride;
  77260. }
  77261. }
  77262. }
  77263. }
  77264. END_JUCE_NAMESPACE
  77265. /*** End of inlined file: juce_Image.cpp ***/
  77266. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77267. BEGIN_JUCE_NAMESPACE
  77268. class ImageCache::Pimpl : public Timer,
  77269. public DeletedAtShutdown
  77270. {
  77271. public:
  77272. Pimpl()
  77273. : cacheTimeout (5000)
  77274. {
  77275. }
  77276. ~Pimpl()
  77277. {
  77278. clearSingletonInstance();
  77279. }
  77280. const Image getFromHashCode (const int64 hashCode)
  77281. {
  77282. const ScopedLock sl (lock);
  77283. for (int i = images.size(); --i >= 0;)
  77284. {
  77285. Item* const item = images.getUnchecked(i);
  77286. if (item->hashCode == hashCode)
  77287. return item->image;
  77288. }
  77289. return Image::null;
  77290. }
  77291. void addImageToCache (const Image& image, const int64 hashCode)
  77292. {
  77293. if (image.isValid())
  77294. {
  77295. if (! isTimerRunning())
  77296. startTimer (2000);
  77297. Item* const item = new Item();
  77298. item->hashCode = hashCode;
  77299. item->image = image;
  77300. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77301. const ScopedLock sl (lock);
  77302. images.add (item);
  77303. }
  77304. }
  77305. void timerCallback()
  77306. {
  77307. const uint32 now = Time::getApproximateMillisecondCounter();
  77308. const ScopedLock sl (lock);
  77309. for (int i = images.size(); --i >= 0;)
  77310. {
  77311. Item* const item = images.getUnchecked(i);
  77312. if (item->image.getReferenceCount() <= 1)
  77313. {
  77314. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77315. images.remove (i);
  77316. }
  77317. else
  77318. {
  77319. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77320. }
  77321. }
  77322. if (images.size() == 0)
  77323. stopTimer();
  77324. }
  77325. struct Item
  77326. {
  77327. Image image;
  77328. int64 hashCode;
  77329. uint32 lastUseTime;
  77330. };
  77331. int cacheTimeout;
  77332. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77333. private:
  77334. OwnedArray<Item> images;
  77335. CriticalSection lock;
  77336. Pimpl (const Pimpl&);
  77337. Pimpl& operator= (const Pimpl&);
  77338. };
  77339. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77340. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77341. {
  77342. if (Pimpl::getInstanceWithoutCreating() != 0)
  77343. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77344. return Image::null;
  77345. }
  77346. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77347. {
  77348. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77349. }
  77350. const Image ImageCache::getFromFile (const File& file)
  77351. {
  77352. const int64 hashCode = file.hashCode64();
  77353. Image image (getFromHashCode (hashCode));
  77354. if (image.isNull())
  77355. {
  77356. image = ImageFileFormat::loadFrom (file);
  77357. addImageToCache (image, hashCode);
  77358. }
  77359. return image;
  77360. }
  77361. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77362. {
  77363. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77364. Image image (getFromHashCode (hashCode));
  77365. if (image.isNull())
  77366. {
  77367. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77368. addImageToCache (image, hashCode);
  77369. }
  77370. return image;
  77371. }
  77372. void ImageCache::setCacheTimeout (const int millisecs)
  77373. {
  77374. Pimpl::getInstance()->cacheTimeout = millisecs;
  77375. }
  77376. END_JUCE_NAMESPACE
  77377. /*** End of inlined file: juce_ImageCache.cpp ***/
  77378. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77379. BEGIN_JUCE_NAMESPACE
  77380. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77381. : values (size_ * size_),
  77382. size (size_)
  77383. {
  77384. clear();
  77385. }
  77386. ImageConvolutionKernel::~ImageConvolutionKernel()
  77387. {
  77388. }
  77389. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77390. {
  77391. if (((unsigned int) x) < (unsigned int) size
  77392. && ((unsigned int) y) < (unsigned int) size)
  77393. {
  77394. return values [x + y * size];
  77395. }
  77396. else
  77397. {
  77398. jassertfalse;
  77399. return 0;
  77400. }
  77401. }
  77402. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77403. {
  77404. if (((unsigned int) x) < (unsigned int) size
  77405. && ((unsigned int) y) < (unsigned int) size)
  77406. {
  77407. values [x + y * size] = value;
  77408. }
  77409. else
  77410. {
  77411. jassertfalse;
  77412. }
  77413. }
  77414. void ImageConvolutionKernel::clear()
  77415. {
  77416. for (int i = size * size; --i >= 0;)
  77417. values[i] = 0;
  77418. }
  77419. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77420. {
  77421. double currentTotal = 0.0;
  77422. for (int i = size * size; --i >= 0;)
  77423. currentTotal += values[i];
  77424. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77425. }
  77426. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77427. {
  77428. for (int i = size * size; --i >= 0;)
  77429. values[i] *= multiplier;
  77430. }
  77431. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77432. {
  77433. const double radiusFactor = -1.0 / (radius * radius * 2);
  77434. const int centre = size >> 1;
  77435. for (int y = size; --y >= 0;)
  77436. {
  77437. for (int x = size; --x >= 0;)
  77438. {
  77439. const int cx = x - centre;
  77440. const int cy = y - centre;
  77441. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77442. }
  77443. }
  77444. setOverallSum (1.0f);
  77445. }
  77446. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77447. const Image& sourceImage,
  77448. const Rectangle<int>& destinationArea) const
  77449. {
  77450. if (sourceImage == destImage)
  77451. {
  77452. destImage.duplicateIfShared();
  77453. }
  77454. else
  77455. {
  77456. if (sourceImage.getWidth() != destImage.getWidth()
  77457. || sourceImage.getHeight() != destImage.getHeight()
  77458. || sourceImage.getFormat() != destImage.getFormat())
  77459. {
  77460. jassertfalse;
  77461. return;
  77462. }
  77463. }
  77464. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77465. if (area.isEmpty())
  77466. return;
  77467. const int right = area.getRight();
  77468. const int bottom = area.getBottom();
  77469. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77470. uint8* line = destData.data;
  77471. const Image::BitmapData srcData (sourceImage, false);
  77472. if (destData.pixelStride == 4)
  77473. {
  77474. for (int y = area.getY(); y < bottom; ++y)
  77475. {
  77476. uint8* dest = line;
  77477. line += destData.lineStride;
  77478. for (int x = area.getX(); x < right; ++x)
  77479. {
  77480. float c1 = 0;
  77481. float c2 = 0;
  77482. float c3 = 0;
  77483. float c4 = 0;
  77484. for (int yy = 0; yy < size; ++yy)
  77485. {
  77486. const int sy = y + yy - (size >> 1);
  77487. if (sy >= srcData.height)
  77488. break;
  77489. if (sy >= 0)
  77490. {
  77491. int sx = x - (size >> 1);
  77492. const uint8* src = srcData.getPixelPointer (sx, sy);
  77493. for (int xx = 0; xx < size; ++xx)
  77494. {
  77495. if (sx >= srcData.width)
  77496. break;
  77497. if (sx >= 0)
  77498. {
  77499. const float kernelMult = values [xx + yy * size];
  77500. c1 += kernelMult * *src++;
  77501. c2 += kernelMult * *src++;
  77502. c3 += kernelMult * *src++;
  77503. c4 += kernelMult * *src++;
  77504. }
  77505. else
  77506. {
  77507. src += 4;
  77508. }
  77509. ++sx;
  77510. }
  77511. }
  77512. }
  77513. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77514. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77515. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77516. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77517. }
  77518. }
  77519. }
  77520. else if (destData.pixelStride == 3)
  77521. {
  77522. for (int y = area.getY(); y < bottom; ++y)
  77523. {
  77524. uint8* dest = line;
  77525. line += destData.lineStride;
  77526. for (int x = area.getX(); x < right; ++x)
  77527. {
  77528. float c1 = 0;
  77529. float c2 = 0;
  77530. float c3 = 0;
  77531. for (int yy = 0; yy < size; ++yy)
  77532. {
  77533. const int sy = y + yy - (size >> 1);
  77534. if (sy >= srcData.height)
  77535. break;
  77536. if (sy >= 0)
  77537. {
  77538. int sx = x - (size >> 1);
  77539. const uint8* src = srcData.getPixelPointer (sx, sy);
  77540. for (int xx = 0; xx < size; ++xx)
  77541. {
  77542. if (sx >= srcData.width)
  77543. break;
  77544. if (sx >= 0)
  77545. {
  77546. const float kernelMult = values [xx + yy * size];
  77547. c1 += kernelMult * *src++;
  77548. c2 += kernelMult * *src++;
  77549. c3 += kernelMult * *src++;
  77550. }
  77551. else
  77552. {
  77553. src += 3;
  77554. }
  77555. ++sx;
  77556. }
  77557. }
  77558. }
  77559. *dest++ = (uint8) roundToInt (c1);
  77560. *dest++ = (uint8) roundToInt (c2);
  77561. *dest++ = (uint8) roundToInt (c3);
  77562. }
  77563. }
  77564. }
  77565. }
  77566. END_JUCE_NAMESPACE
  77567. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77568. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77569. BEGIN_JUCE_NAMESPACE
  77570. /*** Start of inlined file: juce_GIFLoader.h ***/
  77571. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  77572. #define __JUCE_GIFLOADER_JUCEHEADER__
  77573. #ifndef DOXYGEN
  77574. /**
  77575. Used internally by ImageFileFormat - don't use this class directly in your
  77576. application.
  77577. @see ImageFileFormat
  77578. */
  77579. class GIFLoader
  77580. {
  77581. public:
  77582. GIFLoader (InputStream& in);
  77583. ~GIFLoader();
  77584. const Image& getImage() const { return image; }
  77585. private:
  77586. Image image;
  77587. InputStream& input;
  77588. uint8 buffer [300];
  77589. uint8 palette [256][4];
  77590. bool dataBlockIsZero, fresh, finished;
  77591. int currentBit, lastBit, lastByteIndex;
  77592. int codeSize, setCodeSize;
  77593. int maxCode, maxCodeSize;
  77594. int firstcode, oldcode;
  77595. int clearCode, end_code;
  77596. enum { maxGifCode = 1 << 12 };
  77597. int table [2] [maxGifCode];
  77598. int stack [2 * maxGifCode];
  77599. int *sp;
  77600. bool getSizeFromHeader (int& width, int& height);
  77601. bool readPalette (const int numCols);
  77602. int readDataBlock (unsigned char* dest);
  77603. int processExtension (int type, int& transparent);
  77604. int readLZWByte (bool initialise, int input_code_size);
  77605. int getCode (int code_size, bool initialise);
  77606. bool readImage (int interlace, int transparent);
  77607. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77608. GIFLoader (const GIFLoader&);
  77609. GIFLoader& operator= (const GIFLoader&);
  77610. };
  77611. #endif // DOXYGEN
  77612. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  77613. /*** End of inlined file: juce_GIFLoader.h ***/
  77614. class GIFImageFormat : public ImageFileFormat
  77615. {
  77616. public:
  77617. GIFImageFormat() {}
  77618. ~GIFImageFormat() {}
  77619. const String getFormatName()
  77620. {
  77621. return "GIF";
  77622. }
  77623. bool canUnderstand (InputStream& in)
  77624. {
  77625. const int bytesNeeded = 4;
  77626. char header [bytesNeeded];
  77627. return (in.read (header, bytesNeeded) == bytesNeeded)
  77628. && header[0] == 'G'
  77629. && header[1] == 'I'
  77630. && header[2] == 'F';
  77631. }
  77632. const Image decodeImage (InputStream& in)
  77633. {
  77634. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77635. return loader->getImage();
  77636. }
  77637. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77638. {
  77639. return false;
  77640. }
  77641. };
  77642. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77643. {
  77644. static PNGImageFormat png;
  77645. static JPEGImageFormat jpg;
  77646. static GIFImageFormat gif;
  77647. ImageFileFormat* formats[4];
  77648. int numFormats = 0;
  77649. formats [numFormats++] = &png;
  77650. formats [numFormats++] = &jpg;
  77651. formats [numFormats++] = &gif;
  77652. const int64 streamPos = input.getPosition();
  77653. for (int i = 0; i < numFormats; ++i)
  77654. {
  77655. const bool found = formats[i]->canUnderstand (input);
  77656. input.setPosition (streamPos);
  77657. if (found)
  77658. return formats[i];
  77659. }
  77660. return 0;
  77661. }
  77662. const Image ImageFileFormat::loadFrom (InputStream& input)
  77663. {
  77664. ImageFileFormat* const format = findImageFormatForStream (input);
  77665. if (format != 0)
  77666. return format->decodeImage (input);
  77667. return Image::null;
  77668. }
  77669. const Image ImageFileFormat::loadFrom (const File& file)
  77670. {
  77671. InputStream* const in = file.createInputStream();
  77672. if (in != 0)
  77673. {
  77674. BufferedInputStream b (in, 8192, true);
  77675. return loadFrom (b);
  77676. }
  77677. return Image::null;
  77678. }
  77679. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77680. {
  77681. if (rawData != 0 && numBytes > 4)
  77682. {
  77683. MemoryInputStream stream (rawData, numBytes, false);
  77684. return loadFrom (stream);
  77685. }
  77686. return Image::null;
  77687. }
  77688. END_JUCE_NAMESPACE
  77689. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77690. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77691. BEGIN_JUCE_NAMESPACE
  77692. GIFLoader::GIFLoader (InputStream& in)
  77693. : input (in),
  77694. dataBlockIsZero (false),
  77695. fresh (false),
  77696. finished (false)
  77697. {
  77698. currentBit = lastBit = lastByteIndex = 0;
  77699. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77700. firstcode = oldcode = 0;
  77701. clearCode = end_code = 0;
  77702. int imageWidth, imageHeight;
  77703. int transparent = -1;
  77704. if (! getSizeFromHeader (imageWidth, imageHeight))
  77705. return;
  77706. if ((imageWidth <= 0) || (imageHeight <= 0))
  77707. return;
  77708. unsigned char buf [16];
  77709. if (in.read (buf, 3) != 3)
  77710. return;
  77711. int numColours = 2 << (buf[0] & 7);
  77712. if ((buf[0] & 0x80) != 0)
  77713. readPalette (numColours);
  77714. for (;;)
  77715. {
  77716. if (input.read (buf, 1) != 1)
  77717. break;
  77718. if (buf[0] == ';')
  77719. break;
  77720. if (buf[0] == '!')
  77721. {
  77722. if (input.read (buf, 1) != 1)
  77723. break;
  77724. if (processExtension (buf[0], transparent) < 0)
  77725. break;
  77726. continue;
  77727. }
  77728. if (buf[0] != ',')
  77729. continue;
  77730. if (input.read (buf, 9) != 9)
  77731. break;
  77732. imageWidth = makeWord (buf[4], buf[5]);
  77733. imageHeight = makeWord (buf[6], buf[7]);
  77734. numColours = 2 << (buf[8] & 7);
  77735. if ((buf[8] & 0x80) != 0)
  77736. if (! readPalette (numColours))
  77737. break;
  77738. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77739. imageWidth, imageHeight, (transparent >= 0));
  77740. readImage ((buf[8] & 0x40) != 0, transparent);
  77741. break;
  77742. }
  77743. }
  77744. GIFLoader::~GIFLoader()
  77745. {
  77746. }
  77747. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  77748. {
  77749. char b[8];
  77750. if (input.read (b, 6) == 6)
  77751. {
  77752. if ((strncmp ("GIF87a", b, 6) == 0)
  77753. || (strncmp ("GIF89a", b, 6) == 0))
  77754. {
  77755. if (input.read (b, 4) == 4)
  77756. {
  77757. w = makeWord (b[0], b[1]);
  77758. h = makeWord (b[2], b[3]);
  77759. return true;
  77760. }
  77761. }
  77762. }
  77763. return false;
  77764. }
  77765. bool GIFLoader::readPalette (const int numCols)
  77766. {
  77767. unsigned char rgb[4];
  77768. for (int i = 0; i < numCols; ++i)
  77769. {
  77770. input.read (rgb, 3);
  77771. palette [i][0] = rgb[0];
  77772. palette [i][1] = rgb[1];
  77773. palette [i][2] = rgb[2];
  77774. palette [i][3] = 0xff;
  77775. }
  77776. return true;
  77777. }
  77778. int GIFLoader::readDataBlock (unsigned char* const dest)
  77779. {
  77780. unsigned char n;
  77781. if (input.read (&n, 1) == 1)
  77782. {
  77783. dataBlockIsZero = (n == 0);
  77784. if (dataBlockIsZero || (input.read (dest, n) == n))
  77785. return n;
  77786. }
  77787. return -1;
  77788. }
  77789. int GIFLoader::processExtension (const int type, int& transparent)
  77790. {
  77791. unsigned char b [300];
  77792. int n = 0;
  77793. if (type == 0xf9)
  77794. {
  77795. n = readDataBlock (b);
  77796. if (n < 0)
  77797. return 1;
  77798. if ((b[0] & 0x1) != 0)
  77799. transparent = b[3];
  77800. }
  77801. do
  77802. {
  77803. n = readDataBlock (b);
  77804. }
  77805. while (n > 0);
  77806. return n;
  77807. }
  77808. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  77809. {
  77810. if (initialise)
  77811. {
  77812. currentBit = 0;
  77813. lastBit = 0;
  77814. finished = false;
  77815. return 0;
  77816. }
  77817. if ((currentBit + codeSize_) >= lastBit)
  77818. {
  77819. if (finished)
  77820. return -1;
  77821. buffer[0] = buffer [lastByteIndex - 2];
  77822. buffer[1] = buffer [lastByteIndex - 1];
  77823. const int n = readDataBlock (&buffer[2]);
  77824. if (n == 0)
  77825. finished = true;
  77826. lastByteIndex = 2 + n;
  77827. currentBit = (currentBit - lastBit) + 16;
  77828. lastBit = (2 + n) * 8 ;
  77829. }
  77830. int result = 0;
  77831. int i = currentBit;
  77832. for (int j = 0; j < codeSize_; ++j)
  77833. {
  77834. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77835. ++i;
  77836. }
  77837. currentBit += codeSize_;
  77838. return result;
  77839. }
  77840. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  77841. {
  77842. int code, incode, i;
  77843. if (initialise)
  77844. {
  77845. setCodeSize = inputCodeSize;
  77846. codeSize = setCodeSize + 1;
  77847. clearCode = 1 << setCodeSize;
  77848. end_code = clearCode + 1;
  77849. maxCodeSize = 2 * clearCode;
  77850. maxCode = clearCode + 2;
  77851. getCode (0, true);
  77852. fresh = true;
  77853. for (i = 0; i < clearCode; ++i)
  77854. {
  77855. table[0][i] = 0;
  77856. table[1][i] = i;
  77857. }
  77858. for (; i < maxGifCode; ++i)
  77859. {
  77860. table[0][i] = 0;
  77861. table[1][i] = 0;
  77862. }
  77863. sp = stack;
  77864. return 0;
  77865. }
  77866. else if (fresh)
  77867. {
  77868. fresh = false;
  77869. do
  77870. {
  77871. firstcode = oldcode
  77872. = getCode (codeSize, false);
  77873. }
  77874. while (firstcode == clearCode);
  77875. return firstcode;
  77876. }
  77877. if (sp > stack)
  77878. return *--sp;
  77879. while ((code = getCode (codeSize, false)) >= 0)
  77880. {
  77881. if (code == clearCode)
  77882. {
  77883. for (i = 0; i < clearCode; ++i)
  77884. {
  77885. table[0][i] = 0;
  77886. table[1][i] = i;
  77887. }
  77888. for (; i < maxGifCode; ++i)
  77889. {
  77890. table[0][i] = 0;
  77891. table[1][i] = 0;
  77892. }
  77893. codeSize = setCodeSize + 1;
  77894. maxCodeSize = 2 * clearCode;
  77895. maxCode = clearCode + 2;
  77896. sp = stack;
  77897. firstcode = oldcode = getCode (codeSize, false);
  77898. return firstcode;
  77899. }
  77900. else if (code == end_code)
  77901. {
  77902. if (dataBlockIsZero)
  77903. return -2;
  77904. unsigned char buf [260];
  77905. int n;
  77906. while ((n = readDataBlock (buf)) > 0)
  77907. {}
  77908. if (n != 0)
  77909. return -2;
  77910. }
  77911. incode = code;
  77912. if (code >= maxCode)
  77913. {
  77914. *sp++ = firstcode;
  77915. code = oldcode;
  77916. }
  77917. while (code >= clearCode)
  77918. {
  77919. *sp++ = table[1][code];
  77920. if (code == table[0][code])
  77921. return -2;
  77922. code = table[0][code];
  77923. }
  77924. *sp++ = firstcode = table[1][code];
  77925. if ((code = maxCode) < maxGifCode)
  77926. {
  77927. table[0][code] = oldcode;
  77928. table[1][code] = firstcode;
  77929. ++maxCode;
  77930. if ((maxCode >= maxCodeSize)
  77931. && (maxCodeSize < maxGifCode))
  77932. {
  77933. maxCodeSize <<= 1;
  77934. ++codeSize;
  77935. }
  77936. }
  77937. oldcode = incode;
  77938. if (sp > stack)
  77939. return *--sp;
  77940. }
  77941. return code;
  77942. }
  77943. bool GIFLoader::readImage (const int interlace, const int transparent)
  77944. {
  77945. unsigned char c;
  77946. if (input.read (&c, 1) != 1
  77947. || readLZWByte (true, c) < 0)
  77948. return false;
  77949. if (transparent >= 0)
  77950. {
  77951. palette [transparent][0] = 0;
  77952. palette [transparent][1] = 0;
  77953. palette [transparent][2] = 0;
  77954. palette [transparent][3] = 0;
  77955. }
  77956. int index;
  77957. int xpos = 0, ypos = 0, pass = 0;
  77958. const Image::BitmapData destData (image, true);
  77959. uint8* p = destData.data;
  77960. const bool hasAlpha = image.hasAlphaChannel();
  77961. while ((index = readLZWByte (false, c)) >= 0)
  77962. {
  77963. const uint8* const paletteEntry = palette [index];
  77964. if (hasAlpha)
  77965. {
  77966. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77967. paletteEntry[0],
  77968. paletteEntry[1],
  77969. paletteEntry[2]);
  77970. ((PixelARGB*) p)->premultiply();
  77971. }
  77972. else
  77973. {
  77974. ((PixelRGB*) p)->setARGB (0,
  77975. paletteEntry[0],
  77976. paletteEntry[1],
  77977. paletteEntry[2]);
  77978. }
  77979. p += destData.pixelStride;
  77980. ++xpos;
  77981. if (xpos == destData.width)
  77982. {
  77983. xpos = 0;
  77984. if (interlace)
  77985. {
  77986. switch (pass)
  77987. {
  77988. case 0:
  77989. case 1: ypos += 8; break;
  77990. case 2: ypos += 4; break;
  77991. case 3: ypos += 2; break;
  77992. }
  77993. while (ypos >= destData.height)
  77994. {
  77995. ++pass;
  77996. switch (pass)
  77997. {
  77998. case 1: ypos = 4; break;
  77999. case 2: ypos = 2; break;
  78000. case 3: ypos = 1; break;
  78001. default: return true;
  78002. }
  78003. }
  78004. }
  78005. else
  78006. {
  78007. ++ypos;
  78008. }
  78009. p = destData.getPixelPointer (xpos, ypos);
  78010. }
  78011. if (ypos >= destData.height)
  78012. break;
  78013. }
  78014. return true;
  78015. }
  78016. END_JUCE_NAMESPACE
  78017. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78018. #endif
  78019. //==============================================================================
  78020. // some files include lots of library code, so leave them to the end to avoid cluttering
  78021. // up the build for the clean files.
  78022. #if JUCE_BUILD_CORE
  78023. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78024. namespace zlibNamespace
  78025. {
  78026. #if JUCE_INCLUDE_ZLIB_CODE
  78027. #undef OS_CODE
  78028. #undef fdopen
  78029. /*** Start of inlined file: zlib.h ***/
  78030. #ifndef ZLIB_H
  78031. #define ZLIB_H
  78032. /*** Start of inlined file: zconf.h ***/
  78033. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78034. #ifndef ZCONF_H
  78035. #define ZCONF_H
  78036. // *** Just a few hacks here to make it compile nicely with Juce..
  78037. #define Z_PREFIX 1
  78038. #undef __MACTYPES__
  78039. #ifdef _MSC_VER
  78040. #pragma warning (disable : 4131 4127 4244 4267)
  78041. #endif
  78042. /*
  78043. * If you *really* need a unique prefix for all types and library functions,
  78044. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78045. */
  78046. #ifdef Z_PREFIX
  78047. # define deflateInit_ z_deflateInit_
  78048. # define deflate z_deflate
  78049. # define deflateEnd z_deflateEnd
  78050. # define inflateInit_ z_inflateInit_
  78051. # define inflate z_inflate
  78052. # define inflateEnd z_inflateEnd
  78053. # define inflatePrime z_inflatePrime
  78054. # define inflateGetHeader z_inflateGetHeader
  78055. # define adler32_combine z_adler32_combine
  78056. # define crc32_combine z_crc32_combine
  78057. # define deflateInit2_ z_deflateInit2_
  78058. # define deflateSetDictionary z_deflateSetDictionary
  78059. # define deflateCopy z_deflateCopy
  78060. # define deflateReset z_deflateReset
  78061. # define deflateParams z_deflateParams
  78062. # define deflateBound z_deflateBound
  78063. # define deflatePrime z_deflatePrime
  78064. # define inflateInit2_ z_inflateInit2_
  78065. # define inflateSetDictionary z_inflateSetDictionary
  78066. # define inflateSync z_inflateSync
  78067. # define inflateSyncPoint z_inflateSyncPoint
  78068. # define inflateCopy z_inflateCopy
  78069. # define inflateReset z_inflateReset
  78070. # define inflateBack z_inflateBack
  78071. # define inflateBackEnd z_inflateBackEnd
  78072. # define compress z_compress
  78073. # define compress2 z_compress2
  78074. # define compressBound z_compressBound
  78075. # define uncompress z_uncompress
  78076. # define adler32 z_adler32
  78077. # define crc32 z_crc32
  78078. # define get_crc_table z_get_crc_table
  78079. # define zError z_zError
  78080. # define alloc_func z_alloc_func
  78081. # define free_func z_free_func
  78082. # define in_func z_in_func
  78083. # define out_func z_out_func
  78084. # define Byte z_Byte
  78085. # define uInt z_uInt
  78086. # define uLong z_uLong
  78087. # define Bytef z_Bytef
  78088. # define charf z_charf
  78089. # define intf z_intf
  78090. # define uIntf z_uIntf
  78091. # define uLongf z_uLongf
  78092. # define voidpf z_voidpf
  78093. # define voidp z_voidp
  78094. #endif
  78095. #if defined(__MSDOS__) && !defined(MSDOS)
  78096. # define MSDOS
  78097. #endif
  78098. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78099. # define OS2
  78100. #endif
  78101. #if defined(_WINDOWS) && !defined(WINDOWS)
  78102. # define WINDOWS
  78103. #endif
  78104. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78105. # ifndef WIN32
  78106. # define WIN32
  78107. # endif
  78108. #endif
  78109. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78110. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78111. # ifndef SYS16BIT
  78112. # define SYS16BIT
  78113. # endif
  78114. # endif
  78115. #endif
  78116. /*
  78117. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78118. * than 64k bytes at a time (needed on systems with 16-bit int).
  78119. */
  78120. #ifdef SYS16BIT
  78121. # define MAXSEG_64K
  78122. #endif
  78123. #ifdef MSDOS
  78124. # define UNALIGNED_OK
  78125. #endif
  78126. #ifdef __STDC_VERSION__
  78127. # ifndef STDC
  78128. # define STDC
  78129. # endif
  78130. # if __STDC_VERSION__ >= 199901L
  78131. # ifndef STDC99
  78132. # define STDC99
  78133. # endif
  78134. # endif
  78135. #endif
  78136. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78137. # define STDC
  78138. #endif
  78139. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78140. # define STDC
  78141. #endif
  78142. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78143. # define STDC
  78144. #endif
  78145. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78146. # define STDC
  78147. #endif
  78148. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78149. # define STDC
  78150. #endif
  78151. #ifndef STDC
  78152. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78153. # define const /* note: need a more gentle solution here */
  78154. # endif
  78155. #endif
  78156. /* Some Mac compilers merge all .h files incorrectly: */
  78157. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78158. # define NO_DUMMY_DECL
  78159. #endif
  78160. /* Maximum value for memLevel in deflateInit2 */
  78161. #ifndef MAX_MEM_LEVEL
  78162. # ifdef MAXSEG_64K
  78163. # define MAX_MEM_LEVEL 8
  78164. # else
  78165. # define MAX_MEM_LEVEL 9
  78166. # endif
  78167. #endif
  78168. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78169. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78170. * created by gzip. (Files created by minigzip can still be extracted by
  78171. * gzip.)
  78172. */
  78173. #ifndef MAX_WBITS
  78174. # define MAX_WBITS 15 /* 32K LZ77 window */
  78175. #endif
  78176. /* The memory requirements for deflate are (in bytes):
  78177. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78178. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78179. plus a few kilobytes for small objects. For example, if you want to reduce
  78180. the default memory requirements from 256K to 128K, compile with
  78181. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78182. Of course this will generally degrade compression (there's no free lunch).
  78183. The memory requirements for inflate are (in bytes) 1 << windowBits
  78184. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78185. for small objects.
  78186. */
  78187. /* Type declarations */
  78188. #ifndef OF /* function prototypes */
  78189. # ifdef STDC
  78190. # define OF(args) args
  78191. # else
  78192. # define OF(args) ()
  78193. # endif
  78194. #endif
  78195. /* The following definitions for FAR are needed only for MSDOS mixed
  78196. * model programming (small or medium model with some far allocations).
  78197. * This was tested only with MSC; for other MSDOS compilers you may have
  78198. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78199. * just define FAR to be empty.
  78200. */
  78201. #ifdef SYS16BIT
  78202. # if defined(M_I86SM) || defined(M_I86MM)
  78203. /* MSC small or medium model */
  78204. # define SMALL_MEDIUM
  78205. # ifdef _MSC_VER
  78206. # define FAR _far
  78207. # else
  78208. # define FAR far
  78209. # endif
  78210. # endif
  78211. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78212. /* Turbo C small or medium model */
  78213. # define SMALL_MEDIUM
  78214. # ifdef __BORLANDC__
  78215. # define FAR _far
  78216. # else
  78217. # define FAR far
  78218. # endif
  78219. # endif
  78220. #endif
  78221. #if defined(WINDOWS) || defined(WIN32)
  78222. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78223. * This is not mandatory, but it offers a little performance increase.
  78224. */
  78225. # ifdef ZLIB_DLL
  78226. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78227. # ifdef ZLIB_INTERNAL
  78228. # define ZEXTERN extern __declspec(dllexport)
  78229. # else
  78230. # define ZEXTERN extern __declspec(dllimport)
  78231. # endif
  78232. # endif
  78233. # endif /* ZLIB_DLL */
  78234. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78235. * define ZLIB_WINAPI.
  78236. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78237. */
  78238. # ifdef ZLIB_WINAPI
  78239. # ifdef FAR
  78240. # undef FAR
  78241. # endif
  78242. # include <windows.h>
  78243. /* No need for _export, use ZLIB.DEF instead. */
  78244. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78245. # define ZEXPORT WINAPI
  78246. # ifdef WIN32
  78247. # define ZEXPORTVA WINAPIV
  78248. # else
  78249. # define ZEXPORTVA FAR CDECL
  78250. # endif
  78251. # endif
  78252. #endif
  78253. #if defined (__BEOS__)
  78254. # ifdef ZLIB_DLL
  78255. # ifdef ZLIB_INTERNAL
  78256. # define ZEXPORT __declspec(dllexport)
  78257. # define ZEXPORTVA __declspec(dllexport)
  78258. # else
  78259. # define ZEXPORT __declspec(dllimport)
  78260. # define ZEXPORTVA __declspec(dllimport)
  78261. # endif
  78262. # endif
  78263. #endif
  78264. #ifndef ZEXTERN
  78265. # define ZEXTERN extern
  78266. #endif
  78267. #ifndef ZEXPORT
  78268. # define ZEXPORT
  78269. #endif
  78270. #ifndef ZEXPORTVA
  78271. # define ZEXPORTVA
  78272. #endif
  78273. #ifndef FAR
  78274. # define FAR
  78275. #endif
  78276. #if !defined(__MACTYPES__)
  78277. typedef unsigned char Byte; /* 8 bits */
  78278. #endif
  78279. typedef unsigned int uInt; /* 16 bits or more */
  78280. typedef unsigned long uLong; /* 32 bits or more */
  78281. #ifdef SMALL_MEDIUM
  78282. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78283. # define Bytef Byte FAR
  78284. #else
  78285. typedef Byte FAR Bytef;
  78286. #endif
  78287. typedef char FAR charf;
  78288. typedef int FAR intf;
  78289. typedef uInt FAR uIntf;
  78290. typedef uLong FAR uLongf;
  78291. #ifdef STDC
  78292. typedef void const *voidpc;
  78293. typedef void FAR *voidpf;
  78294. typedef void *voidp;
  78295. #else
  78296. typedef Byte const *voidpc;
  78297. typedef Byte FAR *voidpf;
  78298. typedef Byte *voidp;
  78299. #endif
  78300. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78301. # include <sys/types.h> /* for off_t */
  78302. # include <unistd.h> /* for SEEK_* and off_t */
  78303. # ifdef VMS
  78304. # include <unixio.h> /* for off_t */
  78305. # endif
  78306. # define z_off_t off_t
  78307. #endif
  78308. #ifndef SEEK_SET
  78309. # define SEEK_SET 0 /* Seek from beginning of file. */
  78310. # define SEEK_CUR 1 /* Seek from current position. */
  78311. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78312. #endif
  78313. #ifndef z_off_t
  78314. # define z_off_t long
  78315. #endif
  78316. #if defined(__OS400__)
  78317. # define NO_vsnprintf
  78318. #endif
  78319. #if defined(__MVS__)
  78320. # define NO_vsnprintf
  78321. # ifdef FAR
  78322. # undef FAR
  78323. # endif
  78324. #endif
  78325. /* MVS linker does not support external names larger than 8 bytes */
  78326. #if defined(__MVS__)
  78327. # pragma map(deflateInit_,"DEIN")
  78328. # pragma map(deflateInit2_,"DEIN2")
  78329. # pragma map(deflateEnd,"DEEND")
  78330. # pragma map(deflateBound,"DEBND")
  78331. # pragma map(inflateInit_,"ININ")
  78332. # pragma map(inflateInit2_,"ININ2")
  78333. # pragma map(inflateEnd,"INEND")
  78334. # pragma map(inflateSync,"INSY")
  78335. # pragma map(inflateSetDictionary,"INSEDI")
  78336. # pragma map(compressBound,"CMBND")
  78337. # pragma map(inflate_table,"INTABL")
  78338. # pragma map(inflate_fast,"INFA")
  78339. # pragma map(inflate_copyright,"INCOPY")
  78340. #endif
  78341. #endif /* ZCONF_H */
  78342. /*** End of inlined file: zconf.h ***/
  78343. #ifdef __cplusplus
  78344. //extern "C" {
  78345. #endif
  78346. #define ZLIB_VERSION "1.2.3"
  78347. #define ZLIB_VERNUM 0x1230
  78348. /*
  78349. The 'zlib' compression library provides in-memory compression and
  78350. decompression functions, including integrity checks of the uncompressed
  78351. data. This version of the library supports only one compression method
  78352. (deflation) but other algorithms will be added later and will have the same
  78353. stream interface.
  78354. Compression can be done in a single step if the buffers are large
  78355. enough (for example if an input file is mmap'ed), or can be done by
  78356. repeated calls of the compression function. In the latter case, the
  78357. application must provide more input and/or consume the output
  78358. (providing more output space) before each call.
  78359. The compressed data format used by default by the in-memory functions is
  78360. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78361. around a deflate stream, which is itself documented in RFC 1951.
  78362. The library also supports reading and writing files in gzip (.gz) format
  78363. with an interface similar to that of stdio using the functions that start
  78364. with "gz". The gzip format is different from the zlib format. gzip is a
  78365. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78366. This library can optionally read and write gzip streams in memory as well.
  78367. The zlib format was designed to be compact and fast for use in memory
  78368. and on communications channels. The gzip format was designed for single-
  78369. file compression on file systems, has a larger header than zlib to maintain
  78370. directory information, and uses a different, slower check method than zlib.
  78371. The library does not install any signal handler. The decoder checks
  78372. the consistency of the compressed data, so the library should never
  78373. crash even in case of corrupted input.
  78374. */
  78375. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78376. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78377. struct internal_state;
  78378. typedef struct z_stream_s {
  78379. Bytef *next_in; /* next input byte */
  78380. uInt avail_in; /* number of bytes available at next_in */
  78381. uLong total_in; /* total nb of input bytes read so far */
  78382. Bytef *next_out; /* next output byte should be put there */
  78383. uInt avail_out; /* remaining free space at next_out */
  78384. uLong total_out; /* total nb of bytes output so far */
  78385. char *msg; /* last error message, NULL if no error */
  78386. struct internal_state FAR *state; /* not visible by applications */
  78387. alloc_func zalloc; /* used to allocate the internal state */
  78388. free_func zfree; /* used to free the internal state */
  78389. voidpf opaque; /* private data object passed to zalloc and zfree */
  78390. int data_type; /* best guess about the data type: binary or text */
  78391. uLong adler; /* adler32 value of the uncompressed data */
  78392. uLong reserved; /* reserved for future use */
  78393. } z_stream;
  78394. typedef z_stream FAR *z_streamp;
  78395. /*
  78396. gzip header information passed to and from zlib routines. See RFC 1952
  78397. for more details on the meanings of these fields.
  78398. */
  78399. typedef struct gz_header_s {
  78400. int text; /* true if compressed data believed to be text */
  78401. uLong time; /* modification time */
  78402. int xflags; /* extra flags (not used when writing a gzip file) */
  78403. int os; /* operating system */
  78404. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78405. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78406. uInt extra_max; /* space at extra (only when reading header) */
  78407. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78408. uInt name_max; /* space at name (only when reading header) */
  78409. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78410. uInt comm_max; /* space at comment (only when reading header) */
  78411. int hcrc; /* true if there was or will be a header crc */
  78412. int done; /* true when done reading gzip header (not used
  78413. when writing a gzip file) */
  78414. } gz_header;
  78415. typedef gz_header FAR *gz_headerp;
  78416. /*
  78417. The application must update next_in and avail_in when avail_in has
  78418. dropped to zero. It must update next_out and avail_out when avail_out
  78419. has dropped to zero. The application must initialize zalloc, zfree and
  78420. opaque before calling the init function. All other fields are set by the
  78421. compression library and must not be updated by the application.
  78422. The opaque value provided by the application will be passed as the first
  78423. parameter for calls of zalloc and zfree. This can be useful for custom
  78424. memory management. The compression library attaches no meaning to the
  78425. opaque value.
  78426. zalloc must return Z_NULL if there is not enough memory for the object.
  78427. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78428. thread safe.
  78429. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78430. exactly 65536 bytes, but will not be required to allocate more than this
  78431. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78432. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78433. have their offset normalized to zero. The default allocation function
  78434. provided by this library ensures this (see zutil.c). To reduce memory
  78435. requirements and avoid any allocation of 64K objects, at the expense of
  78436. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78437. The fields total_in and total_out can be used for statistics or
  78438. progress reports. After compression, total_in holds the total size of
  78439. the uncompressed data and may be saved for use in the decompressor
  78440. (particularly if the decompressor wants to decompress everything in
  78441. a single step).
  78442. */
  78443. /* constants */
  78444. #define Z_NO_FLUSH 0
  78445. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78446. #define Z_SYNC_FLUSH 2
  78447. #define Z_FULL_FLUSH 3
  78448. #define Z_FINISH 4
  78449. #define Z_BLOCK 5
  78450. /* Allowed flush values; see deflate() and inflate() below for details */
  78451. #define Z_OK 0
  78452. #define Z_STREAM_END 1
  78453. #define Z_NEED_DICT 2
  78454. #define Z_ERRNO (-1)
  78455. #define Z_STREAM_ERROR (-2)
  78456. #define Z_DATA_ERROR (-3)
  78457. #define Z_MEM_ERROR (-4)
  78458. #define Z_BUF_ERROR (-5)
  78459. #define Z_VERSION_ERROR (-6)
  78460. /* Return codes for the compression/decompression functions. Negative
  78461. * values are errors, positive values are used for special but normal events.
  78462. */
  78463. #define Z_NO_COMPRESSION 0
  78464. #define Z_BEST_SPEED 1
  78465. #define Z_BEST_COMPRESSION 9
  78466. #define Z_DEFAULT_COMPRESSION (-1)
  78467. /* compression levels */
  78468. #define Z_FILTERED 1
  78469. #define Z_HUFFMAN_ONLY 2
  78470. #define Z_RLE 3
  78471. #define Z_FIXED 4
  78472. #define Z_DEFAULT_STRATEGY 0
  78473. /* compression strategy; see deflateInit2() below for details */
  78474. #define Z_BINARY 0
  78475. #define Z_TEXT 1
  78476. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78477. #define Z_UNKNOWN 2
  78478. /* Possible values of the data_type field (though see inflate()) */
  78479. #define Z_DEFLATED 8
  78480. /* The deflate compression method (the only one supported in this version) */
  78481. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78482. #define zlib_version zlibVersion()
  78483. /* for compatibility with versions < 1.0.2 */
  78484. /* basic functions */
  78485. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78486. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78487. If the first character differs, the library code actually used is
  78488. not compatible with the zlib.h header file used by the application.
  78489. This check is automatically made by deflateInit and inflateInit.
  78490. */
  78491. /*
  78492. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78493. Initializes the internal stream state for compression. The fields
  78494. zalloc, zfree and opaque must be initialized before by the caller.
  78495. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78496. use default allocation functions.
  78497. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78498. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78499. all (the input data is simply copied a block at a time).
  78500. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78501. compression (currently equivalent to level 6).
  78502. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78503. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78504. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78505. with the version assumed by the caller (ZLIB_VERSION).
  78506. msg is set to null if there is no error message. deflateInit does not
  78507. perform any compression: this will be done by deflate().
  78508. */
  78509. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78510. /*
  78511. deflate compresses as much data as possible, and stops when the input
  78512. buffer becomes empty or the output buffer becomes full. It may introduce some
  78513. output latency (reading input without producing any output) except when
  78514. forced to flush.
  78515. The detailed semantics are as follows. deflate performs one or both of the
  78516. following actions:
  78517. - Compress more input starting at next_in and update next_in and avail_in
  78518. accordingly. If not all input can be processed (because there is not
  78519. enough room in the output buffer), next_in and avail_in are updated and
  78520. processing will resume at this point for the next call of deflate().
  78521. - Provide more output starting at next_out and update next_out and avail_out
  78522. accordingly. This action is forced if the parameter flush is non zero.
  78523. Forcing flush frequently degrades the compression ratio, so this parameter
  78524. should be set only when necessary (in interactive applications).
  78525. Some output may be provided even if flush is not set.
  78526. Before the call of deflate(), the application should ensure that at least
  78527. one of the actions is possible, by providing more input and/or consuming
  78528. more output, and updating avail_in or avail_out accordingly; avail_out
  78529. should never be zero before the call. The application can consume the
  78530. compressed output when it wants, for example when the output buffer is full
  78531. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78532. and with zero avail_out, it must be called again after making room in the
  78533. output buffer because there might be more output pending.
  78534. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78535. decide how much data to accumualte before producing output, in order to
  78536. maximize compression.
  78537. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78538. flushed to the output buffer and the output is aligned on a byte boundary, so
  78539. that the decompressor can get all input data available so far. (In particular
  78540. avail_in is zero after the call if enough output space has been provided
  78541. before the call.) Flushing may degrade compression for some compression
  78542. algorithms and so it should be used only when necessary.
  78543. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78544. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78545. restart from this point if previous compressed data has been damaged or if
  78546. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78547. compression.
  78548. If deflate returns with avail_out == 0, this function must be called again
  78549. with the same value of the flush parameter and more output space (updated
  78550. avail_out), until the flush is complete (deflate returns with non-zero
  78551. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78552. avail_out is greater than six to avoid repeated flush markers due to
  78553. avail_out == 0 on return.
  78554. If the parameter flush is set to Z_FINISH, pending input is processed,
  78555. pending output is flushed and deflate returns with Z_STREAM_END if there
  78556. was enough output space; if deflate returns with Z_OK, this function must be
  78557. called again with Z_FINISH and more output space (updated avail_out) but no
  78558. more input data, until it returns with Z_STREAM_END or an error. After
  78559. deflate has returned Z_STREAM_END, the only possible operations on the
  78560. stream are deflateReset or deflateEnd.
  78561. Z_FINISH can be used immediately after deflateInit if all the compression
  78562. is to be done in a single step. In this case, avail_out must be at least
  78563. the value returned by deflateBound (see below). If deflate does not return
  78564. Z_STREAM_END, then it must be called again as described above.
  78565. deflate() sets strm->adler to the adler32 checksum of all input read
  78566. so far (that is, total_in bytes).
  78567. deflate() may update strm->data_type if it can make a good guess about
  78568. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78569. binary. This field is only for information purposes and does not affect
  78570. the compression algorithm in any manner.
  78571. deflate() returns Z_OK if some progress has been made (more input
  78572. processed or more output produced), Z_STREAM_END if all input has been
  78573. consumed and all output has been produced (only when flush is set to
  78574. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78575. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78576. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78577. fatal, and deflate() can be called again with more input and more output
  78578. space to continue compressing.
  78579. */
  78580. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78581. /*
  78582. All dynamically allocated data structures for this stream are freed.
  78583. This function discards any unprocessed input and does not flush any
  78584. pending output.
  78585. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78586. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78587. prematurely (some input or output was discarded). In the error case,
  78588. msg may be set but then points to a static string (which must not be
  78589. deallocated).
  78590. */
  78591. /*
  78592. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78593. Initializes the internal stream state for decompression. The fields
  78594. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78595. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78596. value depends on the compression method), inflateInit determines the
  78597. compression method from the zlib header and allocates all data structures
  78598. accordingly; otherwise the allocation will be deferred to the first call of
  78599. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78600. use default allocation functions.
  78601. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78602. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78603. version assumed by the caller. msg is set to null if there is no error
  78604. message. inflateInit does not perform any decompression apart from reading
  78605. the zlib header if present: this will be done by inflate(). (So next_in and
  78606. avail_in may be modified, but next_out and avail_out are unchanged.)
  78607. */
  78608. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78609. /*
  78610. inflate decompresses as much data as possible, and stops when the input
  78611. buffer becomes empty or the output buffer becomes full. It may introduce
  78612. some output latency (reading input without producing any output) except when
  78613. forced to flush.
  78614. The detailed semantics are as follows. inflate performs one or both of the
  78615. following actions:
  78616. - Decompress more input starting at next_in and update next_in and avail_in
  78617. accordingly. If not all input can be processed (because there is not
  78618. enough room in the output buffer), next_in is updated and processing
  78619. will resume at this point for the next call of inflate().
  78620. - Provide more output starting at next_out and update next_out and avail_out
  78621. accordingly. inflate() provides as much output as possible, until there
  78622. is no more input data or no more space in the output buffer (see below
  78623. about the flush parameter).
  78624. Before the call of inflate(), the application should ensure that at least
  78625. one of the actions is possible, by providing more input and/or consuming
  78626. more output, and updating the next_* and avail_* values accordingly.
  78627. The application can consume the uncompressed output when it wants, for
  78628. example when the output buffer is full (avail_out == 0), or after each
  78629. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78630. must be called again after making room in the output buffer because there
  78631. might be more output pending.
  78632. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78633. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78634. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78635. if and when it gets to the next deflate block boundary. When decoding the
  78636. zlib or gzip format, this will cause inflate() to return immediately after
  78637. the header and before the first block. When doing a raw inflate, inflate()
  78638. will go ahead and process the first block, and will return when it gets to
  78639. the end of that block, or when it runs out of data.
  78640. The Z_BLOCK option assists in appending to or combining deflate streams.
  78641. Also to assist in this, on return inflate() will set strm->data_type to the
  78642. number of unused bits in the last byte taken from strm->next_in, plus 64
  78643. if inflate() is currently decoding the last block in the deflate stream,
  78644. plus 128 if inflate() returned immediately after decoding an end-of-block
  78645. code or decoding the complete header up to just before the first byte of the
  78646. deflate stream. The end-of-block will not be indicated until all of the
  78647. uncompressed data from that block has been written to strm->next_out. The
  78648. number of unused bits may in general be greater than seven, except when
  78649. bit 7 of data_type is set, in which case the number of unused bits will be
  78650. less than eight.
  78651. inflate() should normally be called until it returns Z_STREAM_END or an
  78652. error. However if all decompression is to be performed in a single step
  78653. (a single call of inflate), the parameter flush should be set to
  78654. Z_FINISH. In this case all pending input is processed and all pending
  78655. output is flushed; avail_out must be large enough to hold all the
  78656. uncompressed data. (The size of the uncompressed data may have been saved
  78657. by the compressor for this purpose.) The next operation on this stream must
  78658. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78659. is never required, but can be used to inform inflate that a faster approach
  78660. may be used for the single inflate() call.
  78661. In this implementation, inflate() always flushes as much output as
  78662. possible to the output buffer, and always uses the faster approach on the
  78663. first call. So the only effect of the flush parameter in this implementation
  78664. is on the return value of inflate(), as noted below, or when it returns early
  78665. because Z_BLOCK is used.
  78666. If a preset dictionary is needed after this call (see inflateSetDictionary
  78667. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78668. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78669. strm->adler to the adler32 checksum of all output produced so far (that is,
  78670. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78671. below. At the end of the stream, inflate() checks that its computed adler32
  78672. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78673. only if the checksum is correct.
  78674. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78675. deflate data. The header type is detected automatically. Any information
  78676. contained in the gzip header is not retained, so applications that need that
  78677. information should instead use raw inflate, see inflateInit2() below, or
  78678. inflateBack() and perform their own processing of the gzip header and
  78679. trailer.
  78680. inflate() returns Z_OK if some progress has been made (more input processed
  78681. or more output produced), Z_STREAM_END if the end of the compressed data has
  78682. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78683. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78684. corrupted (input stream not conforming to the zlib format or incorrect check
  78685. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78686. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78687. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78688. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78689. inflate() can be called again with more input and more output space to
  78690. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78691. call inflateSync() to look for a good compression block if a partial recovery
  78692. of the data is desired.
  78693. */
  78694. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78695. /*
  78696. All dynamically allocated data structures for this stream are freed.
  78697. This function discards any unprocessed input and does not flush any
  78698. pending output.
  78699. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78700. was inconsistent. In the error case, msg may be set but then points to a
  78701. static string (which must not be deallocated).
  78702. */
  78703. /* Advanced functions */
  78704. /*
  78705. The following functions are needed only in some special applications.
  78706. */
  78707. /*
  78708. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78709. int level,
  78710. int method,
  78711. int windowBits,
  78712. int memLevel,
  78713. int strategy));
  78714. This is another version of deflateInit with more compression options. The
  78715. fields next_in, zalloc, zfree and opaque must be initialized before by
  78716. the caller.
  78717. The method parameter is the compression method. It must be Z_DEFLATED in
  78718. this version of the library.
  78719. The windowBits parameter is the base two logarithm of the window size
  78720. (the size of the history buffer). It should be in the range 8..15 for this
  78721. version of the library. Larger values of this parameter result in better
  78722. compression at the expense of memory usage. The default value is 15 if
  78723. deflateInit is used instead.
  78724. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78725. determines the window size. deflate() will then generate raw deflate data
  78726. with no zlib header or trailer, and will not compute an adler32 check value.
  78727. windowBits can also be greater than 15 for optional gzip encoding. Add
  78728. 16 to windowBits to write a simple gzip header and trailer around the
  78729. compressed data instead of a zlib wrapper. The gzip header will have no
  78730. file name, no extra data, no comment, no modification time (set to zero),
  78731. no header crc, and the operating system will be set to 255 (unknown). If a
  78732. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78733. The memLevel parameter specifies how much memory should be allocated
  78734. for the internal compression state. memLevel=1 uses minimum memory but
  78735. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78736. for optimal speed. The default value is 8. See zconf.h for total memory
  78737. usage as a function of windowBits and memLevel.
  78738. The strategy parameter is used to tune the compression algorithm. Use the
  78739. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78740. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78741. string match), or Z_RLE to limit match distances to one (run-length
  78742. encoding). Filtered data consists mostly of small values with a somewhat
  78743. random distribution. In this case, the compression algorithm is tuned to
  78744. compress them better. The effect of Z_FILTERED is to force more Huffman
  78745. coding and less string matching; it is somewhat intermediate between
  78746. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78747. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78748. parameter only affects the compression ratio but not the correctness of the
  78749. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78750. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78751. applications.
  78752. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78753. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78754. method). msg is set to null if there is no error message. deflateInit2 does
  78755. not perform any compression: this will be done by deflate().
  78756. */
  78757. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78758. const Bytef *dictionary,
  78759. uInt dictLength));
  78760. /*
  78761. Initializes the compression dictionary from the given byte sequence
  78762. without producing any compressed output. This function must be called
  78763. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78764. call of deflate. The compressor and decompressor must use exactly the same
  78765. dictionary (see inflateSetDictionary).
  78766. The dictionary should consist of strings (byte sequences) that are likely
  78767. to be encountered later in the data to be compressed, with the most commonly
  78768. used strings preferably put towards the end of the dictionary. Using a
  78769. dictionary is most useful when the data to be compressed is short and can be
  78770. predicted with good accuracy; the data can then be compressed better than
  78771. with the default empty dictionary.
  78772. Depending on the size of the compression data structures selected by
  78773. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78774. discarded, for example if the dictionary is larger than the window size in
  78775. deflate or deflate2. Thus the strings most likely to be useful should be
  78776. put at the end of the dictionary, not at the front. In addition, the
  78777. current implementation of deflate will use at most the window size minus
  78778. 262 bytes of the provided dictionary.
  78779. Upon return of this function, strm->adler is set to the adler32 value
  78780. of the dictionary; the decompressor may later use this value to determine
  78781. which dictionary has been used by the compressor. (The adler32 value
  78782. applies to the whole dictionary even if only a subset of the dictionary is
  78783. actually used by the compressor.) If a raw deflate was requested, then the
  78784. adler32 value is not computed and strm->adler is not set.
  78785. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78786. parameter is invalid (such as NULL dictionary) or the stream state is
  78787. inconsistent (for example if deflate has already been called for this stream
  78788. or if the compression method is bsort). deflateSetDictionary does not
  78789. perform any compression: this will be done by deflate().
  78790. */
  78791. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78792. z_streamp source));
  78793. /*
  78794. Sets the destination stream as a complete copy of the source stream.
  78795. This function can be useful when several compression strategies will be
  78796. tried, for example when there are several ways of pre-processing the input
  78797. data with a filter. The streams that will be discarded should then be freed
  78798. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78799. compression state which can be quite large, so this strategy is slow and
  78800. can consume lots of memory.
  78801. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78802. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78803. (such as zalloc being NULL). msg is left unchanged in both source and
  78804. destination.
  78805. */
  78806. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78807. /*
  78808. This function is equivalent to deflateEnd followed by deflateInit,
  78809. but does not free and reallocate all the internal compression state.
  78810. The stream will keep the same compression level and any other attributes
  78811. that may have been set by deflateInit2.
  78812. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78813. stream state was inconsistent (such as zalloc or state being NULL).
  78814. */
  78815. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78816. int level,
  78817. int strategy));
  78818. /*
  78819. Dynamically update the compression level and compression strategy. The
  78820. interpretation of level and strategy is as in deflateInit2. This can be
  78821. used to switch between compression and straight copy of the input data, or
  78822. to switch to a different kind of input data requiring a different
  78823. strategy. If the compression level is changed, the input available so far
  78824. is compressed with the old level (and may be flushed); the new level will
  78825. take effect only at the next call of deflate().
  78826. Before the call of deflateParams, the stream state must be set as for
  78827. a call of deflate(), since the currently available input may have to
  78828. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78829. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78830. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78831. if strm->avail_out was zero.
  78832. */
  78833. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78834. int good_length,
  78835. int max_lazy,
  78836. int nice_length,
  78837. int max_chain));
  78838. /*
  78839. Fine tune deflate's internal compression parameters. This should only be
  78840. used by someone who understands the algorithm used by zlib's deflate for
  78841. searching for the best matching string, and even then only by the most
  78842. fanatic optimizer trying to squeeze out the last compressed bit for their
  78843. specific input data. Read the deflate.c source code for the meaning of the
  78844. max_lazy, good_length, nice_length, and max_chain parameters.
  78845. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78846. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78847. */
  78848. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78849. uLong sourceLen));
  78850. /*
  78851. deflateBound() returns an upper bound on the compressed size after
  78852. deflation of sourceLen bytes. It must be called after deflateInit()
  78853. or deflateInit2(). This would be used to allocate an output buffer
  78854. for deflation in a single pass, and so would be called before deflate().
  78855. */
  78856. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78857. int bits,
  78858. int value));
  78859. /*
  78860. deflatePrime() inserts bits in the deflate output stream. The intent
  78861. is that this function is used to start off the deflate output with the
  78862. bits leftover from a previous deflate stream when appending to it. As such,
  78863. this function can only be used for raw deflate, and must be used before the
  78864. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78865. less than or equal to 16, and that many of the least significant bits of
  78866. value will be inserted in the output.
  78867. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78868. stream state was inconsistent.
  78869. */
  78870. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78871. gz_headerp head));
  78872. /*
  78873. deflateSetHeader() provides gzip header information for when a gzip
  78874. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78875. after deflateInit2() or deflateReset() and before the first call of
  78876. deflate(). The text, time, os, extra field, name, and comment information
  78877. in the provided gz_header structure are written to the gzip header (xflag is
  78878. ignored -- the extra flags are set according to the compression level). The
  78879. caller must assure that, if not Z_NULL, name and comment are terminated with
  78880. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78881. available there. If hcrc is true, a gzip header crc is included. Note that
  78882. the current versions of the command-line version of gzip (up through version
  78883. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78884. gzip file" and give up.
  78885. If deflateSetHeader is not used, the default gzip header has text false,
  78886. the time set to zero, and os set to 255, with no extra, name, or comment
  78887. fields. The gzip header is returned to the default state by deflateReset().
  78888. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78889. stream state was inconsistent.
  78890. */
  78891. /*
  78892. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78893. int windowBits));
  78894. This is another version of inflateInit with an extra parameter. The
  78895. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78896. before by the caller.
  78897. The windowBits parameter is the base two logarithm of the maximum window
  78898. size (the size of the history buffer). It should be in the range 8..15 for
  78899. this version of the library. The default value is 15 if inflateInit is used
  78900. instead. windowBits must be greater than or equal to the windowBits value
  78901. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78902. deflateInit2() was not used. If a compressed stream with a larger window
  78903. size is given as input, inflate() will return with the error code
  78904. Z_DATA_ERROR instead of trying to allocate a larger window.
  78905. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78906. determines the window size. inflate() will then process raw deflate data,
  78907. not looking for a zlib or gzip header, not generating a check value, and not
  78908. looking for any check values for comparison at the end of the stream. This
  78909. is for use with other formats that use the deflate compressed data format
  78910. such as zip. Those formats provide their own check values. If a custom
  78911. format is developed using the raw deflate format for compressed data, it is
  78912. recommended that a check value such as an adler32 or a crc32 be applied to
  78913. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78914. most applications, the zlib format should be used as is. Note that comments
  78915. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78916. windowBits can also be greater than 15 for optional gzip decoding. Add
  78917. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78918. detection, or add 16 to decode only the gzip format (the zlib format will
  78919. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78920. a crc32 instead of an adler32.
  78921. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78922. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78923. is set to null if there is no error message. inflateInit2 does not perform
  78924. any decompression apart from reading the zlib header if present: this will
  78925. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78926. and avail_out are unchanged.)
  78927. */
  78928. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78929. const Bytef *dictionary,
  78930. uInt dictLength));
  78931. /*
  78932. Initializes the decompression dictionary from the given uncompressed byte
  78933. sequence. This function must be called immediately after a call of inflate,
  78934. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78935. can be determined from the adler32 value returned by that call of inflate.
  78936. The compressor and decompressor must use exactly the same dictionary (see
  78937. deflateSetDictionary). For raw inflate, this function can be called
  78938. immediately after inflateInit2() or inflateReset() and before any call of
  78939. inflate() to set the dictionary. The application must insure that the
  78940. dictionary that was used for compression is provided.
  78941. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78942. parameter is invalid (such as NULL dictionary) or the stream state is
  78943. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78944. expected one (incorrect adler32 value). inflateSetDictionary does not
  78945. perform any decompression: this will be done by subsequent calls of
  78946. inflate().
  78947. */
  78948. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78949. /*
  78950. Skips invalid compressed data until a full flush point (see above the
  78951. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78952. available input is skipped. No output is provided.
  78953. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78954. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78955. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78956. case, the application may save the current current value of total_in which
  78957. indicates where valid compressed data was found. In the error case, the
  78958. application may repeatedly call inflateSync, providing more input each time,
  78959. until success or end of the input data.
  78960. */
  78961. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78962. z_streamp source));
  78963. /*
  78964. Sets the destination stream as a complete copy of the source stream.
  78965. This function can be useful when randomly accessing a large stream. The
  78966. first pass through the stream can periodically record the inflate state,
  78967. allowing restarting inflate at those points when randomly accessing the
  78968. stream.
  78969. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78970. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78971. (such as zalloc being NULL). msg is left unchanged in both source and
  78972. destination.
  78973. */
  78974. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78975. /*
  78976. This function is equivalent to inflateEnd followed by inflateInit,
  78977. but does not free and reallocate all the internal decompression state.
  78978. The stream will keep attributes that may have been set by inflateInit2.
  78979. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78980. stream state was inconsistent (such as zalloc or state being NULL).
  78981. */
  78982. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78983. int bits,
  78984. int value));
  78985. /*
  78986. This function inserts bits in the inflate input stream. The intent is
  78987. that this function is used to start inflating at a bit position in the
  78988. middle of a byte. The provided bits will be used before any bytes are used
  78989. from next_in. This function should only be used with raw inflate, and
  78990. should be used before the first inflate() call after inflateInit2() or
  78991. inflateReset(). bits must be less than or equal to 16, and that many of the
  78992. least significant bits of value will be inserted in the input.
  78993. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78994. stream state was inconsistent.
  78995. */
  78996. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78997. gz_headerp head));
  78998. /*
  78999. inflateGetHeader() requests that gzip header information be stored in the
  79000. provided gz_header structure. inflateGetHeader() may be called after
  79001. inflateInit2() or inflateReset(), and before the first call of inflate().
  79002. As inflate() processes the gzip stream, head->done is zero until the header
  79003. is completed, at which time head->done is set to one. If a zlib stream is
  79004. being decoded, then head->done is set to -1 to indicate that there will be
  79005. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79006. force inflate() to return immediately after header processing is complete
  79007. and before any actual data is decompressed.
  79008. The text, time, xflags, and os fields are filled in with the gzip header
  79009. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79010. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79011. contains the maximum number of bytes to write to extra. Once done is true,
  79012. extra_len contains the actual extra field length, and extra contains the
  79013. extra field, or that field truncated if extra_max is less than extra_len.
  79014. If name is not Z_NULL, then up to name_max characters are written there,
  79015. terminated with a zero unless the length is greater than name_max. If
  79016. comment is not Z_NULL, then up to comm_max characters are written there,
  79017. terminated with a zero unless the length is greater than comm_max. When
  79018. any of extra, name, or comment are not Z_NULL and the respective field is
  79019. not present in the header, then that field is set to Z_NULL to signal its
  79020. absence. This allows the use of deflateSetHeader() with the returned
  79021. structure to duplicate the header. However if those fields are set to
  79022. allocated memory, then the application will need to save those pointers
  79023. elsewhere so that they can be eventually freed.
  79024. If inflateGetHeader is not used, then the header information is simply
  79025. discarded. The header is always checked for validity, including the header
  79026. CRC if present. inflateReset() will reset the process to discard the header
  79027. information. The application would need to call inflateGetHeader() again to
  79028. retrieve the header from the next gzip stream.
  79029. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79030. stream state was inconsistent.
  79031. */
  79032. /*
  79033. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79034. unsigned char FAR *window));
  79035. Initialize the internal stream state for decompression using inflateBack()
  79036. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79037. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79038. derived memory allocation routines are used. windowBits is the base two
  79039. logarithm of the window size, in the range 8..15. window is a caller
  79040. supplied buffer of that size. Except for special applications where it is
  79041. assured that deflate was used with small window sizes, windowBits must be 15
  79042. and a 32K byte window must be supplied to be able to decompress general
  79043. deflate streams.
  79044. See inflateBack() for the usage of these routines.
  79045. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79046. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79047. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79048. match the version of the header file.
  79049. */
  79050. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79051. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79052. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79053. in_func in, void FAR *in_desc,
  79054. out_func out, void FAR *out_desc));
  79055. /*
  79056. inflateBack() does a raw inflate with a single call using a call-back
  79057. interface for input and output. This is more efficient than inflate() for
  79058. file i/o applications in that it avoids copying between the output and the
  79059. sliding window by simply making the window itself the output buffer. This
  79060. function trusts the application to not change the output buffer passed by
  79061. the output function, at least until inflateBack() returns.
  79062. inflateBackInit() must be called first to allocate the internal state
  79063. and to initialize the state with the user-provided window buffer.
  79064. inflateBack() may then be used multiple times to inflate a complete, raw
  79065. deflate stream with each call. inflateBackEnd() is then called to free
  79066. the allocated state.
  79067. A raw deflate stream is one with no zlib or gzip header or trailer.
  79068. This routine would normally be used in a utility that reads zip or gzip
  79069. files and writes out uncompressed files. The utility would decode the
  79070. header and process the trailer on its own, hence this routine expects
  79071. only the raw deflate stream to decompress. This is different from the
  79072. normal behavior of inflate(), which expects either a zlib or gzip header and
  79073. trailer around the deflate stream.
  79074. inflateBack() uses two subroutines supplied by the caller that are then
  79075. called by inflateBack() for input and output. inflateBack() calls those
  79076. routines until it reads a complete deflate stream and writes out all of the
  79077. uncompressed data, or until it encounters an error. The function's
  79078. parameters and return types are defined above in the in_func and out_func
  79079. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79080. number of bytes of provided input, and a pointer to that input in buf. If
  79081. there is no input available, in() must return zero--buf is ignored in that
  79082. case--and inflateBack() will return a buffer error. inflateBack() will call
  79083. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79084. should return zero on success, or non-zero on failure. If out() returns
  79085. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79086. are permitted to change the contents of the window provided to
  79087. inflateBackInit(), which is also the buffer that out() uses to write from.
  79088. The length written by out() will be at most the window size. Any non-zero
  79089. amount of input may be provided by in().
  79090. For convenience, inflateBack() can be provided input on the first call by
  79091. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79092. in() will be called. Therefore strm->next_in must be initialized before
  79093. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79094. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79095. must also be initialized, and then if strm->avail_in is not zero, input will
  79096. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79097. The in_desc and out_desc parameters of inflateBack() is passed as the
  79098. first parameter of in() and out() respectively when they are called. These
  79099. descriptors can be optionally used to pass any information that the caller-
  79100. supplied in() and out() functions need to do their job.
  79101. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79102. pass back any unused input that was provided by the last in() call. The
  79103. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79104. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79105. error in the deflate stream (in which case strm->msg is set to indicate the
  79106. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79107. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79108. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79109. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79110. out() returning non-zero. (in() will always be called before out(), so
  79111. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79112. that inflateBack() cannot return Z_OK.
  79113. */
  79114. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79115. /*
  79116. All memory allocated by inflateBackInit() is freed.
  79117. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79118. state was inconsistent.
  79119. */
  79120. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79121. /* Return flags indicating compile-time options.
  79122. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79123. 1.0: size of uInt
  79124. 3.2: size of uLong
  79125. 5.4: size of voidpf (pointer)
  79126. 7.6: size of z_off_t
  79127. Compiler, assembler, and debug options:
  79128. 8: DEBUG
  79129. 9: ASMV or ASMINF -- use ASM code
  79130. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79131. 11: 0 (reserved)
  79132. One-time table building (smaller code, but not thread-safe if true):
  79133. 12: BUILDFIXED -- build static block decoding tables when needed
  79134. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79135. 14,15: 0 (reserved)
  79136. Library content (indicates missing functionality):
  79137. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79138. deflate code when not needed)
  79139. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79140. and decode gzip streams (to avoid linking crc code)
  79141. 18-19: 0 (reserved)
  79142. Operation variations (changes in library functionality):
  79143. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79144. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79145. 22,23: 0 (reserved)
  79146. The sprintf variant used by gzprintf (zero is best):
  79147. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79148. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79149. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79150. Remainder:
  79151. 27-31: 0 (reserved)
  79152. */
  79153. /* utility functions */
  79154. /*
  79155. The following utility functions are implemented on top of the
  79156. basic stream-oriented functions. To simplify the interface, some
  79157. default options are assumed (compression level and memory usage,
  79158. standard memory allocation functions). The source code of these
  79159. utility functions can easily be modified if you need special options.
  79160. */
  79161. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79162. const Bytef *source, uLong sourceLen));
  79163. /*
  79164. Compresses the source buffer into the destination buffer. sourceLen is
  79165. the byte length of the source buffer. Upon entry, destLen is the total
  79166. size of the destination buffer, which must be at least the value returned
  79167. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79168. compressed buffer.
  79169. This function can be used to compress a whole file at once if the
  79170. input file is mmap'ed.
  79171. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79172. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79173. buffer.
  79174. */
  79175. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79176. const Bytef *source, uLong sourceLen,
  79177. int level));
  79178. /*
  79179. Compresses the source buffer into the destination buffer. The level
  79180. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79181. length of the source buffer. Upon entry, destLen is the total size of the
  79182. destination buffer, which must be at least the value returned by
  79183. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79184. compressed buffer.
  79185. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79186. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79187. Z_STREAM_ERROR if the level parameter is invalid.
  79188. */
  79189. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79190. /*
  79191. compressBound() returns an upper bound on the compressed size after
  79192. compress() or compress2() on sourceLen bytes. It would be used before
  79193. a compress() or compress2() call to allocate the destination buffer.
  79194. */
  79195. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79196. const Bytef *source, uLong sourceLen));
  79197. /*
  79198. Decompresses the source buffer into the destination buffer. sourceLen is
  79199. the byte length of the source buffer. Upon entry, destLen is the total
  79200. size of the destination buffer, which must be large enough to hold the
  79201. entire uncompressed data. (The size of the uncompressed data must have
  79202. been saved previously by the compressor and transmitted to the decompressor
  79203. by some mechanism outside the scope of this compression library.)
  79204. Upon exit, destLen is the actual size of the compressed buffer.
  79205. This function can be used to decompress a whole file at once if the
  79206. input file is mmap'ed.
  79207. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79208. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79209. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79210. */
  79211. typedef voidp gzFile;
  79212. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79213. /*
  79214. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79215. is as in fopen ("rb" or "wb") but can also include a compression level
  79216. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79217. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79218. as in "wb1R". (See the description of deflateInit2 for more information
  79219. about the strategy parameter.)
  79220. gzopen can be used to read a file which is not in gzip format; in this
  79221. case gzread will directly read from the file without decompression.
  79222. gzopen returns NULL if the file could not be opened or if there was
  79223. insufficient memory to allocate the (de)compression state; errno
  79224. can be checked to distinguish the two cases (if errno is zero, the
  79225. zlib error is Z_MEM_ERROR). */
  79226. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79227. /*
  79228. gzdopen() associates a gzFile with the file descriptor fd. File
  79229. descriptors are obtained from calls like open, dup, creat, pipe or
  79230. fileno (in the file has been previously opened with fopen).
  79231. The mode parameter is as in gzopen.
  79232. The next call of gzclose on the returned gzFile will also close the
  79233. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79234. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79235. gzdopen returns NULL if there was insufficient memory to allocate
  79236. the (de)compression state.
  79237. */
  79238. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79239. /*
  79240. Dynamically update the compression level or strategy. See the description
  79241. of deflateInit2 for the meaning of these parameters.
  79242. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79243. opened for writing.
  79244. */
  79245. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79246. /*
  79247. Reads the given number of uncompressed bytes from the compressed file.
  79248. If the input file was not in gzip format, gzread copies the given number
  79249. of bytes into the buffer.
  79250. gzread returns the number of uncompressed bytes actually read (0 for
  79251. end of file, -1 for error). */
  79252. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79253. voidpc buf, unsigned len));
  79254. /*
  79255. Writes the given number of uncompressed bytes into the compressed file.
  79256. gzwrite returns the number of uncompressed bytes actually written
  79257. (0 in case of error).
  79258. */
  79259. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79260. /*
  79261. Converts, formats, and writes the args to the compressed file under
  79262. control of the format string, as in fprintf. gzprintf returns the number of
  79263. uncompressed bytes actually written (0 in case of error). The number of
  79264. uncompressed bytes written is limited to 4095. The caller should assure that
  79265. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79266. return an error (0) with nothing written. In this case, there may also be a
  79267. buffer overflow with unpredictable consequences, which is possible only if
  79268. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79269. because the secure snprintf() or vsnprintf() functions were not available.
  79270. */
  79271. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79272. /*
  79273. Writes the given null-terminated string to the compressed file, excluding
  79274. the terminating null character.
  79275. gzputs returns the number of characters written, or -1 in case of error.
  79276. */
  79277. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79278. /*
  79279. Reads bytes from the compressed file until len-1 characters are read, or
  79280. a newline character is read and transferred to buf, or an end-of-file
  79281. condition is encountered. The string is then terminated with a null
  79282. character.
  79283. gzgets returns buf, or Z_NULL in case of error.
  79284. */
  79285. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79286. /*
  79287. Writes c, converted to an unsigned char, into the compressed file.
  79288. gzputc returns the value that was written, or -1 in case of error.
  79289. */
  79290. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79291. /*
  79292. Reads one byte from the compressed file. gzgetc returns this byte
  79293. or -1 in case of end of file or error.
  79294. */
  79295. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79296. /*
  79297. Push one character back onto the stream to be read again later.
  79298. Only one character of push-back is allowed. gzungetc() returns the
  79299. character pushed, or -1 on failure. gzungetc() will fail if a
  79300. character has been pushed but not read yet, or if c is -1. The pushed
  79301. character will be discarded if the stream is repositioned with gzseek()
  79302. or gzrewind().
  79303. */
  79304. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79305. /*
  79306. Flushes all pending output into the compressed file. The parameter
  79307. flush is as in the deflate() function. The return value is the zlib
  79308. error number (see function gzerror below). gzflush returns Z_OK if
  79309. the flush parameter is Z_FINISH and all output could be flushed.
  79310. gzflush should be called only when strictly necessary because it can
  79311. degrade compression.
  79312. */
  79313. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79314. z_off_t offset, int whence));
  79315. /*
  79316. Sets the starting position for the next gzread or gzwrite on the
  79317. given compressed file. The offset represents a number of bytes in the
  79318. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79319. the value SEEK_END is not supported.
  79320. If the file is opened for reading, this function is emulated but can be
  79321. extremely slow. If the file is opened for writing, only forward seeks are
  79322. supported; gzseek then compresses a sequence of zeroes up to the new
  79323. starting position.
  79324. gzseek returns the resulting offset location as measured in bytes from
  79325. the beginning of the uncompressed stream, or -1 in case of error, in
  79326. particular if the file is opened for writing and the new starting position
  79327. would be before the current position.
  79328. */
  79329. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79330. /*
  79331. Rewinds the given file. This function is supported only for reading.
  79332. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79333. */
  79334. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79335. /*
  79336. Returns the starting position for the next gzread or gzwrite on the
  79337. given compressed file. This position represents a number of bytes in the
  79338. uncompressed data stream.
  79339. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79340. */
  79341. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79342. /*
  79343. Returns 1 when EOF has previously been detected reading the given
  79344. input stream, otherwise zero.
  79345. */
  79346. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79347. /*
  79348. Returns 1 if file is being read directly without decompression, otherwise
  79349. zero.
  79350. */
  79351. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79352. /*
  79353. Flushes all pending output if necessary, closes the compressed file
  79354. and deallocates all the (de)compression state. The return value is the zlib
  79355. error number (see function gzerror below).
  79356. */
  79357. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79358. /*
  79359. Returns the error message for the last error which occurred on the
  79360. given compressed file. errnum is set to zlib error number. If an
  79361. error occurred in the file system and not in the compression library,
  79362. errnum is set to Z_ERRNO and the application may consult errno
  79363. to get the exact error code.
  79364. */
  79365. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79366. /*
  79367. Clears the error and end-of-file flags for file. This is analogous to the
  79368. clearerr() function in stdio. This is useful for continuing to read a gzip
  79369. file that is being written concurrently.
  79370. */
  79371. /* checksum functions */
  79372. /*
  79373. These functions are not related to compression but are exported
  79374. anyway because they might be useful in applications using the
  79375. compression library.
  79376. */
  79377. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79378. /*
  79379. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79380. return the updated checksum. If buf is NULL, this function returns
  79381. the required initial value for the checksum.
  79382. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79383. much faster. Usage example:
  79384. uLong adler = adler32(0L, Z_NULL, 0);
  79385. while (read_buffer(buffer, length) != EOF) {
  79386. adler = adler32(adler, buffer, length);
  79387. }
  79388. if (adler != original_adler) error();
  79389. */
  79390. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79391. z_off_t len2));
  79392. /*
  79393. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79394. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79395. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79396. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79397. */
  79398. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79399. /*
  79400. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79401. updated CRC-32. If buf is NULL, this function returns the required initial
  79402. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79403. performed within this function so it shouldn't be done by the application.
  79404. Usage example:
  79405. uLong crc = crc32(0L, Z_NULL, 0);
  79406. while (read_buffer(buffer, length) != EOF) {
  79407. crc = crc32(crc, buffer, length);
  79408. }
  79409. if (crc != original_crc) error();
  79410. */
  79411. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79412. /*
  79413. Combine two CRC-32 check values into one. For two sequences of bytes,
  79414. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79415. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79416. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79417. len2.
  79418. */
  79419. /* various hacks, don't look :) */
  79420. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79421. * and the compiler's view of z_stream:
  79422. */
  79423. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79424. const char *version, int stream_size));
  79425. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79426. const char *version, int stream_size));
  79427. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79428. int windowBits, int memLevel,
  79429. int strategy, const char *version,
  79430. int stream_size));
  79431. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79432. const char *version, int stream_size));
  79433. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79434. unsigned char FAR *window,
  79435. const char *version,
  79436. int stream_size));
  79437. #define deflateInit(strm, level) \
  79438. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79439. #define inflateInit(strm) \
  79440. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79441. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79442. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79443. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79444. #define inflateInit2(strm, windowBits) \
  79445. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79446. #define inflateBackInit(strm, windowBits, window) \
  79447. inflateBackInit_((strm), (windowBits), (window), \
  79448. ZLIB_VERSION, sizeof(z_stream))
  79449. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79450. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79451. #endif
  79452. ZEXTERN const char * ZEXPORT zError OF((int));
  79453. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79454. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79455. #ifdef __cplusplus
  79456. //}
  79457. #endif
  79458. #endif /* ZLIB_H */
  79459. /*** End of inlined file: zlib.h ***/
  79460. #undef OS_CODE
  79461. #else
  79462. #include <zlib.h>
  79463. #endif
  79464. }
  79465. BEGIN_JUCE_NAMESPACE
  79466. // internal helper object that holds the zlib structures so they don't have to be
  79467. // included publicly.
  79468. class GZIPCompressorHelper
  79469. {
  79470. public:
  79471. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79472. : data (0),
  79473. dataSize (0),
  79474. compLevel (compressionLevel),
  79475. strategy (0),
  79476. setParams (true),
  79477. streamIsValid (false),
  79478. finished (false),
  79479. shouldFinish (false)
  79480. {
  79481. using namespace zlibNamespace;
  79482. zerostruct (stream);
  79483. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79484. nowrap ? -MAX_WBITS : MAX_WBITS,
  79485. 8, strategy) == Z_OK);
  79486. }
  79487. ~GZIPCompressorHelper()
  79488. {
  79489. using namespace zlibNamespace;
  79490. if (streamIsValid)
  79491. deflateEnd (&stream);
  79492. }
  79493. bool needsInput() const throw()
  79494. {
  79495. return dataSize <= 0;
  79496. }
  79497. void setInput (const uint8* const newData, const int size) throw()
  79498. {
  79499. data = newData;
  79500. dataSize = size;
  79501. }
  79502. int doNextBlock (uint8* const dest, const int destSize) throw()
  79503. {
  79504. using namespace zlibNamespace;
  79505. if (streamIsValid)
  79506. {
  79507. stream.next_in = const_cast <uint8*> (data);
  79508. stream.next_out = dest;
  79509. stream.avail_in = dataSize;
  79510. stream.avail_out = destSize;
  79511. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79512. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79513. setParams = false;
  79514. switch (result)
  79515. {
  79516. case Z_STREAM_END:
  79517. finished = true;
  79518. // Deliberate fall-through..
  79519. case Z_OK:
  79520. data += dataSize - stream.avail_in;
  79521. dataSize = stream.avail_in;
  79522. return destSize - stream.avail_out;
  79523. default:
  79524. break;
  79525. }
  79526. }
  79527. return 0;
  79528. }
  79529. private:
  79530. zlibNamespace::z_stream stream;
  79531. const uint8* data;
  79532. int dataSize, compLevel, strategy;
  79533. bool setParams, streamIsValid;
  79534. public:
  79535. bool finished, shouldFinish;
  79536. };
  79537. const int gzipCompBufferSize = 32768;
  79538. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79539. int compressionLevel,
  79540. const bool deleteDestStream,
  79541. const bool noWrap)
  79542. : destStream (destStream_),
  79543. streamToDelete (deleteDestStream ? destStream_ : 0),
  79544. buffer (gzipCompBufferSize)
  79545. {
  79546. if (compressionLevel < 1 || compressionLevel > 9)
  79547. compressionLevel = -1;
  79548. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79549. }
  79550. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79551. {
  79552. flush();
  79553. }
  79554. void GZIPCompressorOutputStream::flush()
  79555. {
  79556. if (! helper->finished)
  79557. {
  79558. helper->shouldFinish = true;
  79559. while (! helper->finished)
  79560. doNextBlock();
  79561. }
  79562. destStream->flush();
  79563. }
  79564. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79565. {
  79566. if (! helper->finished)
  79567. {
  79568. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79569. while (! helper->needsInput())
  79570. {
  79571. if (! doNextBlock())
  79572. return false;
  79573. }
  79574. }
  79575. return true;
  79576. }
  79577. bool GZIPCompressorOutputStream::doNextBlock()
  79578. {
  79579. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79580. if (len > 0)
  79581. return destStream->write (buffer, len);
  79582. else
  79583. return true;
  79584. }
  79585. int64 GZIPCompressorOutputStream::getPosition()
  79586. {
  79587. return destStream->getPosition();
  79588. }
  79589. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79590. {
  79591. jassertfalse; // can't do it!
  79592. return false;
  79593. }
  79594. END_JUCE_NAMESPACE
  79595. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79596. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79597. #if JUCE_MSVC
  79598. #pragma warning (push)
  79599. #pragma warning (disable: 4309 4305)
  79600. #endif
  79601. namespace zlibNamespace
  79602. {
  79603. #if JUCE_INCLUDE_ZLIB_CODE
  79604. #undef OS_CODE
  79605. #undef fdopen
  79606. #define ZLIB_INTERNAL
  79607. #define NO_DUMMY_DECL
  79608. /*** Start of inlined file: adler32.c ***/
  79609. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79610. #define ZLIB_INTERNAL
  79611. #define BASE 65521UL /* largest prime smaller than 65536 */
  79612. #define NMAX 5552
  79613. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79614. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79615. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79616. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79617. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79618. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79619. /* use NO_DIVIDE if your processor does not do division in hardware */
  79620. #ifdef NO_DIVIDE
  79621. # define MOD(a) \
  79622. do { \
  79623. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79624. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79625. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79626. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79627. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79628. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79629. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79630. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79631. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79632. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79633. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79634. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79635. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79636. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79637. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79638. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79639. if (a >= BASE) a -= BASE; \
  79640. } while (0)
  79641. # define MOD4(a) \
  79642. do { \
  79643. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79644. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79645. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79646. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79647. if (a >= BASE) a -= BASE; \
  79648. } while (0)
  79649. #else
  79650. # define MOD(a) a %= BASE
  79651. # define MOD4(a) a %= BASE
  79652. #endif
  79653. /* ========================================================================= */
  79654. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79655. {
  79656. unsigned long sum2;
  79657. unsigned n;
  79658. /* split Adler-32 into component sums */
  79659. sum2 = (adler >> 16) & 0xffff;
  79660. adler &= 0xffff;
  79661. /* in case user likes doing a byte at a time, keep it fast */
  79662. if (len == 1) {
  79663. adler += buf[0];
  79664. if (adler >= BASE)
  79665. adler -= BASE;
  79666. sum2 += adler;
  79667. if (sum2 >= BASE)
  79668. sum2 -= BASE;
  79669. return adler | (sum2 << 16);
  79670. }
  79671. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79672. if (buf == Z_NULL)
  79673. return 1L;
  79674. /* in case short lengths are provided, keep it somewhat fast */
  79675. if (len < 16) {
  79676. while (len--) {
  79677. adler += *buf++;
  79678. sum2 += adler;
  79679. }
  79680. if (adler >= BASE)
  79681. adler -= BASE;
  79682. MOD4(sum2); /* only added so many BASE's */
  79683. return adler | (sum2 << 16);
  79684. }
  79685. /* do length NMAX blocks -- requires just one modulo operation */
  79686. while (len >= NMAX) {
  79687. len -= NMAX;
  79688. n = NMAX / 16; /* NMAX is divisible by 16 */
  79689. do {
  79690. DO16(buf); /* 16 sums unrolled */
  79691. buf += 16;
  79692. } while (--n);
  79693. MOD(adler);
  79694. MOD(sum2);
  79695. }
  79696. /* do remaining bytes (less than NMAX, still just one modulo) */
  79697. if (len) { /* avoid modulos if none remaining */
  79698. while (len >= 16) {
  79699. len -= 16;
  79700. DO16(buf);
  79701. buf += 16;
  79702. }
  79703. while (len--) {
  79704. adler += *buf++;
  79705. sum2 += adler;
  79706. }
  79707. MOD(adler);
  79708. MOD(sum2);
  79709. }
  79710. /* return recombined sums */
  79711. return adler | (sum2 << 16);
  79712. }
  79713. /* ========================================================================= */
  79714. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79715. {
  79716. unsigned long sum1;
  79717. unsigned long sum2;
  79718. unsigned rem;
  79719. /* the derivation of this formula is left as an exercise for the reader */
  79720. rem = (unsigned)(len2 % BASE);
  79721. sum1 = adler1 & 0xffff;
  79722. sum2 = rem * sum1;
  79723. MOD(sum2);
  79724. sum1 += (adler2 & 0xffff) + BASE - 1;
  79725. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79726. if (sum1 > BASE) sum1 -= BASE;
  79727. if (sum1 > BASE) sum1 -= BASE;
  79728. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79729. if (sum2 > BASE) sum2 -= BASE;
  79730. return sum1 | (sum2 << 16);
  79731. }
  79732. /*** End of inlined file: adler32.c ***/
  79733. /*** Start of inlined file: compress.c ***/
  79734. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79735. #define ZLIB_INTERNAL
  79736. /* ===========================================================================
  79737. Compresses the source buffer into the destination buffer. The level
  79738. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79739. length of the source buffer. Upon entry, destLen is the total size of the
  79740. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79741. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79742. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79743. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79744. Z_STREAM_ERROR if the level parameter is invalid.
  79745. */
  79746. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79747. uLong sourceLen, int level)
  79748. {
  79749. z_stream stream;
  79750. int err;
  79751. stream.next_in = (Bytef*)source;
  79752. stream.avail_in = (uInt)sourceLen;
  79753. #ifdef MAXSEG_64K
  79754. /* Check for source > 64K on 16-bit machine: */
  79755. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79756. #endif
  79757. stream.next_out = dest;
  79758. stream.avail_out = (uInt)*destLen;
  79759. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79760. stream.zalloc = (alloc_func)0;
  79761. stream.zfree = (free_func)0;
  79762. stream.opaque = (voidpf)0;
  79763. err = deflateInit(&stream, level);
  79764. if (err != Z_OK) return err;
  79765. err = deflate(&stream, Z_FINISH);
  79766. if (err != Z_STREAM_END) {
  79767. deflateEnd(&stream);
  79768. return err == Z_OK ? Z_BUF_ERROR : err;
  79769. }
  79770. *destLen = stream.total_out;
  79771. err = deflateEnd(&stream);
  79772. return err;
  79773. }
  79774. /* ===========================================================================
  79775. */
  79776. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79777. {
  79778. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79779. }
  79780. /* ===========================================================================
  79781. If the default memLevel or windowBits for deflateInit() is changed, then
  79782. this function needs to be updated.
  79783. */
  79784. uLong ZEXPORT compressBound (uLong sourceLen)
  79785. {
  79786. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79787. }
  79788. /*** End of inlined file: compress.c ***/
  79789. #undef DO1
  79790. #undef DO8
  79791. /*** Start of inlined file: crc32.c ***/
  79792. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79793. /*
  79794. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79795. protection on the static variables used to control the first-use generation
  79796. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79797. first call get_crc_table() to initialize the tables before allowing more than
  79798. one thread to use crc32().
  79799. */
  79800. #ifdef MAKECRCH
  79801. # include <stdio.h>
  79802. # ifndef DYNAMIC_CRC_TABLE
  79803. # define DYNAMIC_CRC_TABLE
  79804. # endif /* !DYNAMIC_CRC_TABLE */
  79805. #endif /* MAKECRCH */
  79806. /*** Start of inlined file: zutil.h ***/
  79807. /* WARNING: this file should *not* be used by applications. It is
  79808. part of the implementation of the compression library and is
  79809. subject to change. Applications should only use zlib.h.
  79810. */
  79811. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79812. #ifndef ZUTIL_H
  79813. #define ZUTIL_H
  79814. #define ZLIB_INTERNAL
  79815. #ifdef STDC
  79816. # ifndef _WIN32_WCE
  79817. # include <stddef.h>
  79818. # endif
  79819. # include <string.h>
  79820. # include <stdlib.h>
  79821. #endif
  79822. #ifdef NO_ERRNO_H
  79823. # ifdef _WIN32_WCE
  79824. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79825. * errno. We define it as a global variable to simplify porting.
  79826. * Its value is always 0 and should not be used. We rename it to
  79827. * avoid conflict with other libraries that use the same workaround.
  79828. */
  79829. # define errno z_errno
  79830. # endif
  79831. extern int errno;
  79832. #else
  79833. # ifndef _WIN32_WCE
  79834. # include <errno.h>
  79835. # endif
  79836. #endif
  79837. #ifndef local
  79838. # define local static
  79839. #endif
  79840. /* compile with -Dlocal if your debugger can't find static symbols */
  79841. typedef unsigned char uch;
  79842. typedef uch FAR uchf;
  79843. typedef unsigned short ush;
  79844. typedef ush FAR ushf;
  79845. typedef unsigned long ulg;
  79846. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79847. /* (size given to avoid silly warnings with Visual C++) */
  79848. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79849. #define ERR_RETURN(strm,err) \
  79850. return (strm->msg = (char*)ERR_MSG(err), (err))
  79851. /* To be used only when the state is known to be valid */
  79852. /* common constants */
  79853. #ifndef DEF_WBITS
  79854. # define DEF_WBITS MAX_WBITS
  79855. #endif
  79856. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79857. #if MAX_MEM_LEVEL >= 8
  79858. # define DEF_MEM_LEVEL 8
  79859. #else
  79860. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79861. #endif
  79862. /* default memLevel */
  79863. #define STORED_BLOCK 0
  79864. #define STATIC_TREES 1
  79865. #define DYN_TREES 2
  79866. /* The three kinds of block type */
  79867. #define MIN_MATCH 3
  79868. #define MAX_MATCH 258
  79869. /* The minimum and maximum match lengths */
  79870. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79871. /* target dependencies */
  79872. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79873. # define OS_CODE 0x00
  79874. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79875. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79876. /* Allow compilation with ANSI keywords only enabled */
  79877. void _Cdecl farfree( void *block );
  79878. void *_Cdecl farmalloc( unsigned long nbytes );
  79879. # else
  79880. # include <alloc.h>
  79881. # endif
  79882. # else /* MSC or DJGPP */
  79883. # include <malloc.h>
  79884. # endif
  79885. #endif
  79886. #ifdef AMIGA
  79887. # define OS_CODE 0x01
  79888. #endif
  79889. #if defined(VAXC) || defined(VMS)
  79890. # define OS_CODE 0x02
  79891. # define F_OPEN(name, mode) \
  79892. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79893. #endif
  79894. #if defined(ATARI) || defined(atarist)
  79895. # define OS_CODE 0x05
  79896. #endif
  79897. #ifdef OS2
  79898. # define OS_CODE 0x06
  79899. # ifdef M_I86
  79900. #include <malloc.h>
  79901. # endif
  79902. #endif
  79903. #if defined(MACOS) || TARGET_OS_MAC
  79904. # define OS_CODE 0x07
  79905. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79906. # include <unix.h> /* for fdopen */
  79907. # else
  79908. # ifndef fdopen
  79909. # define fdopen(fd,mode) NULL /* No fdopen() */
  79910. # endif
  79911. # endif
  79912. #endif
  79913. #ifdef TOPS20
  79914. # define OS_CODE 0x0a
  79915. #endif
  79916. #ifdef WIN32
  79917. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79918. # define OS_CODE 0x0b
  79919. # endif
  79920. #endif
  79921. #ifdef __50SERIES /* Prime/PRIMOS */
  79922. # define OS_CODE 0x0f
  79923. #endif
  79924. #if defined(_BEOS_) || defined(RISCOS)
  79925. # define fdopen(fd,mode) NULL /* No fdopen() */
  79926. #endif
  79927. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79928. # if defined(_WIN32_WCE)
  79929. # define fdopen(fd,mode) NULL /* No fdopen() */
  79930. # ifndef _PTRDIFF_T_DEFINED
  79931. typedef int ptrdiff_t;
  79932. # define _PTRDIFF_T_DEFINED
  79933. # endif
  79934. # else
  79935. # define fdopen(fd,type) _fdopen(fd,type)
  79936. # endif
  79937. #endif
  79938. /* common defaults */
  79939. #ifndef OS_CODE
  79940. # define OS_CODE 0x03 /* assume Unix */
  79941. #endif
  79942. #ifndef F_OPEN
  79943. # define F_OPEN(name, mode) fopen((name), (mode))
  79944. #endif
  79945. /* functions */
  79946. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79947. # ifndef HAVE_VSNPRINTF
  79948. # define HAVE_VSNPRINTF
  79949. # endif
  79950. #endif
  79951. #if defined(__CYGWIN__)
  79952. # ifndef HAVE_VSNPRINTF
  79953. # define HAVE_VSNPRINTF
  79954. # endif
  79955. #endif
  79956. #ifndef HAVE_VSNPRINTF
  79957. # ifdef MSDOS
  79958. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79959. but for now we just assume it doesn't. */
  79960. # define NO_vsnprintf
  79961. # endif
  79962. # ifdef __TURBOC__
  79963. # define NO_vsnprintf
  79964. # endif
  79965. # ifdef WIN32
  79966. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79967. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79968. # define vsnprintf _vsnprintf
  79969. # endif
  79970. # endif
  79971. # ifdef __SASC
  79972. # define NO_vsnprintf
  79973. # endif
  79974. #endif
  79975. #ifdef VMS
  79976. # define NO_vsnprintf
  79977. #endif
  79978. #if defined(pyr)
  79979. # define NO_MEMCPY
  79980. #endif
  79981. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79982. /* Use our own functions for small and medium model with MSC <= 5.0.
  79983. * You may have to use the same strategy for Borland C (untested).
  79984. * The __SC__ check is for Symantec.
  79985. */
  79986. # define NO_MEMCPY
  79987. #endif
  79988. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79989. # define HAVE_MEMCPY
  79990. #endif
  79991. #ifdef HAVE_MEMCPY
  79992. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79993. # define zmemcpy _fmemcpy
  79994. # define zmemcmp _fmemcmp
  79995. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79996. # else
  79997. # define zmemcpy memcpy
  79998. # define zmemcmp memcmp
  79999. # define zmemzero(dest, len) memset(dest, 0, len)
  80000. # endif
  80001. #else
  80002. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80003. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80004. extern void zmemzero OF((Bytef* dest, uInt len));
  80005. #endif
  80006. /* Diagnostic functions */
  80007. #ifdef DEBUG
  80008. # include <stdio.h>
  80009. extern int z_verbose;
  80010. extern void z_error OF((const char *m));
  80011. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80012. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80013. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80014. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80015. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80016. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80017. #else
  80018. # define Assert(cond,msg)
  80019. # define Trace(x)
  80020. # define Tracev(x)
  80021. # define Tracevv(x)
  80022. # define Tracec(c,x)
  80023. # define Tracecv(c,x)
  80024. #endif
  80025. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80026. void zcfree OF((voidpf opaque, voidpf ptr));
  80027. #define ZALLOC(strm, items, size) \
  80028. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80029. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80030. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80031. #endif /* ZUTIL_H */
  80032. /*** End of inlined file: zutil.h ***/
  80033. /* for STDC and FAR definitions */
  80034. #define local static
  80035. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80036. #ifndef NOBYFOUR
  80037. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80038. # include <limits.h>
  80039. # define BYFOUR
  80040. # if (UINT_MAX == 0xffffffffUL)
  80041. typedef unsigned int u4;
  80042. # else
  80043. # if (ULONG_MAX == 0xffffffffUL)
  80044. typedef unsigned long u4;
  80045. # else
  80046. # if (USHRT_MAX == 0xffffffffUL)
  80047. typedef unsigned short u4;
  80048. # else
  80049. # undef BYFOUR /* can't find a four-byte integer type! */
  80050. # endif
  80051. # endif
  80052. # endif
  80053. # endif /* STDC */
  80054. #endif /* !NOBYFOUR */
  80055. /* Definitions for doing the crc four data bytes at a time. */
  80056. #ifdef BYFOUR
  80057. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80058. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80059. local unsigned long crc32_little OF((unsigned long,
  80060. const unsigned char FAR *, unsigned));
  80061. local unsigned long crc32_big OF((unsigned long,
  80062. const unsigned char FAR *, unsigned));
  80063. # define TBLS 8
  80064. #else
  80065. # define TBLS 1
  80066. #endif /* BYFOUR */
  80067. /* Local functions for crc concatenation */
  80068. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80069. unsigned long vec));
  80070. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80071. #ifdef DYNAMIC_CRC_TABLE
  80072. local volatile int crc_table_empty = 1;
  80073. local unsigned long FAR crc_table[TBLS][256];
  80074. local void make_crc_table OF((void));
  80075. #ifdef MAKECRCH
  80076. local void write_table OF((FILE *, const unsigned long FAR *));
  80077. #endif /* MAKECRCH */
  80078. /*
  80079. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80080. 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.
  80081. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80082. with the lowest powers in the most significant bit. Then adding polynomials
  80083. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80084. one. If we call the above polynomial p, and represent a byte as the
  80085. polynomial q, also with the lowest power in the most significant bit (so the
  80086. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80087. where a mod b means the remainder after dividing a by b.
  80088. This calculation is done using the shift-register method of multiplying and
  80089. taking the remainder. The register is initialized to zero, and for each
  80090. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80091. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80092. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80093. out is a one). We start with the highest power (least significant bit) of
  80094. q and repeat for all eight bits of q.
  80095. The first table is simply the CRC of all possible eight bit values. This is
  80096. all the information needed to generate CRCs on data a byte at a time for all
  80097. combinations of CRC register values and incoming bytes. The remaining tables
  80098. allow for word-at-a-time CRC calculation for both big-endian and little-
  80099. endian machines, where a word is four bytes.
  80100. */
  80101. local void make_crc_table()
  80102. {
  80103. unsigned long c;
  80104. int n, k;
  80105. unsigned long poly; /* polynomial exclusive-or pattern */
  80106. /* terms of polynomial defining this crc (except x^32): */
  80107. static volatile int first = 1; /* flag to limit concurrent making */
  80108. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80109. /* See if another task is already doing this (not thread-safe, but better
  80110. than nothing -- significantly reduces duration of vulnerability in
  80111. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80112. if (first) {
  80113. first = 0;
  80114. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80115. poly = 0UL;
  80116. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80117. poly |= 1UL << (31 - p[n]);
  80118. /* generate a crc for every 8-bit value */
  80119. for (n = 0; n < 256; n++) {
  80120. c = (unsigned long)n;
  80121. for (k = 0; k < 8; k++)
  80122. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80123. crc_table[0][n] = c;
  80124. }
  80125. #ifdef BYFOUR
  80126. /* generate crc for each value followed by one, two, and three zeros,
  80127. and then the byte reversal of those as well as the first table */
  80128. for (n = 0; n < 256; n++) {
  80129. c = crc_table[0][n];
  80130. crc_table[4][n] = REV(c);
  80131. for (k = 1; k < 4; k++) {
  80132. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80133. crc_table[k][n] = c;
  80134. crc_table[k + 4][n] = REV(c);
  80135. }
  80136. }
  80137. #endif /* BYFOUR */
  80138. crc_table_empty = 0;
  80139. }
  80140. else { /* not first */
  80141. /* wait for the other guy to finish (not efficient, but rare) */
  80142. while (crc_table_empty)
  80143. ;
  80144. }
  80145. #ifdef MAKECRCH
  80146. /* write out CRC tables to crc32.h */
  80147. {
  80148. FILE *out;
  80149. out = fopen("crc32.h", "w");
  80150. if (out == NULL) return;
  80151. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80152. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80153. fprintf(out, "local const unsigned long FAR ");
  80154. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80155. write_table(out, crc_table[0]);
  80156. # ifdef BYFOUR
  80157. fprintf(out, "#ifdef BYFOUR\n");
  80158. for (k = 1; k < 8; k++) {
  80159. fprintf(out, " },\n {\n");
  80160. write_table(out, crc_table[k]);
  80161. }
  80162. fprintf(out, "#endif\n");
  80163. # endif /* BYFOUR */
  80164. fprintf(out, " }\n};\n");
  80165. fclose(out);
  80166. }
  80167. #endif /* MAKECRCH */
  80168. }
  80169. #ifdef MAKECRCH
  80170. local void write_table(out, table)
  80171. FILE *out;
  80172. const unsigned long FAR *table;
  80173. {
  80174. int n;
  80175. for (n = 0; n < 256; n++)
  80176. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80177. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80178. }
  80179. #endif /* MAKECRCH */
  80180. #else /* !DYNAMIC_CRC_TABLE */
  80181. /* ========================================================================
  80182. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80183. */
  80184. /*** Start of inlined file: crc32.h ***/
  80185. local const unsigned long FAR crc_table[TBLS][256] =
  80186. {
  80187. {
  80188. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80189. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80190. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80191. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80192. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80193. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80194. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80195. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80196. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80197. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80198. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80199. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80200. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80201. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80202. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80203. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80204. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80205. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80206. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80207. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80208. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80209. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80210. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80211. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80212. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80213. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80214. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80215. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80216. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80217. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80218. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80219. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80220. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80221. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80222. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80223. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80224. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80225. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80226. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80227. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80228. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80229. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80230. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80231. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80232. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80233. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80234. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80235. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80236. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80237. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80238. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80239. 0x2d02ef8dUL
  80240. #ifdef BYFOUR
  80241. },
  80242. {
  80243. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80244. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80245. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80246. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80247. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80248. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80249. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80250. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80251. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80252. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80253. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80254. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80255. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80256. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80257. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80258. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80259. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80260. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80261. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80262. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80263. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80264. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80265. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80266. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80267. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80268. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80269. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80270. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80271. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80272. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80273. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80274. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80275. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80276. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80277. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80278. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80279. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80280. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80281. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80282. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80283. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80284. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80285. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80286. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80287. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80288. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80289. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80290. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80291. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80292. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80293. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80294. 0x9324fd72UL
  80295. },
  80296. {
  80297. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80298. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80299. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80300. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80301. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80302. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80303. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80304. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80305. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80306. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80307. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80308. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80309. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80310. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80311. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80312. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80313. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80314. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80315. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80316. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80317. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80318. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80319. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80320. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80321. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80322. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80323. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80324. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80325. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80326. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80327. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80328. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80329. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80330. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80331. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80332. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80333. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80334. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80335. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80336. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80337. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80338. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80339. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80340. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80341. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80342. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80343. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80344. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80345. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80346. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80347. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80348. 0xbe9834edUL
  80349. },
  80350. {
  80351. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80352. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80353. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80354. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80355. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80356. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80357. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80358. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80359. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80360. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80361. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80362. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80363. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80364. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80365. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80366. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80367. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80368. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80369. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80370. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80371. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80372. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80373. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80374. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80375. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80376. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80377. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80378. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80379. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80380. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80381. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80382. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80383. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80384. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80385. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80386. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80387. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80388. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80389. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80390. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80391. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80392. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80393. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80394. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80395. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80396. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80397. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80398. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80399. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80400. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80401. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80402. 0xde0506f1UL
  80403. },
  80404. {
  80405. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80406. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80407. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80408. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80409. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80410. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80411. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80412. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80413. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80414. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80415. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80416. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80417. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80418. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80419. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80420. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80421. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80422. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80423. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80424. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80425. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80426. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80427. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80428. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80429. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80430. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80431. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80432. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80433. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80434. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80435. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80436. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80437. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80438. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80439. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80440. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80441. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80442. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80443. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80444. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80445. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80446. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80447. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80448. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80449. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80450. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80451. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80452. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80453. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80454. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80455. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80456. 0x8def022dUL
  80457. },
  80458. {
  80459. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80460. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80461. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80462. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80463. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80464. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80465. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80466. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80467. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80468. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80469. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80470. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80471. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80472. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80473. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80474. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80475. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80476. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80477. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80478. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80479. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80480. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80481. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80482. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80483. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80484. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80485. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80486. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80487. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80488. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80489. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80490. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80491. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80492. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80493. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80494. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80495. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80496. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80497. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80498. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80499. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80500. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80501. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80502. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80503. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80504. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80505. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80506. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80507. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80508. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80509. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80510. 0x72fd2493UL
  80511. },
  80512. {
  80513. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80514. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80515. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80516. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80517. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80518. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80519. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80520. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80521. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80522. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80523. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80524. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80525. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80526. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80527. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80528. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80529. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80530. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80531. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80532. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80533. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80534. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80535. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80536. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80537. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80538. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80539. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80540. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80541. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80542. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80543. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80544. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80545. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80546. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80547. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80548. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80549. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80550. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80551. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80552. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80553. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80554. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80555. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80556. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80557. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80558. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80559. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80560. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80561. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80562. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80563. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80564. 0xed3498beUL
  80565. },
  80566. {
  80567. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80568. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80569. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80570. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80571. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80572. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80573. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80574. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80575. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80576. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80577. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80578. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80579. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80580. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80581. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80582. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80583. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80584. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80585. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80586. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80587. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80588. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80589. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80590. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80591. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80592. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80593. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80594. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80595. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80596. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80597. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80598. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80599. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80600. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80601. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80602. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80603. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80604. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80605. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80606. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80607. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80608. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80609. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80610. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80611. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80612. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80613. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80614. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80615. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80616. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80617. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80618. 0xf10605deUL
  80619. #endif
  80620. }
  80621. };
  80622. /*** End of inlined file: crc32.h ***/
  80623. #endif /* DYNAMIC_CRC_TABLE */
  80624. /* =========================================================================
  80625. * This function can be used by asm versions of crc32()
  80626. */
  80627. const unsigned long FAR * ZEXPORT get_crc_table()
  80628. {
  80629. #ifdef DYNAMIC_CRC_TABLE
  80630. if (crc_table_empty)
  80631. make_crc_table();
  80632. #endif /* DYNAMIC_CRC_TABLE */
  80633. return (const unsigned long FAR *)crc_table;
  80634. }
  80635. /* ========================================================================= */
  80636. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80637. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80638. /* ========================================================================= */
  80639. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80640. {
  80641. if (buf == Z_NULL) return 0UL;
  80642. #ifdef DYNAMIC_CRC_TABLE
  80643. if (crc_table_empty)
  80644. make_crc_table();
  80645. #endif /* DYNAMIC_CRC_TABLE */
  80646. #ifdef BYFOUR
  80647. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80648. u4 endian;
  80649. endian = 1;
  80650. if (*((unsigned char *)(&endian)))
  80651. return crc32_little(crc, buf, len);
  80652. else
  80653. return crc32_big(crc, buf, len);
  80654. }
  80655. #endif /* BYFOUR */
  80656. crc = crc ^ 0xffffffffUL;
  80657. while (len >= 8) {
  80658. DO8;
  80659. len -= 8;
  80660. }
  80661. if (len) do {
  80662. DO1;
  80663. } while (--len);
  80664. return crc ^ 0xffffffffUL;
  80665. }
  80666. #ifdef BYFOUR
  80667. /* ========================================================================= */
  80668. #define DOLIT4 c ^= *buf4++; \
  80669. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80670. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80671. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80672. /* ========================================================================= */
  80673. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80674. {
  80675. register u4 c;
  80676. register const u4 FAR *buf4;
  80677. c = (u4)crc;
  80678. c = ~c;
  80679. while (len && ((ptrdiff_t)buf & 3)) {
  80680. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80681. len--;
  80682. }
  80683. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80684. while (len >= 32) {
  80685. DOLIT32;
  80686. len -= 32;
  80687. }
  80688. while (len >= 4) {
  80689. DOLIT4;
  80690. len -= 4;
  80691. }
  80692. buf = (const unsigned char FAR *)buf4;
  80693. if (len) do {
  80694. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80695. } while (--len);
  80696. c = ~c;
  80697. return (unsigned long)c;
  80698. }
  80699. /* ========================================================================= */
  80700. #define DOBIG4 c ^= *++buf4; \
  80701. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80702. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80703. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80704. /* ========================================================================= */
  80705. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80706. {
  80707. register u4 c;
  80708. register const u4 FAR *buf4;
  80709. c = REV((u4)crc);
  80710. c = ~c;
  80711. while (len && ((ptrdiff_t)buf & 3)) {
  80712. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80713. len--;
  80714. }
  80715. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80716. buf4--;
  80717. while (len >= 32) {
  80718. DOBIG32;
  80719. len -= 32;
  80720. }
  80721. while (len >= 4) {
  80722. DOBIG4;
  80723. len -= 4;
  80724. }
  80725. buf4++;
  80726. buf = (const unsigned char FAR *)buf4;
  80727. if (len) do {
  80728. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80729. } while (--len);
  80730. c = ~c;
  80731. return (unsigned long)(REV(c));
  80732. }
  80733. #endif /* BYFOUR */
  80734. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80735. /* ========================================================================= */
  80736. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80737. {
  80738. unsigned long sum;
  80739. sum = 0;
  80740. while (vec) {
  80741. if (vec & 1)
  80742. sum ^= *mat;
  80743. vec >>= 1;
  80744. mat++;
  80745. }
  80746. return sum;
  80747. }
  80748. /* ========================================================================= */
  80749. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80750. {
  80751. int n;
  80752. for (n = 0; n < GF2_DIM; n++)
  80753. square[n] = gf2_matrix_times(mat, mat[n]);
  80754. }
  80755. /* ========================================================================= */
  80756. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80757. {
  80758. int n;
  80759. unsigned long row;
  80760. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80761. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80762. /* degenerate case */
  80763. if (len2 == 0)
  80764. return crc1;
  80765. /* put operator for one zero bit in odd */
  80766. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80767. row = 1;
  80768. for (n = 1; n < GF2_DIM; n++) {
  80769. odd[n] = row;
  80770. row <<= 1;
  80771. }
  80772. /* put operator for two zero bits in even */
  80773. gf2_matrix_square(even, odd);
  80774. /* put operator for four zero bits in odd */
  80775. gf2_matrix_square(odd, even);
  80776. /* apply len2 zeros to crc1 (first square will put the operator for one
  80777. zero byte, eight zero bits, in even) */
  80778. do {
  80779. /* apply zeros operator for this bit of len2 */
  80780. gf2_matrix_square(even, odd);
  80781. if (len2 & 1)
  80782. crc1 = gf2_matrix_times(even, crc1);
  80783. len2 >>= 1;
  80784. /* if no more bits set, then done */
  80785. if (len2 == 0)
  80786. break;
  80787. /* another iteration of the loop with odd and even swapped */
  80788. gf2_matrix_square(odd, even);
  80789. if (len2 & 1)
  80790. crc1 = gf2_matrix_times(odd, crc1);
  80791. len2 >>= 1;
  80792. /* if no more bits set, then done */
  80793. } while (len2 != 0);
  80794. /* return combined crc */
  80795. crc1 ^= crc2;
  80796. return crc1;
  80797. }
  80798. /*** End of inlined file: crc32.c ***/
  80799. /*** Start of inlined file: deflate.c ***/
  80800. /*
  80801. * ALGORITHM
  80802. *
  80803. * The "deflation" process depends on being able to identify portions
  80804. * of the input text which are identical to earlier input (within a
  80805. * sliding window trailing behind the input currently being processed).
  80806. *
  80807. * The most straightforward technique turns out to be the fastest for
  80808. * most input files: try all possible matches and select the longest.
  80809. * The key feature of this algorithm is that insertions into the string
  80810. * dictionary are very simple and thus fast, and deletions are avoided
  80811. * completely. Insertions are performed at each input character, whereas
  80812. * string matches are performed only when the previous match ends. So it
  80813. * is preferable to spend more time in matches to allow very fast string
  80814. * insertions and avoid deletions. The matching algorithm for small
  80815. * strings is inspired from that of Rabin & Karp. A brute force approach
  80816. * is used to find longer strings when a small match has been found.
  80817. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80818. * (by Leonid Broukhis).
  80819. * A previous version of this file used a more sophisticated algorithm
  80820. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80821. * time, but has a larger average cost, uses more memory and is patented.
  80822. * However the F&G algorithm may be faster for some highly redundant
  80823. * files if the parameter max_chain_length (described below) is too large.
  80824. *
  80825. * ACKNOWLEDGEMENTS
  80826. *
  80827. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80828. * I found it in 'freeze' written by Leonid Broukhis.
  80829. * Thanks to many people for bug reports and testing.
  80830. *
  80831. * REFERENCES
  80832. *
  80833. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80834. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80835. *
  80836. * A description of the Rabin and Karp algorithm is given in the book
  80837. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80838. *
  80839. * Fiala,E.R., and Greene,D.H.
  80840. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80841. *
  80842. */
  80843. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80844. /*** Start of inlined file: deflate.h ***/
  80845. /* WARNING: this file should *not* be used by applications. It is
  80846. part of the implementation of the compression library and is
  80847. subject to change. Applications should only use zlib.h.
  80848. */
  80849. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80850. #ifndef DEFLATE_H
  80851. #define DEFLATE_H
  80852. /* define NO_GZIP when compiling if you want to disable gzip header and
  80853. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80854. the crc code when it is not needed. For shared libraries, gzip encoding
  80855. should be left enabled. */
  80856. #ifndef NO_GZIP
  80857. # define GZIP
  80858. #endif
  80859. #define NO_DUMMY_DECL
  80860. /* ===========================================================================
  80861. * Internal compression state.
  80862. */
  80863. #define LENGTH_CODES 29
  80864. /* number of length codes, not counting the special END_BLOCK code */
  80865. #define LITERALS 256
  80866. /* number of literal bytes 0..255 */
  80867. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80868. /* number of Literal or Length codes, including the END_BLOCK code */
  80869. #define D_CODES 30
  80870. /* number of distance codes */
  80871. #define BL_CODES 19
  80872. /* number of codes used to transfer the bit lengths */
  80873. #define HEAP_SIZE (2*L_CODES+1)
  80874. /* maximum heap size */
  80875. #define MAX_BITS 15
  80876. /* All codes must not exceed MAX_BITS bits */
  80877. #define INIT_STATE 42
  80878. #define EXTRA_STATE 69
  80879. #define NAME_STATE 73
  80880. #define COMMENT_STATE 91
  80881. #define HCRC_STATE 103
  80882. #define BUSY_STATE 113
  80883. #define FINISH_STATE 666
  80884. /* Stream status */
  80885. /* Data structure describing a single value and its code string. */
  80886. typedef struct ct_data_s {
  80887. union {
  80888. ush freq; /* frequency count */
  80889. ush code; /* bit string */
  80890. } fc;
  80891. union {
  80892. ush dad; /* father node in Huffman tree */
  80893. ush len; /* length of bit string */
  80894. } dl;
  80895. } FAR ct_data;
  80896. #define Freq fc.freq
  80897. #define Code fc.code
  80898. #define Dad dl.dad
  80899. #define Len dl.len
  80900. typedef struct static_tree_desc_s static_tree_desc;
  80901. typedef struct tree_desc_s {
  80902. ct_data *dyn_tree; /* the dynamic tree */
  80903. int max_code; /* largest code with non zero frequency */
  80904. static_tree_desc *stat_desc; /* the corresponding static tree */
  80905. } FAR tree_desc;
  80906. typedef ush Pos;
  80907. typedef Pos FAR Posf;
  80908. typedef unsigned IPos;
  80909. /* A Pos is an index in the character window. We use short instead of int to
  80910. * save space in the various tables. IPos is used only for parameter passing.
  80911. */
  80912. typedef struct internal_state {
  80913. z_streamp strm; /* pointer back to this zlib stream */
  80914. int status; /* as the name implies */
  80915. Bytef *pending_buf; /* output still pending */
  80916. ulg pending_buf_size; /* size of pending_buf */
  80917. Bytef *pending_out; /* next pending byte to output to the stream */
  80918. uInt pending; /* nb of bytes in the pending buffer */
  80919. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80920. gz_headerp gzhead; /* gzip header information to write */
  80921. uInt gzindex; /* where in extra, name, or comment */
  80922. Byte method; /* STORED (for zip only) or DEFLATED */
  80923. int last_flush; /* value of flush param for previous deflate call */
  80924. /* used by deflate.c: */
  80925. uInt w_size; /* LZ77 window size (32K by default) */
  80926. uInt w_bits; /* log2(w_size) (8..16) */
  80927. uInt w_mask; /* w_size - 1 */
  80928. Bytef *window;
  80929. /* Sliding window. Input bytes are read into the second half of the window,
  80930. * and move to the first half later to keep a dictionary of at least wSize
  80931. * bytes. With this organization, matches are limited to a distance of
  80932. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80933. * performed with a length multiple of the block size. Also, it limits
  80934. * the window size to 64K, which is quite useful on MSDOS.
  80935. * To do: use the user input buffer as sliding window.
  80936. */
  80937. ulg window_size;
  80938. /* Actual size of window: 2*wSize, except when the user input buffer
  80939. * is directly used as sliding window.
  80940. */
  80941. Posf *prev;
  80942. /* Link to older string with same hash index. To limit the size of this
  80943. * array to 64K, this link is maintained only for the last 32K strings.
  80944. * An index in this array is thus a window index modulo 32K.
  80945. */
  80946. Posf *head; /* Heads of the hash chains or NIL. */
  80947. uInt ins_h; /* hash index of string to be inserted */
  80948. uInt hash_size; /* number of elements in hash table */
  80949. uInt hash_bits; /* log2(hash_size) */
  80950. uInt hash_mask; /* hash_size-1 */
  80951. uInt hash_shift;
  80952. /* Number of bits by which ins_h must be shifted at each input
  80953. * step. It must be such that after MIN_MATCH steps, the oldest
  80954. * byte no longer takes part in the hash key, that is:
  80955. * hash_shift * MIN_MATCH >= hash_bits
  80956. */
  80957. long block_start;
  80958. /* Window position at the beginning of the current output block. Gets
  80959. * negative when the window is moved backwards.
  80960. */
  80961. uInt match_length; /* length of best match */
  80962. IPos prev_match; /* previous match */
  80963. int match_available; /* set if previous match exists */
  80964. uInt strstart; /* start of string to insert */
  80965. uInt match_start; /* start of matching string */
  80966. uInt lookahead; /* number of valid bytes ahead in window */
  80967. uInt prev_length;
  80968. /* Length of the best match at previous step. Matches not greater than this
  80969. * are discarded. This is used in the lazy match evaluation.
  80970. */
  80971. uInt max_chain_length;
  80972. /* To speed up deflation, hash chains are never searched beyond this
  80973. * length. A higher limit improves compression ratio but degrades the
  80974. * speed.
  80975. */
  80976. uInt max_lazy_match;
  80977. /* Attempt to find a better match only when the current match is strictly
  80978. * smaller than this value. This mechanism is used only for compression
  80979. * levels >= 4.
  80980. */
  80981. # define max_insert_length max_lazy_match
  80982. /* Insert new strings in the hash table only if the match length is not
  80983. * greater than this length. This saves time but degrades compression.
  80984. * max_insert_length is used only for compression levels <= 3.
  80985. */
  80986. int level; /* compression level (1..9) */
  80987. int strategy; /* favor or force Huffman coding*/
  80988. uInt good_match;
  80989. /* Use a faster search when the previous match is longer than this */
  80990. int nice_match; /* Stop searching when current match exceeds this */
  80991. /* used by trees.c: */
  80992. /* Didn't use ct_data typedef below to supress compiler warning */
  80993. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80994. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80995. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80996. struct tree_desc_s l_desc; /* desc. for literal tree */
  80997. struct tree_desc_s d_desc; /* desc. for distance tree */
  80998. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80999. ush bl_count[MAX_BITS+1];
  81000. /* number of codes at each bit length for an optimal tree */
  81001. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81002. int heap_len; /* number of elements in the heap */
  81003. int heap_max; /* element of largest frequency */
  81004. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81005. * The same heap array is used to build all trees.
  81006. */
  81007. uch depth[2*L_CODES+1];
  81008. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81009. */
  81010. uchf *l_buf; /* buffer for literals or lengths */
  81011. uInt lit_bufsize;
  81012. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81013. * limiting lit_bufsize to 64K:
  81014. * - frequencies can be kept in 16 bit counters
  81015. * - if compression is not successful for the first block, all input
  81016. * data is still in the window so we can still emit a stored block even
  81017. * when input comes from standard input. (This can also be done for
  81018. * all blocks if lit_bufsize is not greater than 32K.)
  81019. * - if compression is not successful for a file smaller than 64K, we can
  81020. * even emit a stored file instead of a stored block (saving 5 bytes).
  81021. * This is applicable only for zip (not gzip or zlib).
  81022. * - creating new Huffman trees less frequently may not provide fast
  81023. * adaptation to changes in the input data statistics. (Take for
  81024. * example a binary file with poorly compressible code followed by
  81025. * a highly compressible string table.) Smaller buffer sizes give
  81026. * fast adaptation but have of course the overhead of transmitting
  81027. * trees more frequently.
  81028. * - I can't count above 4
  81029. */
  81030. uInt last_lit; /* running index in l_buf */
  81031. ushf *d_buf;
  81032. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81033. * the same number of elements. To use different lengths, an extra flag
  81034. * array would be necessary.
  81035. */
  81036. ulg opt_len; /* bit length of current block with optimal trees */
  81037. ulg static_len; /* bit length of current block with static trees */
  81038. uInt matches; /* number of string matches in current block */
  81039. int last_eob_len; /* bit length of EOB code for last block */
  81040. #ifdef DEBUG
  81041. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81042. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81043. #endif
  81044. ush bi_buf;
  81045. /* Output buffer. bits are inserted starting at the bottom (least
  81046. * significant bits).
  81047. */
  81048. int bi_valid;
  81049. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81050. * are always zero.
  81051. */
  81052. } FAR deflate_state;
  81053. /* Output a byte on the stream.
  81054. * IN assertion: there is enough room in pending_buf.
  81055. */
  81056. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81057. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81058. /* Minimum amount of lookahead, except at the end of the input file.
  81059. * See deflate.c for comments about the MIN_MATCH+1.
  81060. */
  81061. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81062. /* In order to simplify the code, particularly on 16 bit machines, match
  81063. * distances are limited to MAX_DIST instead of WSIZE.
  81064. */
  81065. /* in trees.c */
  81066. void _tr_init OF((deflate_state *s));
  81067. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81068. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81069. int eof));
  81070. void _tr_align OF((deflate_state *s));
  81071. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81072. int eof));
  81073. #define d_code(dist) \
  81074. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81075. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81076. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81077. * used.
  81078. */
  81079. #ifndef DEBUG
  81080. /* Inline versions of _tr_tally for speed: */
  81081. #if defined(GEN_TREES_H) || !defined(STDC)
  81082. extern uch _length_code[];
  81083. extern uch _dist_code[];
  81084. #else
  81085. extern const uch _length_code[];
  81086. extern const uch _dist_code[];
  81087. #endif
  81088. # define _tr_tally_lit(s, c, flush) \
  81089. { uch cc = (c); \
  81090. s->d_buf[s->last_lit] = 0; \
  81091. s->l_buf[s->last_lit++] = cc; \
  81092. s->dyn_ltree[cc].Freq++; \
  81093. flush = (s->last_lit == s->lit_bufsize-1); \
  81094. }
  81095. # define _tr_tally_dist(s, distance, length, flush) \
  81096. { uch len = (length); \
  81097. ush dist = (distance); \
  81098. s->d_buf[s->last_lit] = dist; \
  81099. s->l_buf[s->last_lit++] = len; \
  81100. dist--; \
  81101. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81102. s->dyn_dtree[d_code(dist)].Freq++; \
  81103. flush = (s->last_lit == s->lit_bufsize-1); \
  81104. }
  81105. #else
  81106. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81107. # define _tr_tally_dist(s, distance, length, flush) \
  81108. flush = _tr_tally(s, distance, length)
  81109. #endif
  81110. #endif /* DEFLATE_H */
  81111. /*** End of inlined file: deflate.h ***/
  81112. const char deflate_copyright[] =
  81113. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81114. /*
  81115. If you use the zlib library in a product, an acknowledgment is welcome
  81116. in the documentation of your product. If for some reason you cannot
  81117. include such an acknowledgment, I would appreciate that you keep this
  81118. copyright string in the executable of your product.
  81119. */
  81120. /* ===========================================================================
  81121. * Function prototypes.
  81122. */
  81123. typedef enum {
  81124. need_more, /* block not completed, need more input or more output */
  81125. block_done, /* block flush performed */
  81126. finish_started, /* finish started, need only more output at next deflate */
  81127. finish_done /* finish done, accept no more input or output */
  81128. } block_state;
  81129. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81130. /* Compression function. Returns the block state after the call. */
  81131. local void fill_window OF((deflate_state *s));
  81132. local block_state deflate_stored OF((deflate_state *s, int flush));
  81133. local block_state deflate_fast OF((deflate_state *s, int flush));
  81134. #ifndef FASTEST
  81135. local block_state deflate_slow OF((deflate_state *s, int flush));
  81136. #endif
  81137. local void lm_init OF((deflate_state *s));
  81138. local void putShortMSB OF((deflate_state *s, uInt b));
  81139. local void flush_pending OF((z_streamp strm));
  81140. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81141. #ifndef FASTEST
  81142. #ifdef ASMV
  81143. void match_init OF((void)); /* asm code initialization */
  81144. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81145. #else
  81146. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81147. #endif
  81148. #endif
  81149. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81150. #ifdef DEBUG
  81151. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81152. int length));
  81153. #endif
  81154. /* ===========================================================================
  81155. * Local data
  81156. */
  81157. #define NIL 0
  81158. /* Tail of hash chains */
  81159. #ifndef TOO_FAR
  81160. # define TOO_FAR 4096
  81161. #endif
  81162. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81163. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81164. /* Minimum amount of lookahead, except at the end of the input file.
  81165. * See deflate.c for comments about the MIN_MATCH+1.
  81166. */
  81167. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81168. * the desired pack level (0..9). The values given below have been tuned to
  81169. * exclude worst case performance for pathological files. Better values may be
  81170. * found for specific files.
  81171. */
  81172. typedef struct config_s {
  81173. ush good_length; /* reduce lazy search above this match length */
  81174. ush max_lazy; /* do not perform lazy search above this match length */
  81175. ush nice_length; /* quit search above this match length */
  81176. ush max_chain;
  81177. compress_func func;
  81178. } config;
  81179. #ifdef FASTEST
  81180. local const config configuration_table[2] = {
  81181. /* good lazy nice chain */
  81182. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81183. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81184. #else
  81185. local const config configuration_table[10] = {
  81186. /* good lazy nice chain */
  81187. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81188. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81189. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81190. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81191. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81192. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81193. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81194. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81195. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81196. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81197. #endif
  81198. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81199. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81200. * meaning.
  81201. */
  81202. #define EQUAL 0
  81203. /* result of memcmp for equal strings */
  81204. #ifndef NO_DUMMY_DECL
  81205. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81206. #endif
  81207. /* ===========================================================================
  81208. * Update a hash value with the given input byte
  81209. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81210. * input characters, so that a running hash key can be computed from the
  81211. * previous key instead of complete recalculation each time.
  81212. */
  81213. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81214. /* ===========================================================================
  81215. * Insert string str in the dictionary and set match_head to the previous head
  81216. * of the hash chain (the most recent string with same hash key). Return
  81217. * the previous length of the hash chain.
  81218. * If this file is compiled with -DFASTEST, the compression level is forced
  81219. * to 1, and no hash chains are maintained.
  81220. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81221. * input characters and the first MIN_MATCH bytes of str are valid
  81222. * (except for the last MIN_MATCH-1 bytes of the input file).
  81223. */
  81224. #ifdef FASTEST
  81225. #define INSERT_STRING(s, str, match_head) \
  81226. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81227. match_head = s->head[s->ins_h], \
  81228. s->head[s->ins_h] = (Pos)(str))
  81229. #else
  81230. #define INSERT_STRING(s, str, match_head) \
  81231. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81232. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81233. s->head[s->ins_h] = (Pos)(str))
  81234. #endif
  81235. /* ===========================================================================
  81236. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81237. * prev[] will be initialized on the fly.
  81238. */
  81239. #define CLEAR_HASH(s) \
  81240. s->head[s->hash_size-1] = NIL; \
  81241. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81242. /* ========================================================================= */
  81243. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81244. {
  81245. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81246. Z_DEFAULT_STRATEGY, version, stream_size);
  81247. /* To do: ignore strm->next_in if we use it as window */
  81248. }
  81249. /* ========================================================================= */
  81250. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81251. {
  81252. deflate_state *s;
  81253. int wrap = 1;
  81254. static const char my_version[] = ZLIB_VERSION;
  81255. ushf *overlay;
  81256. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81257. * output size for (length,distance) codes is <= 24 bits.
  81258. */
  81259. if (version == Z_NULL || version[0] != my_version[0] ||
  81260. stream_size != sizeof(z_stream)) {
  81261. return Z_VERSION_ERROR;
  81262. }
  81263. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81264. strm->msg = Z_NULL;
  81265. if (strm->zalloc == (alloc_func)0) {
  81266. strm->zalloc = zcalloc;
  81267. strm->opaque = (voidpf)0;
  81268. }
  81269. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81270. #ifdef FASTEST
  81271. if (level != 0) level = 1;
  81272. #else
  81273. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81274. #endif
  81275. if (windowBits < 0) { /* suppress zlib wrapper */
  81276. wrap = 0;
  81277. windowBits = -windowBits;
  81278. }
  81279. #ifdef GZIP
  81280. else if (windowBits > 15) {
  81281. wrap = 2; /* write gzip wrapper instead */
  81282. windowBits -= 16;
  81283. }
  81284. #endif
  81285. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81286. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81287. strategy < 0 || strategy > Z_FIXED) {
  81288. return Z_STREAM_ERROR;
  81289. }
  81290. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81291. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81292. if (s == Z_NULL) return Z_MEM_ERROR;
  81293. strm->state = (struct internal_state FAR *)s;
  81294. s->strm = strm;
  81295. s->wrap = wrap;
  81296. s->gzhead = Z_NULL;
  81297. s->w_bits = windowBits;
  81298. s->w_size = 1 << s->w_bits;
  81299. s->w_mask = s->w_size - 1;
  81300. s->hash_bits = memLevel + 7;
  81301. s->hash_size = 1 << s->hash_bits;
  81302. s->hash_mask = s->hash_size - 1;
  81303. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81304. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81305. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81306. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81307. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81308. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81309. s->pending_buf = (uchf *) overlay;
  81310. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81311. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81312. s->pending_buf == Z_NULL) {
  81313. s->status = FINISH_STATE;
  81314. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81315. deflateEnd (strm);
  81316. return Z_MEM_ERROR;
  81317. }
  81318. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81319. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81320. s->level = level;
  81321. s->strategy = strategy;
  81322. s->method = (Byte)method;
  81323. return deflateReset(strm);
  81324. }
  81325. /* ========================================================================= */
  81326. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81327. {
  81328. deflate_state *s;
  81329. uInt length = dictLength;
  81330. uInt n;
  81331. IPos hash_head = 0;
  81332. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81333. strm->state->wrap == 2 ||
  81334. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81335. return Z_STREAM_ERROR;
  81336. s = strm->state;
  81337. if (s->wrap)
  81338. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81339. if (length < MIN_MATCH) return Z_OK;
  81340. if (length > MAX_DIST(s)) {
  81341. length = MAX_DIST(s);
  81342. dictionary += dictLength - length; /* use the tail of the dictionary */
  81343. }
  81344. zmemcpy(s->window, dictionary, length);
  81345. s->strstart = length;
  81346. s->block_start = (long)length;
  81347. /* Insert all strings in the hash table (except for the last two bytes).
  81348. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81349. * call of fill_window.
  81350. */
  81351. s->ins_h = s->window[0];
  81352. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81353. for (n = 0; n <= length - MIN_MATCH; n++) {
  81354. INSERT_STRING(s, n, hash_head);
  81355. }
  81356. if (hash_head) hash_head = 0; /* to make compiler happy */
  81357. return Z_OK;
  81358. }
  81359. /* ========================================================================= */
  81360. int ZEXPORT deflateReset (z_streamp strm)
  81361. {
  81362. deflate_state *s;
  81363. if (strm == Z_NULL || strm->state == Z_NULL ||
  81364. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81365. return Z_STREAM_ERROR;
  81366. }
  81367. strm->total_in = strm->total_out = 0;
  81368. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81369. strm->data_type = Z_UNKNOWN;
  81370. s = (deflate_state *)strm->state;
  81371. s->pending = 0;
  81372. s->pending_out = s->pending_buf;
  81373. if (s->wrap < 0) {
  81374. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81375. }
  81376. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81377. strm->adler =
  81378. #ifdef GZIP
  81379. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81380. #endif
  81381. adler32(0L, Z_NULL, 0);
  81382. s->last_flush = Z_NO_FLUSH;
  81383. _tr_init(s);
  81384. lm_init(s);
  81385. return Z_OK;
  81386. }
  81387. /* ========================================================================= */
  81388. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81389. {
  81390. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81391. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81392. strm->state->gzhead = head;
  81393. return Z_OK;
  81394. }
  81395. /* ========================================================================= */
  81396. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81397. {
  81398. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81399. strm->state->bi_valid = bits;
  81400. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81401. return Z_OK;
  81402. }
  81403. /* ========================================================================= */
  81404. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81405. {
  81406. deflate_state *s;
  81407. compress_func func;
  81408. int err = Z_OK;
  81409. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81410. s = strm->state;
  81411. #ifdef FASTEST
  81412. if (level != 0) level = 1;
  81413. #else
  81414. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81415. #endif
  81416. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81417. return Z_STREAM_ERROR;
  81418. }
  81419. func = configuration_table[s->level].func;
  81420. if (func != configuration_table[level].func && strm->total_in != 0) {
  81421. /* Flush the last buffer: */
  81422. err = deflate(strm, Z_PARTIAL_FLUSH);
  81423. }
  81424. if (s->level != level) {
  81425. s->level = level;
  81426. s->max_lazy_match = configuration_table[level].max_lazy;
  81427. s->good_match = configuration_table[level].good_length;
  81428. s->nice_match = configuration_table[level].nice_length;
  81429. s->max_chain_length = configuration_table[level].max_chain;
  81430. }
  81431. s->strategy = strategy;
  81432. return err;
  81433. }
  81434. /* ========================================================================= */
  81435. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81436. {
  81437. deflate_state *s;
  81438. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81439. s = strm->state;
  81440. s->good_match = good_length;
  81441. s->max_lazy_match = max_lazy;
  81442. s->nice_match = nice_length;
  81443. s->max_chain_length = max_chain;
  81444. return Z_OK;
  81445. }
  81446. /* =========================================================================
  81447. * For the default windowBits of 15 and memLevel of 8, this function returns
  81448. * a close to exact, as well as small, upper bound on the compressed size.
  81449. * They are coded as constants here for a reason--if the #define's are
  81450. * changed, then this function needs to be changed as well. The return
  81451. * value for 15 and 8 only works for those exact settings.
  81452. *
  81453. * For any setting other than those defaults for windowBits and memLevel,
  81454. * the value returned is a conservative worst case for the maximum expansion
  81455. * resulting from using fixed blocks instead of stored blocks, which deflate
  81456. * can emit on compressed data for some combinations of the parameters.
  81457. *
  81458. * This function could be more sophisticated to provide closer upper bounds
  81459. * for every combination of windowBits and memLevel, as well as wrap.
  81460. * But even the conservative upper bound of about 14% expansion does not
  81461. * seem onerous for output buffer allocation.
  81462. */
  81463. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81464. {
  81465. deflate_state *s;
  81466. uLong destLen;
  81467. /* conservative upper bound */
  81468. destLen = sourceLen +
  81469. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81470. /* if can't get parameters, return conservative bound */
  81471. if (strm == Z_NULL || strm->state == Z_NULL)
  81472. return destLen;
  81473. /* if not default parameters, return conservative bound */
  81474. s = strm->state;
  81475. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81476. return destLen;
  81477. /* default settings: return tight bound for that case */
  81478. return compressBound(sourceLen);
  81479. }
  81480. /* =========================================================================
  81481. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81482. * IN assertion: the stream state is correct and there is enough room in
  81483. * pending_buf.
  81484. */
  81485. local void putShortMSB (deflate_state *s, uInt b)
  81486. {
  81487. put_byte(s, (Byte)(b >> 8));
  81488. put_byte(s, (Byte)(b & 0xff));
  81489. }
  81490. /* =========================================================================
  81491. * Flush as much pending output as possible. All deflate() output goes
  81492. * through this function so some applications may wish to modify it
  81493. * to avoid allocating a large strm->next_out buffer and copying into it.
  81494. * (See also read_buf()).
  81495. */
  81496. local void flush_pending (z_streamp strm)
  81497. {
  81498. unsigned len = strm->state->pending;
  81499. if (len > strm->avail_out) len = strm->avail_out;
  81500. if (len == 0) return;
  81501. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81502. strm->next_out += len;
  81503. strm->state->pending_out += len;
  81504. strm->total_out += len;
  81505. strm->avail_out -= len;
  81506. strm->state->pending -= len;
  81507. if (strm->state->pending == 0) {
  81508. strm->state->pending_out = strm->state->pending_buf;
  81509. }
  81510. }
  81511. /* ========================================================================= */
  81512. int ZEXPORT deflate (z_streamp strm, int flush)
  81513. {
  81514. int old_flush; /* value of flush param for previous deflate call */
  81515. deflate_state *s;
  81516. if (strm == Z_NULL || strm->state == Z_NULL ||
  81517. flush > Z_FINISH || flush < 0) {
  81518. return Z_STREAM_ERROR;
  81519. }
  81520. s = strm->state;
  81521. if (strm->next_out == Z_NULL ||
  81522. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81523. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81524. ERR_RETURN(strm, Z_STREAM_ERROR);
  81525. }
  81526. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81527. s->strm = strm; /* just in case */
  81528. old_flush = s->last_flush;
  81529. s->last_flush = flush;
  81530. /* Write the header */
  81531. if (s->status == INIT_STATE) {
  81532. #ifdef GZIP
  81533. if (s->wrap == 2) {
  81534. strm->adler = crc32(0L, Z_NULL, 0);
  81535. put_byte(s, 31);
  81536. put_byte(s, 139);
  81537. put_byte(s, 8);
  81538. if (s->gzhead == NULL) {
  81539. put_byte(s, 0);
  81540. put_byte(s, 0);
  81541. put_byte(s, 0);
  81542. put_byte(s, 0);
  81543. put_byte(s, 0);
  81544. put_byte(s, s->level == 9 ? 2 :
  81545. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81546. 4 : 0));
  81547. put_byte(s, OS_CODE);
  81548. s->status = BUSY_STATE;
  81549. }
  81550. else {
  81551. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81552. (s->gzhead->hcrc ? 2 : 0) +
  81553. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81554. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81555. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81556. );
  81557. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81558. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81559. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81560. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81561. put_byte(s, s->level == 9 ? 2 :
  81562. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81563. 4 : 0));
  81564. put_byte(s, s->gzhead->os & 0xff);
  81565. if (s->gzhead->extra != NULL) {
  81566. put_byte(s, s->gzhead->extra_len & 0xff);
  81567. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81568. }
  81569. if (s->gzhead->hcrc)
  81570. strm->adler = crc32(strm->adler, s->pending_buf,
  81571. s->pending);
  81572. s->gzindex = 0;
  81573. s->status = EXTRA_STATE;
  81574. }
  81575. }
  81576. else
  81577. #endif
  81578. {
  81579. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81580. uInt level_flags;
  81581. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81582. level_flags = 0;
  81583. else if (s->level < 6)
  81584. level_flags = 1;
  81585. else if (s->level == 6)
  81586. level_flags = 2;
  81587. else
  81588. level_flags = 3;
  81589. header |= (level_flags << 6);
  81590. if (s->strstart != 0) header |= PRESET_DICT;
  81591. header += 31 - (header % 31);
  81592. s->status = BUSY_STATE;
  81593. putShortMSB(s, header);
  81594. /* Save the adler32 of the preset dictionary: */
  81595. if (s->strstart != 0) {
  81596. putShortMSB(s, (uInt)(strm->adler >> 16));
  81597. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81598. }
  81599. strm->adler = adler32(0L, Z_NULL, 0);
  81600. }
  81601. }
  81602. #ifdef GZIP
  81603. if (s->status == EXTRA_STATE) {
  81604. if (s->gzhead->extra != NULL) {
  81605. uInt beg = s->pending; /* start of bytes to update crc */
  81606. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81607. if (s->pending == s->pending_buf_size) {
  81608. if (s->gzhead->hcrc && s->pending > beg)
  81609. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81610. s->pending - beg);
  81611. flush_pending(strm);
  81612. beg = s->pending;
  81613. if (s->pending == s->pending_buf_size)
  81614. break;
  81615. }
  81616. put_byte(s, s->gzhead->extra[s->gzindex]);
  81617. s->gzindex++;
  81618. }
  81619. if (s->gzhead->hcrc && s->pending > beg)
  81620. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81621. s->pending - beg);
  81622. if (s->gzindex == s->gzhead->extra_len) {
  81623. s->gzindex = 0;
  81624. s->status = NAME_STATE;
  81625. }
  81626. }
  81627. else
  81628. s->status = NAME_STATE;
  81629. }
  81630. if (s->status == NAME_STATE) {
  81631. if (s->gzhead->name != NULL) {
  81632. uInt beg = s->pending; /* start of bytes to update crc */
  81633. int val;
  81634. do {
  81635. if (s->pending == s->pending_buf_size) {
  81636. if (s->gzhead->hcrc && s->pending > beg)
  81637. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81638. s->pending - beg);
  81639. flush_pending(strm);
  81640. beg = s->pending;
  81641. if (s->pending == s->pending_buf_size) {
  81642. val = 1;
  81643. break;
  81644. }
  81645. }
  81646. val = s->gzhead->name[s->gzindex++];
  81647. put_byte(s, val);
  81648. } while (val != 0);
  81649. if (s->gzhead->hcrc && s->pending > beg)
  81650. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81651. s->pending - beg);
  81652. if (val == 0) {
  81653. s->gzindex = 0;
  81654. s->status = COMMENT_STATE;
  81655. }
  81656. }
  81657. else
  81658. s->status = COMMENT_STATE;
  81659. }
  81660. if (s->status == COMMENT_STATE) {
  81661. if (s->gzhead->comment != NULL) {
  81662. uInt beg = s->pending; /* start of bytes to update crc */
  81663. int val;
  81664. do {
  81665. if (s->pending == s->pending_buf_size) {
  81666. if (s->gzhead->hcrc && s->pending > beg)
  81667. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81668. s->pending - beg);
  81669. flush_pending(strm);
  81670. beg = s->pending;
  81671. if (s->pending == s->pending_buf_size) {
  81672. val = 1;
  81673. break;
  81674. }
  81675. }
  81676. val = s->gzhead->comment[s->gzindex++];
  81677. put_byte(s, val);
  81678. } while (val != 0);
  81679. if (s->gzhead->hcrc && s->pending > beg)
  81680. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81681. s->pending - beg);
  81682. if (val == 0)
  81683. s->status = HCRC_STATE;
  81684. }
  81685. else
  81686. s->status = HCRC_STATE;
  81687. }
  81688. if (s->status == HCRC_STATE) {
  81689. if (s->gzhead->hcrc) {
  81690. if (s->pending + 2 > s->pending_buf_size)
  81691. flush_pending(strm);
  81692. if (s->pending + 2 <= s->pending_buf_size) {
  81693. put_byte(s, (Byte)(strm->adler & 0xff));
  81694. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81695. strm->adler = crc32(0L, Z_NULL, 0);
  81696. s->status = BUSY_STATE;
  81697. }
  81698. }
  81699. else
  81700. s->status = BUSY_STATE;
  81701. }
  81702. #endif
  81703. /* Flush as much pending output as possible */
  81704. if (s->pending != 0) {
  81705. flush_pending(strm);
  81706. if (strm->avail_out == 0) {
  81707. /* Since avail_out is 0, deflate will be called again with
  81708. * more output space, but possibly with both pending and
  81709. * avail_in equal to zero. There won't be anything to do,
  81710. * but this is not an error situation so make sure we
  81711. * return OK instead of BUF_ERROR at next call of deflate:
  81712. */
  81713. s->last_flush = -1;
  81714. return Z_OK;
  81715. }
  81716. /* Make sure there is something to do and avoid duplicate consecutive
  81717. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81718. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81719. */
  81720. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81721. flush != Z_FINISH) {
  81722. ERR_RETURN(strm, Z_BUF_ERROR);
  81723. }
  81724. /* User must not provide more input after the first FINISH: */
  81725. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81726. ERR_RETURN(strm, Z_BUF_ERROR);
  81727. }
  81728. /* Start a new block or continue the current one.
  81729. */
  81730. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81731. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81732. block_state bstate;
  81733. bstate = (*(configuration_table[s->level].func))(s, flush);
  81734. if (bstate == finish_started || bstate == finish_done) {
  81735. s->status = FINISH_STATE;
  81736. }
  81737. if (bstate == need_more || bstate == finish_started) {
  81738. if (strm->avail_out == 0) {
  81739. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81740. }
  81741. return Z_OK;
  81742. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81743. * of deflate should use the same flush parameter to make sure
  81744. * that the flush is complete. So we don't have to output an
  81745. * empty block here, this will be done at next call. This also
  81746. * ensures that for a very small output buffer, we emit at most
  81747. * one empty block.
  81748. */
  81749. }
  81750. if (bstate == block_done) {
  81751. if (flush == Z_PARTIAL_FLUSH) {
  81752. _tr_align(s);
  81753. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81754. _tr_stored_block(s, (char*)0, 0L, 0);
  81755. /* For a full flush, this empty block will be recognized
  81756. * as a special marker by inflate_sync().
  81757. */
  81758. if (flush == Z_FULL_FLUSH) {
  81759. CLEAR_HASH(s); /* forget history */
  81760. }
  81761. }
  81762. flush_pending(strm);
  81763. if (strm->avail_out == 0) {
  81764. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81765. return Z_OK;
  81766. }
  81767. }
  81768. }
  81769. Assert(strm->avail_out > 0, "bug2");
  81770. if (flush != Z_FINISH) return Z_OK;
  81771. if (s->wrap <= 0) return Z_STREAM_END;
  81772. /* Write the trailer */
  81773. #ifdef GZIP
  81774. if (s->wrap == 2) {
  81775. put_byte(s, (Byte)(strm->adler & 0xff));
  81776. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81777. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81778. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81779. put_byte(s, (Byte)(strm->total_in & 0xff));
  81780. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81781. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81782. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81783. }
  81784. else
  81785. #endif
  81786. {
  81787. putShortMSB(s, (uInt)(strm->adler >> 16));
  81788. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81789. }
  81790. flush_pending(strm);
  81791. /* If avail_out is zero, the application will call deflate again
  81792. * to flush the rest.
  81793. */
  81794. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81795. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81796. }
  81797. /* ========================================================================= */
  81798. int ZEXPORT deflateEnd (z_streamp strm)
  81799. {
  81800. int status;
  81801. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81802. status = strm->state->status;
  81803. if (status != INIT_STATE &&
  81804. status != EXTRA_STATE &&
  81805. status != NAME_STATE &&
  81806. status != COMMENT_STATE &&
  81807. status != HCRC_STATE &&
  81808. status != BUSY_STATE &&
  81809. status != FINISH_STATE) {
  81810. return Z_STREAM_ERROR;
  81811. }
  81812. /* Deallocate in reverse order of allocations: */
  81813. TRY_FREE(strm, strm->state->pending_buf);
  81814. TRY_FREE(strm, strm->state->head);
  81815. TRY_FREE(strm, strm->state->prev);
  81816. TRY_FREE(strm, strm->state->window);
  81817. ZFREE(strm, strm->state);
  81818. strm->state = Z_NULL;
  81819. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81820. }
  81821. /* =========================================================================
  81822. * Copy the source state to the destination state.
  81823. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81824. * doesn't have enough memory anyway to duplicate compression states).
  81825. */
  81826. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81827. {
  81828. #ifdef MAXSEG_64K
  81829. return Z_STREAM_ERROR;
  81830. #else
  81831. deflate_state *ds;
  81832. deflate_state *ss;
  81833. ushf *overlay;
  81834. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81835. return Z_STREAM_ERROR;
  81836. }
  81837. ss = source->state;
  81838. zmemcpy(dest, source, sizeof(z_stream));
  81839. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81840. if (ds == Z_NULL) return Z_MEM_ERROR;
  81841. dest->state = (struct internal_state FAR *) ds;
  81842. zmemcpy(ds, ss, sizeof(deflate_state));
  81843. ds->strm = dest;
  81844. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81845. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81846. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81847. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81848. ds->pending_buf = (uchf *) overlay;
  81849. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81850. ds->pending_buf == Z_NULL) {
  81851. deflateEnd (dest);
  81852. return Z_MEM_ERROR;
  81853. }
  81854. /* following zmemcpy do not work for 16-bit MSDOS */
  81855. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81856. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81857. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81858. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81859. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81860. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81861. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81862. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81863. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81864. ds->bl_desc.dyn_tree = ds->bl_tree;
  81865. return Z_OK;
  81866. #endif /* MAXSEG_64K */
  81867. }
  81868. /* ===========================================================================
  81869. * Read a new buffer from the current input stream, update the adler32
  81870. * and total number of bytes read. All deflate() input goes through
  81871. * this function so some applications may wish to modify it to avoid
  81872. * allocating a large strm->next_in buffer and copying from it.
  81873. * (See also flush_pending()).
  81874. */
  81875. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81876. {
  81877. unsigned len = strm->avail_in;
  81878. if (len > size) len = size;
  81879. if (len == 0) return 0;
  81880. strm->avail_in -= len;
  81881. if (strm->state->wrap == 1) {
  81882. strm->adler = adler32(strm->adler, strm->next_in, len);
  81883. }
  81884. #ifdef GZIP
  81885. else if (strm->state->wrap == 2) {
  81886. strm->adler = crc32(strm->adler, strm->next_in, len);
  81887. }
  81888. #endif
  81889. zmemcpy(buf, strm->next_in, len);
  81890. strm->next_in += len;
  81891. strm->total_in += len;
  81892. return (int)len;
  81893. }
  81894. /* ===========================================================================
  81895. * Initialize the "longest match" routines for a new zlib stream
  81896. */
  81897. local void lm_init (deflate_state *s)
  81898. {
  81899. s->window_size = (ulg)2L*s->w_size;
  81900. CLEAR_HASH(s);
  81901. /* Set the default configuration parameters:
  81902. */
  81903. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81904. s->good_match = configuration_table[s->level].good_length;
  81905. s->nice_match = configuration_table[s->level].nice_length;
  81906. s->max_chain_length = configuration_table[s->level].max_chain;
  81907. s->strstart = 0;
  81908. s->block_start = 0L;
  81909. s->lookahead = 0;
  81910. s->match_length = s->prev_length = MIN_MATCH-1;
  81911. s->match_available = 0;
  81912. s->ins_h = 0;
  81913. #ifndef FASTEST
  81914. #ifdef ASMV
  81915. match_init(); /* initialize the asm code */
  81916. #endif
  81917. #endif
  81918. }
  81919. #ifndef FASTEST
  81920. /* ===========================================================================
  81921. * Set match_start to the longest match starting at the given string and
  81922. * return its length. Matches shorter or equal to prev_length are discarded,
  81923. * in which case the result is equal to prev_length and match_start is
  81924. * garbage.
  81925. * IN assertions: cur_match is the head of the hash chain for the current
  81926. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81927. * OUT assertion: the match length is not greater than s->lookahead.
  81928. */
  81929. #ifndef ASMV
  81930. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81931. * match.S. The code will be functionally equivalent.
  81932. */
  81933. local uInt longest_match(deflate_state *s, IPos cur_match)
  81934. {
  81935. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81936. register Bytef *scan = s->window + s->strstart; /* current string */
  81937. register Bytef *match; /* matched string */
  81938. register int len; /* length of current match */
  81939. int best_len = s->prev_length; /* best match length so far */
  81940. int nice_match = s->nice_match; /* stop if match long enough */
  81941. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81942. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81943. /* Stop when cur_match becomes <= limit. To simplify the code,
  81944. * we prevent matches with the string of window index 0.
  81945. */
  81946. Posf *prev = s->prev;
  81947. uInt wmask = s->w_mask;
  81948. #ifdef UNALIGNED_OK
  81949. /* Compare two bytes at a time. Note: this is not always beneficial.
  81950. * Try with and without -DUNALIGNED_OK to check.
  81951. */
  81952. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81953. register ush scan_start = *(ushf*)scan;
  81954. register ush scan_end = *(ushf*)(scan+best_len-1);
  81955. #else
  81956. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81957. register Byte scan_end1 = scan[best_len-1];
  81958. register Byte scan_end = scan[best_len];
  81959. #endif
  81960. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81961. * It is easy to get rid of this optimization if necessary.
  81962. */
  81963. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81964. /* Do not waste too much time if we already have a good match: */
  81965. if (s->prev_length >= s->good_match) {
  81966. chain_length >>= 2;
  81967. }
  81968. /* Do not look for matches beyond the end of the input. This is necessary
  81969. * to make deflate deterministic.
  81970. */
  81971. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81972. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81973. do {
  81974. Assert(cur_match < s->strstart, "no future");
  81975. match = s->window + cur_match;
  81976. /* Skip to next match if the match length cannot increase
  81977. * or if the match length is less than 2. Note that the checks below
  81978. * for insufficient lookahead only occur occasionally for performance
  81979. * reasons. Therefore uninitialized memory will be accessed, and
  81980. * conditional jumps will be made that depend on those values.
  81981. * However the length of the match is limited to the lookahead, so
  81982. * the output of deflate is not affected by the uninitialized values.
  81983. */
  81984. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81985. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81986. * UNALIGNED_OK if your compiler uses a different size.
  81987. */
  81988. if (*(ushf*)(match+best_len-1) != scan_end ||
  81989. *(ushf*)match != scan_start) continue;
  81990. /* It is not necessary to compare scan[2] and match[2] since they are
  81991. * always equal when the other bytes match, given that the hash keys
  81992. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81993. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81994. * lookahead only every 4th comparison; the 128th check will be made
  81995. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81996. * necessary to put more guard bytes at the end of the window, or
  81997. * to check more often for insufficient lookahead.
  81998. */
  81999. Assert(scan[2] == match[2], "scan[2]?");
  82000. scan++, match++;
  82001. do {
  82002. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82003. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82004. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82005. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82006. scan < strend);
  82007. /* The funny "do {}" generates better code on most compilers */
  82008. /* Here, scan <= window+strstart+257 */
  82009. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82010. if (*scan == *match) scan++;
  82011. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82012. scan = strend - (MAX_MATCH-1);
  82013. #else /* UNALIGNED_OK */
  82014. if (match[best_len] != scan_end ||
  82015. match[best_len-1] != scan_end1 ||
  82016. *match != *scan ||
  82017. *++match != scan[1]) continue;
  82018. /* The check at best_len-1 can be removed because it will be made
  82019. * again later. (This heuristic is not always a win.)
  82020. * It is not necessary to compare scan[2] and match[2] since they
  82021. * are always equal when the other bytes match, given that
  82022. * the hash keys are equal and that HASH_BITS >= 8.
  82023. */
  82024. scan += 2, match++;
  82025. Assert(*scan == *match, "match[2]?");
  82026. /* We check for insufficient lookahead only every 8th comparison;
  82027. * the 256th check will be made at strstart+258.
  82028. */
  82029. do {
  82030. } while (*++scan == *++match && *++scan == *++match &&
  82031. *++scan == *++match && *++scan == *++match &&
  82032. *++scan == *++match && *++scan == *++match &&
  82033. *++scan == *++match && *++scan == *++match &&
  82034. scan < strend);
  82035. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82036. len = MAX_MATCH - (int)(strend - scan);
  82037. scan = strend - MAX_MATCH;
  82038. #endif /* UNALIGNED_OK */
  82039. if (len > best_len) {
  82040. s->match_start = cur_match;
  82041. best_len = len;
  82042. if (len >= nice_match) break;
  82043. #ifdef UNALIGNED_OK
  82044. scan_end = *(ushf*)(scan+best_len-1);
  82045. #else
  82046. scan_end1 = scan[best_len-1];
  82047. scan_end = scan[best_len];
  82048. #endif
  82049. }
  82050. } while ((cur_match = prev[cur_match & wmask]) > limit
  82051. && --chain_length != 0);
  82052. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82053. return s->lookahead;
  82054. }
  82055. #endif /* ASMV */
  82056. #endif /* FASTEST */
  82057. /* ---------------------------------------------------------------------------
  82058. * Optimized version for level == 1 or strategy == Z_RLE only
  82059. */
  82060. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82061. {
  82062. register Bytef *scan = s->window + s->strstart; /* current string */
  82063. register Bytef *match; /* matched string */
  82064. register int len; /* length of current match */
  82065. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82066. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82067. * It is easy to get rid of this optimization if necessary.
  82068. */
  82069. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82070. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82071. Assert(cur_match < s->strstart, "no future");
  82072. match = s->window + cur_match;
  82073. /* Return failure if the match length is less than 2:
  82074. */
  82075. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82076. /* The check at best_len-1 can be removed because it will be made
  82077. * again later. (This heuristic is not always a win.)
  82078. * It is not necessary to compare scan[2] and match[2] since they
  82079. * are always equal when the other bytes match, given that
  82080. * the hash keys are equal and that HASH_BITS >= 8.
  82081. */
  82082. scan += 2, match += 2;
  82083. Assert(*scan == *match, "match[2]?");
  82084. /* We check for insufficient lookahead only every 8th comparison;
  82085. * the 256th check will be made at strstart+258.
  82086. */
  82087. do {
  82088. } while (*++scan == *++match && *++scan == *++match &&
  82089. *++scan == *++match && *++scan == *++match &&
  82090. *++scan == *++match && *++scan == *++match &&
  82091. *++scan == *++match && *++scan == *++match &&
  82092. scan < strend);
  82093. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82094. len = MAX_MATCH - (int)(strend - scan);
  82095. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82096. s->match_start = cur_match;
  82097. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82098. }
  82099. #ifdef DEBUG
  82100. /* ===========================================================================
  82101. * Check that the match at match_start is indeed a match.
  82102. */
  82103. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82104. {
  82105. /* check that the match is indeed a match */
  82106. if (zmemcmp(s->window + match,
  82107. s->window + start, length) != EQUAL) {
  82108. fprintf(stderr, " start %u, match %u, length %d\n",
  82109. start, match, length);
  82110. do {
  82111. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82112. } while (--length != 0);
  82113. z_error("invalid match");
  82114. }
  82115. if (z_verbose > 1) {
  82116. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82117. do { putc(s->window[start++], stderr); } while (--length != 0);
  82118. }
  82119. }
  82120. #else
  82121. # define check_match(s, start, match, length)
  82122. #endif /* DEBUG */
  82123. /* ===========================================================================
  82124. * Fill the window when the lookahead becomes insufficient.
  82125. * Updates strstart and lookahead.
  82126. *
  82127. * IN assertion: lookahead < MIN_LOOKAHEAD
  82128. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82129. * At least one byte has been read, or avail_in == 0; reads are
  82130. * performed for at least two bytes (required for the zip translate_eol
  82131. * option -- not supported here).
  82132. */
  82133. local void fill_window (deflate_state *s)
  82134. {
  82135. register unsigned n, m;
  82136. register Posf *p;
  82137. unsigned more; /* Amount of free space at the end of the window. */
  82138. uInt wsize = s->w_size;
  82139. do {
  82140. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82141. /* Deal with !@#$% 64K limit: */
  82142. if (sizeof(int) <= 2) {
  82143. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82144. more = wsize;
  82145. } else if (more == (unsigned)(-1)) {
  82146. /* Very unlikely, but possible on 16 bit machine if
  82147. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82148. */
  82149. more--;
  82150. }
  82151. }
  82152. /* If the window is almost full and there is insufficient lookahead,
  82153. * move the upper half to the lower one to make room in the upper half.
  82154. */
  82155. if (s->strstart >= wsize+MAX_DIST(s)) {
  82156. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82157. s->match_start -= wsize;
  82158. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82159. s->block_start -= (long) wsize;
  82160. /* Slide the hash table (could be avoided with 32 bit values
  82161. at the expense of memory usage). We slide even when level == 0
  82162. to keep the hash table consistent if we switch back to level > 0
  82163. later. (Using level 0 permanently is not an optimal usage of
  82164. zlib, so we don't care about this pathological case.)
  82165. */
  82166. /* %%% avoid this when Z_RLE */
  82167. n = s->hash_size;
  82168. p = &s->head[n];
  82169. do {
  82170. m = *--p;
  82171. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82172. } while (--n);
  82173. n = wsize;
  82174. #ifndef FASTEST
  82175. p = &s->prev[n];
  82176. do {
  82177. m = *--p;
  82178. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82179. /* If n is not on any hash chain, prev[n] is garbage but
  82180. * its value will never be used.
  82181. */
  82182. } while (--n);
  82183. #endif
  82184. more += wsize;
  82185. }
  82186. if (s->strm->avail_in == 0) return;
  82187. /* If there was no sliding:
  82188. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82189. * more == window_size - lookahead - strstart
  82190. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82191. * => more >= window_size - 2*WSIZE + 2
  82192. * In the BIG_MEM or MMAP case (not yet supported),
  82193. * window_size == input_size + MIN_LOOKAHEAD &&
  82194. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82195. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82196. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82197. */
  82198. Assert(more >= 2, "more < 2");
  82199. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82200. s->lookahead += n;
  82201. /* Initialize the hash value now that we have some input: */
  82202. if (s->lookahead >= MIN_MATCH) {
  82203. s->ins_h = s->window[s->strstart];
  82204. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82205. #if MIN_MATCH != 3
  82206. Call UPDATE_HASH() MIN_MATCH-3 more times
  82207. #endif
  82208. }
  82209. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82210. * but this is not important since only literal bytes will be emitted.
  82211. */
  82212. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82213. }
  82214. /* ===========================================================================
  82215. * Flush the current block, with given end-of-file flag.
  82216. * IN assertion: strstart is set to the end of the current match.
  82217. */
  82218. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82219. _tr_flush_block(s, (s->block_start >= 0L ? \
  82220. (charf *)&s->window[(unsigned)s->block_start] : \
  82221. (charf *)Z_NULL), \
  82222. (ulg)((long)s->strstart - s->block_start), \
  82223. (eof)); \
  82224. s->block_start = s->strstart; \
  82225. flush_pending(s->strm); \
  82226. Tracev((stderr,"[FLUSH]")); \
  82227. }
  82228. /* Same but force premature exit if necessary. */
  82229. #define FLUSH_BLOCK(s, eof) { \
  82230. FLUSH_BLOCK_ONLY(s, eof); \
  82231. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82232. }
  82233. /* ===========================================================================
  82234. * Copy without compression as much as possible from the input stream, return
  82235. * the current block state.
  82236. * This function does not insert new strings in the dictionary since
  82237. * uncompressible data is probably not useful. This function is used
  82238. * only for the level=0 compression option.
  82239. * NOTE: this function should be optimized to avoid extra copying from
  82240. * window to pending_buf.
  82241. */
  82242. local block_state deflate_stored(deflate_state *s, int flush)
  82243. {
  82244. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82245. * to pending_buf_size, and each stored block has a 5 byte header:
  82246. */
  82247. ulg max_block_size = 0xffff;
  82248. ulg max_start;
  82249. if (max_block_size > s->pending_buf_size - 5) {
  82250. max_block_size = s->pending_buf_size - 5;
  82251. }
  82252. /* Copy as much as possible from input to output: */
  82253. for (;;) {
  82254. /* Fill the window as much as possible: */
  82255. if (s->lookahead <= 1) {
  82256. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82257. s->block_start >= (long)s->w_size, "slide too late");
  82258. fill_window(s);
  82259. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82260. if (s->lookahead == 0) break; /* flush the current block */
  82261. }
  82262. Assert(s->block_start >= 0L, "block gone");
  82263. s->strstart += s->lookahead;
  82264. s->lookahead = 0;
  82265. /* Emit a stored block if pending_buf will be full: */
  82266. max_start = s->block_start + max_block_size;
  82267. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82268. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82269. s->lookahead = (uInt)(s->strstart - max_start);
  82270. s->strstart = (uInt)max_start;
  82271. FLUSH_BLOCK(s, 0);
  82272. }
  82273. /* Flush if we may have to slide, otherwise block_start may become
  82274. * negative and the data will be gone:
  82275. */
  82276. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82277. FLUSH_BLOCK(s, 0);
  82278. }
  82279. }
  82280. FLUSH_BLOCK(s, flush == Z_FINISH);
  82281. return flush == Z_FINISH ? finish_done : block_done;
  82282. }
  82283. /* ===========================================================================
  82284. * Compress as much as possible from the input stream, return the current
  82285. * block state.
  82286. * This function does not perform lazy evaluation of matches and inserts
  82287. * new strings in the dictionary only for unmatched strings or for short
  82288. * matches. It is used only for the fast compression options.
  82289. */
  82290. local block_state deflate_fast(deflate_state *s, int flush)
  82291. {
  82292. IPos hash_head = NIL; /* head of the hash chain */
  82293. int bflush; /* set if current block must be flushed */
  82294. for (;;) {
  82295. /* Make sure that we always have enough lookahead, except
  82296. * at the end of the input file. We need MAX_MATCH bytes
  82297. * for the next match, plus MIN_MATCH bytes to insert the
  82298. * string following the next match.
  82299. */
  82300. if (s->lookahead < MIN_LOOKAHEAD) {
  82301. fill_window(s);
  82302. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82303. return need_more;
  82304. }
  82305. if (s->lookahead == 0) break; /* flush the current block */
  82306. }
  82307. /* Insert the string window[strstart .. strstart+2] in the
  82308. * dictionary, and set hash_head to the head of the hash chain:
  82309. */
  82310. if (s->lookahead >= MIN_MATCH) {
  82311. INSERT_STRING(s, s->strstart, hash_head);
  82312. }
  82313. /* Find the longest match, discarding those <= prev_length.
  82314. * At this point we have always match_length < MIN_MATCH
  82315. */
  82316. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82317. /* To simplify the code, we prevent matches with the string
  82318. * of window index 0 (in particular we have to avoid a match
  82319. * of the string with itself at the start of the input file).
  82320. */
  82321. #ifdef FASTEST
  82322. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82323. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82324. s->match_length = longest_match_fast (s, hash_head);
  82325. }
  82326. #else
  82327. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82328. s->match_length = longest_match (s, hash_head);
  82329. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82330. s->match_length = longest_match_fast (s, hash_head);
  82331. }
  82332. #endif
  82333. /* longest_match() or longest_match_fast() sets match_start */
  82334. }
  82335. if (s->match_length >= MIN_MATCH) {
  82336. check_match(s, s->strstart, s->match_start, s->match_length);
  82337. _tr_tally_dist(s, s->strstart - s->match_start,
  82338. s->match_length - MIN_MATCH, bflush);
  82339. s->lookahead -= s->match_length;
  82340. /* Insert new strings in the hash table only if the match length
  82341. * is not too large. This saves time but degrades compression.
  82342. */
  82343. #ifndef FASTEST
  82344. if (s->match_length <= s->max_insert_length &&
  82345. s->lookahead >= MIN_MATCH) {
  82346. s->match_length--; /* string at strstart already in table */
  82347. do {
  82348. s->strstart++;
  82349. INSERT_STRING(s, s->strstart, hash_head);
  82350. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82351. * always MIN_MATCH bytes ahead.
  82352. */
  82353. } while (--s->match_length != 0);
  82354. s->strstart++;
  82355. } else
  82356. #endif
  82357. {
  82358. s->strstart += s->match_length;
  82359. s->match_length = 0;
  82360. s->ins_h = s->window[s->strstart];
  82361. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82362. #if MIN_MATCH != 3
  82363. Call UPDATE_HASH() MIN_MATCH-3 more times
  82364. #endif
  82365. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82366. * matter since it will be recomputed at next deflate call.
  82367. */
  82368. }
  82369. } else {
  82370. /* No match, output a literal byte */
  82371. Tracevv((stderr,"%c", s->window[s->strstart]));
  82372. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82373. s->lookahead--;
  82374. s->strstart++;
  82375. }
  82376. if (bflush) FLUSH_BLOCK(s, 0);
  82377. }
  82378. FLUSH_BLOCK(s, flush == Z_FINISH);
  82379. return flush == Z_FINISH ? finish_done : block_done;
  82380. }
  82381. #ifndef FASTEST
  82382. /* ===========================================================================
  82383. * Same as above, but achieves better compression. We use a lazy
  82384. * evaluation for matches: a match is finally adopted only if there is
  82385. * no better match at the next window position.
  82386. */
  82387. local block_state deflate_slow(deflate_state *s, int flush)
  82388. {
  82389. IPos hash_head = NIL; /* head of hash chain */
  82390. int bflush; /* set if current block must be flushed */
  82391. /* Process the input block. */
  82392. for (;;) {
  82393. /* Make sure that we always have enough lookahead, except
  82394. * at the end of the input file. We need MAX_MATCH bytes
  82395. * for the next match, plus MIN_MATCH bytes to insert the
  82396. * string following the next match.
  82397. */
  82398. if (s->lookahead < MIN_LOOKAHEAD) {
  82399. fill_window(s);
  82400. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82401. return need_more;
  82402. }
  82403. if (s->lookahead == 0) break; /* flush the current block */
  82404. }
  82405. /* Insert the string window[strstart .. strstart+2] in the
  82406. * dictionary, and set hash_head to the head of the hash chain:
  82407. */
  82408. if (s->lookahead >= MIN_MATCH) {
  82409. INSERT_STRING(s, s->strstart, hash_head);
  82410. }
  82411. /* Find the longest match, discarding those <= prev_length.
  82412. */
  82413. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82414. s->match_length = MIN_MATCH-1;
  82415. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82416. s->strstart - hash_head <= MAX_DIST(s)) {
  82417. /* To simplify the code, we prevent matches with the string
  82418. * of window index 0 (in particular we have to avoid a match
  82419. * of the string with itself at the start of the input file).
  82420. */
  82421. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82422. s->match_length = longest_match (s, hash_head);
  82423. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82424. s->match_length = longest_match_fast (s, hash_head);
  82425. }
  82426. /* longest_match() or longest_match_fast() sets match_start */
  82427. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82428. #if TOO_FAR <= 32767
  82429. || (s->match_length == MIN_MATCH &&
  82430. s->strstart - s->match_start > TOO_FAR)
  82431. #endif
  82432. )) {
  82433. /* If prev_match is also MIN_MATCH, match_start is garbage
  82434. * but we will ignore the current match anyway.
  82435. */
  82436. s->match_length = MIN_MATCH-1;
  82437. }
  82438. }
  82439. /* If there was a match at the previous step and the current
  82440. * match is not better, output the previous match:
  82441. */
  82442. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82443. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82444. /* Do not insert strings in hash table beyond this. */
  82445. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82446. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82447. s->prev_length - MIN_MATCH, bflush);
  82448. /* Insert in hash table all strings up to the end of the match.
  82449. * strstart-1 and strstart are already inserted. If there is not
  82450. * enough lookahead, the last two strings are not inserted in
  82451. * the hash table.
  82452. */
  82453. s->lookahead -= s->prev_length-1;
  82454. s->prev_length -= 2;
  82455. do {
  82456. if (++s->strstart <= max_insert) {
  82457. INSERT_STRING(s, s->strstart, hash_head);
  82458. }
  82459. } while (--s->prev_length != 0);
  82460. s->match_available = 0;
  82461. s->match_length = MIN_MATCH-1;
  82462. s->strstart++;
  82463. if (bflush) FLUSH_BLOCK(s, 0);
  82464. } else if (s->match_available) {
  82465. /* If there was no match at the previous position, output a
  82466. * single literal. If there was a match but the current match
  82467. * is longer, truncate the previous match to a single literal.
  82468. */
  82469. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82470. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82471. if (bflush) {
  82472. FLUSH_BLOCK_ONLY(s, 0);
  82473. }
  82474. s->strstart++;
  82475. s->lookahead--;
  82476. if (s->strm->avail_out == 0) return need_more;
  82477. } else {
  82478. /* There is no previous match to compare with, wait for
  82479. * the next step to decide.
  82480. */
  82481. s->match_available = 1;
  82482. s->strstart++;
  82483. s->lookahead--;
  82484. }
  82485. }
  82486. Assert (flush != Z_NO_FLUSH, "no flush?");
  82487. if (s->match_available) {
  82488. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82489. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82490. s->match_available = 0;
  82491. }
  82492. FLUSH_BLOCK(s, flush == Z_FINISH);
  82493. return flush == Z_FINISH ? finish_done : block_done;
  82494. }
  82495. #endif /* FASTEST */
  82496. #if 0
  82497. /* ===========================================================================
  82498. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82499. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82500. * deflate switches away from Z_RLE.)
  82501. */
  82502. local block_state deflate_rle(s, flush)
  82503. deflate_state *s;
  82504. int flush;
  82505. {
  82506. int bflush; /* set if current block must be flushed */
  82507. uInt run; /* length of run */
  82508. uInt max; /* maximum length of run */
  82509. uInt prev; /* byte at distance one to match */
  82510. Bytef *scan; /* scan for end of run */
  82511. for (;;) {
  82512. /* Make sure that we always have enough lookahead, except
  82513. * at the end of the input file. We need MAX_MATCH bytes
  82514. * for the longest encodable run.
  82515. */
  82516. if (s->lookahead < MAX_MATCH) {
  82517. fill_window(s);
  82518. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82519. return need_more;
  82520. }
  82521. if (s->lookahead == 0) break; /* flush the current block */
  82522. }
  82523. /* See how many times the previous byte repeats */
  82524. run = 0;
  82525. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82526. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82527. scan = s->window + s->strstart - 1;
  82528. prev = *scan++;
  82529. do {
  82530. if (*scan++ != prev)
  82531. break;
  82532. } while (++run < max);
  82533. }
  82534. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82535. if (run >= MIN_MATCH) {
  82536. check_match(s, s->strstart, s->strstart - 1, run);
  82537. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82538. s->lookahead -= run;
  82539. s->strstart += run;
  82540. } else {
  82541. /* No match, output a literal byte */
  82542. Tracevv((stderr,"%c", s->window[s->strstart]));
  82543. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82544. s->lookahead--;
  82545. s->strstart++;
  82546. }
  82547. if (bflush) FLUSH_BLOCK(s, 0);
  82548. }
  82549. FLUSH_BLOCK(s, flush == Z_FINISH);
  82550. return flush == Z_FINISH ? finish_done : block_done;
  82551. }
  82552. #endif
  82553. /*** End of inlined file: deflate.c ***/
  82554. /*** Start of inlined file: inffast.c ***/
  82555. /*** Start of inlined file: inftrees.h ***/
  82556. /* WARNING: this file should *not* be used by applications. It is
  82557. part of the implementation of the compression library and is
  82558. subject to change. Applications should only use zlib.h.
  82559. */
  82560. #ifndef _INFTREES_H_
  82561. #define _INFTREES_H_
  82562. /* Structure for decoding tables. Each entry provides either the
  82563. information needed to do the operation requested by the code that
  82564. indexed that table entry, or it provides a pointer to another
  82565. table that indexes more bits of the code. op indicates whether
  82566. the entry is a pointer to another table, a literal, a length or
  82567. distance, an end-of-block, or an invalid code. For a table
  82568. pointer, the low four bits of op is the number of index bits of
  82569. that table. For a length or distance, the low four bits of op
  82570. is the number of extra bits to get after the code. bits is
  82571. the number of bits in this code or part of the code to drop off
  82572. of the bit buffer. val is the actual byte to output in the case
  82573. of a literal, the base length or distance, or the offset from
  82574. the current table to the next table. Each entry is four bytes. */
  82575. typedef struct {
  82576. unsigned char op; /* operation, extra bits, table bits */
  82577. unsigned char bits; /* bits in this part of the code */
  82578. unsigned short val; /* offset in table or code value */
  82579. } code;
  82580. /* op values as set by inflate_table():
  82581. 00000000 - literal
  82582. 0000tttt - table link, tttt != 0 is the number of table index bits
  82583. 0001eeee - length or distance, eeee is the number of extra bits
  82584. 01100000 - end of block
  82585. 01000000 - invalid code
  82586. */
  82587. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82588. exhaustive search was 1444 code structures (852 for length/literals
  82589. and 592 for distances, the latter actually the result of an
  82590. exhaustive search). The true maximum is not known, but the value
  82591. below is more than safe. */
  82592. #define ENOUGH 2048
  82593. #define MAXD 592
  82594. /* Type of code to build for inftable() */
  82595. typedef enum {
  82596. CODES,
  82597. LENS,
  82598. DISTS
  82599. } codetype;
  82600. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82601. unsigned codes, code FAR * FAR *table,
  82602. unsigned FAR *bits, unsigned short FAR *work));
  82603. #endif
  82604. /*** End of inlined file: inftrees.h ***/
  82605. /*** Start of inlined file: inflate.h ***/
  82606. /* WARNING: this file should *not* be used by applications. It is
  82607. part of the implementation of the compression library and is
  82608. subject to change. Applications should only use zlib.h.
  82609. */
  82610. #ifndef _INFLATE_H_
  82611. #define _INFLATE_H_
  82612. /* define NO_GZIP when compiling if you want to disable gzip header and
  82613. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82614. the crc code when it is not needed. For shared libraries, gzip decoding
  82615. should be left enabled. */
  82616. #ifndef NO_GZIP
  82617. # define GUNZIP
  82618. #endif
  82619. /* Possible inflate modes between inflate() calls */
  82620. typedef enum {
  82621. HEAD, /* i: waiting for magic header */
  82622. FLAGS, /* i: waiting for method and flags (gzip) */
  82623. TIME, /* i: waiting for modification time (gzip) */
  82624. OS, /* i: waiting for extra flags and operating system (gzip) */
  82625. EXLEN, /* i: waiting for extra length (gzip) */
  82626. EXTRA, /* i: waiting for extra bytes (gzip) */
  82627. NAME, /* i: waiting for end of file name (gzip) */
  82628. COMMENT, /* i: waiting for end of comment (gzip) */
  82629. HCRC, /* i: waiting for header crc (gzip) */
  82630. DICTID, /* i: waiting for dictionary check value */
  82631. DICT, /* waiting for inflateSetDictionary() call */
  82632. TYPE, /* i: waiting for type bits, including last-flag bit */
  82633. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82634. STORED, /* i: waiting for stored size (length and complement) */
  82635. COPY, /* i/o: waiting for input or output to copy stored block */
  82636. TABLE, /* i: waiting for dynamic block table lengths */
  82637. LENLENS, /* i: waiting for code length code lengths */
  82638. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82639. LEN, /* i: waiting for length/lit code */
  82640. LENEXT, /* i: waiting for length extra bits */
  82641. DIST, /* i: waiting for distance code */
  82642. DISTEXT, /* i: waiting for distance extra bits */
  82643. MATCH, /* o: waiting for output space to copy string */
  82644. LIT, /* o: waiting for output space to write literal */
  82645. CHECK, /* i: waiting for 32-bit check value */
  82646. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82647. DONE, /* finished check, done -- remain here until reset */
  82648. BAD, /* got a data error -- remain here until reset */
  82649. MEM, /* got an inflate() memory error -- remain here until reset */
  82650. SYNC /* looking for synchronization bytes to restart inflate() */
  82651. } inflate_mode;
  82652. /*
  82653. State transitions between above modes -
  82654. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82655. Process header:
  82656. HEAD -> (gzip) or (zlib)
  82657. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82658. NAME -> COMMENT -> HCRC -> TYPE
  82659. (zlib) -> DICTID or TYPE
  82660. DICTID -> DICT -> TYPE
  82661. Read deflate blocks:
  82662. TYPE -> STORED or TABLE or LEN or CHECK
  82663. STORED -> COPY -> TYPE
  82664. TABLE -> LENLENS -> CODELENS -> LEN
  82665. Read deflate codes:
  82666. LEN -> LENEXT or LIT or TYPE
  82667. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82668. LIT -> LEN
  82669. Process trailer:
  82670. CHECK -> LENGTH -> DONE
  82671. */
  82672. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82673. struct inflate_state {
  82674. inflate_mode mode; /* current inflate mode */
  82675. int last; /* true if processing last block */
  82676. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82677. int havedict; /* true if dictionary provided */
  82678. int flags; /* gzip header method and flags (0 if zlib) */
  82679. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82680. unsigned long check; /* protected copy of check value */
  82681. unsigned long total; /* protected copy of output count */
  82682. gz_headerp head; /* where to save gzip header information */
  82683. /* sliding window */
  82684. unsigned wbits; /* log base 2 of requested window size */
  82685. unsigned wsize; /* window size or zero if not using window */
  82686. unsigned whave; /* valid bytes in the window */
  82687. unsigned write; /* window write index */
  82688. unsigned char FAR *window; /* allocated sliding window, if needed */
  82689. /* bit accumulator */
  82690. unsigned long hold; /* input bit accumulator */
  82691. unsigned bits; /* number of bits in "in" */
  82692. /* for string and stored block copying */
  82693. unsigned length; /* literal or length of data to copy */
  82694. unsigned offset; /* distance back to copy string from */
  82695. /* for table and code decoding */
  82696. unsigned extra; /* extra bits needed */
  82697. /* fixed and dynamic code tables */
  82698. code const FAR *lencode; /* starting table for length/literal codes */
  82699. code const FAR *distcode; /* starting table for distance codes */
  82700. unsigned lenbits; /* index bits for lencode */
  82701. unsigned distbits; /* index bits for distcode */
  82702. /* dynamic table building */
  82703. unsigned ncode; /* number of code length code lengths */
  82704. unsigned nlen; /* number of length code lengths */
  82705. unsigned ndist; /* number of distance code lengths */
  82706. unsigned have; /* number of code lengths in lens[] */
  82707. code FAR *next; /* next available space in codes[] */
  82708. unsigned short lens[320]; /* temporary storage for code lengths */
  82709. unsigned short work[288]; /* work area for code table building */
  82710. code codes[ENOUGH]; /* space for code tables */
  82711. };
  82712. #endif
  82713. /*** End of inlined file: inflate.h ***/
  82714. /*** Start of inlined file: inffast.h ***/
  82715. /* WARNING: this file should *not* be used by applications. It is
  82716. part of the implementation of the compression library and is
  82717. subject to change. Applications should only use zlib.h.
  82718. */
  82719. void inflate_fast OF((z_streamp strm, unsigned start));
  82720. /*** End of inlined file: inffast.h ***/
  82721. #ifndef ASMINF
  82722. /* Allow machine dependent optimization for post-increment or pre-increment.
  82723. Based on testing to date,
  82724. Pre-increment preferred for:
  82725. - PowerPC G3 (Adler)
  82726. - MIPS R5000 (Randers-Pehrson)
  82727. Post-increment preferred for:
  82728. - none
  82729. No measurable difference:
  82730. - Pentium III (Anderson)
  82731. - M68060 (Nikl)
  82732. */
  82733. #ifdef POSTINC
  82734. # define OFF 0
  82735. # define PUP(a) *(a)++
  82736. #else
  82737. # define OFF 1
  82738. # define PUP(a) *++(a)
  82739. #endif
  82740. /*
  82741. Decode literal, length, and distance codes and write out the resulting
  82742. literal and match bytes until either not enough input or output is
  82743. available, an end-of-block is encountered, or a data error is encountered.
  82744. When large enough input and output buffers are supplied to inflate(), for
  82745. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82746. inflate execution time is spent in this routine.
  82747. Entry assumptions:
  82748. state->mode == LEN
  82749. strm->avail_in >= 6
  82750. strm->avail_out >= 258
  82751. start >= strm->avail_out
  82752. state->bits < 8
  82753. On return, state->mode is one of:
  82754. LEN -- ran out of enough output space or enough available input
  82755. TYPE -- reached end of block code, inflate() to interpret next block
  82756. BAD -- error in block data
  82757. Notes:
  82758. - The maximum input bits used by a length/distance pair is 15 bits for the
  82759. length code, 5 bits for the length extra, 15 bits for the distance code,
  82760. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82761. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82762. checking for available input while decoding.
  82763. - The maximum bytes that a single length/distance pair can output is 258
  82764. bytes, which is the maximum length that can be coded. inflate_fast()
  82765. requires strm->avail_out >= 258 for each loop to avoid checking for
  82766. output space.
  82767. */
  82768. void inflate_fast (z_streamp strm, unsigned start)
  82769. {
  82770. struct inflate_state FAR *state;
  82771. unsigned char FAR *in; /* local strm->next_in */
  82772. unsigned char FAR *last; /* while in < last, enough input available */
  82773. unsigned char FAR *out; /* local strm->next_out */
  82774. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82775. unsigned char FAR *end; /* while out < end, enough space available */
  82776. #ifdef INFLATE_STRICT
  82777. unsigned dmax; /* maximum distance from zlib header */
  82778. #endif
  82779. unsigned wsize; /* window size or zero if not using window */
  82780. unsigned whave; /* valid bytes in the window */
  82781. unsigned write; /* window write index */
  82782. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82783. unsigned long hold; /* local strm->hold */
  82784. unsigned bits; /* local strm->bits */
  82785. code const FAR *lcode; /* local strm->lencode */
  82786. code const FAR *dcode; /* local strm->distcode */
  82787. unsigned lmask; /* mask for first level of length codes */
  82788. unsigned dmask; /* mask for first level of distance codes */
  82789. code thisx; /* retrieved table entry */
  82790. unsigned op; /* code bits, operation, extra bits, or */
  82791. /* window position, window bytes to copy */
  82792. unsigned len; /* match length, unused bytes */
  82793. unsigned dist; /* match distance */
  82794. unsigned char FAR *from; /* where to copy match from */
  82795. /* copy state to local variables */
  82796. state = (struct inflate_state FAR *)strm->state;
  82797. in = strm->next_in - OFF;
  82798. last = in + (strm->avail_in - 5);
  82799. out = strm->next_out - OFF;
  82800. beg = out - (start - strm->avail_out);
  82801. end = out + (strm->avail_out - 257);
  82802. #ifdef INFLATE_STRICT
  82803. dmax = state->dmax;
  82804. #endif
  82805. wsize = state->wsize;
  82806. whave = state->whave;
  82807. write = state->write;
  82808. window = state->window;
  82809. hold = state->hold;
  82810. bits = state->bits;
  82811. lcode = state->lencode;
  82812. dcode = state->distcode;
  82813. lmask = (1U << state->lenbits) - 1;
  82814. dmask = (1U << state->distbits) - 1;
  82815. /* decode literals and length/distances until end-of-block or not enough
  82816. input data or output space */
  82817. do {
  82818. if (bits < 15) {
  82819. hold += (unsigned long)(PUP(in)) << bits;
  82820. bits += 8;
  82821. hold += (unsigned long)(PUP(in)) << bits;
  82822. bits += 8;
  82823. }
  82824. thisx = lcode[hold & lmask];
  82825. dolen:
  82826. op = (unsigned)(thisx.bits);
  82827. hold >>= op;
  82828. bits -= op;
  82829. op = (unsigned)(thisx.op);
  82830. if (op == 0) { /* literal */
  82831. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82832. "inflate: literal '%c'\n" :
  82833. "inflate: literal 0x%02x\n", thisx.val));
  82834. PUP(out) = (unsigned char)(thisx.val);
  82835. }
  82836. else if (op & 16) { /* length base */
  82837. len = (unsigned)(thisx.val);
  82838. op &= 15; /* number of extra bits */
  82839. if (op) {
  82840. if (bits < op) {
  82841. hold += (unsigned long)(PUP(in)) << bits;
  82842. bits += 8;
  82843. }
  82844. len += (unsigned)hold & ((1U << op) - 1);
  82845. hold >>= op;
  82846. bits -= op;
  82847. }
  82848. Tracevv((stderr, "inflate: length %u\n", len));
  82849. if (bits < 15) {
  82850. hold += (unsigned long)(PUP(in)) << bits;
  82851. bits += 8;
  82852. hold += (unsigned long)(PUP(in)) << bits;
  82853. bits += 8;
  82854. }
  82855. thisx = dcode[hold & dmask];
  82856. dodist:
  82857. op = (unsigned)(thisx.bits);
  82858. hold >>= op;
  82859. bits -= op;
  82860. op = (unsigned)(thisx.op);
  82861. if (op & 16) { /* distance base */
  82862. dist = (unsigned)(thisx.val);
  82863. op &= 15; /* number of extra bits */
  82864. if (bits < op) {
  82865. hold += (unsigned long)(PUP(in)) << bits;
  82866. bits += 8;
  82867. if (bits < op) {
  82868. hold += (unsigned long)(PUP(in)) << bits;
  82869. bits += 8;
  82870. }
  82871. }
  82872. dist += (unsigned)hold & ((1U << op) - 1);
  82873. #ifdef INFLATE_STRICT
  82874. if (dist > dmax) {
  82875. strm->msg = (char *)"invalid distance too far back";
  82876. state->mode = BAD;
  82877. break;
  82878. }
  82879. #endif
  82880. hold >>= op;
  82881. bits -= op;
  82882. Tracevv((stderr, "inflate: distance %u\n", dist));
  82883. op = (unsigned)(out - beg); /* max distance in output */
  82884. if (dist > op) { /* see if copy from window */
  82885. op = dist - op; /* distance back in window */
  82886. if (op > whave) {
  82887. strm->msg = (char *)"invalid distance too far back";
  82888. state->mode = BAD;
  82889. break;
  82890. }
  82891. from = window - OFF;
  82892. if (write == 0) { /* very common case */
  82893. from += wsize - op;
  82894. if (op < len) { /* some from window */
  82895. len -= op;
  82896. do {
  82897. PUP(out) = PUP(from);
  82898. } while (--op);
  82899. from = out - dist; /* rest from output */
  82900. }
  82901. }
  82902. else if (write < op) { /* wrap around window */
  82903. from += wsize + write - op;
  82904. op -= write;
  82905. if (op < len) { /* some from end of window */
  82906. len -= op;
  82907. do {
  82908. PUP(out) = PUP(from);
  82909. } while (--op);
  82910. from = window - OFF;
  82911. if (write < len) { /* some from start of window */
  82912. op = write;
  82913. len -= op;
  82914. do {
  82915. PUP(out) = PUP(from);
  82916. } while (--op);
  82917. from = out - dist; /* rest from output */
  82918. }
  82919. }
  82920. }
  82921. else { /* contiguous in window */
  82922. from += write - op;
  82923. if (op < len) { /* some from window */
  82924. len -= op;
  82925. do {
  82926. PUP(out) = PUP(from);
  82927. } while (--op);
  82928. from = out - dist; /* rest from output */
  82929. }
  82930. }
  82931. while (len > 2) {
  82932. PUP(out) = PUP(from);
  82933. PUP(out) = PUP(from);
  82934. PUP(out) = PUP(from);
  82935. len -= 3;
  82936. }
  82937. if (len) {
  82938. PUP(out) = PUP(from);
  82939. if (len > 1)
  82940. PUP(out) = PUP(from);
  82941. }
  82942. }
  82943. else {
  82944. from = out - dist; /* copy direct from output */
  82945. do { /* minimum length is three */
  82946. PUP(out) = PUP(from);
  82947. PUP(out) = PUP(from);
  82948. PUP(out) = PUP(from);
  82949. len -= 3;
  82950. } while (len > 2);
  82951. if (len) {
  82952. PUP(out) = PUP(from);
  82953. if (len > 1)
  82954. PUP(out) = PUP(from);
  82955. }
  82956. }
  82957. }
  82958. else if ((op & 64) == 0) { /* 2nd level distance code */
  82959. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82960. goto dodist;
  82961. }
  82962. else {
  82963. strm->msg = (char *)"invalid distance code";
  82964. state->mode = BAD;
  82965. break;
  82966. }
  82967. }
  82968. else if ((op & 64) == 0) { /* 2nd level length code */
  82969. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82970. goto dolen;
  82971. }
  82972. else if (op & 32) { /* end-of-block */
  82973. Tracevv((stderr, "inflate: end of block\n"));
  82974. state->mode = TYPE;
  82975. break;
  82976. }
  82977. else {
  82978. strm->msg = (char *)"invalid literal/length code";
  82979. state->mode = BAD;
  82980. break;
  82981. }
  82982. } while (in < last && out < end);
  82983. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82984. len = bits >> 3;
  82985. in -= len;
  82986. bits -= len << 3;
  82987. hold &= (1U << bits) - 1;
  82988. /* update state and return */
  82989. strm->next_in = in + OFF;
  82990. strm->next_out = out + OFF;
  82991. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82992. strm->avail_out = (unsigned)(out < end ?
  82993. 257 + (end - out) : 257 - (out - end));
  82994. state->hold = hold;
  82995. state->bits = bits;
  82996. return;
  82997. }
  82998. /*
  82999. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83000. - Using bit fields for code structure
  83001. - Different op definition to avoid & for extra bits (do & for table bits)
  83002. - Three separate decoding do-loops for direct, window, and write == 0
  83003. - Special case for distance > 1 copies to do overlapped load and store copy
  83004. - Explicit branch predictions (based on measured branch probabilities)
  83005. - Deferring match copy and interspersed it with decoding subsequent codes
  83006. - Swapping literal/length else
  83007. - Swapping window/direct else
  83008. - Larger unrolled copy loops (three is about right)
  83009. - Moving len -= 3 statement into middle of loop
  83010. */
  83011. #endif /* !ASMINF */
  83012. /*** End of inlined file: inffast.c ***/
  83013. #undef PULLBYTE
  83014. #undef LOAD
  83015. #undef RESTORE
  83016. #undef INITBITS
  83017. #undef NEEDBITS
  83018. #undef DROPBITS
  83019. #undef BYTEBITS
  83020. /*** Start of inlined file: inflate.c ***/
  83021. /*
  83022. * Change history:
  83023. *
  83024. * 1.2.beta0 24 Nov 2002
  83025. * - First version -- complete rewrite of inflate to simplify code, avoid
  83026. * creation of window when not needed, minimize use of window when it is
  83027. * needed, make inffast.c even faster, implement gzip decoding, and to
  83028. * improve code readability and style over the previous zlib inflate code
  83029. *
  83030. * 1.2.beta1 25 Nov 2002
  83031. * - Use pointers for available input and output checking in inffast.c
  83032. * - Remove input and output counters in inffast.c
  83033. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83034. * - Remove unnecessary second byte pull from length extra in inffast.c
  83035. * - Unroll direct copy to three copies per loop in inffast.c
  83036. *
  83037. * 1.2.beta2 4 Dec 2002
  83038. * - Change external routine names to reduce potential conflicts
  83039. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83040. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83041. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83042. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83043. *
  83044. * 1.2.beta3 22 Dec 2002
  83045. * - Add comments on state->bits assertion in inffast.c
  83046. * - Add comments on op field in inftrees.h
  83047. * - Fix bug in reuse of allocated window after inflateReset()
  83048. * - Remove bit fields--back to byte structure for speed
  83049. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83050. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83051. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83052. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83053. * - Use local copies of stream next and avail values, as well as local bit
  83054. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83055. *
  83056. * 1.2.beta4 1 Jan 2003
  83057. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83058. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83059. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83060. * - Rearrange window copies in inflate_fast() for speed and simplification
  83061. * - Unroll last copy for window match in inflate_fast()
  83062. * - Use local copies of window variables in inflate_fast() for speed
  83063. * - Pull out common write == 0 case for speed in inflate_fast()
  83064. * - Make op and len in inflate_fast() unsigned for consistency
  83065. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83066. * - Simplified bad distance check in inflate_fast()
  83067. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83068. * source file infback.c to provide a call-back interface to inflate for
  83069. * programs like gzip and unzip -- uses window as output buffer to avoid
  83070. * window copying
  83071. *
  83072. * 1.2.beta5 1 Jan 2003
  83073. * - Improved inflateBack() interface to allow the caller to provide initial
  83074. * input in strm.
  83075. * - Fixed stored blocks bug in inflateBack()
  83076. *
  83077. * 1.2.beta6 4 Jan 2003
  83078. * - Added comments in inffast.c on effectiveness of POSTINC
  83079. * - Typecasting all around to reduce compiler warnings
  83080. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83081. * make compilers happy
  83082. * - Changed type of window in inflateBackInit() to unsigned char *
  83083. *
  83084. * 1.2.beta7 27 Jan 2003
  83085. * - Changed many types to unsigned or unsigned short to avoid warnings
  83086. * - Added inflateCopy() function
  83087. *
  83088. * 1.2.0 9 Mar 2003
  83089. * - Changed inflateBack() interface to provide separate opaque descriptors
  83090. * for the in() and out() functions
  83091. * - Changed inflateBack() argument and in_func typedef to swap the length
  83092. * and buffer address return values for the input function
  83093. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83094. *
  83095. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83096. */
  83097. /*** Start of inlined file: inffast.h ***/
  83098. /* WARNING: this file should *not* be used by applications. It is
  83099. part of the implementation of the compression library and is
  83100. subject to change. Applications should only use zlib.h.
  83101. */
  83102. void inflate_fast OF((z_streamp strm, unsigned start));
  83103. /*** End of inlined file: inffast.h ***/
  83104. #ifdef MAKEFIXED
  83105. # ifndef BUILDFIXED
  83106. # define BUILDFIXED
  83107. # endif
  83108. #endif
  83109. /* function prototypes */
  83110. local void fixedtables OF((struct inflate_state FAR *state));
  83111. local int updatewindow OF((z_streamp strm, unsigned out));
  83112. #ifdef BUILDFIXED
  83113. void makefixed OF((void));
  83114. #endif
  83115. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83116. unsigned len));
  83117. int ZEXPORT inflateReset (z_streamp strm)
  83118. {
  83119. struct inflate_state FAR *state;
  83120. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83121. state = (struct inflate_state FAR *)strm->state;
  83122. strm->total_in = strm->total_out = state->total = 0;
  83123. strm->msg = Z_NULL;
  83124. strm->adler = 1; /* to support ill-conceived Java test suite */
  83125. state->mode = HEAD;
  83126. state->last = 0;
  83127. state->havedict = 0;
  83128. state->dmax = 32768U;
  83129. state->head = Z_NULL;
  83130. state->wsize = 0;
  83131. state->whave = 0;
  83132. state->write = 0;
  83133. state->hold = 0;
  83134. state->bits = 0;
  83135. state->lencode = state->distcode = state->next = state->codes;
  83136. Tracev((stderr, "inflate: reset\n"));
  83137. return Z_OK;
  83138. }
  83139. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83140. {
  83141. struct inflate_state FAR *state;
  83142. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83143. state = (struct inflate_state FAR *)strm->state;
  83144. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83145. value &= (1L << bits) - 1;
  83146. state->hold += value << state->bits;
  83147. state->bits += bits;
  83148. return Z_OK;
  83149. }
  83150. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83151. {
  83152. struct inflate_state FAR *state;
  83153. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83154. stream_size != (int)(sizeof(z_stream)))
  83155. return Z_VERSION_ERROR;
  83156. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83157. strm->msg = Z_NULL; /* in case we return an error */
  83158. if (strm->zalloc == (alloc_func)0) {
  83159. strm->zalloc = zcalloc;
  83160. strm->opaque = (voidpf)0;
  83161. }
  83162. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83163. state = (struct inflate_state FAR *)
  83164. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83165. if (state == Z_NULL) return Z_MEM_ERROR;
  83166. Tracev((stderr, "inflate: allocated\n"));
  83167. strm->state = (struct internal_state FAR *)state;
  83168. if (windowBits < 0) {
  83169. state->wrap = 0;
  83170. windowBits = -windowBits;
  83171. }
  83172. else {
  83173. state->wrap = (windowBits >> 4) + 1;
  83174. #ifdef GUNZIP
  83175. if (windowBits < 48) windowBits &= 15;
  83176. #endif
  83177. }
  83178. if (windowBits < 8 || windowBits > 15) {
  83179. ZFREE(strm, state);
  83180. strm->state = Z_NULL;
  83181. return Z_STREAM_ERROR;
  83182. }
  83183. state->wbits = (unsigned)windowBits;
  83184. state->window = Z_NULL;
  83185. return inflateReset(strm);
  83186. }
  83187. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83188. {
  83189. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83190. }
  83191. /*
  83192. Return state with length and distance decoding tables and index sizes set to
  83193. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83194. If BUILDFIXED is defined, then instead this routine builds the tables the
  83195. first time it's called, and returns those tables the first time and
  83196. thereafter. This reduces the size of the code by about 2K bytes, in
  83197. exchange for a little execution time. However, BUILDFIXED should not be
  83198. used for threaded applications, since the rewriting of the tables and virgin
  83199. may not be thread-safe.
  83200. */
  83201. local void fixedtables (struct inflate_state FAR *state)
  83202. {
  83203. #ifdef BUILDFIXED
  83204. static int virgin = 1;
  83205. static code *lenfix, *distfix;
  83206. static code fixed[544];
  83207. /* build fixed huffman tables if first call (may not be thread safe) */
  83208. if (virgin) {
  83209. unsigned sym, bits;
  83210. static code *next;
  83211. /* literal/length table */
  83212. sym = 0;
  83213. while (sym < 144) state->lens[sym++] = 8;
  83214. while (sym < 256) state->lens[sym++] = 9;
  83215. while (sym < 280) state->lens[sym++] = 7;
  83216. while (sym < 288) state->lens[sym++] = 8;
  83217. next = fixed;
  83218. lenfix = next;
  83219. bits = 9;
  83220. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83221. /* distance table */
  83222. sym = 0;
  83223. while (sym < 32) state->lens[sym++] = 5;
  83224. distfix = next;
  83225. bits = 5;
  83226. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83227. /* do this just once */
  83228. virgin = 0;
  83229. }
  83230. #else /* !BUILDFIXED */
  83231. /*** Start of inlined file: inffixed.h ***/
  83232. /* WARNING: this file should *not* be used by applications. It
  83233. is part of the implementation of the compression library and
  83234. is subject to change. Applications should only use zlib.h.
  83235. */
  83236. static const code lenfix[512] = {
  83237. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83238. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83239. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83240. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83241. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83242. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83243. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83244. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83245. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83246. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83247. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83248. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83249. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83250. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83251. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83252. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83253. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83254. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83255. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83256. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83257. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83258. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83259. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83260. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83261. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83262. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83263. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83264. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83265. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83266. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83267. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83268. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83269. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83270. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83271. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83272. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83273. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83274. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83275. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83276. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83277. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83278. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83279. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83280. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83281. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83282. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83283. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83284. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83285. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83286. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83287. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83288. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83289. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83290. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83291. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83292. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83293. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83294. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83295. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83296. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83297. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83298. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83299. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83300. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83301. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83302. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83303. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83304. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83305. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83306. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83307. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83308. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83309. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83310. {0,9,255}
  83311. };
  83312. static const code distfix[32] = {
  83313. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83314. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83315. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83316. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83317. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83318. {22,5,193},{64,5,0}
  83319. };
  83320. /*** End of inlined file: inffixed.h ***/
  83321. #endif /* BUILDFIXED */
  83322. state->lencode = lenfix;
  83323. state->lenbits = 9;
  83324. state->distcode = distfix;
  83325. state->distbits = 5;
  83326. }
  83327. #ifdef MAKEFIXED
  83328. #include <stdio.h>
  83329. /*
  83330. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83331. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83332. those tables to stdout, which would be piped to inffixed.h. A small program
  83333. can simply call makefixed to do this:
  83334. void makefixed(void);
  83335. int main(void)
  83336. {
  83337. makefixed();
  83338. return 0;
  83339. }
  83340. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83341. a.out > inffixed.h
  83342. */
  83343. void makefixed()
  83344. {
  83345. unsigned low, size;
  83346. struct inflate_state state;
  83347. fixedtables(&state);
  83348. puts(" /* inffixed.h -- table for decoding fixed codes");
  83349. puts(" * Generated automatically by makefixed().");
  83350. puts(" */");
  83351. puts("");
  83352. puts(" /* WARNING: this file should *not* be used by applications.");
  83353. puts(" It is part of the implementation of this library and is");
  83354. puts(" subject to change. Applications should only use zlib.h.");
  83355. puts(" */");
  83356. puts("");
  83357. size = 1U << 9;
  83358. printf(" static const code lenfix[%u] = {", size);
  83359. low = 0;
  83360. for (;;) {
  83361. if ((low % 7) == 0) printf("\n ");
  83362. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83363. state.lencode[low].val);
  83364. if (++low == size) break;
  83365. putchar(',');
  83366. }
  83367. puts("\n };");
  83368. size = 1U << 5;
  83369. printf("\n static const code distfix[%u] = {", size);
  83370. low = 0;
  83371. for (;;) {
  83372. if ((low % 6) == 0) printf("\n ");
  83373. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83374. state.distcode[low].val);
  83375. if (++low == size) break;
  83376. putchar(',');
  83377. }
  83378. puts("\n };");
  83379. }
  83380. #endif /* MAKEFIXED */
  83381. /*
  83382. Update the window with the last wsize (normally 32K) bytes written before
  83383. returning. If window does not exist yet, create it. This is only called
  83384. when a window is already in use, or when output has been written during this
  83385. inflate call, but the end of the deflate stream has not been reached yet.
  83386. It is also called to create a window for dictionary data when a dictionary
  83387. is loaded.
  83388. Providing output buffers larger than 32K to inflate() should provide a speed
  83389. advantage, since only the last 32K of output is copied to the sliding window
  83390. upon return from inflate(), and since all distances after the first 32K of
  83391. output will fall in the output data, making match copies simpler and faster.
  83392. The advantage may be dependent on the size of the processor's data caches.
  83393. */
  83394. local int updatewindow (z_streamp strm, unsigned out)
  83395. {
  83396. struct inflate_state FAR *state;
  83397. unsigned copy, dist;
  83398. state = (struct inflate_state FAR *)strm->state;
  83399. /* if it hasn't been done already, allocate space for the window */
  83400. if (state->window == Z_NULL) {
  83401. state->window = (unsigned char FAR *)
  83402. ZALLOC(strm, 1U << state->wbits,
  83403. sizeof(unsigned char));
  83404. if (state->window == Z_NULL) return 1;
  83405. }
  83406. /* if window not in use yet, initialize */
  83407. if (state->wsize == 0) {
  83408. state->wsize = 1U << state->wbits;
  83409. state->write = 0;
  83410. state->whave = 0;
  83411. }
  83412. /* copy state->wsize or less output bytes into the circular window */
  83413. copy = out - strm->avail_out;
  83414. if (copy >= state->wsize) {
  83415. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83416. state->write = 0;
  83417. state->whave = state->wsize;
  83418. }
  83419. else {
  83420. dist = state->wsize - state->write;
  83421. if (dist > copy) dist = copy;
  83422. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83423. copy -= dist;
  83424. if (copy) {
  83425. zmemcpy(state->window, strm->next_out - copy, copy);
  83426. state->write = copy;
  83427. state->whave = state->wsize;
  83428. }
  83429. else {
  83430. state->write += dist;
  83431. if (state->write == state->wsize) state->write = 0;
  83432. if (state->whave < state->wsize) state->whave += dist;
  83433. }
  83434. }
  83435. return 0;
  83436. }
  83437. /* Macros for inflate(): */
  83438. /* check function to use adler32() for zlib or crc32() for gzip */
  83439. #ifdef GUNZIP
  83440. # define UPDATE(check, buf, len) \
  83441. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83442. #else
  83443. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83444. #endif
  83445. /* check macros for header crc */
  83446. #ifdef GUNZIP
  83447. # define CRC2(check, word) \
  83448. do { \
  83449. hbuf[0] = (unsigned char)(word); \
  83450. hbuf[1] = (unsigned char)((word) >> 8); \
  83451. check = crc32(check, hbuf, 2); \
  83452. } while (0)
  83453. # define CRC4(check, word) \
  83454. do { \
  83455. hbuf[0] = (unsigned char)(word); \
  83456. hbuf[1] = (unsigned char)((word) >> 8); \
  83457. hbuf[2] = (unsigned char)((word) >> 16); \
  83458. hbuf[3] = (unsigned char)((word) >> 24); \
  83459. check = crc32(check, hbuf, 4); \
  83460. } while (0)
  83461. #endif
  83462. /* Load registers with state in inflate() for speed */
  83463. #define LOAD() \
  83464. do { \
  83465. put = strm->next_out; \
  83466. left = strm->avail_out; \
  83467. next = strm->next_in; \
  83468. have = strm->avail_in; \
  83469. hold = state->hold; \
  83470. bits = state->bits; \
  83471. } while (0)
  83472. /* Restore state from registers in inflate() */
  83473. #define RESTORE() \
  83474. do { \
  83475. strm->next_out = put; \
  83476. strm->avail_out = left; \
  83477. strm->next_in = next; \
  83478. strm->avail_in = have; \
  83479. state->hold = hold; \
  83480. state->bits = bits; \
  83481. } while (0)
  83482. /* Clear the input bit accumulator */
  83483. #define INITBITS() \
  83484. do { \
  83485. hold = 0; \
  83486. bits = 0; \
  83487. } while (0)
  83488. /* Get a byte of input into the bit accumulator, or return from inflate()
  83489. if there is no input available. */
  83490. #define PULLBYTE() \
  83491. do { \
  83492. if (have == 0) goto inf_leave; \
  83493. have--; \
  83494. hold += (unsigned long)(*next++) << bits; \
  83495. bits += 8; \
  83496. } while (0)
  83497. /* Assure that there are at least n bits in the bit accumulator. If there is
  83498. not enough available input to do that, then return from inflate(). */
  83499. #define NEEDBITS(n) \
  83500. do { \
  83501. while (bits < (unsigned)(n)) \
  83502. PULLBYTE(); \
  83503. } while (0)
  83504. /* Return the low n bits of the bit accumulator (n < 16) */
  83505. #define BITS(n) \
  83506. ((unsigned)hold & ((1U << (n)) - 1))
  83507. /* Remove n bits from the bit accumulator */
  83508. #define DROPBITS(n) \
  83509. do { \
  83510. hold >>= (n); \
  83511. bits -= (unsigned)(n); \
  83512. } while (0)
  83513. /* Remove zero to seven bits as needed to go to a byte boundary */
  83514. #define BYTEBITS() \
  83515. do { \
  83516. hold >>= bits & 7; \
  83517. bits -= bits & 7; \
  83518. } while (0)
  83519. /* Reverse the bytes in a 32-bit value */
  83520. #define REVERSE(q) \
  83521. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83522. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83523. /*
  83524. inflate() uses a state machine to process as much input data and generate as
  83525. much output data as possible before returning. The state machine is
  83526. structured roughly as follows:
  83527. for (;;) switch (state) {
  83528. ...
  83529. case STATEn:
  83530. if (not enough input data or output space to make progress)
  83531. return;
  83532. ... make progress ...
  83533. state = STATEm;
  83534. break;
  83535. ...
  83536. }
  83537. so when inflate() is called again, the same case is attempted again, and
  83538. if the appropriate resources are provided, the machine proceeds to the
  83539. next state. The NEEDBITS() macro is usually the way the state evaluates
  83540. whether it can proceed or should return. NEEDBITS() does the return if
  83541. the requested bits are not available. The typical use of the BITS macros
  83542. is:
  83543. NEEDBITS(n);
  83544. ... do something with BITS(n) ...
  83545. DROPBITS(n);
  83546. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83547. input left to load n bits into the accumulator, or it continues. BITS(n)
  83548. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83549. the low n bits off the accumulator. INITBITS() clears the accumulator
  83550. and sets the number of available bits to zero. BYTEBITS() discards just
  83551. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83552. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83553. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83554. if there is no input available. The decoding of variable length codes uses
  83555. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83556. code, and no more.
  83557. Some states loop until they get enough input, making sure that enough
  83558. state information is maintained to continue the loop where it left off
  83559. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83560. would all have to actually be part of the saved state in case NEEDBITS()
  83561. returns:
  83562. case STATEw:
  83563. while (want < need) {
  83564. NEEDBITS(n);
  83565. keep[want++] = BITS(n);
  83566. DROPBITS(n);
  83567. }
  83568. state = STATEx;
  83569. case STATEx:
  83570. As shown above, if the next state is also the next case, then the break
  83571. is omitted.
  83572. A state may also return if there is not enough output space available to
  83573. complete that state. Those states are copying stored data, writing a
  83574. literal byte, and copying a matching string.
  83575. When returning, a "goto inf_leave" is used to update the total counters,
  83576. update the check value, and determine whether any progress has been made
  83577. during that inflate() call in order to return the proper return code.
  83578. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83579. When there is a window, goto inf_leave will update the window with the last
  83580. output written. If a goto inf_leave occurs in the middle of decompression
  83581. and there is no window currently, goto inf_leave will create one and copy
  83582. output to the window for the next call of inflate().
  83583. In this implementation, the flush parameter of inflate() only affects the
  83584. return code (per zlib.h). inflate() always writes as much as possible to
  83585. strm->next_out, given the space available and the provided input--the effect
  83586. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83587. the allocation of and copying into a sliding window until necessary, which
  83588. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83589. stream available. So the only thing the flush parameter actually does is:
  83590. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83591. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83592. */
  83593. int ZEXPORT inflate (z_streamp strm, int flush)
  83594. {
  83595. struct inflate_state FAR *state;
  83596. unsigned char FAR *next; /* next input */
  83597. unsigned char FAR *put; /* next output */
  83598. unsigned have, left; /* available input and output */
  83599. unsigned long hold; /* bit buffer */
  83600. unsigned bits; /* bits in bit buffer */
  83601. unsigned in, out; /* save starting available input and output */
  83602. unsigned copy; /* number of stored or match bytes to copy */
  83603. unsigned char FAR *from; /* where to copy match bytes from */
  83604. code thisx; /* current decoding table entry */
  83605. code last; /* parent table entry */
  83606. unsigned len; /* length to copy for repeats, bits to drop */
  83607. int ret; /* return code */
  83608. #ifdef GUNZIP
  83609. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83610. #endif
  83611. static const unsigned short order[19] = /* permutation of code lengths */
  83612. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83613. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83614. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83615. return Z_STREAM_ERROR;
  83616. state = (struct inflate_state FAR *)strm->state;
  83617. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83618. LOAD();
  83619. in = have;
  83620. out = left;
  83621. ret = Z_OK;
  83622. for (;;)
  83623. switch (state->mode) {
  83624. case HEAD:
  83625. if (state->wrap == 0) {
  83626. state->mode = TYPEDO;
  83627. break;
  83628. }
  83629. NEEDBITS(16);
  83630. #ifdef GUNZIP
  83631. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83632. state->check = crc32(0L, Z_NULL, 0);
  83633. CRC2(state->check, hold);
  83634. INITBITS();
  83635. state->mode = FLAGS;
  83636. break;
  83637. }
  83638. state->flags = 0; /* expect zlib header */
  83639. if (state->head != Z_NULL)
  83640. state->head->done = -1;
  83641. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83642. #else
  83643. if (
  83644. #endif
  83645. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83646. strm->msg = (char *)"incorrect header check";
  83647. state->mode = BAD;
  83648. break;
  83649. }
  83650. if (BITS(4) != Z_DEFLATED) {
  83651. strm->msg = (char *)"unknown compression method";
  83652. state->mode = BAD;
  83653. break;
  83654. }
  83655. DROPBITS(4);
  83656. len = BITS(4) + 8;
  83657. if (len > state->wbits) {
  83658. strm->msg = (char *)"invalid window size";
  83659. state->mode = BAD;
  83660. break;
  83661. }
  83662. state->dmax = 1U << len;
  83663. Tracev((stderr, "inflate: zlib header ok\n"));
  83664. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83665. state->mode = hold & 0x200 ? DICTID : TYPE;
  83666. INITBITS();
  83667. break;
  83668. #ifdef GUNZIP
  83669. case FLAGS:
  83670. NEEDBITS(16);
  83671. state->flags = (int)(hold);
  83672. if ((state->flags & 0xff) != Z_DEFLATED) {
  83673. strm->msg = (char *)"unknown compression method";
  83674. state->mode = BAD;
  83675. break;
  83676. }
  83677. if (state->flags & 0xe000) {
  83678. strm->msg = (char *)"unknown header flags set";
  83679. state->mode = BAD;
  83680. break;
  83681. }
  83682. if (state->head != Z_NULL)
  83683. state->head->text = (int)((hold >> 8) & 1);
  83684. if (state->flags & 0x0200) CRC2(state->check, hold);
  83685. INITBITS();
  83686. state->mode = TIME;
  83687. case TIME:
  83688. NEEDBITS(32);
  83689. if (state->head != Z_NULL)
  83690. state->head->time = hold;
  83691. if (state->flags & 0x0200) CRC4(state->check, hold);
  83692. INITBITS();
  83693. state->mode = OS;
  83694. case OS:
  83695. NEEDBITS(16);
  83696. if (state->head != Z_NULL) {
  83697. state->head->xflags = (int)(hold & 0xff);
  83698. state->head->os = (int)(hold >> 8);
  83699. }
  83700. if (state->flags & 0x0200) CRC2(state->check, hold);
  83701. INITBITS();
  83702. state->mode = EXLEN;
  83703. case EXLEN:
  83704. if (state->flags & 0x0400) {
  83705. NEEDBITS(16);
  83706. state->length = (unsigned)(hold);
  83707. if (state->head != Z_NULL)
  83708. state->head->extra_len = (unsigned)hold;
  83709. if (state->flags & 0x0200) CRC2(state->check, hold);
  83710. INITBITS();
  83711. }
  83712. else if (state->head != Z_NULL)
  83713. state->head->extra = Z_NULL;
  83714. state->mode = EXTRA;
  83715. case EXTRA:
  83716. if (state->flags & 0x0400) {
  83717. copy = state->length;
  83718. if (copy > have) copy = have;
  83719. if (copy) {
  83720. if (state->head != Z_NULL &&
  83721. state->head->extra != Z_NULL) {
  83722. len = state->head->extra_len - state->length;
  83723. zmemcpy(state->head->extra + len, next,
  83724. len + copy > state->head->extra_max ?
  83725. state->head->extra_max - len : copy);
  83726. }
  83727. if (state->flags & 0x0200)
  83728. state->check = crc32(state->check, next, copy);
  83729. have -= copy;
  83730. next += copy;
  83731. state->length -= copy;
  83732. }
  83733. if (state->length) goto inf_leave;
  83734. }
  83735. state->length = 0;
  83736. state->mode = NAME;
  83737. case NAME:
  83738. if (state->flags & 0x0800) {
  83739. if (have == 0) goto inf_leave;
  83740. copy = 0;
  83741. do {
  83742. len = (unsigned)(next[copy++]);
  83743. if (state->head != Z_NULL &&
  83744. state->head->name != Z_NULL &&
  83745. state->length < state->head->name_max)
  83746. state->head->name[state->length++] = len;
  83747. } while (len && copy < have);
  83748. if (state->flags & 0x0200)
  83749. state->check = crc32(state->check, next, copy);
  83750. have -= copy;
  83751. next += copy;
  83752. if (len) goto inf_leave;
  83753. }
  83754. else if (state->head != Z_NULL)
  83755. state->head->name = Z_NULL;
  83756. state->length = 0;
  83757. state->mode = COMMENT;
  83758. case COMMENT:
  83759. if (state->flags & 0x1000) {
  83760. if (have == 0) goto inf_leave;
  83761. copy = 0;
  83762. do {
  83763. len = (unsigned)(next[copy++]);
  83764. if (state->head != Z_NULL &&
  83765. state->head->comment != Z_NULL &&
  83766. state->length < state->head->comm_max)
  83767. state->head->comment[state->length++] = len;
  83768. } while (len && copy < have);
  83769. if (state->flags & 0x0200)
  83770. state->check = crc32(state->check, next, copy);
  83771. have -= copy;
  83772. next += copy;
  83773. if (len) goto inf_leave;
  83774. }
  83775. else if (state->head != Z_NULL)
  83776. state->head->comment = Z_NULL;
  83777. state->mode = HCRC;
  83778. case HCRC:
  83779. if (state->flags & 0x0200) {
  83780. NEEDBITS(16);
  83781. if (hold != (state->check & 0xffff)) {
  83782. strm->msg = (char *)"header crc mismatch";
  83783. state->mode = BAD;
  83784. break;
  83785. }
  83786. INITBITS();
  83787. }
  83788. if (state->head != Z_NULL) {
  83789. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83790. state->head->done = 1;
  83791. }
  83792. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83793. state->mode = TYPE;
  83794. break;
  83795. #endif
  83796. case DICTID:
  83797. NEEDBITS(32);
  83798. strm->adler = state->check = REVERSE(hold);
  83799. INITBITS();
  83800. state->mode = DICT;
  83801. case DICT:
  83802. if (state->havedict == 0) {
  83803. RESTORE();
  83804. return Z_NEED_DICT;
  83805. }
  83806. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83807. state->mode = TYPE;
  83808. case TYPE:
  83809. if (flush == Z_BLOCK) goto inf_leave;
  83810. case TYPEDO:
  83811. if (state->last) {
  83812. BYTEBITS();
  83813. state->mode = CHECK;
  83814. break;
  83815. }
  83816. NEEDBITS(3);
  83817. state->last = BITS(1);
  83818. DROPBITS(1);
  83819. switch (BITS(2)) {
  83820. case 0: /* stored block */
  83821. Tracev((stderr, "inflate: stored block%s\n",
  83822. state->last ? " (last)" : ""));
  83823. state->mode = STORED;
  83824. break;
  83825. case 1: /* fixed block */
  83826. fixedtables(state);
  83827. Tracev((stderr, "inflate: fixed codes block%s\n",
  83828. state->last ? " (last)" : ""));
  83829. state->mode = LEN; /* decode codes */
  83830. break;
  83831. case 2: /* dynamic block */
  83832. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83833. state->last ? " (last)" : ""));
  83834. state->mode = TABLE;
  83835. break;
  83836. case 3:
  83837. strm->msg = (char *)"invalid block type";
  83838. state->mode = BAD;
  83839. }
  83840. DROPBITS(2);
  83841. break;
  83842. case STORED:
  83843. BYTEBITS(); /* go to byte boundary */
  83844. NEEDBITS(32);
  83845. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83846. strm->msg = (char *)"invalid stored block lengths";
  83847. state->mode = BAD;
  83848. break;
  83849. }
  83850. state->length = (unsigned)hold & 0xffff;
  83851. Tracev((stderr, "inflate: stored length %u\n",
  83852. state->length));
  83853. INITBITS();
  83854. state->mode = COPY;
  83855. case COPY:
  83856. copy = state->length;
  83857. if (copy) {
  83858. if (copy > have) copy = have;
  83859. if (copy > left) copy = left;
  83860. if (copy == 0) goto inf_leave;
  83861. zmemcpy(put, next, copy);
  83862. have -= copy;
  83863. next += copy;
  83864. left -= copy;
  83865. put += copy;
  83866. state->length -= copy;
  83867. break;
  83868. }
  83869. Tracev((stderr, "inflate: stored end\n"));
  83870. state->mode = TYPE;
  83871. break;
  83872. case TABLE:
  83873. NEEDBITS(14);
  83874. state->nlen = BITS(5) + 257;
  83875. DROPBITS(5);
  83876. state->ndist = BITS(5) + 1;
  83877. DROPBITS(5);
  83878. state->ncode = BITS(4) + 4;
  83879. DROPBITS(4);
  83880. #ifndef PKZIP_BUG_WORKAROUND
  83881. if (state->nlen > 286 || state->ndist > 30) {
  83882. strm->msg = (char *)"too many length or distance symbols";
  83883. state->mode = BAD;
  83884. break;
  83885. }
  83886. #endif
  83887. Tracev((stderr, "inflate: table sizes ok\n"));
  83888. state->have = 0;
  83889. state->mode = LENLENS;
  83890. case LENLENS:
  83891. while (state->have < state->ncode) {
  83892. NEEDBITS(3);
  83893. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83894. DROPBITS(3);
  83895. }
  83896. while (state->have < 19)
  83897. state->lens[order[state->have++]] = 0;
  83898. state->next = state->codes;
  83899. state->lencode = (code const FAR *)(state->next);
  83900. state->lenbits = 7;
  83901. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83902. &(state->lenbits), state->work);
  83903. if (ret) {
  83904. strm->msg = (char *)"invalid code lengths set";
  83905. state->mode = BAD;
  83906. break;
  83907. }
  83908. Tracev((stderr, "inflate: code lengths ok\n"));
  83909. state->have = 0;
  83910. state->mode = CODELENS;
  83911. case CODELENS:
  83912. while (state->have < state->nlen + state->ndist) {
  83913. for (;;) {
  83914. thisx = state->lencode[BITS(state->lenbits)];
  83915. if ((unsigned)(thisx.bits) <= bits) break;
  83916. PULLBYTE();
  83917. }
  83918. if (thisx.val < 16) {
  83919. NEEDBITS(thisx.bits);
  83920. DROPBITS(thisx.bits);
  83921. state->lens[state->have++] = thisx.val;
  83922. }
  83923. else {
  83924. if (thisx.val == 16) {
  83925. NEEDBITS(thisx.bits + 2);
  83926. DROPBITS(thisx.bits);
  83927. if (state->have == 0) {
  83928. strm->msg = (char *)"invalid bit length repeat";
  83929. state->mode = BAD;
  83930. break;
  83931. }
  83932. len = state->lens[state->have - 1];
  83933. copy = 3 + BITS(2);
  83934. DROPBITS(2);
  83935. }
  83936. else if (thisx.val == 17) {
  83937. NEEDBITS(thisx.bits + 3);
  83938. DROPBITS(thisx.bits);
  83939. len = 0;
  83940. copy = 3 + BITS(3);
  83941. DROPBITS(3);
  83942. }
  83943. else {
  83944. NEEDBITS(thisx.bits + 7);
  83945. DROPBITS(thisx.bits);
  83946. len = 0;
  83947. copy = 11 + BITS(7);
  83948. DROPBITS(7);
  83949. }
  83950. if (state->have + copy > state->nlen + state->ndist) {
  83951. strm->msg = (char *)"invalid bit length repeat";
  83952. state->mode = BAD;
  83953. break;
  83954. }
  83955. while (copy--)
  83956. state->lens[state->have++] = (unsigned short)len;
  83957. }
  83958. }
  83959. /* handle error breaks in while */
  83960. if (state->mode == BAD) break;
  83961. /* build code tables */
  83962. state->next = state->codes;
  83963. state->lencode = (code const FAR *)(state->next);
  83964. state->lenbits = 9;
  83965. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83966. &(state->lenbits), state->work);
  83967. if (ret) {
  83968. strm->msg = (char *)"invalid literal/lengths set";
  83969. state->mode = BAD;
  83970. break;
  83971. }
  83972. state->distcode = (code const FAR *)(state->next);
  83973. state->distbits = 6;
  83974. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83975. &(state->next), &(state->distbits), state->work);
  83976. if (ret) {
  83977. strm->msg = (char *)"invalid distances set";
  83978. state->mode = BAD;
  83979. break;
  83980. }
  83981. Tracev((stderr, "inflate: codes ok\n"));
  83982. state->mode = LEN;
  83983. case LEN:
  83984. if (have >= 6 && left >= 258) {
  83985. RESTORE();
  83986. inflate_fast(strm, out);
  83987. LOAD();
  83988. break;
  83989. }
  83990. for (;;) {
  83991. thisx = state->lencode[BITS(state->lenbits)];
  83992. if ((unsigned)(thisx.bits) <= bits) break;
  83993. PULLBYTE();
  83994. }
  83995. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83996. last = thisx;
  83997. for (;;) {
  83998. thisx = state->lencode[last.val +
  83999. (BITS(last.bits + last.op) >> last.bits)];
  84000. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84001. PULLBYTE();
  84002. }
  84003. DROPBITS(last.bits);
  84004. }
  84005. DROPBITS(thisx.bits);
  84006. state->length = (unsigned)thisx.val;
  84007. if ((int)(thisx.op) == 0) {
  84008. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84009. "inflate: literal '%c'\n" :
  84010. "inflate: literal 0x%02x\n", thisx.val));
  84011. state->mode = LIT;
  84012. break;
  84013. }
  84014. if (thisx.op & 32) {
  84015. Tracevv((stderr, "inflate: end of block\n"));
  84016. state->mode = TYPE;
  84017. break;
  84018. }
  84019. if (thisx.op & 64) {
  84020. strm->msg = (char *)"invalid literal/length code";
  84021. state->mode = BAD;
  84022. break;
  84023. }
  84024. state->extra = (unsigned)(thisx.op) & 15;
  84025. state->mode = LENEXT;
  84026. case LENEXT:
  84027. if (state->extra) {
  84028. NEEDBITS(state->extra);
  84029. state->length += BITS(state->extra);
  84030. DROPBITS(state->extra);
  84031. }
  84032. Tracevv((stderr, "inflate: length %u\n", state->length));
  84033. state->mode = DIST;
  84034. case DIST:
  84035. for (;;) {
  84036. thisx = state->distcode[BITS(state->distbits)];
  84037. if ((unsigned)(thisx.bits) <= bits) break;
  84038. PULLBYTE();
  84039. }
  84040. if ((thisx.op & 0xf0) == 0) {
  84041. last = thisx;
  84042. for (;;) {
  84043. thisx = state->distcode[last.val +
  84044. (BITS(last.bits + last.op) >> last.bits)];
  84045. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84046. PULLBYTE();
  84047. }
  84048. DROPBITS(last.bits);
  84049. }
  84050. DROPBITS(thisx.bits);
  84051. if (thisx.op & 64) {
  84052. strm->msg = (char *)"invalid distance code";
  84053. state->mode = BAD;
  84054. break;
  84055. }
  84056. state->offset = (unsigned)thisx.val;
  84057. state->extra = (unsigned)(thisx.op) & 15;
  84058. state->mode = DISTEXT;
  84059. case DISTEXT:
  84060. if (state->extra) {
  84061. NEEDBITS(state->extra);
  84062. state->offset += BITS(state->extra);
  84063. DROPBITS(state->extra);
  84064. }
  84065. #ifdef INFLATE_STRICT
  84066. if (state->offset > state->dmax) {
  84067. strm->msg = (char *)"invalid distance too far back";
  84068. state->mode = BAD;
  84069. break;
  84070. }
  84071. #endif
  84072. if (state->offset > state->whave + out - left) {
  84073. strm->msg = (char *)"invalid distance too far back";
  84074. state->mode = BAD;
  84075. break;
  84076. }
  84077. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84078. state->mode = MATCH;
  84079. case MATCH:
  84080. if (left == 0) goto inf_leave;
  84081. copy = out - left;
  84082. if (state->offset > copy) { /* copy from window */
  84083. copy = state->offset - copy;
  84084. if (copy > state->write) {
  84085. copy -= state->write;
  84086. from = state->window + (state->wsize - copy);
  84087. }
  84088. else
  84089. from = state->window + (state->write - copy);
  84090. if (copy > state->length) copy = state->length;
  84091. }
  84092. else { /* copy from output */
  84093. from = put - state->offset;
  84094. copy = state->length;
  84095. }
  84096. if (copy > left) copy = left;
  84097. left -= copy;
  84098. state->length -= copy;
  84099. do {
  84100. *put++ = *from++;
  84101. } while (--copy);
  84102. if (state->length == 0) state->mode = LEN;
  84103. break;
  84104. case LIT:
  84105. if (left == 0) goto inf_leave;
  84106. *put++ = (unsigned char)(state->length);
  84107. left--;
  84108. state->mode = LEN;
  84109. break;
  84110. case CHECK:
  84111. if (state->wrap) {
  84112. NEEDBITS(32);
  84113. out -= left;
  84114. strm->total_out += out;
  84115. state->total += out;
  84116. if (out)
  84117. strm->adler = state->check =
  84118. UPDATE(state->check, put - out, out);
  84119. out = left;
  84120. if ((
  84121. #ifdef GUNZIP
  84122. state->flags ? hold :
  84123. #endif
  84124. REVERSE(hold)) != state->check) {
  84125. strm->msg = (char *)"incorrect data check";
  84126. state->mode = BAD;
  84127. break;
  84128. }
  84129. INITBITS();
  84130. Tracev((stderr, "inflate: check matches trailer\n"));
  84131. }
  84132. #ifdef GUNZIP
  84133. state->mode = LENGTH;
  84134. case LENGTH:
  84135. if (state->wrap && state->flags) {
  84136. NEEDBITS(32);
  84137. if (hold != (state->total & 0xffffffffUL)) {
  84138. strm->msg = (char *)"incorrect length check";
  84139. state->mode = BAD;
  84140. break;
  84141. }
  84142. INITBITS();
  84143. Tracev((stderr, "inflate: length matches trailer\n"));
  84144. }
  84145. #endif
  84146. state->mode = DONE;
  84147. case DONE:
  84148. ret = Z_STREAM_END;
  84149. goto inf_leave;
  84150. case BAD:
  84151. ret = Z_DATA_ERROR;
  84152. goto inf_leave;
  84153. case MEM:
  84154. return Z_MEM_ERROR;
  84155. case SYNC:
  84156. default:
  84157. return Z_STREAM_ERROR;
  84158. }
  84159. /*
  84160. Return from inflate(), updating the total counts and the check value.
  84161. If there was no progress during the inflate() call, return a buffer
  84162. error. Call updatewindow() to create and/or update the window state.
  84163. Note: a memory error from inflate() is non-recoverable.
  84164. */
  84165. inf_leave:
  84166. RESTORE();
  84167. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84168. if (updatewindow(strm, out)) {
  84169. state->mode = MEM;
  84170. return Z_MEM_ERROR;
  84171. }
  84172. in -= strm->avail_in;
  84173. out -= strm->avail_out;
  84174. strm->total_in += in;
  84175. strm->total_out += out;
  84176. state->total += out;
  84177. if (state->wrap && out)
  84178. strm->adler = state->check =
  84179. UPDATE(state->check, strm->next_out - out, out);
  84180. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84181. (state->mode == TYPE ? 128 : 0);
  84182. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84183. ret = Z_BUF_ERROR;
  84184. return ret;
  84185. }
  84186. int ZEXPORT inflateEnd (z_streamp strm)
  84187. {
  84188. struct inflate_state FAR *state;
  84189. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84190. return Z_STREAM_ERROR;
  84191. state = (struct inflate_state FAR *)strm->state;
  84192. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84193. ZFREE(strm, strm->state);
  84194. strm->state = Z_NULL;
  84195. Tracev((stderr, "inflate: end\n"));
  84196. return Z_OK;
  84197. }
  84198. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84199. {
  84200. struct inflate_state FAR *state;
  84201. unsigned long id_;
  84202. /* check state */
  84203. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84204. state = (struct inflate_state FAR *)strm->state;
  84205. if (state->wrap != 0 && state->mode != DICT)
  84206. return Z_STREAM_ERROR;
  84207. /* check for correct dictionary id */
  84208. if (state->mode == DICT) {
  84209. id_ = adler32(0L, Z_NULL, 0);
  84210. id_ = adler32(id_, dictionary, dictLength);
  84211. if (id_ != state->check)
  84212. return Z_DATA_ERROR;
  84213. }
  84214. /* copy dictionary to window */
  84215. if (updatewindow(strm, strm->avail_out)) {
  84216. state->mode = MEM;
  84217. return Z_MEM_ERROR;
  84218. }
  84219. if (dictLength > state->wsize) {
  84220. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84221. state->wsize);
  84222. state->whave = state->wsize;
  84223. }
  84224. else {
  84225. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84226. dictLength);
  84227. state->whave = dictLength;
  84228. }
  84229. state->havedict = 1;
  84230. Tracev((stderr, "inflate: dictionary set\n"));
  84231. return Z_OK;
  84232. }
  84233. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84234. {
  84235. struct inflate_state FAR *state;
  84236. /* check state */
  84237. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84238. state = (struct inflate_state FAR *)strm->state;
  84239. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84240. /* save header structure */
  84241. state->head = head;
  84242. head->done = 0;
  84243. return Z_OK;
  84244. }
  84245. /*
  84246. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84247. or when out of input. When called, *have is the number of pattern bytes
  84248. found in order so far, in 0..3. On return *have is updated to the new
  84249. state. If on return *have equals four, then the pattern was found and the
  84250. return value is how many bytes were read including the last byte of the
  84251. pattern. If *have is less than four, then the pattern has not been found
  84252. yet and the return value is len. In the latter case, syncsearch() can be
  84253. called again with more data and the *have state. *have is initialized to
  84254. zero for the first call.
  84255. */
  84256. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84257. {
  84258. unsigned got;
  84259. unsigned next;
  84260. got = *have;
  84261. next = 0;
  84262. while (next < len && got < 4) {
  84263. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84264. got++;
  84265. else if (buf[next])
  84266. got = 0;
  84267. else
  84268. got = 4 - got;
  84269. next++;
  84270. }
  84271. *have = got;
  84272. return next;
  84273. }
  84274. int ZEXPORT inflateSync (z_streamp strm)
  84275. {
  84276. unsigned len; /* number of bytes to look at or looked at */
  84277. unsigned long in, out; /* temporary to save total_in and total_out */
  84278. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84279. struct inflate_state FAR *state;
  84280. /* check parameters */
  84281. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84282. state = (struct inflate_state FAR *)strm->state;
  84283. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84284. /* if first time, start search in bit buffer */
  84285. if (state->mode != SYNC) {
  84286. state->mode = SYNC;
  84287. state->hold <<= state->bits & 7;
  84288. state->bits -= state->bits & 7;
  84289. len = 0;
  84290. while (state->bits >= 8) {
  84291. buf[len++] = (unsigned char)(state->hold);
  84292. state->hold >>= 8;
  84293. state->bits -= 8;
  84294. }
  84295. state->have = 0;
  84296. syncsearch(&(state->have), buf, len);
  84297. }
  84298. /* search available input */
  84299. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84300. strm->avail_in -= len;
  84301. strm->next_in += len;
  84302. strm->total_in += len;
  84303. /* return no joy or set up to restart inflate() on a new block */
  84304. if (state->have != 4) return Z_DATA_ERROR;
  84305. in = strm->total_in; out = strm->total_out;
  84306. inflateReset(strm);
  84307. strm->total_in = in; strm->total_out = out;
  84308. state->mode = TYPE;
  84309. return Z_OK;
  84310. }
  84311. /*
  84312. Returns true if inflate is currently at the end of a block generated by
  84313. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84314. implementation to provide an additional safety check. PPP uses
  84315. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84316. block. When decompressing, PPP checks that at the end of input packet,
  84317. inflate is waiting for these length bytes.
  84318. */
  84319. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84320. {
  84321. struct inflate_state FAR *state;
  84322. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84323. state = (struct inflate_state FAR *)strm->state;
  84324. return state->mode == STORED && state->bits == 0;
  84325. }
  84326. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84327. {
  84328. struct inflate_state FAR *state;
  84329. struct inflate_state FAR *copy;
  84330. unsigned char FAR *window;
  84331. unsigned wsize;
  84332. /* check input */
  84333. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84334. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84335. return Z_STREAM_ERROR;
  84336. state = (struct inflate_state FAR *)source->state;
  84337. /* allocate space */
  84338. copy = (struct inflate_state FAR *)
  84339. ZALLOC(source, 1, sizeof(struct inflate_state));
  84340. if (copy == Z_NULL) return Z_MEM_ERROR;
  84341. window = Z_NULL;
  84342. if (state->window != Z_NULL) {
  84343. window = (unsigned char FAR *)
  84344. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84345. if (window == Z_NULL) {
  84346. ZFREE(source, copy);
  84347. return Z_MEM_ERROR;
  84348. }
  84349. }
  84350. /* copy state */
  84351. zmemcpy(dest, source, sizeof(z_stream));
  84352. zmemcpy(copy, state, sizeof(struct inflate_state));
  84353. if (state->lencode >= state->codes &&
  84354. state->lencode <= state->codes + ENOUGH - 1) {
  84355. copy->lencode = copy->codes + (state->lencode - state->codes);
  84356. copy->distcode = copy->codes + (state->distcode - state->codes);
  84357. }
  84358. copy->next = copy->codes + (state->next - state->codes);
  84359. if (window != Z_NULL) {
  84360. wsize = 1U << state->wbits;
  84361. zmemcpy(window, state->window, wsize);
  84362. }
  84363. copy->window = window;
  84364. dest->state = (struct internal_state FAR *)copy;
  84365. return Z_OK;
  84366. }
  84367. /*** End of inlined file: inflate.c ***/
  84368. /*** Start of inlined file: inftrees.c ***/
  84369. #define MAXBITS 15
  84370. const char inflate_copyright[] =
  84371. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84372. /*
  84373. If you use the zlib library in a product, an acknowledgment is welcome
  84374. in the documentation of your product. If for some reason you cannot
  84375. include such an acknowledgment, I would appreciate that you keep this
  84376. copyright string in the executable of your product.
  84377. */
  84378. /*
  84379. Build a set of tables to decode the provided canonical Huffman code.
  84380. The code lengths are lens[0..codes-1]. The result starts at *table,
  84381. whose indices are 0..2^bits-1. work is a writable array of at least
  84382. lens shorts, which is used as a work area. type is the type of code
  84383. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84384. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84385. on return points to the next available entry's address. bits is the
  84386. requested root table index bits, and on return it is the actual root
  84387. table index bits. It will differ if the request is greater than the
  84388. longest code or if it is less than the shortest code.
  84389. */
  84390. int inflate_table (codetype type,
  84391. unsigned short FAR *lens,
  84392. unsigned codes,
  84393. code FAR * FAR *table,
  84394. unsigned FAR *bits,
  84395. unsigned short FAR *work)
  84396. {
  84397. unsigned len; /* a code's length in bits */
  84398. unsigned sym; /* index of code symbols */
  84399. unsigned min, max; /* minimum and maximum code lengths */
  84400. unsigned root; /* number of index bits for root table */
  84401. unsigned curr; /* number of index bits for current table */
  84402. unsigned drop; /* code bits to drop for sub-table */
  84403. int left; /* number of prefix codes available */
  84404. unsigned used; /* code entries in table used */
  84405. unsigned huff; /* Huffman code */
  84406. unsigned incr; /* for incrementing code, index */
  84407. unsigned fill; /* index for replicating entries */
  84408. unsigned low; /* low bits for current root entry */
  84409. unsigned mask; /* mask for low root bits */
  84410. code thisx; /* table entry for duplication */
  84411. code FAR *next; /* next available space in table */
  84412. const unsigned short FAR *base; /* base value table to use */
  84413. const unsigned short FAR *extra; /* extra bits table to use */
  84414. int end; /* use base and extra for symbol > end */
  84415. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84416. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84417. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84418. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84419. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84420. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84421. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84422. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84423. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84424. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84425. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84426. 8193, 12289, 16385, 24577, 0, 0};
  84427. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84428. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84429. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84430. 28, 28, 29, 29, 64, 64};
  84431. /*
  84432. Process a set of code lengths to create a canonical Huffman code. The
  84433. code lengths are lens[0..codes-1]. Each length corresponds to the
  84434. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84435. symbols by length from short to long, and retaining the symbol order
  84436. for codes with equal lengths. Then the code starts with all zero bits
  84437. for the first code of the shortest length, and the codes are integer
  84438. increments for the same length, and zeros are appended as the length
  84439. increases. For the deflate format, these bits are stored backwards
  84440. from their more natural integer increment ordering, and so when the
  84441. decoding tables are built in the large loop below, the integer codes
  84442. are incremented backwards.
  84443. This routine assumes, but does not check, that all of the entries in
  84444. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84445. 1..MAXBITS is interpreted as that code length. zero means that that
  84446. symbol does not occur in this code.
  84447. The codes are sorted by computing a count of codes for each length,
  84448. creating from that a table of starting indices for each length in the
  84449. sorted table, and then entering the symbols in order in the sorted
  84450. table. The sorted table is work[], with that space being provided by
  84451. the caller.
  84452. The length counts are used for other purposes as well, i.e. finding
  84453. the minimum and maximum length codes, determining if there are any
  84454. codes at all, checking for a valid set of lengths, and looking ahead
  84455. at length counts to determine sub-table sizes when building the
  84456. decoding tables.
  84457. */
  84458. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84459. for (len = 0; len <= MAXBITS; len++)
  84460. count[len] = 0;
  84461. for (sym = 0; sym < codes; sym++)
  84462. count[lens[sym]]++;
  84463. /* bound code lengths, force root to be within code lengths */
  84464. root = *bits;
  84465. for (max = MAXBITS; max >= 1; max--)
  84466. if (count[max] != 0) break;
  84467. if (root > max) root = max;
  84468. if (max == 0) { /* no symbols to code at all */
  84469. thisx.op = (unsigned char)64; /* invalid code marker */
  84470. thisx.bits = (unsigned char)1;
  84471. thisx.val = (unsigned short)0;
  84472. *(*table)++ = thisx; /* make a table to force an error */
  84473. *(*table)++ = thisx;
  84474. *bits = 1;
  84475. return 0; /* no symbols, but wait for decoding to report error */
  84476. }
  84477. for (min = 1; min <= MAXBITS; min++)
  84478. if (count[min] != 0) break;
  84479. if (root < min) root = min;
  84480. /* check for an over-subscribed or incomplete set of lengths */
  84481. left = 1;
  84482. for (len = 1; len <= MAXBITS; len++) {
  84483. left <<= 1;
  84484. left -= count[len];
  84485. if (left < 0) return -1; /* over-subscribed */
  84486. }
  84487. if (left > 0 && (type == CODES || max != 1))
  84488. return -1; /* incomplete set */
  84489. /* generate offsets into symbol table for each length for sorting */
  84490. offs[1] = 0;
  84491. for (len = 1; len < MAXBITS; len++)
  84492. offs[len + 1] = offs[len] + count[len];
  84493. /* sort symbols by length, by symbol order within each length */
  84494. for (sym = 0; sym < codes; sym++)
  84495. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84496. /*
  84497. Create and fill in decoding tables. In this loop, the table being
  84498. filled is at next and has curr index bits. The code being used is huff
  84499. with length len. That code is converted to an index by dropping drop
  84500. bits off of the bottom. For codes where len is less than drop + curr,
  84501. those top drop + curr - len bits are incremented through all values to
  84502. fill the table with replicated entries.
  84503. root is the number of index bits for the root table. When len exceeds
  84504. root, sub-tables are created pointed to by the root entry with an index
  84505. of the low root bits of huff. This is saved in low to check for when a
  84506. new sub-table should be started. drop is zero when the root table is
  84507. being filled, and drop is root when sub-tables are being filled.
  84508. When a new sub-table is needed, it is necessary to look ahead in the
  84509. code lengths to determine what size sub-table is needed. The length
  84510. counts are used for this, and so count[] is decremented as codes are
  84511. entered in the tables.
  84512. used keeps track of how many table entries have been allocated from the
  84513. provided *table space. It is checked when a LENS table is being made
  84514. against the space in *table, ENOUGH, minus the maximum space needed by
  84515. the worst case distance code, MAXD. This should never happen, but the
  84516. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84517. This assumes that when type == LENS, bits == 9.
  84518. sym increments through all symbols, and the loop terminates when
  84519. all codes of length max, i.e. all codes, have been processed. This
  84520. routine permits incomplete codes, so another loop after this one fills
  84521. in the rest of the decoding tables with invalid code markers.
  84522. */
  84523. /* set up for code type */
  84524. switch (type) {
  84525. case CODES:
  84526. base = extra = work; /* dummy value--not used */
  84527. end = 19;
  84528. break;
  84529. case LENS:
  84530. base = lbase;
  84531. base -= 257;
  84532. extra = lext;
  84533. extra -= 257;
  84534. end = 256;
  84535. break;
  84536. default: /* DISTS */
  84537. base = dbase;
  84538. extra = dext;
  84539. end = -1;
  84540. }
  84541. /* initialize state for loop */
  84542. huff = 0; /* starting code */
  84543. sym = 0; /* starting code symbol */
  84544. len = min; /* starting code length */
  84545. next = *table; /* current table to fill in */
  84546. curr = root; /* current table index bits */
  84547. drop = 0; /* current bits to drop from code for index */
  84548. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84549. used = 1U << root; /* use root table entries */
  84550. mask = used - 1; /* mask for comparing low */
  84551. /* check available table space */
  84552. if (type == LENS && used >= ENOUGH - MAXD)
  84553. return 1;
  84554. /* process all codes and make table entries */
  84555. for (;;) {
  84556. /* create table entry */
  84557. thisx.bits = (unsigned char)(len - drop);
  84558. if ((int)(work[sym]) < end) {
  84559. thisx.op = (unsigned char)0;
  84560. thisx.val = work[sym];
  84561. }
  84562. else if ((int)(work[sym]) > end) {
  84563. thisx.op = (unsigned char)(extra[work[sym]]);
  84564. thisx.val = base[work[sym]];
  84565. }
  84566. else {
  84567. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84568. thisx.val = 0;
  84569. }
  84570. /* replicate for those indices with low len bits equal to huff */
  84571. incr = 1U << (len - drop);
  84572. fill = 1U << curr;
  84573. min = fill; /* save offset to next table */
  84574. do {
  84575. fill -= incr;
  84576. next[(huff >> drop) + fill] = thisx;
  84577. } while (fill != 0);
  84578. /* backwards increment the len-bit code huff */
  84579. incr = 1U << (len - 1);
  84580. while (huff & incr)
  84581. incr >>= 1;
  84582. if (incr != 0) {
  84583. huff &= incr - 1;
  84584. huff += incr;
  84585. }
  84586. else
  84587. huff = 0;
  84588. /* go to next symbol, update count, len */
  84589. sym++;
  84590. if (--(count[len]) == 0) {
  84591. if (len == max) break;
  84592. len = lens[work[sym]];
  84593. }
  84594. /* create new sub-table if needed */
  84595. if (len > root && (huff & mask) != low) {
  84596. /* if first time, transition to sub-tables */
  84597. if (drop == 0)
  84598. drop = root;
  84599. /* increment past last table */
  84600. next += min; /* here min is 1 << curr */
  84601. /* determine length of next table */
  84602. curr = len - drop;
  84603. left = (int)(1 << curr);
  84604. while (curr + drop < max) {
  84605. left -= count[curr + drop];
  84606. if (left <= 0) break;
  84607. curr++;
  84608. left <<= 1;
  84609. }
  84610. /* check for enough space */
  84611. used += 1U << curr;
  84612. if (type == LENS && used >= ENOUGH - MAXD)
  84613. return 1;
  84614. /* point entry in root table to sub-table */
  84615. low = huff & mask;
  84616. (*table)[low].op = (unsigned char)curr;
  84617. (*table)[low].bits = (unsigned char)root;
  84618. (*table)[low].val = (unsigned short)(next - *table);
  84619. }
  84620. }
  84621. /*
  84622. Fill in rest of table for incomplete codes. This loop is similar to the
  84623. loop above in incrementing huff for table indices. It is assumed that
  84624. len is equal to curr + drop, so there is no loop needed to increment
  84625. through high index bits. When the current sub-table is filled, the loop
  84626. drops back to the root table to fill in any remaining entries there.
  84627. */
  84628. thisx.op = (unsigned char)64; /* invalid code marker */
  84629. thisx.bits = (unsigned char)(len - drop);
  84630. thisx.val = (unsigned short)0;
  84631. while (huff != 0) {
  84632. /* when done with sub-table, drop back to root table */
  84633. if (drop != 0 && (huff & mask) != low) {
  84634. drop = 0;
  84635. len = root;
  84636. next = *table;
  84637. thisx.bits = (unsigned char)len;
  84638. }
  84639. /* put invalid code marker in table */
  84640. next[huff >> drop] = thisx;
  84641. /* backwards increment the len-bit code huff */
  84642. incr = 1U << (len - 1);
  84643. while (huff & incr)
  84644. incr >>= 1;
  84645. if (incr != 0) {
  84646. huff &= incr - 1;
  84647. huff += incr;
  84648. }
  84649. else
  84650. huff = 0;
  84651. }
  84652. /* set return parameters */
  84653. *table += used;
  84654. *bits = root;
  84655. return 0;
  84656. }
  84657. /*** End of inlined file: inftrees.c ***/
  84658. /*** Start of inlined file: trees.c ***/
  84659. /*
  84660. * ALGORITHM
  84661. *
  84662. * The "deflation" process uses several Huffman trees. The more
  84663. * common source values are represented by shorter bit sequences.
  84664. *
  84665. * Each code tree is stored in a compressed form which is itself
  84666. * a Huffman encoding of the lengths of all the code strings (in
  84667. * ascending order by source values). The actual code strings are
  84668. * reconstructed from the lengths in the inflate process, as described
  84669. * in the deflate specification.
  84670. *
  84671. * REFERENCES
  84672. *
  84673. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84674. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84675. *
  84676. * Storer, James A.
  84677. * Data Compression: Methods and Theory, pp. 49-50.
  84678. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84679. *
  84680. * Sedgewick, R.
  84681. * Algorithms, p290.
  84682. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84683. */
  84684. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84685. /* #define GEN_TREES_H */
  84686. #ifdef DEBUG
  84687. # include <ctype.h>
  84688. #endif
  84689. /* ===========================================================================
  84690. * Constants
  84691. */
  84692. #define MAX_BL_BITS 7
  84693. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84694. #define END_BLOCK 256
  84695. /* end of block literal code */
  84696. #define REP_3_6 16
  84697. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84698. #define REPZ_3_10 17
  84699. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84700. #define REPZ_11_138 18
  84701. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84702. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84703. = {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};
  84704. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84705. = {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};
  84706. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84707. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84708. local const uch bl_order[BL_CODES]
  84709. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84710. /* The lengths of the bit length codes are sent in order of decreasing
  84711. * probability, to avoid transmitting the lengths for unused bit length codes.
  84712. */
  84713. #define Buf_size (8 * 2*sizeof(char))
  84714. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84715. * more than 16 bits on some systems.)
  84716. */
  84717. /* ===========================================================================
  84718. * Local data. These are initialized only once.
  84719. */
  84720. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84721. #if defined(GEN_TREES_H) || !defined(STDC)
  84722. /* non ANSI compilers may not accept trees.h */
  84723. local ct_data static_ltree[L_CODES+2];
  84724. /* The static literal tree. Since the bit lengths are imposed, there is no
  84725. * need for the L_CODES extra codes used during heap construction. However
  84726. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84727. * below).
  84728. */
  84729. local ct_data static_dtree[D_CODES];
  84730. /* The static distance tree. (Actually a trivial tree since all codes use
  84731. * 5 bits.)
  84732. */
  84733. uch _dist_code[DIST_CODE_LEN];
  84734. /* Distance codes. The first 256 values correspond to the distances
  84735. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84736. * the 15 bit distances.
  84737. */
  84738. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84739. /* length code for each normalized match length (0 == MIN_MATCH) */
  84740. local int base_length[LENGTH_CODES];
  84741. /* First normalized length for each code (0 = MIN_MATCH) */
  84742. local int base_dist[D_CODES];
  84743. /* First normalized distance for each code (0 = distance of 1) */
  84744. #else
  84745. /*** Start of inlined file: trees.h ***/
  84746. local const ct_data static_ltree[L_CODES+2] = {
  84747. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84748. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84749. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84750. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84751. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84752. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84753. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84754. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84755. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84756. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84757. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84758. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84759. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84760. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84761. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84762. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84763. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84764. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84765. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84766. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84767. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84768. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84769. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84770. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84771. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84772. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84773. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84774. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84775. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84776. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84777. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84778. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84779. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84780. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84781. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84782. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84783. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84784. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84785. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84786. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84787. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84788. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84789. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84790. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84791. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84792. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84793. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84794. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84795. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84796. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84797. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84798. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84799. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84800. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84801. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84802. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84803. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84804. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84805. };
  84806. local const ct_data static_dtree[D_CODES] = {
  84807. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84808. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84809. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84810. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84811. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84812. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84813. };
  84814. const uch _dist_code[DIST_CODE_LEN] = {
  84815. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84816. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84817. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84818. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84819. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84820. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84821. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84822. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84823. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84824. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84825. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84826. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84827. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84828. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84829. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84830. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84831. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84832. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84833. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84834. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84835. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84836. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84837. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84838. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84839. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84840. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84841. };
  84842. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84843. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84844. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84845. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84846. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84847. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84848. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84849. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84850. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84851. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84852. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84853. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84854. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84855. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84856. };
  84857. local const int base_length[LENGTH_CODES] = {
  84858. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84859. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84860. };
  84861. local const int base_dist[D_CODES] = {
  84862. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84863. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84864. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84865. };
  84866. /*** End of inlined file: trees.h ***/
  84867. #endif /* GEN_TREES_H */
  84868. struct static_tree_desc_s {
  84869. const ct_data *static_tree; /* static tree or NULL */
  84870. const intf *extra_bits; /* extra bits for each code or NULL */
  84871. int extra_base; /* base index for extra_bits */
  84872. int elems; /* max number of elements in the tree */
  84873. int max_length; /* max bit length for the codes */
  84874. };
  84875. local static_tree_desc static_l_desc =
  84876. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84877. local static_tree_desc static_d_desc =
  84878. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84879. local static_tree_desc static_bl_desc =
  84880. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84881. /* ===========================================================================
  84882. * Local (static) routines in this file.
  84883. */
  84884. local void tr_static_init OF((void));
  84885. local void init_block OF((deflate_state *s));
  84886. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84887. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84888. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84889. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84890. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84891. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84892. local int build_bl_tree OF((deflate_state *s));
  84893. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84894. int blcodes));
  84895. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84896. ct_data *dtree));
  84897. local void set_data_type OF((deflate_state *s));
  84898. local unsigned bi_reverse OF((unsigned value, int length));
  84899. local void bi_windup OF((deflate_state *s));
  84900. local void bi_flush OF((deflate_state *s));
  84901. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84902. int header));
  84903. #ifdef GEN_TREES_H
  84904. local void gen_trees_header OF((void));
  84905. #endif
  84906. #ifndef DEBUG
  84907. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84908. /* Send a code of the given tree. c and tree must not have side effects */
  84909. #else /* DEBUG */
  84910. # define send_code(s, c, tree) \
  84911. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84912. send_bits(s, tree[c].Code, tree[c].Len); }
  84913. #endif
  84914. /* ===========================================================================
  84915. * Output a short LSB first on the stream.
  84916. * IN assertion: there is enough room in pendingBuf.
  84917. */
  84918. #define put_short(s, w) { \
  84919. put_byte(s, (uch)((w) & 0xff)); \
  84920. put_byte(s, (uch)((ush)(w) >> 8)); \
  84921. }
  84922. /* ===========================================================================
  84923. * Send a value on a given number of bits.
  84924. * IN assertion: length <= 16 and value fits in length bits.
  84925. */
  84926. #ifdef DEBUG
  84927. local void send_bits OF((deflate_state *s, int value, int length));
  84928. local void send_bits (deflate_state *s, int value, int length)
  84929. {
  84930. Tracevv((stderr," l %2d v %4x ", length, value));
  84931. Assert(length > 0 && length <= 15, "invalid length");
  84932. s->bits_sent += (ulg)length;
  84933. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84934. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84935. * unused bits in value.
  84936. */
  84937. if (s->bi_valid > (int)Buf_size - length) {
  84938. s->bi_buf |= (value << s->bi_valid);
  84939. put_short(s, s->bi_buf);
  84940. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84941. s->bi_valid += length - Buf_size;
  84942. } else {
  84943. s->bi_buf |= value << s->bi_valid;
  84944. s->bi_valid += length;
  84945. }
  84946. }
  84947. #else /* !DEBUG */
  84948. #define send_bits(s, value, length) \
  84949. { int len = length;\
  84950. if (s->bi_valid > (int)Buf_size - len) {\
  84951. int val = value;\
  84952. s->bi_buf |= (val << s->bi_valid);\
  84953. put_short(s, s->bi_buf);\
  84954. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84955. s->bi_valid += len - Buf_size;\
  84956. } else {\
  84957. s->bi_buf |= (value) << s->bi_valid;\
  84958. s->bi_valid += len;\
  84959. }\
  84960. }
  84961. #endif /* DEBUG */
  84962. /* the arguments must not have side effects */
  84963. /* ===========================================================================
  84964. * Initialize the various 'constant' tables.
  84965. */
  84966. local void tr_static_init()
  84967. {
  84968. #if defined(GEN_TREES_H) || !defined(STDC)
  84969. static int static_init_done = 0;
  84970. int n; /* iterates over tree elements */
  84971. int bits; /* bit counter */
  84972. int length; /* length value */
  84973. int code; /* code value */
  84974. int dist; /* distance index */
  84975. ush bl_count[MAX_BITS+1];
  84976. /* number of codes at each bit length for an optimal tree */
  84977. if (static_init_done) return;
  84978. /* For some embedded targets, global variables are not initialized: */
  84979. static_l_desc.static_tree = static_ltree;
  84980. static_l_desc.extra_bits = extra_lbits;
  84981. static_d_desc.static_tree = static_dtree;
  84982. static_d_desc.extra_bits = extra_dbits;
  84983. static_bl_desc.extra_bits = extra_blbits;
  84984. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84985. length = 0;
  84986. for (code = 0; code < LENGTH_CODES-1; code++) {
  84987. base_length[code] = length;
  84988. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84989. _length_code[length++] = (uch)code;
  84990. }
  84991. }
  84992. Assert (length == 256, "tr_static_init: length != 256");
  84993. /* Note that the length 255 (match length 258) can be represented
  84994. * in two different ways: code 284 + 5 bits or code 285, so we
  84995. * overwrite length_code[255] to use the best encoding:
  84996. */
  84997. _length_code[length-1] = (uch)code;
  84998. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84999. dist = 0;
  85000. for (code = 0 ; code < 16; code++) {
  85001. base_dist[code] = dist;
  85002. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85003. _dist_code[dist++] = (uch)code;
  85004. }
  85005. }
  85006. Assert (dist == 256, "tr_static_init: dist != 256");
  85007. dist >>= 7; /* from now on, all distances are divided by 128 */
  85008. for ( ; code < D_CODES; code++) {
  85009. base_dist[code] = dist << 7;
  85010. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85011. _dist_code[256 + dist++] = (uch)code;
  85012. }
  85013. }
  85014. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85015. /* Construct the codes of the static literal tree */
  85016. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85017. n = 0;
  85018. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85019. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85020. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85021. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85022. /* Codes 286 and 287 do not exist, but we must include them in the
  85023. * tree construction to get a canonical Huffman tree (longest code
  85024. * all ones)
  85025. */
  85026. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85027. /* The static distance tree is trivial: */
  85028. for (n = 0; n < D_CODES; n++) {
  85029. static_dtree[n].Len = 5;
  85030. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85031. }
  85032. static_init_done = 1;
  85033. # ifdef GEN_TREES_H
  85034. gen_trees_header();
  85035. # endif
  85036. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85037. }
  85038. /* ===========================================================================
  85039. * Genererate the file trees.h describing the static trees.
  85040. */
  85041. #ifdef GEN_TREES_H
  85042. # ifndef DEBUG
  85043. # include <stdio.h>
  85044. # endif
  85045. # define SEPARATOR(i, last, width) \
  85046. ((i) == (last)? "\n};\n\n" : \
  85047. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85048. void gen_trees_header()
  85049. {
  85050. FILE *header = fopen("trees.h", "w");
  85051. int i;
  85052. Assert (header != NULL, "Can't open trees.h");
  85053. fprintf(header,
  85054. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85055. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85056. for (i = 0; i < L_CODES+2; i++) {
  85057. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85058. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85059. }
  85060. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85061. for (i = 0; i < D_CODES; i++) {
  85062. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85063. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85064. }
  85065. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85066. for (i = 0; i < DIST_CODE_LEN; i++) {
  85067. fprintf(header, "%2u%s", _dist_code[i],
  85068. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85069. }
  85070. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85071. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85072. fprintf(header, "%2u%s", _length_code[i],
  85073. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85074. }
  85075. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85076. for (i = 0; i < LENGTH_CODES; i++) {
  85077. fprintf(header, "%1u%s", base_length[i],
  85078. SEPARATOR(i, LENGTH_CODES-1, 20));
  85079. }
  85080. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85081. for (i = 0; i < D_CODES; i++) {
  85082. fprintf(header, "%5u%s", base_dist[i],
  85083. SEPARATOR(i, D_CODES-1, 10));
  85084. }
  85085. fclose(header);
  85086. }
  85087. #endif /* GEN_TREES_H */
  85088. /* ===========================================================================
  85089. * Initialize the tree data structures for a new zlib stream.
  85090. */
  85091. void _tr_init(deflate_state *s)
  85092. {
  85093. tr_static_init();
  85094. s->l_desc.dyn_tree = s->dyn_ltree;
  85095. s->l_desc.stat_desc = &static_l_desc;
  85096. s->d_desc.dyn_tree = s->dyn_dtree;
  85097. s->d_desc.stat_desc = &static_d_desc;
  85098. s->bl_desc.dyn_tree = s->bl_tree;
  85099. s->bl_desc.stat_desc = &static_bl_desc;
  85100. s->bi_buf = 0;
  85101. s->bi_valid = 0;
  85102. s->last_eob_len = 8; /* enough lookahead for inflate */
  85103. #ifdef DEBUG
  85104. s->compressed_len = 0L;
  85105. s->bits_sent = 0L;
  85106. #endif
  85107. /* Initialize the first block of the first file: */
  85108. init_block(s);
  85109. }
  85110. /* ===========================================================================
  85111. * Initialize a new block.
  85112. */
  85113. local void init_block (deflate_state *s)
  85114. {
  85115. int n; /* iterates over tree elements */
  85116. /* Initialize the trees. */
  85117. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85118. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85119. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85120. s->dyn_ltree[END_BLOCK].Freq = 1;
  85121. s->opt_len = s->static_len = 0L;
  85122. s->last_lit = s->matches = 0;
  85123. }
  85124. #define SMALLEST 1
  85125. /* Index within the heap array of least frequent node in the Huffman tree */
  85126. /* ===========================================================================
  85127. * Remove the smallest element from the heap and recreate the heap with
  85128. * one less element. Updates heap and heap_len.
  85129. */
  85130. #define pqremove(s, tree, top) \
  85131. {\
  85132. top = s->heap[SMALLEST]; \
  85133. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85134. pqdownheap(s, tree, SMALLEST); \
  85135. }
  85136. /* ===========================================================================
  85137. * Compares to subtrees, using the tree depth as tie breaker when
  85138. * the subtrees have equal frequency. This minimizes the worst case length.
  85139. */
  85140. #define smaller(tree, n, m, depth) \
  85141. (tree[n].Freq < tree[m].Freq || \
  85142. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85143. /* ===========================================================================
  85144. * Restore the heap property by moving down the tree starting at node k,
  85145. * exchanging a node with the smallest of its two sons if necessary, stopping
  85146. * when the heap property is re-established (each father smaller than its
  85147. * two sons).
  85148. */
  85149. local void pqdownheap (deflate_state *s,
  85150. ct_data *tree, /* the tree to restore */
  85151. int k) /* node to move down */
  85152. {
  85153. int v = s->heap[k];
  85154. int j = k << 1; /* left son of k */
  85155. while (j <= s->heap_len) {
  85156. /* Set j to the smallest of the two sons: */
  85157. if (j < s->heap_len &&
  85158. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85159. j++;
  85160. }
  85161. /* Exit if v is smaller than both sons */
  85162. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85163. /* Exchange v with the smallest son */
  85164. s->heap[k] = s->heap[j]; k = j;
  85165. /* And continue down the tree, setting j to the left son of k */
  85166. j <<= 1;
  85167. }
  85168. s->heap[k] = v;
  85169. }
  85170. /* ===========================================================================
  85171. * Compute the optimal bit lengths for a tree and update the total bit length
  85172. * for the current block.
  85173. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85174. * above are the tree nodes sorted by increasing frequency.
  85175. * OUT assertions: the field len is set to the optimal bit length, the
  85176. * array bl_count contains the frequencies for each bit length.
  85177. * The length opt_len is updated; static_len is also updated if stree is
  85178. * not null.
  85179. */
  85180. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85181. {
  85182. ct_data *tree = desc->dyn_tree;
  85183. int max_code = desc->max_code;
  85184. const ct_data *stree = desc->stat_desc->static_tree;
  85185. const intf *extra = desc->stat_desc->extra_bits;
  85186. int base = desc->stat_desc->extra_base;
  85187. int max_length = desc->stat_desc->max_length;
  85188. int h; /* heap index */
  85189. int n, m; /* iterate over the tree elements */
  85190. int bits; /* bit length */
  85191. int xbits; /* extra bits */
  85192. ush f; /* frequency */
  85193. int overflow = 0; /* number of elements with bit length too large */
  85194. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85195. /* In a first pass, compute the optimal bit lengths (which may
  85196. * overflow in the case of the bit length tree).
  85197. */
  85198. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85199. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85200. n = s->heap[h];
  85201. bits = tree[tree[n].Dad].Len + 1;
  85202. if (bits > max_length) bits = max_length, overflow++;
  85203. tree[n].Len = (ush)bits;
  85204. /* We overwrite tree[n].Dad which is no longer needed */
  85205. if (n > max_code) continue; /* not a leaf node */
  85206. s->bl_count[bits]++;
  85207. xbits = 0;
  85208. if (n >= base) xbits = extra[n-base];
  85209. f = tree[n].Freq;
  85210. s->opt_len += (ulg)f * (bits + xbits);
  85211. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85212. }
  85213. if (overflow == 0) return;
  85214. Trace((stderr,"\nbit length overflow\n"));
  85215. /* This happens for example on obj2 and pic of the Calgary corpus */
  85216. /* Find the first bit length which could increase: */
  85217. do {
  85218. bits = max_length-1;
  85219. while (s->bl_count[bits] == 0) bits--;
  85220. s->bl_count[bits]--; /* move one leaf down the tree */
  85221. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85222. s->bl_count[max_length]--;
  85223. /* The brother of the overflow item also moves one step up,
  85224. * but this does not affect bl_count[max_length]
  85225. */
  85226. overflow -= 2;
  85227. } while (overflow > 0);
  85228. /* Now recompute all bit lengths, scanning in increasing frequency.
  85229. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85230. * lengths instead of fixing only the wrong ones. This idea is taken
  85231. * from 'ar' written by Haruhiko Okumura.)
  85232. */
  85233. for (bits = max_length; bits != 0; bits--) {
  85234. n = s->bl_count[bits];
  85235. while (n != 0) {
  85236. m = s->heap[--h];
  85237. if (m > max_code) continue;
  85238. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85239. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85240. s->opt_len += ((long)bits - (long)tree[m].Len)
  85241. *(long)tree[m].Freq;
  85242. tree[m].Len = (ush)bits;
  85243. }
  85244. n--;
  85245. }
  85246. }
  85247. }
  85248. /* ===========================================================================
  85249. * Generate the codes for a given tree and bit counts (which need not be
  85250. * optimal).
  85251. * IN assertion: the array bl_count contains the bit length statistics for
  85252. * the given tree and the field len is set for all tree elements.
  85253. * OUT assertion: the field code is set for all tree elements of non
  85254. * zero code length.
  85255. */
  85256. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85257. int max_code, /* largest code with non zero frequency */
  85258. ushf *bl_count) /* number of codes at each bit length */
  85259. {
  85260. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85261. ush code = 0; /* running code value */
  85262. int bits; /* bit index */
  85263. int n; /* code index */
  85264. /* The distribution counts are first used to generate the code values
  85265. * without bit reversal.
  85266. */
  85267. for (bits = 1; bits <= MAX_BITS; bits++) {
  85268. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85269. }
  85270. /* Check that the bit counts in bl_count are consistent. The last code
  85271. * must be all ones.
  85272. */
  85273. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85274. "inconsistent bit counts");
  85275. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85276. for (n = 0; n <= max_code; n++) {
  85277. int len = tree[n].Len;
  85278. if (len == 0) continue;
  85279. /* Now reverse the bits */
  85280. tree[n].Code = bi_reverse(next_code[len]++, len);
  85281. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85282. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85283. }
  85284. }
  85285. /* ===========================================================================
  85286. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85287. * Update the total bit length for the current block.
  85288. * IN assertion: the field freq is set for all tree elements.
  85289. * OUT assertions: the fields len and code are set to the optimal bit length
  85290. * and corresponding code. The length opt_len is updated; static_len is
  85291. * also updated if stree is not null. The field max_code is set.
  85292. */
  85293. local void build_tree (deflate_state *s,
  85294. tree_desc *desc) /* the tree descriptor */
  85295. {
  85296. ct_data *tree = desc->dyn_tree;
  85297. const ct_data *stree = desc->stat_desc->static_tree;
  85298. int elems = desc->stat_desc->elems;
  85299. int n, m; /* iterate over heap elements */
  85300. int max_code = -1; /* largest code with non zero frequency */
  85301. int node; /* new node being created */
  85302. /* Construct the initial heap, with least frequent element in
  85303. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85304. * heap[0] is not used.
  85305. */
  85306. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85307. for (n = 0; n < elems; n++) {
  85308. if (tree[n].Freq != 0) {
  85309. s->heap[++(s->heap_len)] = max_code = n;
  85310. s->depth[n] = 0;
  85311. } else {
  85312. tree[n].Len = 0;
  85313. }
  85314. }
  85315. /* The pkzip format requires that at least one distance code exists,
  85316. * and that at least one bit should be sent even if there is only one
  85317. * possible code. So to avoid special checks later on we force at least
  85318. * two codes of non zero frequency.
  85319. */
  85320. while (s->heap_len < 2) {
  85321. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85322. tree[node].Freq = 1;
  85323. s->depth[node] = 0;
  85324. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85325. /* node is 0 or 1 so it does not have extra bits */
  85326. }
  85327. desc->max_code = max_code;
  85328. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85329. * establish sub-heaps of increasing lengths:
  85330. */
  85331. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85332. /* Construct the Huffman tree by repeatedly combining the least two
  85333. * frequent nodes.
  85334. */
  85335. node = elems; /* next internal node of the tree */
  85336. do {
  85337. pqremove(s, tree, n); /* n = node of least frequency */
  85338. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85339. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85340. s->heap[--(s->heap_max)] = m;
  85341. /* Create a new node father of n and m */
  85342. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85343. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85344. s->depth[n] : s->depth[m]) + 1);
  85345. tree[n].Dad = tree[m].Dad = (ush)node;
  85346. #ifdef DUMP_BL_TREE
  85347. if (tree == s->bl_tree) {
  85348. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85349. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85350. }
  85351. #endif
  85352. /* and insert the new node in the heap */
  85353. s->heap[SMALLEST] = node++;
  85354. pqdownheap(s, tree, SMALLEST);
  85355. } while (s->heap_len >= 2);
  85356. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85357. /* At this point, the fields freq and dad are set. We can now
  85358. * generate the bit lengths.
  85359. */
  85360. gen_bitlen(s, (tree_desc *)desc);
  85361. /* The field len is now set, we can generate the bit codes */
  85362. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85363. }
  85364. /* ===========================================================================
  85365. * Scan a literal or distance tree to determine the frequencies of the codes
  85366. * in the bit length tree.
  85367. */
  85368. local void scan_tree (deflate_state *s,
  85369. ct_data *tree, /* the tree to be scanned */
  85370. int max_code) /* and its largest code of non zero frequency */
  85371. {
  85372. int n; /* iterates over all tree elements */
  85373. int prevlen = -1; /* last emitted length */
  85374. int curlen; /* length of current code */
  85375. int nextlen = tree[0].Len; /* length of next code */
  85376. int count = 0; /* repeat count of the current code */
  85377. int max_count = 7; /* max repeat count */
  85378. int min_count = 4; /* min repeat count */
  85379. if (nextlen == 0) max_count = 138, min_count = 3;
  85380. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85381. for (n = 0; n <= max_code; n++) {
  85382. curlen = nextlen; nextlen = tree[n+1].Len;
  85383. if (++count < max_count && curlen == nextlen) {
  85384. continue;
  85385. } else if (count < min_count) {
  85386. s->bl_tree[curlen].Freq += count;
  85387. } else if (curlen != 0) {
  85388. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85389. s->bl_tree[REP_3_6].Freq++;
  85390. } else if (count <= 10) {
  85391. s->bl_tree[REPZ_3_10].Freq++;
  85392. } else {
  85393. s->bl_tree[REPZ_11_138].Freq++;
  85394. }
  85395. count = 0; prevlen = curlen;
  85396. if (nextlen == 0) {
  85397. max_count = 138, min_count = 3;
  85398. } else if (curlen == nextlen) {
  85399. max_count = 6, min_count = 3;
  85400. } else {
  85401. max_count = 7, min_count = 4;
  85402. }
  85403. }
  85404. }
  85405. /* ===========================================================================
  85406. * Send a literal or distance tree in compressed form, using the codes in
  85407. * bl_tree.
  85408. */
  85409. local void send_tree (deflate_state *s,
  85410. ct_data *tree, /* the tree to be scanned */
  85411. int max_code) /* and its largest code of non zero frequency */
  85412. {
  85413. int n; /* iterates over all tree elements */
  85414. int prevlen = -1; /* last emitted length */
  85415. int curlen; /* length of current code */
  85416. int nextlen = tree[0].Len; /* length of next code */
  85417. int count = 0; /* repeat count of the current code */
  85418. int max_count = 7; /* max repeat count */
  85419. int min_count = 4; /* min repeat count */
  85420. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85421. if (nextlen == 0) max_count = 138, min_count = 3;
  85422. for (n = 0; n <= max_code; n++) {
  85423. curlen = nextlen; nextlen = tree[n+1].Len;
  85424. if (++count < max_count && curlen == nextlen) {
  85425. continue;
  85426. } else if (count < min_count) {
  85427. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85428. } else if (curlen != 0) {
  85429. if (curlen != prevlen) {
  85430. send_code(s, curlen, s->bl_tree); count--;
  85431. }
  85432. Assert(count >= 3 && count <= 6, " 3_6?");
  85433. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85434. } else if (count <= 10) {
  85435. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85436. } else {
  85437. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85438. }
  85439. count = 0; prevlen = curlen;
  85440. if (nextlen == 0) {
  85441. max_count = 138, min_count = 3;
  85442. } else if (curlen == nextlen) {
  85443. max_count = 6, min_count = 3;
  85444. } else {
  85445. max_count = 7, min_count = 4;
  85446. }
  85447. }
  85448. }
  85449. /* ===========================================================================
  85450. * Construct the Huffman tree for the bit lengths and return the index in
  85451. * bl_order of the last bit length code to send.
  85452. */
  85453. local int build_bl_tree (deflate_state *s)
  85454. {
  85455. int max_blindex; /* index of last bit length code of non zero freq */
  85456. /* Determine the bit length frequencies for literal and distance trees */
  85457. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85458. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85459. /* Build the bit length tree: */
  85460. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85461. /* opt_len now includes the length of the tree representations, except
  85462. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85463. */
  85464. /* Determine the number of bit length codes to send. The pkzip format
  85465. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85466. * 3 but the actual value used is 4.)
  85467. */
  85468. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85469. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85470. }
  85471. /* Update opt_len to include the bit length tree and counts */
  85472. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85473. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85474. s->opt_len, s->static_len));
  85475. return max_blindex;
  85476. }
  85477. /* ===========================================================================
  85478. * Send the header for a block using dynamic Huffman trees: the counts, the
  85479. * lengths of the bit length codes, the literal tree and the distance tree.
  85480. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85481. */
  85482. local void send_all_trees (deflate_state *s,
  85483. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85484. {
  85485. int rank; /* index in bl_order */
  85486. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85487. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85488. "too many codes");
  85489. Tracev((stderr, "\nbl counts: "));
  85490. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85491. send_bits(s, dcodes-1, 5);
  85492. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85493. for (rank = 0; rank < blcodes; rank++) {
  85494. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85495. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85496. }
  85497. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85498. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85499. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85500. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85501. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85502. }
  85503. /* ===========================================================================
  85504. * Send a stored block
  85505. */
  85506. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85507. {
  85508. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85509. #ifdef DEBUG
  85510. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85511. s->compressed_len += (stored_len + 4) << 3;
  85512. #endif
  85513. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85514. }
  85515. /* ===========================================================================
  85516. * Send one empty static block to give enough lookahead for inflate.
  85517. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85518. * The current inflate code requires 9 bits of lookahead. If the
  85519. * last two codes for the previous block (real code plus EOB) were coded
  85520. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85521. * the last real code. In this case we send two empty static blocks instead
  85522. * of one. (There are no problems if the previous block is stored or fixed.)
  85523. * To simplify the code, we assume the worst case of last real code encoded
  85524. * on one bit only.
  85525. */
  85526. void _tr_align (deflate_state *s)
  85527. {
  85528. send_bits(s, STATIC_TREES<<1, 3);
  85529. send_code(s, END_BLOCK, static_ltree);
  85530. #ifdef DEBUG
  85531. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85532. #endif
  85533. bi_flush(s);
  85534. /* Of the 10 bits for the empty block, we have already sent
  85535. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85536. * the EOB of the previous block) was thus at least one plus the length
  85537. * of the EOB plus what we have just sent of the empty static block.
  85538. */
  85539. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85540. send_bits(s, STATIC_TREES<<1, 3);
  85541. send_code(s, END_BLOCK, static_ltree);
  85542. #ifdef DEBUG
  85543. s->compressed_len += 10L;
  85544. #endif
  85545. bi_flush(s);
  85546. }
  85547. s->last_eob_len = 7;
  85548. }
  85549. /* ===========================================================================
  85550. * Determine the best encoding for the current block: dynamic trees, static
  85551. * trees or store, and output the encoded block to the zip file.
  85552. */
  85553. void _tr_flush_block (deflate_state *s,
  85554. charf *buf, /* input block, or NULL if too old */
  85555. ulg stored_len, /* length of input block */
  85556. int eof) /* true if this is the last block for a file */
  85557. {
  85558. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85559. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85560. /* Build the Huffman trees unless a stored block is forced */
  85561. if (s->level > 0) {
  85562. /* Check if the file is binary or text */
  85563. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85564. set_data_type(s);
  85565. /* Construct the literal and distance trees */
  85566. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85567. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85568. s->static_len));
  85569. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85570. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85571. s->static_len));
  85572. /* At this point, opt_len and static_len are the total bit lengths of
  85573. * the compressed block data, excluding the tree representations.
  85574. */
  85575. /* Build the bit length tree for the above two trees, and get the index
  85576. * in bl_order of the last bit length code to send.
  85577. */
  85578. max_blindex = build_bl_tree(s);
  85579. /* Determine the best encoding. Compute the block lengths in bytes. */
  85580. opt_lenb = (s->opt_len+3+7)>>3;
  85581. static_lenb = (s->static_len+3+7)>>3;
  85582. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85583. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85584. s->last_lit));
  85585. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85586. } else {
  85587. Assert(buf != (char*)0, "lost buf");
  85588. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85589. }
  85590. #ifdef FORCE_STORED
  85591. if (buf != (char*)0) { /* force stored block */
  85592. #else
  85593. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85594. /* 4: two words for the lengths */
  85595. #endif
  85596. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85597. * Otherwise we can't have processed more than WSIZE input bytes since
  85598. * the last block flush, because compression would have been
  85599. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85600. * transform a block into a stored block.
  85601. */
  85602. _tr_stored_block(s, buf, stored_len, eof);
  85603. #ifdef FORCE_STATIC
  85604. } else if (static_lenb >= 0) { /* force static trees */
  85605. #else
  85606. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85607. #endif
  85608. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85609. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85610. #ifdef DEBUG
  85611. s->compressed_len += 3 + s->static_len;
  85612. #endif
  85613. } else {
  85614. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85615. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85616. max_blindex+1);
  85617. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85618. #ifdef DEBUG
  85619. s->compressed_len += 3 + s->opt_len;
  85620. #endif
  85621. }
  85622. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85623. /* The above check is made mod 2^32, for files larger than 512 MB
  85624. * and uLong implemented on 32 bits.
  85625. */
  85626. init_block(s);
  85627. if (eof) {
  85628. bi_windup(s);
  85629. #ifdef DEBUG
  85630. s->compressed_len += 7; /* align on byte boundary */
  85631. #endif
  85632. }
  85633. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85634. s->compressed_len-7*eof));
  85635. }
  85636. /* ===========================================================================
  85637. * Save the match info and tally the frequency counts. Return true if
  85638. * the current block must be flushed.
  85639. */
  85640. int _tr_tally (deflate_state *s,
  85641. unsigned dist, /* distance of matched string */
  85642. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85643. {
  85644. s->d_buf[s->last_lit] = (ush)dist;
  85645. s->l_buf[s->last_lit++] = (uch)lc;
  85646. if (dist == 0) {
  85647. /* lc is the unmatched char */
  85648. s->dyn_ltree[lc].Freq++;
  85649. } else {
  85650. s->matches++;
  85651. /* Here, lc is the match length - MIN_MATCH */
  85652. dist--; /* dist = match distance - 1 */
  85653. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85654. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85655. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85656. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85657. s->dyn_dtree[d_code(dist)].Freq++;
  85658. }
  85659. #ifdef TRUNCATE_BLOCK
  85660. /* Try to guess if it is profitable to stop the current block here */
  85661. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85662. /* Compute an upper bound for the compressed length */
  85663. ulg out_length = (ulg)s->last_lit*8L;
  85664. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85665. int dcode;
  85666. for (dcode = 0; dcode < D_CODES; dcode++) {
  85667. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85668. (5L+extra_dbits[dcode]);
  85669. }
  85670. out_length >>= 3;
  85671. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85672. s->last_lit, in_length, out_length,
  85673. 100L - out_length*100L/in_length));
  85674. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85675. }
  85676. #endif
  85677. return (s->last_lit == s->lit_bufsize-1);
  85678. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85679. * on 16 bit machines and because stored blocks are restricted to
  85680. * 64K-1 bytes.
  85681. */
  85682. }
  85683. /* ===========================================================================
  85684. * Send the block data compressed using the given Huffman trees
  85685. */
  85686. local void compress_block (deflate_state *s,
  85687. ct_data *ltree, /* literal tree */
  85688. ct_data *dtree) /* distance tree */
  85689. {
  85690. unsigned dist; /* distance of matched string */
  85691. int lc; /* match length or unmatched char (if dist == 0) */
  85692. unsigned lx = 0; /* running index in l_buf */
  85693. unsigned code; /* the code to send */
  85694. int extra; /* number of extra bits to send */
  85695. if (s->last_lit != 0) do {
  85696. dist = s->d_buf[lx];
  85697. lc = s->l_buf[lx++];
  85698. if (dist == 0) {
  85699. send_code(s, lc, ltree); /* send a literal byte */
  85700. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85701. } else {
  85702. /* Here, lc is the match length - MIN_MATCH */
  85703. code = _length_code[lc];
  85704. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85705. extra = extra_lbits[code];
  85706. if (extra != 0) {
  85707. lc -= base_length[code];
  85708. send_bits(s, lc, extra); /* send the extra length bits */
  85709. }
  85710. dist--; /* dist is now the match distance - 1 */
  85711. code = d_code(dist);
  85712. Assert (code < D_CODES, "bad d_code");
  85713. send_code(s, code, dtree); /* send the distance code */
  85714. extra = extra_dbits[code];
  85715. if (extra != 0) {
  85716. dist -= base_dist[code];
  85717. send_bits(s, dist, extra); /* send the extra distance bits */
  85718. }
  85719. } /* literal or match pair ? */
  85720. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85721. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85722. "pendingBuf overflow");
  85723. } while (lx < s->last_lit);
  85724. send_code(s, END_BLOCK, ltree);
  85725. s->last_eob_len = ltree[END_BLOCK].Len;
  85726. }
  85727. /* ===========================================================================
  85728. * Set the data type to BINARY or TEXT, using a crude approximation:
  85729. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85730. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85731. * IN assertion: the fields Freq of dyn_ltree are set.
  85732. */
  85733. local void set_data_type (deflate_state *s)
  85734. {
  85735. int n;
  85736. for (n = 0; n < 9; n++)
  85737. if (s->dyn_ltree[n].Freq != 0)
  85738. break;
  85739. if (n == 9)
  85740. for (n = 14; n < 32; n++)
  85741. if (s->dyn_ltree[n].Freq != 0)
  85742. break;
  85743. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85744. }
  85745. /* ===========================================================================
  85746. * Reverse the first len bits of a code, using straightforward code (a faster
  85747. * method would use a table)
  85748. * IN assertion: 1 <= len <= 15
  85749. */
  85750. local unsigned bi_reverse (unsigned code, int len)
  85751. {
  85752. register unsigned res = 0;
  85753. do {
  85754. res |= code & 1;
  85755. code >>= 1, res <<= 1;
  85756. } while (--len > 0);
  85757. return res >> 1;
  85758. }
  85759. /* ===========================================================================
  85760. * Flush the bit buffer, keeping at most 7 bits in it.
  85761. */
  85762. local void bi_flush (deflate_state *s)
  85763. {
  85764. if (s->bi_valid == 16) {
  85765. put_short(s, s->bi_buf);
  85766. s->bi_buf = 0;
  85767. s->bi_valid = 0;
  85768. } else if (s->bi_valid >= 8) {
  85769. put_byte(s, (Byte)s->bi_buf);
  85770. s->bi_buf >>= 8;
  85771. s->bi_valid -= 8;
  85772. }
  85773. }
  85774. /* ===========================================================================
  85775. * Flush the bit buffer and align the output on a byte boundary
  85776. */
  85777. local void bi_windup (deflate_state *s)
  85778. {
  85779. if (s->bi_valid > 8) {
  85780. put_short(s, s->bi_buf);
  85781. } else if (s->bi_valid > 0) {
  85782. put_byte(s, (Byte)s->bi_buf);
  85783. }
  85784. s->bi_buf = 0;
  85785. s->bi_valid = 0;
  85786. #ifdef DEBUG
  85787. s->bits_sent = (s->bits_sent+7) & ~7;
  85788. #endif
  85789. }
  85790. /* ===========================================================================
  85791. * Copy a stored block, storing first the length and its
  85792. * one's complement if requested.
  85793. */
  85794. local void copy_block(deflate_state *s,
  85795. charf *buf, /* the input data */
  85796. unsigned len, /* its length */
  85797. int header) /* true if block header must be written */
  85798. {
  85799. bi_windup(s); /* align on byte boundary */
  85800. s->last_eob_len = 8; /* enough lookahead for inflate */
  85801. if (header) {
  85802. put_short(s, (ush)len);
  85803. put_short(s, (ush)~len);
  85804. #ifdef DEBUG
  85805. s->bits_sent += 2*16;
  85806. #endif
  85807. }
  85808. #ifdef DEBUG
  85809. s->bits_sent += (ulg)len<<3;
  85810. #endif
  85811. while (len--) {
  85812. put_byte(s, *buf++);
  85813. }
  85814. }
  85815. /*** End of inlined file: trees.c ***/
  85816. /*** Start of inlined file: zutil.c ***/
  85817. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85818. #ifndef NO_DUMMY_DECL
  85819. struct internal_state {int dummy;}; /* for buggy compilers */
  85820. #endif
  85821. const char * const z_errmsg[10] = {
  85822. "need dictionary", /* Z_NEED_DICT 2 */
  85823. "stream end", /* Z_STREAM_END 1 */
  85824. "", /* Z_OK 0 */
  85825. "file error", /* Z_ERRNO (-1) */
  85826. "stream error", /* Z_STREAM_ERROR (-2) */
  85827. "data error", /* Z_DATA_ERROR (-3) */
  85828. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85829. "buffer error", /* Z_BUF_ERROR (-5) */
  85830. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85831. ""};
  85832. /*const char * ZEXPORT zlibVersion()
  85833. {
  85834. return ZLIB_VERSION;
  85835. }
  85836. uLong ZEXPORT zlibCompileFlags()
  85837. {
  85838. uLong flags;
  85839. flags = 0;
  85840. switch (sizeof(uInt)) {
  85841. case 2: break;
  85842. case 4: flags += 1; break;
  85843. case 8: flags += 2; break;
  85844. default: flags += 3;
  85845. }
  85846. switch (sizeof(uLong)) {
  85847. case 2: break;
  85848. case 4: flags += 1 << 2; break;
  85849. case 8: flags += 2 << 2; break;
  85850. default: flags += 3 << 2;
  85851. }
  85852. switch (sizeof(voidpf)) {
  85853. case 2: break;
  85854. case 4: flags += 1 << 4; break;
  85855. case 8: flags += 2 << 4; break;
  85856. default: flags += 3 << 4;
  85857. }
  85858. switch (sizeof(z_off_t)) {
  85859. case 2: break;
  85860. case 4: flags += 1 << 6; break;
  85861. case 8: flags += 2 << 6; break;
  85862. default: flags += 3 << 6;
  85863. }
  85864. #ifdef DEBUG
  85865. flags += 1 << 8;
  85866. #endif
  85867. #if defined(ASMV) || defined(ASMINF)
  85868. flags += 1 << 9;
  85869. #endif
  85870. #ifdef ZLIB_WINAPI
  85871. flags += 1 << 10;
  85872. #endif
  85873. #ifdef BUILDFIXED
  85874. flags += 1 << 12;
  85875. #endif
  85876. #ifdef DYNAMIC_CRC_TABLE
  85877. flags += 1 << 13;
  85878. #endif
  85879. #ifdef NO_GZCOMPRESS
  85880. flags += 1L << 16;
  85881. #endif
  85882. #ifdef NO_GZIP
  85883. flags += 1L << 17;
  85884. #endif
  85885. #ifdef PKZIP_BUG_WORKAROUND
  85886. flags += 1L << 20;
  85887. #endif
  85888. #ifdef FASTEST
  85889. flags += 1L << 21;
  85890. #endif
  85891. #ifdef STDC
  85892. # ifdef NO_vsnprintf
  85893. flags += 1L << 25;
  85894. # ifdef HAS_vsprintf_void
  85895. flags += 1L << 26;
  85896. # endif
  85897. # else
  85898. # ifdef HAS_vsnprintf_void
  85899. flags += 1L << 26;
  85900. # endif
  85901. # endif
  85902. #else
  85903. flags += 1L << 24;
  85904. # ifdef NO_snprintf
  85905. flags += 1L << 25;
  85906. # ifdef HAS_sprintf_void
  85907. flags += 1L << 26;
  85908. # endif
  85909. # else
  85910. # ifdef HAS_snprintf_void
  85911. flags += 1L << 26;
  85912. # endif
  85913. # endif
  85914. #endif
  85915. return flags;
  85916. }*/
  85917. #ifdef DEBUG
  85918. # ifndef verbose
  85919. # define verbose 0
  85920. # endif
  85921. int z_verbose = verbose;
  85922. void z_error (const char *m)
  85923. {
  85924. fprintf(stderr, "%s\n", m);
  85925. exit(1);
  85926. }
  85927. #endif
  85928. /* exported to allow conversion of error code to string for compress() and
  85929. * uncompress()
  85930. */
  85931. const char * ZEXPORT zError(int err)
  85932. {
  85933. return ERR_MSG(err);
  85934. }
  85935. #if defined(_WIN32_WCE)
  85936. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85937. * errno. We define it as a global variable to simplify porting.
  85938. * Its value is always 0 and should not be used.
  85939. */
  85940. int errno = 0;
  85941. #endif
  85942. #ifndef HAVE_MEMCPY
  85943. void zmemcpy(dest, source, len)
  85944. Bytef* dest;
  85945. const Bytef* source;
  85946. uInt len;
  85947. {
  85948. if (len == 0) return;
  85949. do {
  85950. *dest++ = *source++; /* ??? to be unrolled */
  85951. } while (--len != 0);
  85952. }
  85953. int zmemcmp(s1, s2, len)
  85954. const Bytef* s1;
  85955. const Bytef* s2;
  85956. uInt len;
  85957. {
  85958. uInt j;
  85959. for (j = 0; j < len; j++) {
  85960. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85961. }
  85962. return 0;
  85963. }
  85964. void zmemzero(dest, len)
  85965. Bytef* dest;
  85966. uInt len;
  85967. {
  85968. if (len == 0) return;
  85969. do {
  85970. *dest++ = 0; /* ??? to be unrolled */
  85971. } while (--len != 0);
  85972. }
  85973. #endif
  85974. #ifdef SYS16BIT
  85975. #ifdef __TURBOC__
  85976. /* Turbo C in 16-bit mode */
  85977. # define MY_ZCALLOC
  85978. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85979. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85980. * must fix the pointer. Warning: the pointer must be put back to its
  85981. * original form in order to free it, use zcfree().
  85982. */
  85983. #define MAX_PTR 10
  85984. /* 10*64K = 640K */
  85985. local int next_ptr = 0;
  85986. typedef struct ptr_table_s {
  85987. voidpf org_ptr;
  85988. voidpf new_ptr;
  85989. } ptr_table;
  85990. local ptr_table table[MAX_PTR];
  85991. /* This table is used to remember the original form of pointers
  85992. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85993. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85994. * protected from concurrent access. This hack doesn't work anyway on
  85995. * a protected system like OS/2. Use Microsoft C instead.
  85996. */
  85997. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85998. {
  85999. voidpf buf = opaque; /* just to make some compilers happy */
  86000. ulg bsize = (ulg)items*size;
  86001. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86002. * will return a usable pointer which doesn't have to be normalized.
  86003. */
  86004. if (bsize < 65520L) {
  86005. buf = farmalloc(bsize);
  86006. if (*(ush*)&buf != 0) return buf;
  86007. } else {
  86008. buf = farmalloc(bsize + 16L);
  86009. }
  86010. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86011. table[next_ptr].org_ptr = buf;
  86012. /* Normalize the pointer to seg:0 */
  86013. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86014. *(ush*)&buf = 0;
  86015. table[next_ptr++].new_ptr = buf;
  86016. return buf;
  86017. }
  86018. void zcfree (voidpf opaque, voidpf ptr)
  86019. {
  86020. int n;
  86021. if (*(ush*)&ptr != 0) { /* object < 64K */
  86022. farfree(ptr);
  86023. return;
  86024. }
  86025. /* Find the original pointer */
  86026. for (n = 0; n < next_ptr; n++) {
  86027. if (ptr != table[n].new_ptr) continue;
  86028. farfree(table[n].org_ptr);
  86029. while (++n < next_ptr) {
  86030. table[n-1] = table[n];
  86031. }
  86032. next_ptr--;
  86033. return;
  86034. }
  86035. ptr = opaque; /* just to make some compilers happy */
  86036. Assert(0, "zcfree: ptr not found");
  86037. }
  86038. #endif /* __TURBOC__ */
  86039. #ifdef M_I86
  86040. /* Microsoft C in 16-bit mode */
  86041. # define MY_ZCALLOC
  86042. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86043. # define _halloc halloc
  86044. # define _hfree hfree
  86045. #endif
  86046. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86047. {
  86048. if (opaque) opaque = 0; /* to make compiler happy */
  86049. return _halloc((long)items, size);
  86050. }
  86051. void zcfree (voidpf opaque, voidpf ptr)
  86052. {
  86053. if (opaque) opaque = 0; /* to make compiler happy */
  86054. _hfree(ptr);
  86055. }
  86056. #endif /* M_I86 */
  86057. #endif /* SYS16BIT */
  86058. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86059. #ifndef STDC
  86060. extern voidp malloc OF((uInt size));
  86061. extern voidp calloc OF((uInt items, uInt size));
  86062. extern void free OF((voidpf ptr));
  86063. #endif
  86064. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86065. {
  86066. if (opaque) items += size - size; /* make compiler happy */
  86067. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86068. (voidpf)calloc(items, size);
  86069. }
  86070. void zcfree (voidpf opaque, voidpf ptr)
  86071. {
  86072. free(ptr);
  86073. if (opaque) return; /* make compiler happy */
  86074. }
  86075. #endif /* MY_ZCALLOC */
  86076. /*** End of inlined file: zutil.c ***/
  86077. #undef Byte
  86078. #else
  86079. #include <zlib.h>
  86080. #endif
  86081. }
  86082. #if JUCE_MSVC
  86083. #pragma warning (pop)
  86084. #endif
  86085. BEGIN_JUCE_NAMESPACE
  86086. // internal helper object that holds the zlib structures so they don't have to be
  86087. // included publicly.
  86088. class GZIPDecompressHelper
  86089. {
  86090. public:
  86091. GZIPDecompressHelper (const bool noWrap)
  86092. : finished (true),
  86093. needsDictionary (false),
  86094. error (true),
  86095. streamIsValid (false),
  86096. data (0),
  86097. dataSize (0)
  86098. {
  86099. using namespace zlibNamespace;
  86100. zerostruct (stream);
  86101. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86102. finished = error = ! streamIsValid;
  86103. }
  86104. ~GZIPDecompressHelper()
  86105. {
  86106. using namespace zlibNamespace;
  86107. if (streamIsValid)
  86108. inflateEnd (&stream);
  86109. }
  86110. bool needsInput() const throw() { return dataSize <= 0; }
  86111. void setInput (uint8* const data_, const int size) throw()
  86112. {
  86113. data = data_;
  86114. dataSize = size;
  86115. }
  86116. int doNextBlock (uint8* const dest, const int destSize)
  86117. {
  86118. using namespace zlibNamespace;
  86119. if (streamIsValid && data != 0 && ! finished)
  86120. {
  86121. stream.next_in = data;
  86122. stream.next_out = dest;
  86123. stream.avail_in = dataSize;
  86124. stream.avail_out = destSize;
  86125. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86126. {
  86127. case Z_STREAM_END:
  86128. finished = true;
  86129. // deliberate fall-through
  86130. case Z_OK:
  86131. data += dataSize - stream.avail_in;
  86132. dataSize = stream.avail_in;
  86133. return destSize - stream.avail_out;
  86134. case Z_NEED_DICT:
  86135. needsDictionary = true;
  86136. data += dataSize - stream.avail_in;
  86137. dataSize = stream.avail_in;
  86138. break;
  86139. case Z_DATA_ERROR:
  86140. case Z_MEM_ERROR:
  86141. error = true;
  86142. default:
  86143. break;
  86144. }
  86145. }
  86146. return 0;
  86147. }
  86148. bool finished, needsDictionary, error, streamIsValid;
  86149. private:
  86150. zlibNamespace::z_stream stream;
  86151. uint8* data;
  86152. int dataSize;
  86153. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86154. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86155. };
  86156. const int gzipDecompBufferSize = 32768;
  86157. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86158. const bool deleteSourceWhenDestroyed,
  86159. const bool noWrap_,
  86160. const int64 uncompressedStreamLength_)
  86161. : sourceStream (sourceStream_),
  86162. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86163. uncompressedStreamLength (uncompressedStreamLength_),
  86164. noWrap (noWrap_),
  86165. isEof (false),
  86166. activeBufferSize (0),
  86167. originalSourcePos (sourceStream_->getPosition()),
  86168. currentPos (0),
  86169. buffer (gzipDecompBufferSize),
  86170. helper (new GZIPDecompressHelper (noWrap_))
  86171. {
  86172. }
  86173. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86174. {
  86175. }
  86176. int64 GZIPDecompressorInputStream::getTotalLength()
  86177. {
  86178. return uncompressedStreamLength;
  86179. }
  86180. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86181. {
  86182. if ((howMany > 0) && ! isEof)
  86183. {
  86184. jassert (destBuffer != 0);
  86185. if (destBuffer != 0)
  86186. {
  86187. int numRead = 0;
  86188. uint8* d = static_cast <uint8*> (destBuffer);
  86189. while (! helper->error)
  86190. {
  86191. const int n = helper->doNextBlock (d, howMany);
  86192. currentPos += n;
  86193. if (n == 0)
  86194. {
  86195. if (helper->finished || helper->needsDictionary)
  86196. {
  86197. isEof = true;
  86198. return numRead;
  86199. }
  86200. if (helper->needsInput())
  86201. {
  86202. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  86203. if (activeBufferSize > 0)
  86204. {
  86205. helper->setInput (buffer, activeBufferSize);
  86206. }
  86207. else
  86208. {
  86209. isEof = true;
  86210. return numRead;
  86211. }
  86212. }
  86213. }
  86214. else
  86215. {
  86216. numRead += n;
  86217. howMany -= n;
  86218. d += n;
  86219. if (howMany <= 0)
  86220. return numRead;
  86221. }
  86222. }
  86223. }
  86224. }
  86225. return 0;
  86226. }
  86227. bool GZIPDecompressorInputStream::isExhausted()
  86228. {
  86229. return helper->error || isEof;
  86230. }
  86231. int64 GZIPDecompressorInputStream::getPosition()
  86232. {
  86233. return currentPos;
  86234. }
  86235. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86236. {
  86237. if (newPos < currentPos)
  86238. {
  86239. // to go backwards, reset the stream and start again..
  86240. isEof = false;
  86241. activeBufferSize = 0;
  86242. currentPos = 0;
  86243. helper = new GZIPDecompressHelper (noWrap);
  86244. sourceStream->setPosition (originalSourcePos);
  86245. }
  86246. skipNextBytes (newPos - currentPos);
  86247. return true;
  86248. }
  86249. END_JUCE_NAMESPACE
  86250. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86251. #endif
  86252. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86253. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86254. #if JUCE_USE_FLAC
  86255. #if JUCE_WINDOWS
  86256. #include <windows.h>
  86257. #endif
  86258. namespace FlacNamespace
  86259. {
  86260. #if JUCE_INCLUDE_FLAC_CODE
  86261. #if JUCE_MSVC
  86262. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86263. #endif
  86264. #define FLAC__NO_DLL 1
  86265. #if ! defined (SIZE_MAX)
  86266. #define SIZE_MAX 0xffffffff
  86267. #endif
  86268. #define __STDC_LIMIT_MACROS 1
  86269. /*** Start of inlined file: all.h ***/
  86270. #ifndef FLAC__ALL_H
  86271. #define FLAC__ALL_H
  86272. /*** Start of inlined file: export.h ***/
  86273. #ifndef FLAC__EXPORT_H
  86274. #define FLAC__EXPORT_H
  86275. /** \file include/FLAC/export.h
  86276. *
  86277. * \brief
  86278. * This module contains #defines and symbols for exporting function
  86279. * calls, and providing version information and compiled-in features.
  86280. *
  86281. * See the \link flac_export export \endlink module.
  86282. */
  86283. /** \defgroup flac_export FLAC/export.h: export symbols
  86284. * \ingroup flac
  86285. *
  86286. * \brief
  86287. * This module contains #defines and symbols for exporting function
  86288. * calls, and providing version information and compiled-in features.
  86289. *
  86290. * If you are compiling with MSVC and will link to the static library
  86291. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86292. * make sure the symbols are exported properly.
  86293. *
  86294. * \{
  86295. */
  86296. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86297. #define FLAC_API
  86298. #else
  86299. #ifdef FLAC_API_EXPORTS
  86300. #define FLAC_API _declspec(dllexport)
  86301. #else
  86302. #define FLAC_API _declspec(dllimport)
  86303. #endif
  86304. #endif
  86305. /** These #defines will mirror the libtool-based library version number, see
  86306. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86307. */
  86308. #define FLAC_API_VERSION_CURRENT 10
  86309. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86310. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86311. #ifdef __cplusplus
  86312. extern "C" {
  86313. #endif
  86314. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86315. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86316. #ifdef __cplusplus
  86317. }
  86318. #endif
  86319. /* \} */
  86320. #endif
  86321. /*** End of inlined file: export.h ***/
  86322. /*** Start of inlined file: assert.h ***/
  86323. #ifndef FLAC__ASSERT_H
  86324. #define FLAC__ASSERT_H
  86325. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86326. #ifdef DEBUG
  86327. #include <assert.h>
  86328. #define FLAC__ASSERT(x) assert(x)
  86329. #define FLAC__ASSERT_DECLARATION(x) x
  86330. #else
  86331. #define FLAC__ASSERT(x)
  86332. #define FLAC__ASSERT_DECLARATION(x)
  86333. #endif
  86334. #endif
  86335. /*** End of inlined file: assert.h ***/
  86336. /*** Start of inlined file: callback.h ***/
  86337. #ifndef FLAC__CALLBACK_H
  86338. #define FLAC__CALLBACK_H
  86339. /*** Start of inlined file: ordinals.h ***/
  86340. #ifndef FLAC__ORDINALS_H
  86341. #define FLAC__ORDINALS_H
  86342. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86343. #include <inttypes.h>
  86344. #endif
  86345. typedef signed char FLAC__int8;
  86346. typedef unsigned char FLAC__uint8;
  86347. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86348. typedef __int16 FLAC__int16;
  86349. typedef __int32 FLAC__int32;
  86350. typedef __int64 FLAC__int64;
  86351. typedef unsigned __int16 FLAC__uint16;
  86352. typedef unsigned __int32 FLAC__uint32;
  86353. typedef unsigned __int64 FLAC__uint64;
  86354. #elif defined(__EMX__)
  86355. typedef short FLAC__int16;
  86356. typedef long FLAC__int32;
  86357. typedef long long FLAC__int64;
  86358. typedef unsigned short FLAC__uint16;
  86359. typedef unsigned long FLAC__uint32;
  86360. typedef unsigned long long FLAC__uint64;
  86361. #else
  86362. typedef int16_t FLAC__int16;
  86363. typedef int32_t FLAC__int32;
  86364. typedef int64_t FLAC__int64;
  86365. typedef uint16_t FLAC__uint16;
  86366. typedef uint32_t FLAC__uint32;
  86367. typedef uint64_t FLAC__uint64;
  86368. #endif
  86369. typedef int FLAC__bool;
  86370. typedef FLAC__uint8 FLAC__byte;
  86371. #ifdef true
  86372. #undef true
  86373. #endif
  86374. #ifdef false
  86375. #undef false
  86376. #endif
  86377. #ifndef __cplusplus
  86378. #define true 1
  86379. #define false 0
  86380. #endif
  86381. #endif
  86382. /*** End of inlined file: ordinals.h ***/
  86383. #include <stdlib.h> /* for size_t */
  86384. /** \file include/FLAC/callback.h
  86385. *
  86386. * \brief
  86387. * This module defines the structures for describing I/O callbacks
  86388. * to the other FLAC interfaces.
  86389. *
  86390. * See the detailed documentation for callbacks in the
  86391. * \link flac_callbacks callbacks \endlink module.
  86392. */
  86393. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86394. * \ingroup flac
  86395. *
  86396. * \brief
  86397. * This module defines the structures for describing I/O callbacks
  86398. * to the other FLAC interfaces.
  86399. *
  86400. * The purpose of the I/O callback functions is to create a common way
  86401. * for the metadata interfaces to handle I/O.
  86402. *
  86403. * Originally the metadata interfaces required filenames as the way of
  86404. * specifying FLAC files to operate on. This is problematic in some
  86405. * environments so there is an additional option to specify a set of
  86406. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86407. *
  86408. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86409. * opaque structure for a data source.
  86410. *
  86411. * The callback function prototypes are similar (but not identical) to the
  86412. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86413. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86414. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86415. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86416. * is required. \warning You generally CANNOT directly use fseek or ftell
  86417. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86418. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86419. * large files. You will have to find an equivalent function (e.g. ftello),
  86420. * or write a wrapper. The same is true for feof() since this is usually
  86421. * implemented as a macro, not as a function whose address can be taken.
  86422. *
  86423. * \{
  86424. */
  86425. #ifdef __cplusplus
  86426. extern "C" {
  86427. #endif
  86428. /** This is the opaque handle type used by the callbacks. Typically
  86429. * this is a \c FILE* or address of a file descriptor.
  86430. */
  86431. typedef void* FLAC__IOHandle;
  86432. /** Signature for the read callback.
  86433. * The signature and semantics match POSIX fread() implementations
  86434. * and can generally be used interchangeably.
  86435. *
  86436. * \param ptr The address of the read buffer.
  86437. * \param size The size of the records to be read.
  86438. * \param nmemb The number of records to be read.
  86439. * \param handle The handle to the data source.
  86440. * \retval size_t
  86441. * The number of records read.
  86442. */
  86443. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86444. /** Signature for the write callback.
  86445. * The signature and semantics match POSIX fwrite() implementations
  86446. * and can generally be used interchangeably.
  86447. *
  86448. * \param ptr The address of the write buffer.
  86449. * \param size The size of the records to be written.
  86450. * \param nmemb The number of records to be written.
  86451. * \param handle The handle to the data source.
  86452. * \retval size_t
  86453. * The number of records written.
  86454. */
  86455. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86456. /** Signature for the seek callback.
  86457. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86458. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86459. * and 32-bits wide.
  86460. *
  86461. * \param handle The handle to the data source.
  86462. * \param offset The new position, relative to \a whence
  86463. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86464. * \retval int
  86465. * \c 0 on success, \c -1 on error.
  86466. */
  86467. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86468. /** Signature for the tell callback.
  86469. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86470. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86471. * and 32-bits wide.
  86472. *
  86473. * \param handle The handle to the data source.
  86474. * \retval FLAC__int64
  86475. * The current position on success, \c -1 on error.
  86476. */
  86477. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86478. /** Signature for the EOF callback.
  86479. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86480. * on many systems, feof() is a macro, so in this case a wrapper function
  86481. * must be provided instead.
  86482. *
  86483. * \param handle The handle to the data source.
  86484. * \retval int
  86485. * \c 0 if not at end of file, nonzero if at end of file.
  86486. */
  86487. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86488. /** Signature for the close callback.
  86489. * The signature and semantics match POSIX fclose() implementations
  86490. * and can generally be used interchangeably.
  86491. *
  86492. * \param handle The handle to the data source.
  86493. * \retval int
  86494. * \c 0 on success, \c EOF on error.
  86495. */
  86496. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86497. /** A structure for holding a set of callbacks.
  86498. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86499. * describe which of the callbacks are required. The ones that are not
  86500. * required may be set to NULL.
  86501. *
  86502. * If the seek requirement for an interface is optional, you can signify that
  86503. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86504. */
  86505. typedef struct {
  86506. FLAC__IOCallback_Read read;
  86507. FLAC__IOCallback_Write write;
  86508. FLAC__IOCallback_Seek seek;
  86509. FLAC__IOCallback_Tell tell;
  86510. FLAC__IOCallback_Eof eof;
  86511. FLAC__IOCallback_Close close;
  86512. } FLAC__IOCallbacks;
  86513. /* \} */
  86514. #ifdef __cplusplus
  86515. }
  86516. #endif
  86517. #endif
  86518. /*** End of inlined file: callback.h ***/
  86519. /*** Start of inlined file: format.h ***/
  86520. #ifndef FLAC__FORMAT_H
  86521. #define FLAC__FORMAT_H
  86522. #ifdef __cplusplus
  86523. extern "C" {
  86524. #endif
  86525. /** \file include/FLAC/format.h
  86526. *
  86527. * \brief
  86528. * This module contains structure definitions for the representation
  86529. * of FLAC format components in memory. These are the basic
  86530. * structures used by the rest of the interfaces.
  86531. *
  86532. * See the detailed documentation in the
  86533. * \link flac_format format \endlink module.
  86534. */
  86535. /** \defgroup flac_format FLAC/format.h: format components
  86536. * \ingroup flac
  86537. *
  86538. * \brief
  86539. * This module contains structure definitions for the representation
  86540. * of FLAC format components in memory. These are the basic
  86541. * structures used by the rest of the interfaces.
  86542. *
  86543. * First, you should be familiar with the
  86544. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86545. * follow directly from the specification. As a user of libFLAC, the
  86546. * interesting parts really are the structures that describe the frame
  86547. * header and metadata blocks.
  86548. *
  86549. * The format structures here are very primitive, designed to store
  86550. * information in an efficient way. Reading information from the
  86551. * structures is easy but creating or modifying them directly is
  86552. * more complex. For the most part, as a user of a library, editing
  86553. * is not necessary; however, for metadata blocks it is, so there are
  86554. * convenience functions provided in the \link flac_metadata metadata
  86555. * module \endlink to simplify the manipulation of metadata blocks.
  86556. *
  86557. * \note
  86558. * It's not the best convention, but symbols ending in _LEN are in bits
  86559. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86560. * global variables because they are usually used when declaring byte
  86561. * arrays and some compilers require compile-time knowledge of array
  86562. * sizes when declared on the stack.
  86563. *
  86564. * \{
  86565. */
  86566. /*
  86567. Most of the values described in this file are defined by the FLAC
  86568. format specification. There is nothing to tune here.
  86569. */
  86570. /** The largest legal metadata type code. */
  86571. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86572. /** The minimum block size, in samples, permitted by the format. */
  86573. #define FLAC__MIN_BLOCK_SIZE (16u)
  86574. /** The maximum block size, in samples, permitted by the format. */
  86575. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86576. /** The maximum block size, in samples, permitted by the FLAC subset for
  86577. * sample rates up to 48kHz. */
  86578. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86579. /** The maximum number of channels permitted by the format. */
  86580. #define FLAC__MAX_CHANNELS (8u)
  86581. /** The minimum sample resolution permitted by the format. */
  86582. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86583. /** The maximum sample resolution permitted by the format. */
  86584. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86585. /** The maximum sample resolution permitted by libFLAC.
  86586. *
  86587. * \warning
  86588. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86589. * the reference encoder/decoder is currently limited to 24 bits because
  86590. * of prevalent 32-bit math, so make sure and use this value when
  86591. * appropriate.
  86592. */
  86593. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86594. /** The maximum sample rate permitted by the format. The value is
  86595. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86596. * as to why.
  86597. */
  86598. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86599. /** The maximum LPC order permitted by the format. */
  86600. #define FLAC__MAX_LPC_ORDER (32u)
  86601. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86602. * up to 48kHz. */
  86603. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86604. /** The minimum quantized linear predictor coefficient precision
  86605. * permitted by the format.
  86606. */
  86607. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86608. /** The maximum quantized linear predictor coefficient precision
  86609. * permitted by the format.
  86610. */
  86611. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86612. /** The maximum order of the fixed predictors permitted by the format. */
  86613. #define FLAC__MAX_FIXED_ORDER (4u)
  86614. /** The maximum Rice partition order permitted by the format. */
  86615. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86616. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86617. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86618. /** The version string of the release, stamped onto the libraries and binaries.
  86619. *
  86620. * \note
  86621. * This does not correspond to the shared library version number, which
  86622. * is used to determine binary compatibility.
  86623. */
  86624. extern FLAC_API const char *FLAC__VERSION_STRING;
  86625. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86626. * This is a NUL-terminated ASCII string; when inserted into the
  86627. * VORBIS_COMMENT the trailing null is stripped.
  86628. */
  86629. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86630. /** The byte string representation of the beginning of a FLAC stream. */
  86631. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86632. /** The 32-bit integer big-endian representation of the beginning of
  86633. * a FLAC stream.
  86634. */
  86635. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86636. /** The length of the FLAC signature in bits. */
  86637. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86638. /** The length of the FLAC signature in bytes. */
  86639. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86640. /*****************************************************************************
  86641. *
  86642. * Subframe structures
  86643. *
  86644. *****************************************************************************/
  86645. /*****************************************************************************/
  86646. /** An enumeration of the available entropy coding methods. */
  86647. typedef enum {
  86648. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86649. /**< Residual is coded by partitioning into contexts, each with it's own
  86650. * 4-bit Rice parameter. */
  86651. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86652. /**< Residual is coded by partitioning into contexts, each with it's own
  86653. * 5-bit Rice parameter. */
  86654. } FLAC__EntropyCodingMethodType;
  86655. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86656. *
  86657. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86658. * give the string equivalent. The contents should not be modified.
  86659. */
  86660. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86661. /** Contents of a Rice partitioned residual
  86662. */
  86663. typedef struct {
  86664. unsigned *parameters;
  86665. /**< The Rice parameters for each context. */
  86666. unsigned *raw_bits;
  86667. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86668. * partitions and zero for unescaped partitions.
  86669. */
  86670. unsigned capacity_by_order;
  86671. /**< The capacity of the \a parameters and \a raw_bits arrays
  86672. * specified as an order, i.e. the number of array elements
  86673. * allocated is 2 ^ \a capacity_by_order.
  86674. */
  86675. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86676. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86677. */
  86678. typedef struct {
  86679. unsigned order;
  86680. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86681. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86682. /**< The context's Rice parameters and/or raw bits. */
  86683. } FLAC__EntropyCodingMethod_PartitionedRice;
  86684. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86685. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86686. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86687. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86688. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86689. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86690. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86691. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86692. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86693. */
  86694. typedef struct {
  86695. FLAC__EntropyCodingMethodType type;
  86696. union {
  86697. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86698. } data;
  86699. } FLAC__EntropyCodingMethod;
  86700. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86701. /*****************************************************************************/
  86702. /** An enumeration of the available subframe types. */
  86703. typedef enum {
  86704. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86705. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86706. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86707. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86708. } FLAC__SubframeType;
  86709. /** Maps a FLAC__SubframeType to a C string.
  86710. *
  86711. * Using a FLAC__SubframeType as the index to this array will
  86712. * give the string equivalent. The contents should not be modified.
  86713. */
  86714. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86715. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86716. */
  86717. typedef struct {
  86718. FLAC__int32 value; /**< The constant signal value. */
  86719. } FLAC__Subframe_Constant;
  86720. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86721. */
  86722. typedef struct {
  86723. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86724. } FLAC__Subframe_Verbatim;
  86725. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86726. */
  86727. typedef struct {
  86728. FLAC__EntropyCodingMethod entropy_coding_method;
  86729. /**< The residual coding method. */
  86730. unsigned order;
  86731. /**< The polynomial order. */
  86732. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86733. /**< Warmup samples to prime the predictor, length == order. */
  86734. const FLAC__int32 *residual;
  86735. /**< The residual signal, length == (blocksize minus order) samples. */
  86736. } FLAC__Subframe_Fixed;
  86737. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86738. */
  86739. typedef struct {
  86740. FLAC__EntropyCodingMethod entropy_coding_method;
  86741. /**< The residual coding method. */
  86742. unsigned order;
  86743. /**< The FIR order. */
  86744. unsigned qlp_coeff_precision;
  86745. /**< Quantized FIR filter coefficient precision in bits. */
  86746. int quantization_level;
  86747. /**< The qlp coeff shift needed. */
  86748. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86749. /**< FIR filter coefficients. */
  86750. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86751. /**< Warmup samples to prime the predictor, length == order. */
  86752. const FLAC__int32 *residual;
  86753. /**< The residual signal, length == (blocksize minus order) samples. */
  86754. } FLAC__Subframe_LPC;
  86755. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86756. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86757. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86758. */
  86759. typedef struct {
  86760. FLAC__SubframeType type;
  86761. union {
  86762. FLAC__Subframe_Constant constant;
  86763. FLAC__Subframe_Fixed fixed;
  86764. FLAC__Subframe_LPC lpc;
  86765. FLAC__Subframe_Verbatim verbatim;
  86766. } data;
  86767. unsigned wasted_bits;
  86768. } FLAC__Subframe;
  86769. /** == 1 (bit)
  86770. *
  86771. * This used to be a zero-padding bit (hence the name
  86772. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86773. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86774. * to mean something else.
  86775. */
  86776. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86777. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86778. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86779. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86780. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86781. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86782. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86783. /*****************************************************************************/
  86784. /*****************************************************************************
  86785. *
  86786. * Frame structures
  86787. *
  86788. *****************************************************************************/
  86789. /** An enumeration of the available channel assignments. */
  86790. typedef enum {
  86791. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86792. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86793. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86794. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86795. } FLAC__ChannelAssignment;
  86796. /** Maps a FLAC__ChannelAssignment to a C string.
  86797. *
  86798. * Using a FLAC__ChannelAssignment as the index to this array will
  86799. * give the string equivalent. The contents should not be modified.
  86800. */
  86801. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86802. /** An enumeration of the possible frame numbering methods. */
  86803. typedef enum {
  86804. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86805. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86806. } FLAC__FrameNumberType;
  86807. /** Maps a FLAC__FrameNumberType to a C string.
  86808. *
  86809. * Using a FLAC__FrameNumberType as the index to this array will
  86810. * give the string equivalent. The contents should not be modified.
  86811. */
  86812. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86813. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86814. */
  86815. typedef struct {
  86816. unsigned blocksize;
  86817. /**< The number of samples per subframe. */
  86818. unsigned sample_rate;
  86819. /**< The sample rate in Hz. */
  86820. unsigned channels;
  86821. /**< The number of channels (== number of subframes). */
  86822. FLAC__ChannelAssignment channel_assignment;
  86823. /**< The channel assignment for the frame. */
  86824. unsigned bits_per_sample;
  86825. /**< The sample resolution. */
  86826. FLAC__FrameNumberType number_type;
  86827. /**< The numbering scheme used for the frame. As a convenience, the
  86828. * decoder will always convert a frame number to a sample number because
  86829. * the rules are complex. */
  86830. union {
  86831. FLAC__uint32 frame_number;
  86832. FLAC__uint64 sample_number;
  86833. } number;
  86834. /**< The frame number or sample number of first sample in frame;
  86835. * use the \a number_type value to determine which to use. */
  86836. FLAC__uint8 crc;
  86837. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86838. * of the raw frame header bytes, meaning everything before the CRC byte
  86839. * including the sync code.
  86840. */
  86841. } FLAC__FrameHeader;
  86842. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86843. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86844. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86845. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86846. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86847. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86848. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86849. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86850. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86851. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86852. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86853. */
  86854. typedef struct {
  86855. FLAC__uint16 crc;
  86856. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86857. * 0) of the bytes before the crc, back to and including the frame header
  86858. * sync code.
  86859. */
  86860. } FLAC__FrameFooter;
  86861. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86862. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86863. */
  86864. typedef struct {
  86865. FLAC__FrameHeader header;
  86866. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86867. FLAC__FrameFooter footer;
  86868. } FLAC__Frame;
  86869. /*****************************************************************************/
  86870. /*****************************************************************************
  86871. *
  86872. * Meta-data structures
  86873. *
  86874. *****************************************************************************/
  86875. /** An enumeration of the available metadata block types. */
  86876. typedef enum {
  86877. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86878. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86879. FLAC__METADATA_TYPE_PADDING = 1,
  86880. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86881. FLAC__METADATA_TYPE_APPLICATION = 2,
  86882. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86883. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86884. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86885. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86886. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86887. FLAC__METADATA_TYPE_CUESHEET = 5,
  86888. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86889. FLAC__METADATA_TYPE_PICTURE = 6,
  86890. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86891. FLAC__METADATA_TYPE_UNDEFINED = 7
  86892. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86893. } FLAC__MetadataType;
  86894. /** Maps a FLAC__MetadataType to a C string.
  86895. *
  86896. * Using a FLAC__MetadataType as the index to this array will
  86897. * give the string equivalent. The contents should not be modified.
  86898. */
  86899. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86900. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86901. */
  86902. typedef struct {
  86903. unsigned min_blocksize, max_blocksize;
  86904. unsigned min_framesize, max_framesize;
  86905. unsigned sample_rate;
  86906. unsigned channels;
  86907. unsigned bits_per_sample;
  86908. FLAC__uint64 total_samples;
  86909. FLAC__byte md5sum[16];
  86910. } FLAC__StreamMetadata_StreamInfo;
  86911. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86912. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86913. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86914. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86915. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86916. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86917. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86918. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86919. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86920. /** The total stream length of the STREAMINFO block in bytes. */
  86921. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86922. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86923. */
  86924. typedef struct {
  86925. int dummy;
  86926. /**< Conceptually this is an empty struct since we don't store the
  86927. * padding bytes. Empty structs are not allowed by some C compilers,
  86928. * hence the dummy.
  86929. */
  86930. } FLAC__StreamMetadata_Padding;
  86931. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86932. */
  86933. typedef struct {
  86934. FLAC__byte id[4];
  86935. FLAC__byte *data;
  86936. } FLAC__StreamMetadata_Application;
  86937. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86938. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86939. */
  86940. typedef struct {
  86941. FLAC__uint64 sample_number;
  86942. /**< The sample number of the target frame. */
  86943. FLAC__uint64 stream_offset;
  86944. /**< The offset, in bytes, of the target frame with respect to
  86945. * beginning of the first frame. */
  86946. unsigned frame_samples;
  86947. /**< The number of samples in the target frame. */
  86948. } FLAC__StreamMetadata_SeekPoint;
  86949. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86950. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86951. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86952. /** The total stream length of a seek point in bytes. */
  86953. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86954. /** The value used in the \a sample_number field of
  86955. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86956. * point (== 0xffffffffffffffff).
  86957. */
  86958. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86959. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86960. *
  86961. * \note From the format specification:
  86962. * - The seek points must be sorted by ascending sample number.
  86963. * - Each seek point's sample number must be the first sample of the
  86964. * target frame.
  86965. * - Each seek point's sample number must be unique within the table.
  86966. * - Existence of a SEEKTABLE block implies a correct setting of
  86967. * total_samples in the stream_info block.
  86968. * - Behavior is undefined when more than one SEEKTABLE block is
  86969. * present in a stream.
  86970. */
  86971. typedef struct {
  86972. unsigned num_points;
  86973. FLAC__StreamMetadata_SeekPoint *points;
  86974. } FLAC__StreamMetadata_SeekTable;
  86975. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86976. *
  86977. * For convenience, the APIs maintain a trailing NUL character at the end of
  86978. * \a entry which is not counted toward \a length, i.e.
  86979. * \code strlen(entry) == length \endcode
  86980. */
  86981. typedef struct {
  86982. FLAC__uint32 length;
  86983. FLAC__byte *entry;
  86984. } FLAC__StreamMetadata_VorbisComment_Entry;
  86985. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86986. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86987. */
  86988. typedef struct {
  86989. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86990. FLAC__uint32 num_comments;
  86991. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86992. } FLAC__StreamMetadata_VorbisComment;
  86993. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86994. /** FLAC CUESHEET track index structure. (See the
  86995. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86996. * the full description of each field.)
  86997. */
  86998. typedef struct {
  86999. FLAC__uint64 offset;
  87000. /**< Offset in samples, relative to the track offset, of the index
  87001. * point.
  87002. */
  87003. FLAC__byte number;
  87004. /**< The index point number. */
  87005. } FLAC__StreamMetadata_CueSheet_Index;
  87006. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87007. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87008. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87009. /** FLAC CUESHEET track structure. (See the
  87010. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87011. * the full description of each field.)
  87012. */
  87013. typedef struct {
  87014. FLAC__uint64 offset;
  87015. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87016. FLAC__byte number;
  87017. /**< The track number. */
  87018. char isrc[13];
  87019. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87020. unsigned type:1;
  87021. /**< The track type: 0 for audio, 1 for non-audio. */
  87022. unsigned pre_emphasis:1;
  87023. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87024. FLAC__byte num_indices;
  87025. /**< The number of track index points. */
  87026. FLAC__StreamMetadata_CueSheet_Index *indices;
  87027. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87028. } FLAC__StreamMetadata_CueSheet_Track;
  87029. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87030. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87031. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87032. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87033. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87034. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87035. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87036. /** FLAC CUESHEET structure. (See the
  87037. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87038. * for the full description of each field.)
  87039. */
  87040. typedef struct {
  87041. char media_catalog_number[129];
  87042. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87043. * general, the media catalog number may be 0 to 128 bytes long; any
  87044. * unused characters should be right-padded with NUL characters.
  87045. */
  87046. FLAC__uint64 lead_in;
  87047. /**< The number of lead-in samples. */
  87048. FLAC__bool is_cd;
  87049. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87050. unsigned num_tracks;
  87051. /**< The number of tracks. */
  87052. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87053. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87054. } FLAC__StreamMetadata_CueSheet;
  87055. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87056. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87057. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87058. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87059. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87060. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87061. typedef enum {
  87062. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87063. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87064. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87065. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87066. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87067. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87068. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87069. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87070. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87071. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87072. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87073. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87074. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87075. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87076. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87077. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87078. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87079. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87080. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87081. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87082. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87083. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87084. } FLAC__StreamMetadata_Picture_Type;
  87085. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87086. *
  87087. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87088. * will give the string equivalent. The contents should not be
  87089. * modified.
  87090. */
  87091. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87092. /** FLAC PICTURE structure. (See the
  87093. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87094. * for the full description of each field.)
  87095. */
  87096. typedef struct {
  87097. FLAC__StreamMetadata_Picture_Type type;
  87098. /**< The kind of picture stored. */
  87099. char *mime_type;
  87100. /**< Picture data's MIME type, in ASCII printable characters
  87101. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87102. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87103. * MIME type of '-->' is also allowed, in which case the picture
  87104. * data should be a complete URL. In file storage, the MIME type is
  87105. * stored as a 32-bit length followed by the ASCII string with no NUL
  87106. * terminator, but is converted to a plain C string in this structure
  87107. * for convenience.
  87108. */
  87109. FLAC__byte *description;
  87110. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87111. * the description is stored as a 32-bit length followed by the UTF-8
  87112. * string with no NUL terminator, but is converted to a plain C string
  87113. * in this structure for convenience.
  87114. */
  87115. FLAC__uint32 width;
  87116. /**< Picture's width in pixels. */
  87117. FLAC__uint32 height;
  87118. /**< Picture's height in pixels. */
  87119. FLAC__uint32 depth;
  87120. /**< Picture's color depth in bits-per-pixel. */
  87121. FLAC__uint32 colors;
  87122. /**< For indexed palettes (like GIF), picture's number of colors (the
  87123. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87124. */
  87125. FLAC__uint32 data_length;
  87126. /**< Length of binary picture data in bytes. */
  87127. FLAC__byte *data;
  87128. /**< Binary picture data. */
  87129. } FLAC__StreamMetadata_Picture;
  87130. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87131. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87132. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87133. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87134. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87135. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87136. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87137. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87138. /** Structure that is used when a metadata block of unknown type is loaded.
  87139. * The contents are opaque. The structure is used only internally to
  87140. * correctly handle unknown metadata.
  87141. */
  87142. typedef struct {
  87143. FLAC__byte *data;
  87144. } FLAC__StreamMetadata_Unknown;
  87145. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87146. */
  87147. typedef struct {
  87148. FLAC__MetadataType type;
  87149. /**< The type of the metadata block; used determine which member of the
  87150. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87151. * then \a data.unknown must be used. */
  87152. FLAC__bool is_last;
  87153. /**< \c true if this metadata block is the last, else \a false */
  87154. unsigned length;
  87155. /**< Length, in bytes, of the block data as it appears in the stream. */
  87156. union {
  87157. FLAC__StreamMetadata_StreamInfo stream_info;
  87158. FLAC__StreamMetadata_Padding padding;
  87159. FLAC__StreamMetadata_Application application;
  87160. FLAC__StreamMetadata_SeekTable seek_table;
  87161. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87162. FLAC__StreamMetadata_CueSheet cue_sheet;
  87163. FLAC__StreamMetadata_Picture picture;
  87164. FLAC__StreamMetadata_Unknown unknown;
  87165. } data;
  87166. /**< Polymorphic block data; use the \a type value to determine which
  87167. * to use. */
  87168. } FLAC__StreamMetadata;
  87169. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87170. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87171. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87172. /** The total stream length of a metadata block header in bytes. */
  87173. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87174. /*****************************************************************************/
  87175. /*****************************************************************************
  87176. *
  87177. * Utility functions
  87178. *
  87179. *****************************************************************************/
  87180. /** Tests that a sample rate is valid for FLAC.
  87181. *
  87182. * \param sample_rate The sample rate to test for compliance.
  87183. * \retval FLAC__bool
  87184. * \c true if the given sample rate conforms to the specification, else
  87185. * \c false.
  87186. */
  87187. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87188. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87189. * for valid sample rates are slightly more complex since the rate has to
  87190. * be expressible completely in the frame header.
  87191. *
  87192. * \param sample_rate The sample rate to test for compliance.
  87193. * \retval FLAC__bool
  87194. * \c true if the given sample rate conforms to the specification for the
  87195. * subset, else \c false.
  87196. */
  87197. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87198. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87199. * comment specification.
  87200. *
  87201. * Vorbis comment names must be composed only of characters from
  87202. * [0x20-0x3C,0x3E-0x7D].
  87203. *
  87204. * \param name A NUL-terminated string to be checked.
  87205. * \assert
  87206. * \code name != NULL \endcode
  87207. * \retval FLAC__bool
  87208. * \c false if entry name is illegal, else \c true.
  87209. */
  87210. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87211. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87212. * comment specification.
  87213. *
  87214. * Vorbis comment values must be valid UTF-8 sequences.
  87215. *
  87216. * \param value A string to be checked.
  87217. * \param length A the length of \a value in bytes. May be
  87218. * \c (unsigned)(-1) to indicate that \a value is a plain
  87219. * UTF-8 NUL-terminated string.
  87220. * \assert
  87221. * \code value != NULL \endcode
  87222. * \retval FLAC__bool
  87223. * \c false if entry name is illegal, else \c true.
  87224. */
  87225. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87226. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87227. * comment specification.
  87228. *
  87229. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87230. * 'value' must be legal according to
  87231. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87232. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87233. *
  87234. * \param entry An entry to be checked.
  87235. * \param length The length of \a entry in bytes.
  87236. * \assert
  87237. * \code value != NULL \endcode
  87238. * \retval FLAC__bool
  87239. * \c false if entry name is illegal, else \c true.
  87240. */
  87241. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87242. /** Check a seek table to see if it conforms to the FLAC specification.
  87243. * See the format specification for limits on the contents of the
  87244. * seek table.
  87245. *
  87246. * \param seek_table A pointer to a seek table to be checked.
  87247. * \assert
  87248. * \code seek_table != NULL \endcode
  87249. * \retval FLAC__bool
  87250. * \c false if seek table is illegal, else \c true.
  87251. */
  87252. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87253. /** Sort a seek table's seek points according to the format specification.
  87254. * This includes a "unique-ification" step to remove duplicates, i.e.
  87255. * seek points with identical \a sample_number values. Duplicate seek
  87256. * points are converted into placeholder points and sorted to the end of
  87257. * the table.
  87258. *
  87259. * \param seek_table A pointer to a seek table to be sorted.
  87260. * \assert
  87261. * \code seek_table != NULL \endcode
  87262. * \retval unsigned
  87263. * The number of duplicate seek points converted into placeholders.
  87264. */
  87265. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87266. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87267. * See the format specification for limits on the contents of the
  87268. * cue sheet.
  87269. *
  87270. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87271. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87272. * stringent requirements for a CD-DA (audio) disc.
  87273. * \param violation Address of a pointer to a string. If there is a
  87274. * violation, a pointer to a string explanation of the
  87275. * violation will be returned here. \a violation may be
  87276. * \c NULL if you don't need the returned string. Do not
  87277. * free the returned string; it will always point to static
  87278. * data.
  87279. * \assert
  87280. * \code cue_sheet != NULL \endcode
  87281. * \retval FLAC__bool
  87282. * \c false if cue sheet is illegal, else \c true.
  87283. */
  87284. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87285. /** Check picture data to see if it conforms to the FLAC specification.
  87286. * See the format specification for limits on the contents of the
  87287. * PICTURE block.
  87288. *
  87289. * \param picture A pointer to existing picture data to be checked.
  87290. * \param violation Address of a pointer to a string. If there is a
  87291. * violation, a pointer to a string explanation of the
  87292. * violation will be returned here. \a violation may be
  87293. * \c NULL if you don't need the returned string. Do not
  87294. * free the returned string; it will always point to static
  87295. * data.
  87296. * \assert
  87297. * \code picture != NULL \endcode
  87298. * \retval FLAC__bool
  87299. * \c false if picture data is illegal, else \c true.
  87300. */
  87301. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87302. /* \} */
  87303. #ifdef __cplusplus
  87304. }
  87305. #endif
  87306. #endif
  87307. /*** End of inlined file: format.h ***/
  87308. /*** Start of inlined file: metadata.h ***/
  87309. #ifndef FLAC__METADATA_H
  87310. #define FLAC__METADATA_H
  87311. #include <sys/types.h> /* for off_t */
  87312. /* --------------------------------------------------------------------
  87313. (For an example of how all these routines are used, see the source
  87314. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87315. metaflac in src/metaflac/)
  87316. ------------------------------------------------------------------*/
  87317. /** \file include/FLAC/metadata.h
  87318. *
  87319. * \brief
  87320. * This module provides functions for creating and manipulating FLAC
  87321. * metadata blocks in memory, and three progressively more powerful
  87322. * interfaces for traversing and editing metadata in FLAC files.
  87323. *
  87324. * See the detailed documentation for each interface in the
  87325. * \link flac_metadata metadata \endlink module.
  87326. */
  87327. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87328. * \ingroup flac
  87329. *
  87330. * \brief
  87331. * This module provides functions for creating and manipulating FLAC
  87332. * metadata blocks in memory, and three progressively more powerful
  87333. * interfaces for traversing and editing metadata in native FLAC files.
  87334. * Note that currently only the Chain interface (level 2) supports Ogg
  87335. * FLAC files, and it is read-only i.e. no writing back changed
  87336. * metadata to file.
  87337. *
  87338. * There are three metadata interfaces of increasing complexity:
  87339. *
  87340. * Level 0:
  87341. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87342. * PICTURE blocks.
  87343. *
  87344. * Level 1:
  87345. * Read-write access to all metadata blocks. This level is write-
  87346. * efficient in most cases (more on this below), and uses less memory
  87347. * than level 2.
  87348. *
  87349. * Level 2:
  87350. * Read-write access to all metadata blocks. This level is write-
  87351. * efficient in all cases, but uses more memory since all metadata for
  87352. * the whole file is read into memory and manipulated before writing
  87353. * out again.
  87354. *
  87355. * What do we mean by efficient? Since FLAC metadata appears at the
  87356. * beginning of the file, when writing metadata back to a FLAC file
  87357. * it is possible to grow or shrink the metadata such that the entire
  87358. * file must be rewritten. However, if the size remains the same during
  87359. * changes or PADDING blocks are utilized, only the metadata needs to be
  87360. * overwritten, which is much faster.
  87361. *
  87362. * Efficient means the whole file is rewritten at most one time, and only
  87363. * when necessary. Level 1 is not efficient only in the case that you
  87364. * cause more than one metadata block to grow or shrink beyond what can
  87365. * be accomodated by padding. In this case you should probably use level
  87366. * 2, which allows you to edit all the metadata for a file in memory and
  87367. * write it out all at once.
  87368. *
  87369. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87370. * front of the file.
  87371. *
  87372. * All levels access files via their filenames. In addition, level 2
  87373. * has additional alternative read and write functions that take an I/O
  87374. * handle and callbacks, for situations where access by filename is not
  87375. * possible.
  87376. *
  87377. * In addition to the three interfaces, this module defines functions for
  87378. * creating and manipulating various metadata objects in memory. As we see
  87379. * from the Format module, FLAC metadata blocks in memory are very primitive
  87380. * structures for storing information in an efficient way. Reading
  87381. * information from the structures is easy but creating or modifying them
  87382. * directly is more complex. The metadata object routines here facilitate
  87383. * this by taking care of the consistency and memory management drudgery.
  87384. *
  87385. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87386. * metadata however, you will not probably not need these.
  87387. *
  87388. * From a dependency standpoint, none of the encoders or decoders require
  87389. * the metadata module. This is so that embedded users can strip out the
  87390. * metadata module from libFLAC to reduce the size and complexity.
  87391. */
  87392. #ifdef __cplusplus
  87393. extern "C" {
  87394. #endif
  87395. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87396. * \ingroup flac_metadata
  87397. *
  87398. * \brief
  87399. * The level 0 interface consists of individual routines to read the
  87400. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87401. * only a filename.
  87402. *
  87403. * They try to skip any ID3v2 tag at the head of the file.
  87404. *
  87405. * \{
  87406. */
  87407. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87408. * will try to skip any ID3v2 tag at the head of the file.
  87409. *
  87410. * \param filename The path to the FLAC file to read.
  87411. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87412. * FLAC__StreamMetadata is a simple structure with no
  87413. * memory allocation involved, you pass the address of
  87414. * an existing structure. It need not be initialized.
  87415. * \assert
  87416. * \code filename != NULL \endcode
  87417. * \code streaminfo != NULL \endcode
  87418. * \retval FLAC__bool
  87419. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87420. * \c false if there was a memory allocation error, a file decoder error,
  87421. * or the file contained no STREAMINFO block. (A memory allocation error
  87422. * is possible because this function must set up a file decoder.)
  87423. */
  87424. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87425. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87426. * function will try to skip any ID3v2 tag at the head of the file.
  87427. *
  87428. * \param filename The path to the FLAC file to read.
  87429. * \param tags The address where the returned pointer will be
  87430. * stored. The \a tags object must be deleted by
  87431. * the caller using FLAC__metadata_object_delete().
  87432. * \assert
  87433. * \code filename != NULL \endcode
  87434. * \code tags != NULL \endcode
  87435. * \retval FLAC__bool
  87436. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87437. * and \a *tags will be set to the address of the metadata structure.
  87438. * Returns \c false if there was a memory allocation error, a file
  87439. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87440. * \a *tags will be set to \c NULL.
  87441. */
  87442. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87443. /** Read the CUESHEET metadata block of the given FLAC file. This
  87444. * function will try to skip any ID3v2 tag at the head of the file.
  87445. *
  87446. * \param filename The path to the FLAC file to read.
  87447. * \param cuesheet The address where the returned pointer will be
  87448. * stored. The \a cuesheet object must be deleted by
  87449. * the caller using FLAC__metadata_object_delete().
  87450. * \assert
  87451. * \code filename != NULL \endcode
  87452. * \code cuesheet != NULL \endcode
  87453. * \retval FLAC__bool
  87454. * \c true if a valid CUESHEET block was read from \a filename,
  87455. * and \a *cuesheet will be set to the address of the metadata
  87456. * structure. Returns \c false if there was a memory allocation
  87457. * error, a file decoder error, or the file contained no CUESHEET
  87458. * block, and \a *cuesheet will be set to \c NULL.
  87459. */
  87460. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87461. /** Read a PICTURE metadata block of the given FLAC file. This
  87462. * function will try to skip any ID3v2 tag at the head of the file.
  87463. * Since there can be more than one PICTURE block in a file, this
  87464. * function takes a number of parameters that act as constraints to
  87465. * the search. The PICTURE block with the largest area matching all
  87466. * the constraints will be returned, or \a *picture will be set to
  87467. * \c NULL if there was no such block.
  87468. *
  87469. * \param filename The path to the FLAC file to read.
  87470. * \param picture The address where the returned pointer will be
  87471. * stored. The \a picture object must be deleted by
  87472. * the caller using FLAC__metadata_object_delete().
  87473. * \param type The desired picture type. Use \c -1 to mean
  87474. * "any type".
  87475. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87476. * string will be matched exactly. Use \c NULL to
  87477. * mean "any MIME type".
  87478. * \param description The desired description. The string will be
  87479. * matched exactly. Use \c NULL to mean "any
  87480. * description".
  87481. * \param max_width The maximum width in pixels desired. Use
  87482. * \c (unsigned)(-1) to mean "any width".
  87483. * \param max_height The maximum height in pixels desired. Use
  87484. * \c (unsigned)(-1) to mean "any height".
  87485. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87486. * Use \c (unsigned)(-1) to mean "any depth".
  87487. * \param max_colors The maximum number of colors desired. Use
  87488. * \c (unsigned)(-1) to mean "any number of colors".
  87489. * \assert
  87490. * \code filename != NULL \endcode
  87491. * \code picture != NULL \endcode
  87492. * \retval FLAC__bool
  87493. * \c true if a valid PICTURE block was read from \a filename,
  87494. * and \a *picture will be set to the address of the metadata
  87495. * structure. Returns \c false if there was a memory allocation
  87496. * error, a file decoder error, or the file contained no PICTURE
  87497. * block, and \a *picture will be set to \c NULL.
  87498. */
  87499. 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);
  87500. /* \} */
  87501. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87502. * \ingroup flac_metadata
  87503. *
  87504. * \brief
  87505. * The level 1 interface provides read-write access to FLAC file metadata and
  87506. * operates directly on the FLAC file.
  87507. *
  87508. * The general usage of this interface is:
  87509. *
  87510. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87511. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87512. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87513. * see if the file is writable, or only read access is allowed.
  87514. * - Use FLAC__metadata_simple_iterator_next() and
  87515. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87516. * This is does not read the actual blocks themselves.
  87517. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87518. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87519. * forward from the front of the file.
  87520. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87521. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87522. * the current iterator position. The returned object is yours to modify
  87523. * and free.
  87524. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87525. * back. You must have write permission to the original file. Make sure to
  87526. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87527. * below.
  87528. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87529. * Use the object creation functions from
  87530. * \link flac_metadata_object here \endlink to generate new objects.
  87531. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87532. * currently referred to by the iterator, or replace it with padding.
  87533. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87534. * finished.
  87535. *
  87536. * \note
  87537. * The FLAC file remains open the whole time between
  87538. * FLAC__metadata_simple_iterator_init() and
  87539. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87540. * the file during this time.
  87541. *
  87542. * \note
  87543. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87544. * FLAC__StreamMetadata objects. These are managed automatically.
  87545. *
  87546. * \note
  87547. * If any of the modification functions
  87548. * (FLAC__metadata_simple_iterator_set_block(),
  87549. * FLAC__metadata_simple_iterator_delete_block(),
  87550. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87551. * you should delete the iterator as it may no longer be valid.
  87552. *
  87553. * \{
  87554. */
  87555. struct FLAC__Metadata_SimpleIterator;
  87556. /** The opaque structure definition for the level 1 iterator type.
  87557. * See the
  87558. * \link flac_metadata_level1 metadata level 1 module \endlink
  87559. * for a detailed description.
  87560. */
  87561. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87562. /** Status type for FLAC__Metadata_SimpleIterator.
  87563. *
  87564. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87565. */
  87566. typedef enum {
  87567. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87568. /**< The iterator is in the normal OK state */
  87569. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87570. /**< The data passed into a function violated the function's usage criteria */
  87571. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87572. /**< The iterator could not open the target file */
  87573. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87574. /**< The iterator could not find the FLAC signature at the start of the file */
  87575. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87576. /**< The iterator tried to write to a file that was not writable */
  87577. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87578. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87579. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87580. /**< The iterator encountered an error while reading the FLAC file */
  87581. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87582. /**< The iterator encountered an error while seeking in the FLAC file */
  87583. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87584. /**< The iterator encountered an error while writing the FLAC file */
  87585. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87586. /**< The iterator encountered an error renaming the FLAC file */
  87587. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87588. /**< The iterator encountered an error removing the temporary file */
  87589. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87590. /**< Memory allocation failed */
  87591. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87592. /**< The caller violated an assertion or an unexpected error occurred */
  87593. } FLAC__Metadata_SimpleIteratorStatus;
  87594. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87595. *
  87596. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87597. * will give the string equivalent. The contents should not be modified.
  87598. */
  87599. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87600. /** Create a new iterator instance.
  87601. *
  87602. * \retval FLAC__Metadata_SimpleIterator*
  87603. * \c NULL if there was an error allocating memory, else the new instance.
  87604. */
  87605. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87606. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87607. *
  87608. * \param iterator A pointer to an existing iterator.
  87609. * \assert
  87610. * \code iterator != NULL \endcode
  87611. */
  87612. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87613. /** Get the current status of the iterator. Call this after a function
  87614. * returns \c false to get the reason for the error. Also resets the status
  87615. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87616. *
  87617. * \param iterator A pointer to an existing iterator.
  87618. * \assert
  87619. * \code iterator != NULL \endcode
  87620. * \retval FLAC__Metadata_SimpleIteratorStatus
  87621. * The current status of the iterator.
  87622. */
  87623. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87624. /** Initialize the iterator to point to the first metadata block in the
  87625. * given FLAC file.
  87626. *
  87627. * \param iterator A pointer to an existing iterator.
  87628. * \param filename The path to the FLAC file.
  87629. * \param read_only If \c true, the FLAC file will be opened
  87630. * in read-only mode; if \c false, the FLAC
  87631. * file will be opened for edit even if no
  87632. * edits are performed.
  87633. * \param preserve_file_stats If \c true, the owner and modification
  87634. * time will be preserved even if the FLAC
  87635. * file is written to.
  87636. * \assert
  87637. * \code iterator != NULL \endcode
  87638. * \code filename != NULL \endcode
  87639. * \retval FLAC__bool
  87640. * \c false if a memory allocation error occurs, the file can't be
  87641. * opened, or another error occurs, else \c true.
  87642. */
  87643. 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);
  87644. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87645. * FLAC__metadata_simple_iterator_set_block() and
  87646. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87647. *
  87648. * \param iterator A pointer to an existing iterator.
  87649. * \assert
  87650. * \code iterator != NULL \endcode
  87651. * \retval FLAC__bool
  87652. * See above.
  87653. */
  87654. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87655. /** Moves the iterator forward one metadata block, returning \c false if
  87656. * already at the end.
  87657. *
  87658. * \param iterator A pointer to an existing initialized iterator.
  87659. * \assert
  87660. * \code iterator != NULL \endcode
  87661. * \a iterator has been successfully initialized with
  87662. * FLAC__metadata_simple_iterator_init()
  87663. * \retval FLAC__bool
  87664. * \c false if already at the last metadata block of the chain, else
  87665. * \c true.
  87666. */
  87667. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87668. /** Moves the iterator backward one metadata block, returning \c false if
  87669. * already at the beginning.
  87670. *
  87671. * \param iterator A pointer to an existing initialized iterator.
  87672. * \assert
  87673. * \code iterator != NULL \endcode
  87674. * \a iterator has been successfully initialized with
  87675. * FLAC__metadata_simple_iterator_init()
  87676. * \retval FLAC__bool
  87677. * \c false if already at the first metadata block of the chain, else
  87678. * \c true.
  87679. */
  87680. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87681. /** Returns a flag telling if the current metadata block is the last.
  87682. *
  87683. * \param iterator A pointer to an existing initialized iterator.
  87684. * \assert
  87685. * \code iterator != NULL \endcode
  87686. * \a iterator has been successfully initialized with
  87687. * FLAC__metadata_simple_iterator_init()
  87688. * \retval FLAC__bool
  87689. * \c true if the current metadata block is the last in the file,
  87690. * else \c false.
  87691. */
  87692. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87693. /** Get the offset of the metadata block at the current position. This
  87694. * avoids reading the actual block data which can save time for large
  87695. * blocks.
  87696. *
  87697. * \param iterator A pointer to an existing initialized iterator.
  87698. * \assert
  87699. * \code iterator != NULL \endcode
  87700. * \a iterator has been successfully initialized with
  87701. * FLAC__metadata_simple_iterator_init()
  87702. * \retval off_t
  87703. * The offset of the metadata block at the current iterator position.
  87704. * This is the byte offset relative to the beginning of the file of
  87705. * the current metadata block's header.
  87706. */
  87707. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87708. /** Get the type of the metadata block at the current position. This
  87709. * avoids reading the actual block data which can save time for large
  87710. * blocks.
  87711. *
  87712. * \param iterator A pointer to an existing initialized iterator.
  87713. * \assert
  87714. * \code iterator != NULL \endcode
  87715. * \a iterator has been successfully initialized with
  87716. * FLAC__metadata_simple_iterator_init()
  87717. * \retval FLAC__MetadataType
  87718. * The type of the metadata block at the current iterator position.
  87719. */
  87720. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87721. /** Get the length of the metadata block at the current position. This
  87722. * avoids reading the actual block data which can save time for large
  87723. * blocks.
  87724. *
  87725. * \param iterator A pointer to an existing initialized iterator.
  87726. * \assert
  87727. * \code iterator != NULL \endcode
  87728. * \a iterator has been successfully initialized with
  87729. * FLAC__metadata_simple_iterator_init()
  87730. * \retval unsigned
  87731. * The length of the metadata block at the current iterator position.
  87732. * The is same length as that in the
  87733. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87734. * i.e. the length of the metadata body that follows the header.
  87735. */
  87736. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87737. /** Get the application ID of the \c APPLICATION block at the current
  87738. * position. This avoids reading the actual block data which can save
  87739. * time for large blocks.
  87740. *
  87741. * \param iterator A pointer to an existing initialized iterator.
  87742. * \param id A pointer to a buffer of at least \c 4 bytes where
  87743. * the ID will be stored.
  87744. * \assert
  87745. * \code iterator != NULL \endcode
  87746. * \code id != NULL \endcode
  87747. * \a iterator has been successfully initialized with
  87748. * FLAC__metadata_simple_iterator_init()
  87749. * \retval FLAC__bool
  87750. * \c true if the ID was successfully read, else \c false, in which
  87751. * case you should check FLAC__metadata_simple_iterator_status() to
  87752. * find out why. If the status is
  87753. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87754. * current metadata block is not an \c APPLICATION block. Otherwise
  87755. * if the status is
  87756. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87757. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87758. * occurred and the iterator can no longer be used.
  87759. */
  87760. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87761. /** Get the metadata block at the current position. You can modify the
  87762. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87763. * write it back to the FLAC file.
  87764. *
  87765. * You must call FLAC__metadata_object_delete() on the returned object
  87766. * when you are finished with it.
  87767. *
  87768. * \param iterator A pointer to an existing initialized iterator.
  87769. * \assert
  87770. * \code iterator != NULL \endcode
  87771. * \a iterator has been successfully initialized with
  87772. * FLAC__metadata_simple_iterator_init()
  87773. * \retval FLAC__StreamMetadata*
  87774. * The current metadata block, or \c NULL if there was a memory
  87775. * allocation error.
  87776. */
  87777. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87778. /** Write a block back to the FLAC file. This function tries to be
  87779. * as efficient as possible; how the block is actually written is
  87780. * shown by the following:
  87781. *
  87782. * Existing block is a STREAMINFO block and the new block is a
  87783. * STREAMINFO block: the new block is written in place. Make sure
  87784. * you know what you're doing when changing the values of a
  87785. * STREAMINFO block.
  87786. *
  87787. * Existing block is a STREAMINFO block and the new block is a
  87788. * not a STREAMINFO block: this is an error since the first block
  87789. * must be a STREAMINFO block. Returns \c false without altering the
  87790. * file.
  87791. *
  87792. * Existing block is not a STREAMINFO block and the new block is a
  87793. * STREAMINFO block: this is an error since there may be only one
  87794. * STREAMINFO block. Returns \c false without altering the file.
  87795. *
  87796. * Existing block and new block are the same length: the existing
  87797. * block will be replaced by the new block, written in place.
  87798. *
  87799. * Existing block is longer than new block: if use_padding is \c true,
  87800. * the existing block will be overwritten in place with the new
  87801. * block followed by a PADDING block, if possible, to make the total
  87802. * size the same as the existing block. Remember that a padding
  87803. * block requires at least four bytes so if the difference in size
  87804. * between the new block and existing block is less than that, the
  87805. * entire file will have to be rewritten, using the new block's
  87806. * exact size. If use_padding is \c false, the entire file will be
  87807. * rewritten, replacing the existing block by the new block.
  87808. *
  87809. * Existing block is shorter than new block: if use_padding is \c true,
  87810. * the function will try and expand the new block into the following
  87811. * PADDING block, if it exists and doing so won't shrink the PADDING
  87812. * block to less than 4 bytes. If there is no following PADDING
  87813. * block, or it will shrink to less than 4 bytes, or use_padding is
  87814. * \c false, the entire file is rewritten, replacing the existing block
  87815. * with the new block. Note that in this case any following PADDING
  87816. * block is preserved as is.
  87817. *
  87818. * After writing the block, the iterator will remain in the same
  87819. * place, i.e. pointing to the new block.
  87820. *
  87821. * \param iterator A pointer to an existing initialized iterator.
  87822. * \param block The block to set.
  87823. * \param use_padding See above.
  87824. * \assert
  87825. * \code iterator != NULL \endcode
  87826. * \a iterator has been successfully initialized with
  87827. * FLAC__metadata_simple_iterator_init()
  87828. * \code block != NULL \endcode
  87829. * \retval FLAC__bool
  87830. * \c true if successful, else \c false.
  87831. */
  87832. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87833. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87834. * except that instead of writing over an existing block, it appends
  87835. * a block after the existing block. \a use_padding is again used to
  87836. * tell the function to try an expand into following padding in an
  87837. * attempt to avoid rewriting the entire file.
  87838. *
  87839. * This function will fail and return \c false if given a STREAMINFO
  87840. * block.
  87841. *
  87842. * After writing the block, the iterator will be pointing to the
  87843. * new block.
  87844. *
  87845. * \param iterator A pointer to an existing initialized iterator.
  87846. * \param block The block to set.
  87847. * \param use_padding See above.
  87848. * \assert
  87849. * \code iterator != NULL \endcode
  87850. * \a iterator has been successfully initialized with
  87851. * FLAC__metadata_simple_iterator_init()
  87852. * \code block != NULL \endcode
  87853. * \retval FLAC__bool
  87854. * \c true if successful, else \c false.
  87855. */
  87856. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87857. /** Deletes the block at the current position. This will cause the
  87858. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87859. * in which case the block will be replaced by an equal-sized PADDING
  87860. * block. The iterator will be left pointing to the block before the
  87861. * one just deleted.
  87862. *
  87863. * You may not delete the STREAMINFO block.
  87864. *
  87865. * \param iterator A pointer to an existing initialized iterator.
  87866. * \param use_padding See above.
  87867. * \assert
  87868. * \code iterator != NULL \endcode
  87869. * \a iterator has been successfully initialized with
  87870. * FLAC__metadata_simple_iterator_init()
  87871. * \retval FLAC__bool
  87872. * \c true if successful, else \c false.
  87873. */
  87874. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87875. /* \} */
  87876. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87877. * \ingroup flac_metadata
  87878. *
  87879. * \brief
  87880. * The level 2 interface provides read-write access to FLAC file metadata;
  87881. * all metadata is read into memory, operated on in memory, and then written
  87882. * to file, which is more efficient than level 1 when editing multiple blocks.
  87883. *
  87884. * Currently Ogg FLAC is supported for read only, via
  87885. * FLAC__metadata_chain_read_ogg() but a subsequent
  87886. * FLAC__metadata_chain_write() will fail.
  87887. *
  87888. * The general usage of this interface is:
  87889. *
  87890. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87891. * linked list of FLAC metadata blocks.
  87892. * - Read all metadata into the the chain from a FLAC file using
  87893. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87894. * check the status.
  87895. * - Optionally, consolidate the padding using
  87896. * FLAC__metadata_chain_merge_padding() or
  87897. * FLAC__metadata_chain_sort_padding().
  87898. * - Create a new iterator using FLAC__metadata_iterator_new()
  87899. * - Initialize the iterator to point to the first element in the chain
  87900. * using FLAC__metadata_iterator_init()
  87901. * - Traverse the chain using FLAC__metadata_iterator_next and
  87902. * FLAC__metadata_iterator_prev().
  87903. * - Get a block for reading or modification using
  87904. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87905. * inside the chain is returned, so the block is yours to modify.
  87906. * Changes will be reflected in the FLAC file when you write the
  87907. * chain. You can also add and delete blocks (see functions below).
  87908. * - When done, write out the chain using FLAC__metadata_chain_write().
  87909. * Make sure to read the whole comment to the function below.
  87910. * - Delete the chain using FLAC__metadata_chain_delete().
  87911. *
  87912. * \note
  87913. * Even though the FLAC file is not open while the chain is being
  87914. * manipulated, you must not alter the file externally during
  87915. * this time. The chain assumes the FLAC file will not change
  87916. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87917. * and FLAC__metadata_chain_write().
  87918. *
  87919. * \note
  87920. * Do not modify the is_last, length, or type fields of returned
  87921. * FLAC__StreamMetadata objects. These are managed automatically.
  87922. *
  87923. * \note
  87924. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87925. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87926. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87927. * become owned by the chain and they will be deleted when the chain is
  87928. * deleted.
  87929. *
  87930. * \{
  87931. */
  87932. struct FLAC__Metadata_Chain;
  87933. /** The opaque structure definition for the level 2 chain type.
  87934. */
  87935. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87936. struct FLAC__Metadata_Iterator;
  87937. /** The opaque structure definition for the level 2 iterator type.
  87938. */
  87939. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87940. typedef enum {
  87941. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87942. /**< The chain is in the normal OK state */
  87943. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87944. /**< The data passed into a function violated the function's usage criteria */
  87945. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87946. /**< The chain could not open the target file */
  87947. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87948. /**< The chain could not find the FLAC signature at the start of the file */
  87949. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87950. /**< The chain tried to write to a file that was not writable */
  87951. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87952. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87953. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87954. /**< The chain encountered an error while reading the FLAC file */
  87955. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87956. /**< The chain encountered an error while seeking in the FLAC file */
  87957. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87958. /**< The chain encountered an error while writing the FLAC file */
  87959. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87960. /**< The chain encountered an error renaming the FLAC file */
  87961. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87962. /**< The chain encountered an error removing the temporary file */
  87963. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87964. /**< Memory allocation failed */
  87965. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87966. /**< The caller violated an assertion or an unexpected error occurred */
  87967. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87968. /**< One or more of the required callbacks was NULL */
  87969. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87970. /**< FLAC__metadata_chain_write() was called on a chain read by
  87971. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87972. * or
  87973. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87974. * was called on a chain read by
  87975. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87976. * Matching read/write methods must always be used. */
  87977. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87978. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87979. * chain write requires a tempfile; use
  87980. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87981. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87982. * called when the chain write does not require a tempfile; use
  87983. * FLAC__metadata_chain_write_with_callbacks() instead.
  87984. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87985. * before writing via callbacks. */
  87986. } FLAC__Metadata_ChainStatus;
  87987. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87988. *
  87989. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87990. * will give the string equivalent. The contents should not be modified.
  87991. */
  87992. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87993. /*********** FLAC__Metadata_Chain ***********/
  87994. /** Create a new chain instance.
  87995. *
  87996. * \retval FLAC__Metadata_Chain*
  87997. * \c NULL if there was an error allocating memory, else the new instance.
  87998. */
  87999. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88000. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88001. *
  88002. * \param chain A pointer to an existing chain.
  88003. * \assert
  88004. * \code chain != NULL \endcode
  88005. */
  88006. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88007. /** Get the current status of the chain. Call this after a function
  88008. * returns \c false to get the reason for the error. Also resets the
  88009. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88010. *
  88011. * \param chain A pointer to an existing chain.
  88012. * \assert
  88013. * \code chain != NULL \endcode
  88014. * \retval FLAC__Metadata_ChainStatus
  88015. * The current status of the chain.
  88016. */
  88017. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88018. /** Read all metadata from a FLAC file into the chain.
  88019. *
  88020. * \param chain A pointer to an existing chain.
  88021. * \param filename The path to the FLAC file to read.
  88022. * \assert
  88023. * \code chain != NULL \endcode
  88024. * \code filename != NULL \endcode
  88025. * \retval FLAC__bool
  88026. * \c true if a valid list of metadata blocks was read from
  88027. * \a filename, else \c false. On failure, check the status with
  88028. * FLAC__metadata_chain_status().
  88029. */
  88030. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88031. /** Read all metadata from an Ogg FLAC file into the chain.
  88032. *
  88033. * \note Ogg FLAC metadata data writing is not supported yet and
  88034. * FLAC__metadata_chain_write() will fail.
  88035. *
  88036. * \param chain A pointer to an existing chain.
  88037. * \param filename The path to the Ogg FLAC file to read.
  88038. * \assert
  88039. * \code chain != NULL \endcode
  88040. * \code filename != NULL \endcode
  88041. * \retval FLAC__bool
  88042. * \c true if a valid list of metadata blocks was read from
  88043. * \a filename, else \c false. On failure, check the status with
  88044. * FLAC__metadata_chain_status().
  88045. */
  88046. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88047. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88048. *
  88049. * The \a handle need only be open for reading, but must be seekable.
  88050. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88051. * for Windows).
  88052. *
  88053. * \param chain A pointer to an existing chain.
  88054. * \param handle The I/O handle of the FLAC stream to read. The
  88055. * handle will NOT be closed after the metadata is read;
  88056. * that is the duty of the caller.
  88057. * \param callbacks
  88058. * A set of callbacks to use for I/O. The mandatory
  88059. * callbacks are \a read, \a seek, and \a tell.
  88060. * \assert
  88061. * \code chain != NULL \endcode
  88062. * \retval FLAC__bool
  88063. * \c true if a valid list of metadata blocks was read from
  88064. * \a handle, else \c false. On failure, check the status with
  88065. * FLAC__metadata_chain_status().
  88066. */
  88067. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88068. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88069. *
  88070. * The \a handle need only be open for reading, but must be seekable.
  88071. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88072. * for Windows).
  88073. *
  88074. * \note Ogg FLAC metadata data writing is not supported yet and
  88075. * FLAC__metadata_chain_write() will fail.
  88076. *
  88077. * \param chain A pointer to an existing chain.
  88078. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88079. * handle will NOT be closed after the metadata is read;
  88080. * that is the duty of the caller.
  88081. * \param callbacks
  88082. * A set of callbacks to use for I/O. The mandatory
  88083. * callbacks are \a read, \a seek, and \a tell.
  88084. * \assert
  88085. * \code chain != NULL \endcode
  88086. * \retval FLAC__bool
  88087. * \c true if a valid list of metadata blocks was read from
  88088. * \a handle, else \c false. On failure, check the status with
  88089. * FLAC__metadata_chain_status().
  88090. */
  88091. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88092. /** Checks if writing the given chain would require the use of a
  88093. * temporary file, or if it could be written in place.
  88094. *
  88095. * Under certain conditions, padding can be utilized so that writing
  88096. * edited metadata back to the FLAC file does not require rewriting the
  88097. * entire file. If rewriting is required, then a temporary workfile is
  88098. * required. When writing metadata using callbacks, you must check
  88099. * this function to know whether to call
  88100. * FLAC__metadata_chain_write_with_callbacks() or
  88101. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88102. * writing with FLAC__metadata_chain_write(), the temporary file is
  88103. * handled internally.
  88104. *
  88105. * \param chain A pointer to an existing chain.
  88106. * \param use_padding
  88107. * Whether or not padding will be allowed to be used
  88108. * during the write. The value of \a use_padding given
  88109. * here must match the value later passed to
  88110. * FLAC__metadata_chain_write_with_callbacks() or
  88111. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88112. * \assert
  88113. * \code chain != NULL \endcode
  88114. * \retval FLAC__bool
  88115. * \c true if writing the current chain would require a tempfile, or
  88116. * \c false if metadata can be written in place.
  88117. */
  88118. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88119. /** Write all metadata out to the FLAC file. This function tries to be as
  88120. * efficient as possible; how the metadata is actually written is shown by
  88121. * the following:
  88122. *
  88123. * If the current chain is the same size as the existing metadata, the new
  88124. * data is written in place.
  88125. *
  88126. * If the current chain is longer than the existing metadata, and
  88127. * \a use_padding is \c true, and the last block is a PADDING block of
  88128. * sufficient length, the function will truncate the final padding block
  88129. * so that the overall size of the metadata is the same as the existing
  88130. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88131. * the above conditions are met, the entire FLAC file must be rewritten.
  88132. * If you want to use padding this way it is a good idea to call
  88133. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88134. * amount of padding to work with, unless you need to preserve ordering
  88135. * of the PADDING blocks for some reason.
  88136. *
  88137. * If the current chain is shorter than the existing metadata, and
  88138. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88139. * is extended to make the overall size the same as the existing data. If
  88140. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88141. * PADDING block is added to the end of the new data to make it the same
  88142. * size as the existing data (if possible, see the note to
  88143. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88144. * and the new data is written in place. If none of the above apply or
  88145. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88146. *
  88147. * If \a preserve_file_stats is \c true, the owner and modification time will
  88148. * be preserved even if the FLAC file is written.
  88149. *
  88150. * For this write function to be used, the chain must have been read with
  88151. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88152. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88153. *
  88154. * \param chain A pointer to an existing chain.
  88155. * \param use_padding See above.
  88156. * \param preserve_file_stats See above.
  88157. * \assert
  88158. * \code chain != NULL \endcode
  88159. * \retval FLAC__bool
  88160. * \c true if the write succeeded, else \c false. On failure,
  88161. * check the status with FLAC__metadata_chain_status().
  88162. */
  88163. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88164. /** Write all metadata out to a FLAC stream via callbacks.
  88165. *
  88166. * (See FLAC__metadata_chain_write() for the details on how padding is
  88167. * used to write metadata in place if possible.)
  88168. *
  88169. * The \a handle must be open for updating and be seekable. The
  88170. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88171. * for Windows).
  88172. *
  88173. * For this write function to be used, the chain must have been read with
  88174. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88175. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88176. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88177. * \c false.
  88178. *
  88179. * \param chain A pointer to an existing chain.
  88180. * \param use_padding See FLAC__metadata_chain_write()
  88181. * \param handle The I/O handle of the FLAC stream to write. The
  88182. * handle will NOT be closed after the metadata is
  88183. * written; that is the duty of the caller.
  88184. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88185. * callbacks are \a write and \a seek.
  88186. * \assert
  88187. * \code chain != NULL \endcode
  88188. * \retval FLAC__bool
  88189. * \c true if the write succeeded, else \c false. On failure,
  88190. * check the status with FLAC__metadata_chain_status().
  88191. */
  88192. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88193. /** Write all metadata out to a FLAC stream via callbacks.
  88194. *
  88195. * (See FLAC__metadata_chain_write() for the details on how padding is
  88196. * used to write metadata in place if possible.)
  88197. *
  88198. * This version of the write-with-callbacks function must be used when
  88199. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88200. * this function, you must supply an I/O handle corresponding to the
  88201. * FLAC file to edit, and a temporary handle to which the new FLAC
  88202. * file will be written. It is the caller's job to move this temporary
  88203. * FLAC file on top of the original FLAC file to complete the metadata
  88204. * edit.
  88205. *
  88206. * The \a handle must be open for reading and be seekable. The
  88207. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88208. * for Windows).
  88209. *
  88210. * The \a temp_handle must be open for writing. The
  88211. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88212. * for Windows). It should be an empty stream, or at least positioned
  88213. * at the start-of-file (in which case it is the caller's duty to
  88214. * truncate it on return).
  88215. *
  88216. * For this write function to be used, the chain must have been read with
  88217. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88218. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88219. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88220. * \c true.
  88221. *
  88222. * \param chain A pointer to an existing chain.
  88223. * \param use_padding See FLAC__metadata_chain_write()
  88224. * \param handle The I/O handle of the original FLAC stream to read.
  88225. * The handle will NOT be closed after the metadata is
  88226. * written; that is the duty of the caller.
  88227. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88228. * The mandatory callbacks are \a read, \a seek, and
  88229. * \a eof.
  88230. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88231. * handle will NOT be closed after the metadata is
  88232. * written; that is the duty of the caller.
  88233. * \param temp_callbacks
  88234. * A set of callbacks to use for I/O on temp_handle.
  88235. * The only mandatory callback is \a write.
  88236. * \assert
  88237. * \code chain != NULL \endcode
  88238. * \retval FLAC__bool
  88239. * \c true if the write succeeded, else \c false. On failure,
  88240. * check the status with FLAC__metadata_chain_status().
  88241. */
  88242. 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);
  88243. /** Merge adjacent PADDING blocks into a single block.
  88244. *
  88245. * \note This function does not write to the FLAC file, it only
  88246. * modifies the chain.
  88247. *
  88248. * \warning Any iterator on the current chain will become invalid after this
  88249. * call. You should delete the iterator and get a new one.
  88250. *
  88251. * \param chain A pointer to an existing chain.
  88252. * \assert
  88253. * \code chain != NULL \endcode
  88254. */
  88255. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88256. /** This function will move all PADDING blocks to the end on the metadata,
  88257. * then merge them into a single block.
  88258. *
  88259. * \note This function does not write to the FLAC file, it only
  88260. * modifies the chain.
  88261. *
  88262. * \warning Any iterator on the current chain will become invalid after this
  88263. * call. You should delete the iterator and get a new one.
  88264. *
  88265. * \param chain A pointer to an existing chain.
  88266. * \assert
  88267. * \code chain != NULL \endcode
  88268. */
  88269. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88270. /*********** FLAC__Metadata_Iterator ***********/
  88271. /** Create a new iterator instance.
  88272. *
  88273. * \retval FLAC__Metadata_Iterator*
  88274. * \c NULL if there was an error allocating memory, else the new instance.
  88275. */
  88276. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88277. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88278. *
  88279. * \param iterator A pointer to an existing iterator.
  88280. * \assert
  88281. * \code iterator != NULL \endcode
  88282. */
  88283. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88284. /** Initialize the iterator to point to the first metadata block in the
  88285. * given chain.
  88286. *
  88287. * \param iterator A pointer to an existing iterator.
  88288. * \param chain A pointer to an existing and initialized (read) chain.
  88289. * \assert
  88290. * \code iterator != NULL \endcode
  88291. * \code chain != NULL \endcode
  88292. */
  88293. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88294. /** Moves the iterator forward one metadata block, returning \c false if
  88295. * already at the end.
  88296. *
  88297. * \param iterator A pointer to an existing initialized iterator.
  88298. * \assert
  88299. * \code iterator != NULL \endcode
  88300. * \a iterator has been successfully initialized with
  88301. * FLAC__metadata_iterator_init()
  88302. * \retval FLAC__bool
  88303. * \c false if already at the last metadata block of the chain, else
  88304. * \c true.
  88305. */
  88306. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88307. /** Moves the iterator backward one metadata block, returning \c false if
  88308. * already at the beginning.
  88309. *
  88310. * \param iterator A pointer to an existing initialized iterator.
  88311. * \assert
  88312. * \code iterator != NULL \endcode
  88313. * \a iterator has been successfully initialized with
  88314. * FLAC__metadata_iterator_init()
  88315. * \retval FLAC__bool
  88316. * \c false if already at the first metadata block of the chain, else
  88317. * \c true.
  88318. */
  88319. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88320. /** Get the type of the metadata block at the current position.
  88321. *
  88322. * \param iterator A pointer to an existing initialized iterator.
  88323. * \assert
  88324. * \code iterator != NULL \endcode
  88325. * \a iterator has been successfully initialized with
  88326. * FLAC__metadata_iterator_init()
  88327. * \retval FLAC__MetadataType
  88328. * The type of the metadata block at the current iterator position.
  88329. */
  88330. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88331. /** Get the metadata block at the current position. You can modify
  88332. * the block in place but must write the chain before the changes
  88333. * are reflected to the FLAC file. You do not need to call
  88334. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88335. * the pointer returned by FLAC__metadata_iterator_get_block()
  88336. * points directly into the chain.
  88337. *
  88338. * \warning
  88339. * Do not call FLAC__metadata_object_delete() on the returned object;
  88340. * to delete a block use FLAC__metadata_iterator_delete_block().
  88341. *
  88342. * \param iterator A pointer to an existing initialized iterator.
  88343. * \assert
  88344. * \code iterator != NULL \endcode
  88345. * \a iterator has been successfully initialized with
  88346. * FLAC__metadata_iterator_init()
  88347. * \retval FLAC__StreamMetadata*
  88348. * The current metadata block.
  88349. */
  88350. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88351. /** Set the metadata block at the current position, replacing the existing
  88352. * block. The new block passed in becomes owned by the chain and it will be
  88353. * deleted when the chain is deleted.
  88354. *
  88355. * \param iterator A pointer to an existing initialized iterator.
  88356. * \param block A pointer to a metadata block.
  88357. * \assert
  88358. * \code iterator != NULL \endcode
  88359. * \a iterator has been successfully initialized with
  88360. * FLAC__metadata_iterator_init()
  88361. * \code block != NULL \endcode
  88362. * \retval FLAC__bool
  88363. * \c false if the conditions in the above description are not met, or
  88364. * a memory allocation error occurs, otherwise \c true.
  88365. */
  88366. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88367. /** Removes the current block from the chain. If \a replace_with_padding is
  88368. * \c true, the block will instead be replaced with a padding block of equal
  88369. * size. You can not delete the STREAMINFO block. The iterator will be
  88370. * left pointing to the block before the one just "deleted", even if
  88371. * \a replace_with_padding is \c true.
  88372. *
  88373. * \param iterator A pointer to an existing initialized iterator.
  88374. * \param replace_with_padding See above.
  88375. * \assert
  88376. * \code iterator != NULL \endcode
  88377. * \a iterator has been successfully initialized with
  88378. * FLAC__metadata_iterator_init()
  88379. * \retval FLAC__bool
  88380. * \c false if the conditions in the above description are not met,
  88381. * otherwise \c true.
  88382. */
  88383. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88384. /** Insert a new block before the current block. You cannot insert a block
  88385. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88386. * as there can be only one, the one that already exists at the head when you
  88387. * read in a chain. The chain takes ownership of the new block and it will be
  88388. * deleted when the chain is deleted. The iterator will be left pointing to
  88389. * the new block.
  88390. *
  88391. * \param iterator A pointer to an existing initialized iterator.
  88392. * \param block A pointer to a metadata block to insert.
  88393. * \assert
  88394. * \code iterator != NULL \endcode
  88395. * \a iterator has been successfully initialized with
  88396. * FLAC__metadata_iterator_init()
  88397. * \retval FLAC__bool
  88398. * \c false if the conditions in the above description are not met, or
  88399. * a memory allocation error occurs, otherwise \c true.
  88400. */
  88401. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88402. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88403. * block as there can be only one, the one that already exists at the head when
  88404. * you read in a chain. The chain takes ownership of the new block and it will
  88405. * be deleted when the chain is deleted. The iterator will be left pointing to
  88406. * the new block.
  88407. *
  88408. * \param iterator A pointer to an existing initialized iterator.
  88409. * \param block A pointer to a metadata block to insert.
  88410. * \assert
  88411. * \code iterator != NULL \endcode
  88412. * \a iterator has been successfully initialized with
  88413. * FLAC__metadata_iterator_init()
  88414. * \retval FLAC__bool
  88415. * \c false if the conditions in the above description are not met, or
  88416. * a memory allocation error occurs, otherwise \c true.
  88417. */
  88418. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88419. /* \} */
  88420. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88421. * \ingroup flac_metadata
  88422. *
  88423. * \brief
  88424. * This module contains methods for manipulating FLAC metadata objects.
  88425. *
  88426. * Since many are variable length we have to be careful about the memory
  88427. * management. We decree that all pointers to data in the object are
  88428. * owned by the object and memory-managed by the object.
  88429. *
  88430. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88431. * functions to create all instances. When using the
  88432. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88433. * \a copy to \c true to have the function make it's own copy of the data, or
  88434. * to \c false to give the object ownership of your data. In the latter case
  88435. * your pointer must be freeable by free() and will be free()d when the object
  88436. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88437. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88438. * the length argument is 0 and the \a copy argument is \c false.
  88439. *
  88440. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88441. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88442. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88443. * case of a memory allocation error.
  88444. *
  88445. * We don't have the convenience of C++ here, so note that the library relies
  88446. * on you to keep the types straight. In other words, if you pass, for
  88447. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88448. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88449. * failure.
  88450. *
  88451. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88452. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88453. * toward the length or stored in the stream, but it can make working with plain
  88454. * comments (those that don't contain embedded-NULs in the value) easier.
  88455. * Entries passed into these functions have trailing NULs added if missing, and
  88456. * returned entries are guaranteed to have a trailing NUL.
  88457. *
  88458. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88459. * comment entry/name/value will first validate that it complies with the Vorbis
  88460. * comment specification and return false if it does not.
  88461. *
  88462. * There is no need to recalculate the length field on metadata blocks you
  88463. * have modified. They will be calculated automatically before they are
  88464. * written back to a file.
  88465. *
  88466. * \{
  88467. */
  88468. /** Create a new metadata object instance of the given type.
  88469. *
  88470. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88471. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88472. * the vendor string set (but zero comments).
  88473. *
  88474. * Do not pass in a value greater than or equal to
  88475. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88476. * doing.
  88477. *
  88478. * \param type Type of object to create
  88479. * \retval FLAC__StreamMetadata*
  88480. * \c NULL if there was an error allocating memory or the type code is
  88481. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88482. */
  88483. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88484. /** Create a copy of an existing metadata object.
  88485. *
  88486. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88487. * object is also copied. The caller takes ownership of the new block and
  88488. * is responsible for freeing it with FLAC__metadata_object_delete().
  88489. *
  88490. * \param object Pointer to object to copy.
  88491. * \assert
  88492. * \code object != NULL \endcode
  88493. * \retval FLAC__StreamMetadata*
  88494. * \c NULL if there was an error allocating memory, else the new instance.
  88495. */
  88496. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88497. /** Free a metadata object. Deletes the object pointed to by \a object.
  88498. *
  88499. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88500. * object is also deleted.
  88501. *
  88502. * \param object A pointer to an existing object.
  88503. * \assert
  88504. * \code object != NULL \endcode
  88505. */
  88506. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88507. /** Compares two metadata objects.
  88508. *
  88509. * The compare is "deep", i.e. dynamically allocated data within the
  88510. * object is also compared.
  88511. *
  88512. * \param block1 A pointer to an existing object.
  88513. * \param block2 A pointer to an existing object.
  88514. * \assert
  88515. * \code block1 != NULL \endcode
  88516. * \code block2 != NULL \endcode
  88517. * \retval FLAC__bool
  88518. * \c true if objects are identical, else \c false.
  88519. */
  88520. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88521. /** Sets the application data of an APPLICATION block.
  88522. *
  88523. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88524. * takes ownership of the pointer. The existing data will be freed if this
  88525. * function is successful, otherwise the original data will remain if \a copy
  88526. * is \c true and malloc() fails.
  88527. *
  88528. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88529. *
  88530. * \param object A pointer to an existing APPLICATION object.
  88531. * \param data A pointer to the data to set.
  88532. * \param length The length of \a data in bytes.
  88533. * \param copy See above.
  88534. * \assert
  88535. * \code object != NULL \endcode
  88536. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88537. * \code (data != NULL && length > 0) ||
  88538. * (data == NULL && length == 0 && copy == false) \endcode
  88539. * \retval FLAC__bool
  88540. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88541. */
  88542. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88543. /** Resize the seekpoint array.
  88544. *
  88545. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88546. * points will be added to the end.
  88547. *
  88548. * \param object A pointer to an existing SEEKTABLE object.
  88549. * \param new_num_points The desired length of the array; may be \c 0.
  88550. * \assert
  88551. * \code object != NULL \endcode
  88552. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88553. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88554. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88555. * \retval FLAC__bool
  88556. * \c false if memory allocation error, else \c true.
  88557. */
  88558. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88559. /** Set a seekpoint in a seektable.
  88560. *
  88561. * \param object A pointer to an existing SEEKTABLE object.
  88562. * \param point_num Index into seekpoint array to set.
  88563. * \param point The point to set.
  88564. * \assert
  88565. * \code object != NULL \endcode
  88566. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88567. * \code object->data.seek_table.num_points > point_num \endcode
  88568. */
  88569. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88570. /** Insert a seekpoint into a seektable.
  88571. *
  88572. * \param object A pointer to an existing SEEKTABLE object.
  88573. * \param point_num Index into seekpoint array to set.
  88574. * \param point The point to set.
  88575. * \assert
  88576. * \code object != NULL \endcode
  88577. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88578. * \code object->data.seek_table.num_points >= point_num \endcode
  88579. * \retval FLAC__bool
  88580. * \c false if memory allocation error, else \c true.
  88581. */
  88582. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88583. /** Delete a seekpoint from a seektable.
  88584. *
  88585. * \param object A pointer to an existing SEEKTABLE object.
  88586. * \param point_num Index into seekpoint array to set.
  88587. * \assert
  88588. * \code object != NULL \endcode
  88589. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88590. * \code object->data.seek_table.num_points > point_num \endcode
  88591. * \retval FLAC__bool
  88592. * \c false if memory allocation error, else \c true.
  88593. */
  88594. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88595. /** Check a seektable to see if it conforms to the FLAC specification.
  88596. * See the format specification for limits on the contents of the
  88597. * seektable.
  88598. *
  88599. * \param object A pointer to an existing SEEKTABLE object.
  88600. * \assert
  88601. * \code object != NULL \endcode
  88602. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88603. * \retval FLAC__bool
  88604. * \c false if seek table is illegal, else \c true.
  88605. */
  88606. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88607. /** Append a number of placeholder points to the end of a seek table.
  88608. *
  88609. * \note
  88610. * As with the other ..._seektable_template_... functions, you should
  88611. * call FLAC__metadata_object_seektable_template_sort() when finished
  88612. * to make the seek table legal.
  88613. *
  88614. * \param object A pointer to an existing SEEKTABLE object.
  88615. * \param num The number of placeholder points to append.
  88616. * \assert
  88617. * \code object != NULL \endcode
  88618. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88619. * \retval FLAC__bool
  88620. * \c false if memory allocation fails, else \c true.
  88621. */
  88622. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88623. /** Append a specific seek point template to the end of a seek table.
  88624. *
  88625. * \note
  88626. * As with the other ..._seektable_template_... functions, you should
  88627. * call FLAC__metadata_object_seektable_template_sort() when finished
  88628. * to make the seek table legal.
  88629. *
  88630. * \param object A pointer to an existing SEEKTABLE object.
  88631. * \param sample_number The sample number of the seek point template.
  88632. * \assert
  88633. * \code object != NULL \endcode
  88634. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88635. * \retval FLAC__bool
  88636. * \c false if memory allocation fails, else \c true.
  88637. */
  88638. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88639. /** Append specific seek point templates to the end of a seek table.
  88640. *
  88641. * \note
  88642. * As with the other ..._seektable_template_... functions, you should
  88643. * call FLAC__metadata_object_seektable_template_sort() when finished
  88644. * to make the seek table legal.
  88645. *
  88646. * \param object A pointer to an existing SEEKTABLE object.
  88647. * \param sample_numbers An array of sample numbers for the seek points.
  88648. * \param num The number of seek point templates to append.
  88649. * \assert
  88650. * \code object != NULL \endcode
  88651. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88652. * \retval FLAC__bool
  88653. * \c false if memory allocation fails, else \c true.
  88654. */
  88655. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88656. /** Append a set of evenly-spaced seek point templates to the end of a
  88657. * seek table.
  88658. *
  88659. * \note
  88660. * As with the other ..._seektable_template_... functions, you should
  88661. * call FLAC__metadata_object_seektable_template_sort() when finished
  88662. * to make the seek table legal.
  88663. *
  88664. * \param object A pointer to an existing SEEKTABLE object.
  88665. * \param num The number of placeholder points to append.
  88666. * \param total_samples The total number of samples to be encoded;
  88667. * the seekpoints will be spaced approximately
  88668. * \a total_samples / \a num samples apart.
  88669. * \assert
  88670. * \code object != NULL \endcode
  88671. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88672. * \code total_samples > 0 \endcode
  88673. * \retval FLAC__bool
  88674. * \c false if memory allocation fails, else \c true.
  88675. */
  88676. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88677. /** Append a set of evenly-spaced seek point templates to the end of a
  88678. * seek table.
  88679. *
  88680. * \note
  88681. * As with the other ..._seektable_template_... functions, you should
  88682. * call FLAC__metadata_object_seektable_template_sort() when finished
  88683. * to make the seek table legal.
  88684. *
  88685. * \param object A pointer to an existing SEEKTABLE object.
  88686. * \param samples The number of samples apart to space the placeholder
  88687. * points. The first point will be at sample \c 0, the
  88688. * second at sample \a samples, then 2*\a samples, and
  88689. * so on. As long as \a samples and \a total_samples
  88690. * are greater than \c 0, there will always be at least
  88691. * one seekpoint at sample \c 0.
  88692. * \param total_samples The total number of samples to be encoded;
  88693. * the seekpoints will be spaced
  88694. * \a samples samples apart.
  88695. * \assert
  88696. * \code object != NULL \endcode
  88697. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88698. * \code samples > 0 \endcode
  88699. * \code total_samples > 0 \endcode
  88700. * \retval FLAC__bool
  88701. * \c false if memory allocation fails, else \c true.
  88702. */
  88703. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88704. /** Sort a seek table's seek points according to the format specification,
  88705. * removing duplicates.
  88706. *
  88707. * \param object A pointer to a seek table to be sorted.
  88708. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88709. * If \c true, duplicates are deleted and the seek table is
  88710. * shrunk appropriately; the number of placeholder points
  88711. * present in the seek table will be the same after the call
  88712. * as before.
  88713. * \assert
  88714. * \code object != NULL \endcode
  88715. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88716. * \retval FLAC__bool
  88717. * \c false if realloc() fails, else \c true.
  88718. */
  88719. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88720. /** Sets the vendor string in a VORBIS_COMMENT block.
  88721. *
  88722. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88723. * one already.
  88724. *
  88725. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88726. * takes ownership of the \c entry.entry pointer.
  88727. *
  88728. * \note If this function returns \c false, the caller still owns the
  88729. * pointer.
  88730. *
  88731. * \param object A pointer to an existing VORBIS_COMMENT object.
  88732. * \param entry The entry to set the vendor string to.
  88733. * \param copy See above.
  88734. * \assert
  88735. * \code object != NULL \endcode
  88736. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88737. * \code (entry.entry != NULL && entry.length > 0) ||
  88738. * (entry.entry == NULL && entry.length == 0) \endcode
  88739. * \retval FLAC__bool
  88740. * \c false if memory allocation fails or \a entry does not comply with the
  88741. * Vorbis comment specification, else \c true.
  88742. */
  88743. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88744. /** Resize the comment array.
  88745. *
  88746. * If the size shrinks, elements will truncated; if it grows, new empty
  88747. * fields will be added to the end.
  88748. *
  88749. * \param object A pointer to an existing VORBIS_COMMENT object.
  88750. * \param new_num_comments The desired length of the array; may be \c 0.
  88751. * \assert
  88752. * \code object != NULL \endcode
  88753. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88754. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88755. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88756. * \retval FLAC__bool
  88757. * \c false if memory allocation fails, else \c true.
  88758. */
  88759. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88760. /** Sets a comment in a VORBIS_COMMENT block.
  88761. *
  88762. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88763. * one already.
  88764. *
  88765. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88766. * takes ownership of the \c entry.entry pointer.
  88767. *
  88768. * \note If this function returns \c false, the caller still owns the
  88769. * pointer.
  88770. *
  88771. * \param object A pointer to an existing VORBIS_COMMENT object.
  88772. * \param comment_num Index into comment array to set.
  88773. * \param entry The entry to set the comment to.
  88774. * \param copy See above.
  88775. * \assert
  88776. * \code object != NULL \endcode
  88777. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88778. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88779. * \code (entry.entry != NULL && entry.length > 0) ||
  88780. * (entry.entry == NULL && entry.length == 0) \endcode
  88781. * \retval FLAC__bool
  88782. * \c false if memory allocation fails or \a entry does not comply with the
  88783. * Vorbis comment specification, else \c true.
  88784. */
  88785. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88786. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88787. *
  88788. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88789. * one already.
  88790. *
  88791. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88792. * takes ownership of the \c entry.entry pointer.
  88793. *
  88794. * \note If this function returns \c false, the caller still owns the
  88795. * pointer.
  88796. *
  88797. * \param object A pointer to an existing VORBIS_COMMENT object.
  88798. * \param comment_num The index at which to insert the comment. The comments
  88799. * at and after \a comment_num move right one position.
  88800. * To append a comment to the end, set \a comment_num to
  88801. * \c object->data.vorbis_comment.num_comments .
  88802. * \param entry The comment to insert.
  88803. * \param copy See above.
  88804. * \assert
  88805. * \code object != NULL \endcode
  88806. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88807. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88808. * \code (entry.entry != NULL && entry.length > 0) ||
  88809. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88810. * \retval FLAC__bool
  88811. * \c false if memory allocation fails or \a entry does not comply with the
  88812. * Vorbis comment specification, else \c true.
  88813. */
  88814. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88815. /** Appends a comment to a VORBIS_COMMENT block.
  88816. *
  88817. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88818. * one already.
  88819. *
  88820. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88821. * takes ownership of the \c entry.entry pointer.
  88822. *
  88823. * \note If this function returns \c false, the caller still owns the
  88824. * pointer.
  88825. *
  88826. * \param object A pointer to an existing VORBIS_COMMENT object.
  88827. * \param entry The comment to insert.
  88828. * \param copy See above.
  88829. * \assert
  88830. * \code object != NULL \endcode
  88831. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88832. * \code (entry.entry != NULL && entry.length > 0) ||
  88833. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88834. * \retval FLAC__bool
  88835. * \c false if memory allocation fails or \a entry does not comply with the
  88836. * Vorbis comment specification, else \c true.
  88837. */
  88838. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88839. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88840. *
  88841. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88842. * one already.
  88843. *
  88844. * Depending on the the value of \a all, either all or just the first comment
  88845. * whose field name(s) match the given entry's name will be replaced by the
  88846. * given entry. If no comments match, \a entry will simply be appended.
  88847. *
  88848. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88849. * takes ownership of the \c entry.entry pointer.
  88850. *
  88851. * \note If this function returns \c false, the caller still owns the
  88852. * pointer.
  88853. *
  88854. * \param object A pointer to an existing VORBIS_COMMENT object.
  88855. * \param entry The comment to insert.
  88856. * \param all If \c true, all comments whose field name matches
  88857. * \a entry's field name will be removed, and \a entry will
  88858. * be inserted at the position of the first matching
  88859. * comment. If \c false, only the first comment whose
  88860. * field name matches \a entry's field name will be
  88861. * replaced with \a entry.
  88862. * \param copy See above.
  88863. * \assert
  88864. * \code object != NULL \endcode
  88865. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88866. * \code (entry.entry != NULL && entry.length > 0) ||
  88867. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88868. * \retval FLAC__bool
  88869. * \c false if memory allocation fails or \a entry does not comply with the
  88870. * Vorbis comment specification, else \c true.
  88871. */
  88872. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88873. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88874. *
  88875. * \param object A pointer to an existing VORBIS_COMMENT object.
  88876. * \param comment_num The index of the comment to delete.
  88877. * \assert
  88878. * \code object != NULL \endcode
  88879. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88880. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88881. * \retval FLAC__bool
  88882. * \c false if realloc() fails, else \c true.
  88883. */
  88884. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88885. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88886. *
  88887. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88888. * memory and shall be owned by the caller. For convenience the entry will
  88889. * have a terminating NUL.
  88890. *
  88891. * \param entry A pointer to a Vorbis comment entry. The entry's
  88892. * \c entry pointer should not point to allocated
  88893. * memory as it will be overwritten.
  88894. * \param field_name The field name in ASCII, \c NUL terminated.
  88895. * \param field_value The field value in UTF-8, \c NUL terminated.
  88896. * \assert
  88897. * \code entry != NULL \endcode
  88898. * \code field_name != NULL \endcode
  88899. * \code field_value != NULL \endcode
  88900. * \retval FLAC__bool
  88901. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88902. * not comply with the Vorbis comment specification, else \c true.
  88903. */
  88904. 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);
  88905. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88906. *
  88907. * The returned pointers to name and value will be allocated by malloc()
  88908. * and shall be owned by the caller.
  88909. *
  88910. * \param entry An existing Vorbis comment entry.
  88911. * \param field_name The address of where the returned pointer to the
  88912. * field name will be stored.
  88913. * \param field_value The address of where the returned pointer to the
  88914. * field value will be stored.
  88915. * \assert
  88916. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88917. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88918. * \code field_name != NULL \endcode
  88919. * \code field_value != NULL \endcode
  88920. * \retval FLAC__bool
  88921. * \c false if memory allocation fails or \a entry does not comply with the
  88922. * Vorbis comment specification, else \c true.
  88923. */
  88924. 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);
  88925. /** Check if the given Vorbis comment entry's field name matches the given
  88926. * field name.
  88927. *
  88928. * \param entry An existing Vorbis comment entry.
  88929. * \param field_name The field name to check.
  88930. * \param field_name_length The length of \a field_name, not including the
  88931. * terminating \c NUL.
  88932. * \assert
  88933. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88934. * \retval FLAC__bool
  88935. * \c true if the field names match, else \c false
  88936. */
  88937. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88938. /** Find a Vorbis comment with the given field name.
  88939. *
  88940. * The search begins at entry number \a offset; use an offset of 0 to
  88941. * search from the beginning of the comment array.
  88942. *
  88943. * \param object A pointer to an existing VORBIS_COMMENT object.
  88944. * \param offset The offset into the comment array from where to start
  88945. * the search.
  88946. * \param field_name The field name of the comment to find.
  88947. * \assert
  88948. * \code object != NULL \endcode
  88949. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88950. * \code field_name != NULL \endcode
  88951. * \retval int
  88952. * The offset in the comment array of the first comment whose field
  88953. * name matches \a field_name, or \c -1 if no match was found.
  88954. */
  88955. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88956. /** Remove first Vorbis comment matching the given field name.
  88957. *
  88958. * \param object A pointer to an existing VORBIS_COMMENT object.
  88959. * \param field_name The field name of comment to delete.
  88960. * \assert
  88961. * \code object != NULL \endcode
  88962. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88963. * \retval int
  88964. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88965. * \c 1 for one matching entry deleted.
  88966. */
  88967. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88968. /** Remove all Vorbis comments matching the given field name.
  88969. *
  88970. * \param object A pointer to an existing VORBIS_COMMENT object.
  88971. * \param field_name The field name of comments to delete.
  88972. * \assert
  88973. * \code object != NULL \endcode
  88974. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88975. * \retval int
  88976. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88977. * else the number of matching entries deleted.
  88978. */
  88979. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88980. /** Create a new CUESHEET track instance.
  88981. *
  88982. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88983. *
  88984. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88985. * \c NULL if there was an error allocating memory, else the new instance.
  88986. */
  88987. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88988. /** Create a copy of an existing CUESHEET track object.
  88989. *
  88990. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88991. * object is also copied. The caller takes ownership of the new object and
  88992. * is responsible for freeing it with
  88993. * FLAC__metadata_object_cuesheet_track_delete().
  88994. *
  88995. * \param object Pointer to object to copy.
  88996. * \assert
  88997. * \code object != NULL \endcode
  88998. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88999. * \c NULL if there was an error allocating memory, else the new instance.
  89000. */
  89001. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89002. /** Delete a CUESHEET track object
  89003. *
  89004. * \param object A pointer to an existing CUESHEET track object.
  89005. * \assert
  89006. * \code object != NULL \endcode
  89007. */
  89008. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89009. /** Resize a track's index point array.
  89010. *
  89011. * If the size shrinks, elements will truncated; if it grows, new blank
  89012. * indices will be added to the end.
  89013. *
  89014. * \param object A pointer to an existing CUESHEET object.
  89015. * \param track_num The index of the track to modify. NOTE: this is not
  89016. * necessarily the same as the track's \a number field.
  89017. * \param new_num_indices The desired length of the array; may be \c 0.
  89018. * \assert
  89019. * \code object != NULL \endcode
  89020. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89021. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89022. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89023. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89024. * \retval FLAC__bool
  89025. * \c false if memory allocation error, else \c true.
  89026. */
  89027. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89028. /** Insert an index point in a CUESHEET track at the given index.
  89029. *
  89030. * \param object A pointer to an existing CUESHEET object.
  89031. * \param track_num The index of the track to modify. NOTE: this is not
  89032. * necessarily the same as the track's \a number field.
  89033. * \param index_num The index into the track's index array at which to
  89034. * insert the index point. NOTE: this is not necessarily
  89035. * the same as the index point's \a number field. The
  89036. * indices at and after \a index_num move right one
  89037. * position. To append an index point to the end, set
  89038. * \a index_num to
  89039. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89040. * \param index The index point to insert.
  89041. * \assert
  89042. * \code object != NULL \endcode
  89043. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89044. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89045. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89046. * \retval FLAC__bool
  89047. * \c false if realloc() fails, else \c true.
  89048. */
  89049. 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);
  89050. /** Insert a blank index point in a CUESHEET track at the given index.
  89051. *
  89052. * A blank index point is one in which all field values are zero.
  89053. *
  89054. * \param object A pointer to an existing CUESHEET object.
  89055. * \param track_num The index of the track to modify. NOTE: this is not
  89056. * necessarily the same as the track's \a number field.
  89057. * \param index_num The index into the track's index array at which to
  89058. * insert the index point. NOTE: this is not necessarily
  89059. * the same as the index point's \a number field. The
  89060. * indices at and after \a index_num move right one
  89061. * position. To append an index point to the end, set
  89062. * \a index_num to
  89063. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89064. * \assert
  89065. * \code object != NULL \endcode
  89066. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89067. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89068. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89069. * \retval FLAC__bool
  89070. * \c false if realloc() fails, else \c true.
  89071. */
  89072. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89073. /** Delete an index point in a CUESHEET track at the given index.
  89074. *
  89075. * \param object A pointer to an existing CUESHEET object.
  89076. * \param track_num The index into the track array of the track to
  89077. * modify. NOTE: this is not necessarily the same
  89078. * as the track's \a number field.
  89079. * \param index_num The index into the track's index array of the index
  89080. * to delete. NOTE: this is not necessarily the same
  89081. * as the index's \a number field.
  89082. * \assert
  89083. * \code object != NULL \endcode
  89084. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89085. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89086. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89087. * \retval FLAC__bool
  89088. * \c false if realloc() fails, else \c true.
  89089. */
  89090. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89091. /** Resize the track array.
  89092. *
  89093. * If the size shrinks, elements will truncated; if it grows, new blank
  89094. * tracks will be added to the end.
  89095. *
  89096. * \param object A pointer to an existing CUESHEET object.
  89097. * \param new_num_tracks The desired length of the array; may be \c 0.
  89098. * \assert
  89099. * \code object != NULL \endcode
  89100. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89101. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89102. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89103. * \retval FLAC__bool
  89104. * \c false if memory allocation error, else \c true.
  89105. */
  89106. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89107. /** Sets a track in a CUESHEET block.
  89108. *
  89109. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89110. * takes ownership of the \a track pointer.
  89111. *
  89112. * \param object A pointer to an existing CUESHEET object.
  89113. * \param track_num Index into track array to set. NOTE: this is not
  89114. * necessarily the same as the track's \a number field.
  89115. * \param track The track to set the track to. You may safely pass in
  89116. * a const pointer if \a copy is \c true.
  89117. * \param copy See above.
  89118. * \assert
  89119. * \code object != NULL \endcode
  89120. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89121. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89122. * \code (track->indices != NULL && track->num_indices > 0) ||
  89123. * (track->indices == NULL && track->num_indices == 0)
  89124. * \retval FLAC__bool
  89125. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89126. */
  89127. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89128. /** Insert a track in a CUESHEET block at the given index.
  89129. *
  89130. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89131. * takes ownership of the \a track pointer.
  89132. *
  89133. * \param object A pointer to an existing CUESHEET object.
  89134. * \param track_num The index at which to insert the track. NOTE: this
  89135. * is not necessarily the same as the track's \a number
  89136. * field. The tracks at and after \a track_num move right
  89137. * one position. To append a track to the end, set
  89138. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89139. * \param track The track to insert. You may safely pass in a const
  89140. * pointer if \a copy is \c true.
  89141. * \param copy See above.
  89142. * \assert
  89143. * \code object != NULL \endcode
  89144. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89145. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89146. * \retval FLAC__bool
  89147. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89148. */
  89149. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89150. /** Insert a blank track in a CUESHEET block at the given index.
  89151. *
  89152. * A blank track is one in which all field values are zero.
  89153. *
  89154. * \param object A pointer to an existing CUESHEET object.
  89155. * \param track_num The index at which to insert the track. NOTE: this
  89156. * is not necessarily the same as the track's \a number
  89157. * field. The tracks at and after \a track_num move right
  89158. * one position. To append a track to the end, set
  89159. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89160. * \assert
  89161. * \code object != NULL \endcode
  89162. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89163. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89164. * \retval FLAC__bool
  89165. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89166. */
  89167. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89168. /** Delete a track in a CUESHEET block at the given index.
  89169. *
  89170. * \param object A pointer to an existing CUESHEET object.
  89171. * \param track_num The index into the track array of the track to
  89172. * delete. NOTE: this is not necessarily the same
  89173. * as the track's \a number field.
  89174. * \assert
  89175. * \code object != NULL \endcode
  89176. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89177. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89178. * \retval FLAC__bool
  89179. * \c false if realloc() fails, else \c true.
  89180. */
  89181. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89182. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89183. * See the format specification for limits on the contents of the
  89184. * cue sheet.
  89185. *
  89186. * \param object A pointer to an existing CUESHEET object.
  89187. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89188. * stringent requirements for a CD-DA (audio) disc.
  89189. * \param violation Address of a pointer to a string. If there is a
  89190. * violation, a pointer to a string explanation of the
  89191. * violation will be returned here. \a violation may be
  89192. * \c NULL if you don't need the returned string. Do not
  89193. * free the returned string; it will always point to static
  89194. * data.
  89195. * \assert
  89196. * \code object != NULL \endcode
  89197. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89198. * \retval FLAC__bool
  89199. * \c false if cue sheet is illegal, else \c true.
  89200. */
  89201. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89202. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89203. * assumes the cue sheet corresponds to a CD; the result is undefined
  89204. * if the cuesheet's is_cd bit is not set.
  89205. *
  89206. * \param object A pointer to an existing CUESHEET object.
  89207. * \assert
  89208. * \code object != NULL \endcode
  89209. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89210. * \retval FLAC__uint32
  89211. * The unsigned integer representation of the CDDB/freedb ID
  89212. */
  89213. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89214. /** Sets the MIME type of a PICTURE block.
  89215. *
  89216. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89217. * takes ownership of the pointer. The existing string will be freed if this
  89218. * function is successful, otherwise the original string will remain if \a copy
  89219. * is \c true and malloc() fails.
  89220. *
  89221. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89222. *
  89223. * \param object A pointer to an existing PICTURE object.
  89224. * \param mime_type A pointer to the MIME type string. The string must be
  89225. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89226. * is done.
  89227. * \param copy See above.
  89228. * \assert
  89229. * \code object != NULL \endcode
  89230. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89231. * \code (mime_type != NULL) \endcode
  89232. * \retval FLAC__bool
  89233. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89234. */
  89235. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89236. /** Sets the description of a PICTURE block.
  89237. *
  89238. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89239. * takes ownership of the pointer. The existing string will be freed if this
  89240. * function is successful, otherwise the original string will remain if \a copy
  89241. * is \c true and malloc() fails.
  89242. *
  89243. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89244. *
  89245. * \param object A pointer to an existing PICTURE object.
  89246. * \param description A pointer to the description string. The string must be
  89247. * valid UTF-8, NUL-terminated. No validation is done.
  89248. * \param copy See above.
  89249. * \assert
  89250. * \code object != NULL \endcode
  89251. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89252. * \code (description != NULL) \endcode
  89253. * \retval FLAC__bool
  89254. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89255. */
  89256. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89257. /** Sets the picture data of a PICTURE block.
  89258. *
  89259. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89260. * takes ownership of the pointer. Also sets the \a data_length field of the
  89261. * metadata object to what is passed in as the \a length parameter. The
  89262. * existing data will be freed if this function is successful, otherwise the
  89263. * original data and data_length will remain if \a copy is \c true and
  89264. * malloc() fails.
  89265. *
  89266. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89267. *
  89268. * \param object A pointer to an existing PICTURE object.
  89269. * \param data A pointer to the data to set.
  89270. * \param length The length of \a data in bytes.
  89271. * \param copy See above.
  89272. * \assert
  89273. * \code object != NULL \endcode
  89274. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89275. * \code (data != NULL && length > 0) ||
  89276. * (data == NULL && length == 0 && copy == false) \endcode
  89277. * \retval FLAC__bool
  89278. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89279. */
  89280. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89281. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89282. * See the format specification for limits on the contents of the
  89283. * PICTURE block.
  89284. *
  89285. * \param object A pointer to existing PICTURE block to be checked.
  89286. * \param violation Address of a pointer to a string. If there is a
  89287. * violation, a pointer to a string explanation of the
  89288. * violation will be returned here. \a violation may be
  89289. * \c NULL if you don't need the returned string. Do not
  89290. * free the returned string; it will always point to static
  89291. * data.
  89292. * \assert
  89293. * \code object != NULL \endcode
  89294. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89295. * \retval FLAC__bool
  89296. * \c false if PICTURE block is illegal, else \c true.
  89297. */
  89298. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89299. /* \} */
  89300. #ifdef __cplusplus
  89301. }
  89302. #endif
  89303. #endif
  89304. /*** End of inlined file: metadata.h ***/
  89305. /*** Start of inlined file: stream_decoder.h ***/
  89306. #ifndef FLAC__STREAM_DECODER_H
  89307. #define FLAC__STREAM_DECODER_H
  89308. #include <stdio.h> /* for FILE */
  89309. #ifdef __cplusplus
  89310. extern "C" {
  89311. #endif
  89312. /** \file include/FLAC/stream_decoder.h
  89313. *
  89314. * \brief
  89315. * This module contains the functions which implement the stream
  89316. * decoder.
  89317. *
  89318. * See the detailed documentation in the
  89319. * \link flac_stream_decoder stream decoder \endlink module.
  89320. */
  89321. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89322. * \ingroup flac
  89323. *
  89324. * \brief
  89325. * This module describes the decoder layers provided by libFLAC.
  89326. *
  89327. * The stream decoder can be used to decode complete streams either from
  89328. * the client via callbacks, or directly from a file, depending on how
  89329. * it is initialized. When decoding via callbacks, the client provides
  89330. * callbacks for reading FLAC data and writing decoded samples, and
  89331. * handling metadata and errors. If the client also supplies seek-related
  89332. * callback, the decoder function for sample-accurate seeking within the
  89333. * FLAC input is also available. When decoding from a file, the client
  89334. * needs only supply a filename or open \c FILE* and write/metadata/error
  89335. * callbacks; the rest of the callbacks are supplied internally. For more
  89336. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89337. */
  89338. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89339. * \ingroup flac_decoder
  89340. *
  89341. * \brief
  89342. * This module contains the functions which implement the stream
  89343. * decoder.
  89344. *
  89345. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89346. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89347. *
  89348. * The basic usage of this decoder is as follows:
  89349. * - The program creates an instance of a decoder using
  89350. * FLAC__stream_decoder_new().
  89351. * - The program overrides the default settings using
  89352. * FLAC__stream_decoder_set_*() functions.
  89353. * - The program initializes the instance to validate the settings and
  89354. * prepare for decoding using
  89355. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89356. * or FLAC__stream_decoder_init_file() for native FLAC,
  89357. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89358. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89359. * - The program calls the FLAC__stream_decoder_process_*() functions
  89360. * to decode data, which subsequently calls the callbacks.
  89361. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89362. * which flushes the input and output and resets the decoder to the
  89363. * uninitialized state.
  89364. * - The instance may be used again or deleted with
  89365. * FLAC__stream_decoder_delete().
  89366. *
  89367. * In more detail, the program will create a new instance by calling
  89368. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89369. * functions to override the default decoder options, and call
  89370. * one of the FLAC__stream_decoder_init_*() functions.
  89371. *
  89372. * There are three initialization functions for native FLAC, one for
  89373. * setting up the decoder to decode FLAC data from the client via
  89374. * callbacks, and two for decoding directly from a FLAC file.
  89375. *
  89376. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89377. * You must also supply several callbacks for handling I/O. Some (like
  89378. * seeking) are optional, depending on the capabilities of the input.
  89379. *
  89380. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89381. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89382. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89383. * the other callbacks internally.
  89384. *
  89385. * There are three similarly-named init functions for decoding from Ogg
  89386. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89387. * library has been built with Ogg support.
  89388. *
  89389. * Once the decoder is initialized, your program will call one of several
  89390. * functions to start the decoding process:
  89391. *
  89392. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89393. * most one metadata block or audio frame and return, calling either the
  89394. * metadata callback or write callback, respectively, once. If the decoder
  89395. * loses sync it will return with only the error callback being called.
  89396. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89397. * to process the stream from the current location and stop upon reaching
  89398. * the first audio frame. The client will get one metadata, write, or error
  89399. * callback per metadata block, audio frame, or sync error, respectively.
  89400. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89401. * to process the stream from the current location until the read callback
  89402. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89403. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89404. * write, or error callback per metadata block, audio frame, or sync error,
  89405. * respectively.
  89406. *
  89407. * When the decoder has finished decoding (normally or through an abort),
  89408. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89409. * ensures the decoder is in the correct state and frees memory. Then the
  89410. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89411. * again to decode another stream.
  89412. *
  89413. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89414. * At any point after the stream decoder has been initialized, the client can
  89415. * call this function to seek to an exact sample within the stream.
  89416. * Subsequently, the first time the write callback is called it will be
  89417. * passed a (possibly partial) block starting at that sample.
  89418. *
  89419. * If the client cannot seek via the callback interface provided, but still
  89420. * has another way of seeking, it can flush the decoder using
  89421. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89422. * through the read callback.
  89423. *
  89424. * The stream decoder also provides MD5 signature checking. If this is
  89425. * turned on before initialization, FLAC__stream_decoder_finish() will
  89426. * report when the decoded MD5 signature does not match the one stored
  89427. * in the STREAMINFO block. MD5 checking is automatically turned off
  89428. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89429. * in the STREAMINFO block or when a seek is attempted.
  89430. *
  89431. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89432. * attention. By default, the decoder only calls the metadata_callback for
  89433. * the STREAMINFO block. These functions allow you to tell the decoder
  89434. * explicitly which blocks to parse and return via the metadata_callback
  89435. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89436. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89437. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89438. * which blocks to return. Remember that metadata blocks can potentially
  89439. * be big (for example, cover art) so filtering out the ones you don't
  89440. * use can reduce the memory requirements of the decoder. Also note the
  89441. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89442. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89443. * filtering APPLICATION blocks based on the application ID.
  89444. *
  89445. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89446. * they still can legally be filtered from the metadata_callback.
  89447. *
  89448. * \note
  89449. * The "set" functions may only be called when the decoder is in the
  89450. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89451. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89452. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89453. * return \c true, otherwise \c false.
  89454. *
  89455. * \note
  89456. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89457. * defaults, including the callbacks.
  89458. *
  89459. * \{
  89460. */
  89461. /** State values for a FLAC__StreamDecoder
  89462. *
  89463. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89464. */
  89465. typedef enum {
  89466. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89467. /**< The decoder is ready to search for metadata. */
  89468. FLAC__STREAM_DECODER_READ_METADATA,
  89469. /**< The decoder is ready to or is in the process of reading metadata. */
  89470. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89471. /**< The decoder is ready to or is in the process of searching for the
  89472. * frame sync code.
  89473. */
  89474. FLAC__STREAM_DECODER_READ_FRAME,
  89475. /**< The decoder is ready to or is in the process of reading a frame. */
  89476. FLAC__STREAM_DECODER_END_OF_STREAM,
  89477. /**< The decoder has reached the end of the stream. */
  89478. FLAC__STREAM_DECODER_OGG_ERROR,
  89479. /**< An error occurred in the underlying Ogg layer. */
  89480. FLAC__STREAM_DECODER_SEEK_ERROR,
  89481. /**< An error occurred while seeking. The decoder must be flushed
  89482. * with FLAC__stream_decoder_flush() or reset with
  89483. * FLAC__stream_decoder_reset() before decoding can continue.
  89484. */
  89485. FLAC__STREAM_DECODER_ABORTED,
  89486. /**< The decoder was aborted by the read callback. */
  89487. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89488. /**< An error occurred allocating memory. The decoder is in an invalid
  89489. * state and can no longer be used.
  89490. */
  89491. FLAC__STREAM_DECODER_UNINITIALIZED
  89492. /**< The decoder is in the uninitialized state; one of the
  89493. * FLAC__stream_decoder_init_*() functions must be called before samples
  89494. * can be processed.
  89495. */
  89496. } FLAC__StreamDecoderState;
  89497. /** Maps a FLAC__StreamDecoderState to a C string.
  89498. *
  89499. * Using a FLAC__StreamDecoderState as the index to this array
  89500. * will give the string equivalent. The contents should not be modified.
  89501. */
  89502. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89503. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89504. */
  89505. typedef enum {
  89506. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89507. /**< Initialization was successful. */
  89508. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89509. /**< The library was not compiled with support for the given container
  89510. * format.
  89511. */
  89512. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89513. /**< A required callback was not supplied. */
  89514. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89515. /**< An error occurred allocating memory. */
  89516. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89517. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89518. * FLAC__stream_decoder_init_ogg_file(). */
  89519. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89520. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89521. * already initialized, usually because
  89522. * FLAC__stream_decoder_finish() was not called.
  89523. */
  89524. } FLAC__StreamDecoderInitStatus;
  89525. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89526. *
  89527. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89528. * will give the string equivalent. The contents should not be modified.
  89529. */
  89530. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89531. /** Return values for the FLAC__StreamDecoder read callback.
  89532. */
  89533. typedef enum {
  89534. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89535. /**< The read was OK and decoding can continue. */
  89536. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89537. /**< The read was attempted while at the end of the stream. Note that
  89538. * the client must only return this value when the read callback was
  89539. * called when already at the end of the stream. Otherwise, if the read
  89540. * itself moves to the end of the stream, the client should still return
  89541. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89542. * the next read callback it should return
  89543. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89544. * of \c 0.
  89545. */
  89546. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89547. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89548. } FLAC__StreamDecoderReadStatus;
  89549. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89550. *
  89551. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89552. * will give the string equivalent. The contents should not be modified.
  89553. */
  89554. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89555. /** Return values for the FLAC__StreamDecoder seek callback.
  89556. */
  89557. typedef enum {
  89558. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89559. /**< The seek was OK and decoding can continue. */
  89560. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89561. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89562. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89563. /**< Client does not support seeking. */
  89564. } FLAC__StreamDecoderSeekStatus;
  89565. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89566. *
  89567. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89568. * will give the string equivalent. The contents should not be modified.
  89569. */
  89570. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89571. /** Return values for the FLAC__StreamDecoder tell callback.
  89572. */
  89573. typedef enum {
  89574. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89575. /**< The tell was OK and decoding can continue. */
  89576. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89577. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89578. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89579. /**< Client does not support telling the position. */
  89580. } FLAC__StreamDecoderTellStatus;
  89581. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89582. *
  89583. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89584. * will give the string equivalent. The contents should not be modified.
  89585. */
  89586. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89587. /** Return values for the FLAC__StreamDecoder length callback.
  89588. */
  89589. typedef enum {
  89590. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89591. /**< The length call was OK and decoding can continue. */
  89592. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89593. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89594. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89595. /**< Client does not support reporting the length. */
  89596. } FLAC__StreamDecoderLengthStatus;
  89597. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89598. *
  89599. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89600. * will give the string equivalent. The contents should not be modified.
  89601. */
  89602. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89603. /** Return values for the FLAC__StreamDecoder write callback.
  89604. */
  89605. typedef enum {
  89606. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89607. /**< The write was OK and decoding can continue. */
  89608. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89609. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89610. } FLAC__StreamDecoderWriteStatus;
  89611. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89612. *
  89613. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89614. * will give the string equivalent. The contents should not be modified.
  89615. */
  89616. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89617. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89618. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89619. * all. The rest could be caused by bad sync (false synchronization on
  89620. * data that is not the start of a frame) or corrupted data. The error
  89621. * itself is the decoder's best guess at what happened assuming a correct
  89622. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89623. * could be caused by a correct sync on the start of a frame, but some
  89624. * data in the frame header was corrupted. Or it could be the result of
  89625. * syncing on a point the stream that looked like the starting of a frame
  89626. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89627. * could be because the decoder encountered a valid frame made by a future
  89628. * version of the encoder which it cannot parse, or because of a false
  89629. * sync making it appear as though an encountered frame was generated by
  89630. * a future encoder.
  89631. */
  89632. typedef enum {
  89633. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89634. /**< An error in the stream caused the decoder to lose synchronization. */
  89635. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89636. /**< The decoder encountered a corrupted frame header. */
  89637. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89638. /**< The frame's data did not match the CRC in the footer. */
  89639. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89640. /**< The decoder encountered reserved fields in use in the stream. */
  89641. } FLAC__StreamDecoderErrorStatus;
  89642. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89643. *
  89644. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89645. * will give the string equivalent. The contents should not be modified.
  89646. */
  89647. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89648. /***********************************************************************
  89649. *
  89650. * class FLAC__StreamDecoder
  89651. *
  89652. ***********************************************************************/
  89653. struct FLAC__StreamDecoderProtected;
  89654. struct FLAC__StreamDecoderPrivate;
  89655. /** The opaque structure definition for the stream decoder type.
  89656. * See the \link flac_stream_decoder stream decoder module \endlink
  89657. * for a detailed description.
  89658. */
  89659. typedef struct {
  89660. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89661. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89662. } FLAC__StreamDecoder;
  89663. /** Signature for the read callback.
  89664. *
  89665. * A function pointer matching this signature must be passed to
  89666. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89667. * called when the decoder needs more input data. The address of the
  89668. * buffer to be filled is supplied, along with the number of bytes the
  89669. * buffer can hold. The callback may choose to supply less data and
  89670. * modify the byte count but must be careful not to overflow the buffer.
  89671. * The callback then returns a status code chosen from
  89672. * FLAC__StreamDecoderReadStatus.
  89673. *
  89674. * Here is an example of a read callback for stdio streams:
  89675. * \code
  89676. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89677. * {
  89678. * FILE *file = ((MyClientData*)client_data)->file;
  89679. * if(*bytes > 0) {
  89680. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89681. * if(ferror(file))
  89682. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89683. * else if(*bytes == 0)
  89684. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89685. * else
  89686. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89687. * }
  89688. * else
  89689. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89690. * }
  89691. * \endcode
  89692. *
  89693. * \note In general, FLAC__StreamDecoder functions which change the
  89694. * state should not be called on the \a decoder while in the callback.
  89695. *
  89696. * \param decoder The decoder instance calling the callback.
  89697. * \param buffer A pointer to a location for the callee to store
  89698. * data to be decoded.
  89699. * \param bytes A pointer to the size of the buffer. On entry
  89700. * to the callback, it contains the maximum number
  89701. * of bytes that may be stored in \a buffer. The
  89702. * callee must set it to the actual number of bytes
  89703. * stored (0 in case of error or end-of-stream) before
  89704. * returning.
  89705. * \param client_data The callee's client data set through
  89706. * FLAC__stream_decoder_init_*().
  89707. * \retval FLAC__StreamDecoderReadStatus
  89708. * The callee's return status. Note that the callback should return
  89709. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89710. * zero bytes were read and there is no more data to be read.
  89711. */
  89712. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89713. /** Signature for the seek callback.
  89714. *
  89715. * A function pointer matching this signature may be passed to
  89716. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89717. * called when the decoder needs to seek the input stream. The decoder
  89718. * will pass the absolute byte offset to seek to, 0 meaning the
  89719. * beginning of the stream.
  89720. *
  89721. * Here is an example of a seek callback for stdio streams:
  89722. * \code
  89723. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89724. * {
  89725. * FILE *file = ((MyClientData*)client_data)->file;
  89726. * if(file == stdin)
  89727. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89728. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89729. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89730. * else
  89731. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89732. * }
  89733. * \endcode
  89734. *
  89735. * \note In general, FLAC__StreamDecoder functions which change the
  89736. * state should not be called on the \a decoder while in the callback.
  89737. *
  89738. * \param decoder The decoder instance calling the callback.
  89739. * \param absolute_byte_offset The offset from the beginning of the stream
  89740. * to seek to.
  89741. * \param client_data The callee's client data set through
  89742. * FLAC__stream_decoder_init_*().
  89743. * \retval FLAC__StreamDecoderSeekStatus
  89744. * The callee's return status.
  89745. */
  89746. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89747. /** Signature for the tell callback.
  89748. *
  89749. * A function pointer matching this signature may be passed to
  89750. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89751. * called when the decoder wants to know the current position of the
  89752. * stream. The callback should return the byte offset from the
  89753. * beginning of the stream.
  89754. *
  89755. * Here is an example of a tell callback for stdio streams:
  89756. * \code
  89757. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89758. * {
  89759. * FILE *file = ((MyClientData*)client_data)->file;
  89760. * off_t pos;
  89761. * if(file == stdin)
  89762. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89763. * else if((pos = ftello(file)) < 0)
  89764. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89765. * else {
  89766. * *absolute_byte_offset = (FLAC__uint64)pos;
  89767. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89768. * }
  89769. * }
  89770. * \endcode
  89771. *
  89772. * \note In general, FLAC__StreamDecoder functions which change the
  89773. * state should not be called on the \a decoder while in the callback.
  89774. *
  89775. * \param decoder The decoder instance calling the callback.
  89776. * \param absolute_byte_offset A pointer to storage for the current offset
  89777. * from the beginning of the stream.
  89778. * \param client_data The callee's client data set through
  89779. * FLAC__stream_decoder_init_*().
  89780. * \retval FLAC__StreamDecoderTellStatus
  89781. * The callee's return status.
  89782. */
  89783. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89784. /** Signature for the length callback.
  89785. *
  89786. * A function pointer matching this signature may be passed to
  89787. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89788. * called when the decoder wants to know the total length of the stream
  89789. * in bytes.
  89790. *
  89791. * Here is an example of a length callback for stdio streams:
  89792. * \code
  89793. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89794. * {
  89795. * FILE *file = ((MyClientData*)client_data)->file;
  89796. * struct stat filestats;
  89797. *
  89798. * if(file == stdin)
  89799. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89800. * else if(fstat(fileno(file), &filestats) != 0)
  89801. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89802. * else {
  89803. * *stream_length = (FLAC__uint64)filestats.st_size;
  89804. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89805. * }
  89806. * }
  89807. * \endcode
  89808. *
  89809. * \note In general, FLAC__StreamDecoder functions which change the
  89810. * state should not be called on the \a decoder while in the callback.
  89811. *
  89812. * \param decoder The decoder instance calling the callback.
  89813. * \param stream_length A pointer to storage for the length of the stream
  89814. * in bytes.
  89815. * \param client_data The callee's client data set through
  89816. * FLAC__stream_decoder_init_*().
  89817. * \retval FLAC__StreamDecoderLengthStatus
  89818. * The callee's return status.
  89819. */
  89820. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89821. /** Signature for the EOF callback.
  89822. *
  89823. * A function pointer matching this signature may be passed to
  89824. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89825. * called when the decoder needs to know if the end of the stream has
  89826. * been reached.
  89827. *
  89828. * Here is an example of a EOF callback for stdio streams:
  89829. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89830. * \code
  89831. * {
  89832. * FILE *file = ((MyClientData*)client_data)->file;
  89833. * return feof(file)? true : false;
  89834. * }
  89835. * \endcode
  89836. *
  89837. * \note In general, FLAC__StreamDecoder functions which change the
  89838. * state should not be called on the \a decoder while in the callback.
  89839. *
  89840. * \param decoder The decoder instance calling the callback.
  89841. * \param client_data The callee's client data set through
  89842. * FLAC__stream_decoder_init_*().
  89843. * \retval FLAC__bool
  89844. * \c true if the currently at the end of the stream, else \c false.
  89845. */
  89846. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89847. /** Signature for the write callback.
  89848. *
  89849. * A function pointer matching this signature must be passed to one of
  89850. * the FLAC__stream_decoder_init_*() functions.
  89851. * The supplied function will be called when the decoder has decoded a
  89852. * single audio frame. The decoder will pass the frame metadata as well
  89853. * as an array of pointers (one for each channel) pointing to the
  89854. * decoded audio.
  89855. *
  89856. * \note In general, FLAC__StreamDecoder functions which change the
  89857. * state should not be called on the \a decoder while in the callback.
  89858. *
  89859. * \param decoder The decoder instance calling the callback.
  89860. * \param frame The description of the decoded frame. See
  89861. * FLAC__Frame.
  89862. * \param buffer An array of pointers to decoded channels of data.
  89863. * Each pointer will point to an array of signed
  89864. * samples of length \a frame->header.blocksize.
  89865. * Channels will be ordered according to the FLAC
  89866. * specification; see the documentation for the
  89867. * <A HREF="../format.html#frame_header">frame header</A>.
  89868. * \param client_data The callee's client data set through
  89869. * FLAC__stream_decoder_init_*().
  89870. * \retval FLAC__StreamDecoderWriteStatus
  89871. * The callee's return status.
  89872. */
  89873. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89874. /** Signature for the metadata callback.
  89875. *
  89876. * A function pointer matching this signature must be passed to one of
  89877. * the FLAC__stream_decoder_init_*() functions.
  89878. * The supplied function will be called when the decoder has decoded a
  89879. * metadata block. In a valid FLAC file there will always be one
  89880. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89881. * These will be supplied by the decoder in the same order as they
  89882. * appear in the stream and always before the first audio frame (i.e.
  89883. * write callback). The metadata block that is passed in must not be
  89884. * modified, and it doesn't live beyond the callback, so you should make
  89885. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89886. * elsewhere. Since metadata blocks can potentially be large, by
  89887. * default the decoder only calls the metadata callback for the
  89888. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89889. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89890. *
  89891. * \note In general, FLAC__StreamDecoder functions which change the
  89892. * state should not be called on the \a decoder while in the callback.
  89893. *
  89894. * \param decoder The decoder instance calling the callback.
  89895. * \param metadata The decoded metadata block.
  89896. * \param client_data The callee's client data set through
  89897. * FLAC__stream_decoder_init_*().
  89898. */
  89899. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89900. /** Signature for the error callback.
  89901. *
  89902. * A function pointer matching this signature must be passed to one of
  89903. * the FLAC__stream_decoder_init_*() functions.
  89904. * The supplied function will be called whenever an error occurs during
  89905. * decoding.
  89906. *
  89907. * \note In general, FLAC__StreamDecoder functions which change the
  89908. * state should not be called on the \a decoder while in the callback.
  89909. *
  89910. * \param decoder The decoder instance calling the callback.
  89911. * \param status The error encountered by the decoder.
  89912. * \param client_data The callee's client data set through
  89913. * FLAC__stream_decoder_init_*().
  89914. */
  89915. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89916. /***********************************************************************
  89917. *
  89918. * Class constructor/destructor
  89919. *
  89920. ***********************************************************************/
  89921. /** Create a new stream decoder instance. The instance is created with
  89922. * default settings; see the individual FLAC__stream_decoder_set_*()
  89923. * functions for each setting's default.
  89924. *
  89925. * \retval FLAC__StreamDecoder*
  89926. * \c NULL if there was an error allocating memory, else the new instance.
  89927. */
  89928. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89929. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89930. *
  89931. * \param decoder A pointer to an existing decoder.
  89932. * \assert
  89933. * \code decoder != NULL \endcode
  89934. */
  89935. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89936. /***********************************************************************
  89937. *
  89938. * Public class method prototypes
  89939. *
  89940. ***********************************************************************/
  89941. /** Set the serial number for the FLAC stream within the Ogg container.
  89942. * The default behavior is to use the serial number of the first Ogg
  89943. * page. Setting a serial number here will explicitly specify which
  89944. * stream is to be decoded.
  89945. *
  89946. * \note
  89947. * This does not need to be set for native FLAC decoding.
  89948. *
  89949. * \default \c use serial number of first page
  89950. * \param decoder A decoder instance to set.
  89951. * \param serial_number See above.
  89952. * \assert
  89953. * \code decoder != NULL \endcode
  89954. * \retval FLAC__bool
  89955. * \c false if the decoder is already initialized, else \c true.
  89956. */
  89957. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89958. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89959. * compute the MD5 signature of the unencoded audio data while decoding
  89960. * and compare it to the signature from the STREAMINFO block, if it
  89961. * exists, during FLAC__stream_decoder_finish().
  89962. *
  89963. * MD5 signature checking will be turned off (until the next
  89964. * FLAC__stream_decoder_reset()) if there is no signature in the
  89965. * STREAMINFO block or when a seek is attempted.
  89966. *
  89967. * Clients that do not use the MD5 check should leave this off to speed
  89968. * up decoding.
  89969. *
  89970. * \default \c false
  89971. * \param decoder A decoder instance to set.
  89972. * \param value Flag value (see above).
  89973. * \assert
  89974. * \code decoder != NULL \endcode
  89975. * \retval FLAC__bool
  89976. * \c false if the decoder is already initialized, else \c true.
  89977. */
  89978. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89979. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89980. *
  89981. * \default By default, only the \c STREAMINFO block is returned via the
  89982. * metadata callback.
  89983. * \param decoder A decoder instance to set.
  89984. * \param type See above.
  89985. * \assert
  89986. * \code decoder != NULL \endcode
  89987. * \a type is valid
  89988. * \retval FLAC__bool
  89989. * \c false if the decoder is already initialized, else \c true.
  89990. */
  89991. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89992. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89993. * given \a id.
  89994. *
  89995. * \default By default, only the \c STREAMINFO block is returned via the
  89996. * metadata callback.
  89997. * \param decoder A decoder instance to set.
  89998. * \param id See above.
  89999. * \assert
  90000. * \code decoder != NULL \endcode
  90001. * \code id != NULL \endcode
  90002. * \retval FLAC__bool
  90003. * \c false if the decoder is already initialized, else \c true.
  90004. */
  90005. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90006. /** Direct the decoder to pass on all metadata blocks of any type.
  90007. *
  90008. * \default By default, only the \c STREAMINFO block is returned via the
  90009. * metadata callback.
  90010. * \param decoder A decoder instance to set.
  90011. * \assert
  90012. * \code decoder != NULL \endcode
  90013. * \retval FLAC__bool
  90014. * \c false if the decoder is already initialized, else \c true.
  90015. */
  90016. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90017. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90018. *
  90019. * \default By default, only the \c STREAMINFO block is returned via the
  90020. * metadata callback.
  90021. * \param decoder A decoder instance to set.
  90022. * \param type See above.
  90023. * \assert
  90024. * \code decoder != NULL \endcode
  90025. * \a type is valid
  90026. * \retval FLAC__bool
  90027. * \c false if the decoder is already initialized, else \c true.
  90028. */
  90029. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90030. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90031. * the given \a id.
  90032. *
  90033. * \default By default, only the \c STREAMINFO block is returned via the
  90034. * metadata callback.
  90035. * \param decoder A decoder instance to set.
  90036. * \param id See above.
  90037. * \assert
  90038. * \code decoder != NULL \endcode
  90039. * \code id != NULL \endcode
  90040. * \retval FLAC__bool
  90041. * \c false if the decoder is already initialized, else \c true.
  90042. */
  90043. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90044. /** Direct the decoder to filter out all metadata blocks of any type.
  90045. *
  90046. * \default By default, only the \c STREAMINFO block is returned via the
  90047. * metadata callback.
  90048. * \param decoder A decoder instance to set.
  90049. * \assert
  90050. * \code decoder != NULL \endcode
  90051. * \retval FLAC__bool
  90052. * \c false if the decoder is already initialized, else \c true.
  90053. */
  90054. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90055. /** Get the current decoder state.
  90056. *
  90057. * \param decoder A decoder instance to query.
  90058. * \assert
  90059. * \code decoder != NULL \endcode
  90060. * \retval FLAC__StreamDecoderState
  90061. * The current decoder state.
  90062. */
  90063. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90064. /** Get the current decoder state as a C string.
  90065. *
  90066. * \param decoder A decoder instance to query.
  90067. * \assert
  90068. * \code decoder != NULL \endcode
  90069. * \retval const char *
  90070. * The decoder state as a C string. Do not modify the contents.
  90071. */
  90072. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90073. /** Get the "MD5 signature checking" flag.
  90074. * This is the value of the setting, not whether or not the decoder is
  90075. * currently checking the MD5 (remember, it can be turned off automatically
  90076. * by a seek). When the decoder is reset the flag will be restored to the
  90077. * value returned by this function.
  90078. *
  90079. * \param decoder A decoder instance to query.
  90080. * \assert
  90081. * \code decoder != NULL \endcode
  90082. * \retval FLAC__bool
  90083. * See above.
  90084. */
  90085. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90086. /** Get the total number of samples in the stream being decoded.
  90087. * Will only be valid after decoding has started and will contain the
  90088. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90089. *
  90090. * \param decoder A decoder instance to query.
  90091. * \assert
  90092. * \code decoder != NULL \endcode
  90093. * \retval unsigned
  90094. * See above.
  90095. */
  90096. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90097. /** Get the current number of channels in the stream being decoded.
  90098. * Will only be valid after decoding has started and will contain the
  90099. * value from the most recently decoded frame header.
  90100. *
  90101. * \param decoder A decoder instance to query.
  90102. * \assert
  90103. * \code decoder != NULL \endcode
  90104. * \retval unsigned
  90105. * See above.
  90106. */
  90107. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90108. /** Get the current channel assignment in the stream being decoded.
  90109. * Will only be valid after decoding has started and will contain the
  90110. * value from the most recently decoded frame header.
  90111. *
  90112. * \param decoder A decoder instance to query.
  90113. * \assert
  90114. * \code decoder != NULL \endcode
  90115. * \retval FLAC__ChannelAssignment
  90116. * See above.
  90117. */
  90118. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90119. /** Get the current sample resolution in the stream being decoded.
  90120. * Will only be valid after decoding has started and will contain the
  90121. * value from the most recently decoded frame header.
  90122. *
  90123. * \param decoder A decoder instance to query.
  90124. * \assert
  90125. * \code decoder != NULL \endcode
  90126. * \retval unsigned
  90127. * See above.
  90128. */
  90129. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90130. /** Get the current sample rate in Hz of the stream being decoded.
  90131. * Will only be valid after decoding has started and will contain the
  90132. * value from the most recently decoded frame header.
  90133. *
  90134. * \param decoder A decoder instance to query.
  90135. * \assert
  90136. * \code decoder != NULL \endcode
  90137. * \retval unsigned
  90138. * See above.
  90139. */
  90140. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90141. /** Get the current blocksize of the stream being decoded.
  90142. * Will only be valid after decoding has started and will contain the
  90143. * value from the most recently decoded frame header.
  90144. *
  90145. * \param decoder A decoder instance to query.
  90146. * \assert
  90147. * \code decoder != NULL \endcode
  90148. * \retval unsigned
  90149. * See above.
  90150. */
  90151. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90152. /** Returns the decoder's current read position within the stream.
  90153. * The position is the byte offset from the start of the stream.
  90154. * Bytes before this position have been fully decoded. Note that
  90155. * there may still be undecoded bytes in the decoder's read FIFO.
  90156. * The returned position is correct even after a seek.
  90157. *
  90158. * \warning This function currently only works for native FLAC,
  90159. * not Ogg FLAC streams.
  90160. *
  90161. * \param decoder A decoder instance to query.
  90162. * \param position Address at which to return the desired position.
  90163. * \assert
  90164. * \code decoder != NULL \endcode
  90165. * \code position != NULL \endcode
  90166. * \retval FLAC__bool
  90167. * \c true if successful, \c false if the stream is not native FLAC,
  90168. * or there was an error from the 'tell' callback or it returned
  90169. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90170. */
  90171. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90172. /** Initialize the decoder instance to decode native FLAC streams.
  90173. *
  90174. * This flavor of initialization sets up the decoder to decode from a
  90175. * native FLAC stream. I/O is performed via callbacks to the client.
  90176. * For decoding from a plain file via filename or open FILE*,
  90177. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90178. * provide a simpler interface.
  90179. *
  90180. * This function should be called after FLAC__stream_decoder_new() and
  90181. * FLAC__stream_decoder_set_*() but before any of the
  90182. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90183. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90184. * if initialization succeeded.
  90185. *
  90186. * \param decoder An uninitialized decoder instance.
  90187. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90188. * pointer must not be \c NULL.
  90189. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90190. * pointer may be \c NULL if seeking is not
  90191. * supported. If \a seek_callback is not \c NULL then a
  90192. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90193. * Alternatively, a dummy seek callback that just
  90194. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90195. * may also be supplied, all though this is slightly
  90196. * less efficient for the decoder.
  90197. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90198. * pointer may be \c NULL if not supported by the client. If
  90199. * \a seek_callback is not \c NULL then a
  90200. * \a tell_callback must also be supplied.
  90201. * Alternatively, a dummy tell callback that just
  90202. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90203. * may also be supplied, all though this is slightly
  90204. * less efficient for the decoder.
  90205. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90206. * pointer may be \c NULL if not supported by the client. If
  90207. * \a seek_callback is not \c NULL then a
  90208. * \a length_callback must also be supplied.
  90209. * Alternatively, a dummy length callback that just
  90210. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90211. * may also be supplied, all though this is slightly
  90212. * less efficient for the decoder.
  90213. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90214. * pointer may be \c NULL if not supported by the client. If
  90215. * \a seek_callback is not \c NULL then a
  90216. * \a eof_callback must also be supplied.
  90217. * Alternatively, a dummy length callback that just
  90218. * returns \c false
  90219. * may also be supplied, all though this is slightly
  90220. * less efficient for the decoder.
  90221. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90222. * pointer must not be \c NULL.
  90223. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90224. * pointer may be \c NULL if the callback is not
  90225. * desired.
  90226. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90227. * pointer must not be \c NULL.
  90228. * \param client_data This value will be supplied to callbacks in their
  90229. * \a client_data argument.
  90230. * \assert
  90231. * \code decoder != NULL \endcode
  90232. * \retval FLAC__StreamDecoderInitStatus
  90233. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90234. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90235. */
  90236. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90237. FLAC__StreamDecoder *decoder,
  90238. FLAC__StreamDecoderReadCallback read_callback,
  90239. FLAC__StreamDecoderSeekCallback seek_callback,
  90240. FLAC__StreamDecoderTellCallback tell_callback,
  90241. FLAC__StreamDecoderLengthCallback length_callback,
  90242. FLAC__StreamDecoderEofCallback eof_callback,
  90243. FLAC__StreamDecoderWriteCallback write_callback,
  90244. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90245. FLAC__StreamDecoderErrorCallback error_callback,
  90246. void *client_data
  90247. );
  90248. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90249. *
  90250. * This flavor of initialization sets up the decoder to decode from a
  90251. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90252. * client. For decoding from a plain file via filename or open FILE*,
  90253. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90254. * provide a simpler interface.
  90255. *
  90256. * This function should be called after FLAC__stream_decoder_new() and
  90257. * FLAC__stream_decoder_set_*() but before any of the
  90258. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90259. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90260. * if initialization succeeded.
  90261. *
  90262. * \note Support for Ogg FLAC in the library is optional. If this
  90263. * library has been built without support for Ogg FLAC, this function
  90264. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90265. *
  90266. * \param decoder An uninitialized decoder instance.
  90267. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90268. * pointer must not be \c NULL.
  90269. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90270. * pointer may be \c NULL if seeking is not
  90271. * supported. If \a seek_callback is not \c NULL then a
  90272. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90273. * Alternatively, a dummy seek callback that just
  90274. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90275. * may also be supplied, all though this is slightly
  90276. * less efficient for the decoder.
  90277. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90278. * pointer may be \c NULL if not supported by the client. If
  90279. * \a seek_callback is not \c NULL then a
  90280. * \a tell_callback must also be supplied.
  90281. * Alternatively, a dummy tell callback that just
  90282. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90283. * may also be supplied, all though this is slightly
  90284. * less efficient for the decoder.
  90285. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90286. * pointer may be \c NULL if not supported by the client. If
  90287. * \a seek_callback is not \c NULL then a
  90288. * \a length_callback must also be supplied.
  90289. * Alternatively, a dummy length callback that just
  90290. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90291. * may also be supplied, all though this is slightly
  90292. * less efficient for the decoder.
  90293. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90294. * pointer may be \c NULL if not supported by the client. If
  90295. * \a seek_callback is not \c NULL then a
  90296. * \a eof_callback must also be supplied.
  90297. * Alternatively, a dummy length callback that just
  90298. * returns \c false
  90299. * may also be supplied, all though this is slightly
  90300. * less efficient for the decoder.
  90301. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90302. * pointer must not be \c NULL.
  90303. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90304. * pointer may be \c NULL if the callback is not
  90305. * desired.
  90306. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90307. * pointer must not be \c NULL.
  90308. * \param client_data This value will be supplied to callbacks in their
  90309. * \a client_data argument.
  90310. * \assert
  90311. * \code decoder != NULL \endcode
  90312. * \retval FLAC__StreamDecoderInitStatus
  90313. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90314. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90315. */
  90316. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90317. FLAC__StreamDecoder *decoder,
  90318. FLAC__StreamDecoderReadCallback read_callback,
  90319. FLAC__StreamDecoderSeekCallback seek_callback,
  90320. FLAC__StreamDecoderTellCallback tell_callback,
  90321. FLAC__StreamDecoderLengthCallback length_callback,
  90322. FLAC__StreamDecoderEofCallback eof_callback,
  90323. FLAC__StreamDecoderWriteCallback write_callback,
  90324. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90325. FLAC__StreamDecoderErrorCallback error_callback,
  90326. void *client_data
  90327. );
  90328. /** Initialize the decoder instance to decode native FLAC files.
  90329. *
  90330. * This flavor of initialization sets up the decoder to decode from a
  90331. * plain native FLAC file. For non-stdio streams, you must use
  90332. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90333. *
  90334. * This function should be called after FLAC__stream_decoder_new() and
  90335. * FLAC__stream_decoder_set_*() but before any of the
  90336. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90337. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90338. * if initialization succeeded.
  90339. *
  90340. * \param decoder An uninitialized decoder instance.
  90341. * \param file An open FLAC file. The file should have been
  90342. * opened with mode \c "rb" and rewound. The file
  90343. * becomes owned by the decoder and should not be
  90344. * manipulated by the client while decoding.
  90345. * Unless \a file is \c stdin, it will be closed
  90346. * when FLAC__stream_decoder_finish() is called.
  90347. * Note however that seeking will not work when
  90348. * decoding from \c stdout since it is not seekable.
  90349. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90350. * pointer must not be \c NULL.
  90351. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90352. * pointer may be \c NULL if the callback is not
  90353. * desired.
  90354. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90355. * pointer must not be \c NULL.
  90356. * \param client_data This value will be supplied to callbacks in their
  90357. * \a client_data argument.
  90358. * \assert
  90359. * \code decoder != NULL \endcode
  90360. * \code file != NULL \endcode
  90361. * \retval FLAC__StreamDecoderInitStatus
  90362. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90363. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90364. */
  90365. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90366. FLAC__StreamDecoder *decoder,
  90367. FILE *file,
  90368. FLAC__StreamDecoderWriteCallback write_callback,
  90369. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90370. FLAC__StreamDecoderErrorCallback error_callback,
  90371. void *client_data
  90372. );
  90373. /** Initialize the decoder instance to decode Ogg FLAC files.
  90374. *
  90375. * This flavor of initialization sets up the decoder to decode from a
  90376. * plain Ogg FLAC file. For non-stdio streams, you must use
  90377. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90378. *
  90379. * This function should be called after FLAC__stream_decoder_new() and
  90380. * FLAC__stream_decoder_set_*() but before any of the
  90381. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90382. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90383. * if initialization succeeded.
  90384. *
  90385. * \note Support for Ogg FLAC in the library is optional. If this
  90386. * library has been built without support for Ogg FLAC, this function
  90387. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90388. *
  90389. * \param decoder An uninitialized decoder instance.
  90390. * \param file An open FLAC file. The file should have been
  90391. * opened with mode \c "rb" and rewound. The file
  90392. * becomes owned by the decoder and should not be
  90393. * manipulated by the client while decoding.
  90394. * Unless \a file is \c stdin, it will be closed
  90395. * when FLAC__stream_decoder_finish() is called.
  90396. * Note however that seeking will not work when
  90397. * decoding from \c stdout since it is not seekable.
  90398. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90399. * pointer must not be \c NULL.
  90400. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90401. * pointer may be \c NULL if the callback is not
  90402. * desired.
  90403. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90404. * pointer must not be \c NULL.
  90405. * \param client_data This value will be supplied to callbacks in their
  90406. * \a client_data argument.
  90407. * \assert
  90408. * \code decoder != NULL \endcode
  90409. * \code file != NULL \endcode
  90410. * \retval FLAC__StreamDecoderInitStatus
  90411. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90412. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90413. */
  90414. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90415. FLAC__StreamDecoder *decoder,
  90416. FILE *file,
  90417. FLAC__StreamDecoderWriteCallback write_callback,
  90418. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90419. FLAC__StreamDecoderErrorCallback error_callback,
  90420. void *client_data
  90421. );
  90422. /** Initialize the decoder instance to decode native FLAC files.
  90423. *
  90424. * This flavor of initialization sets up the decoder to decode from a plain
  90425. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90426. * example, with Unicode filenames on Windows), you must use
  90427. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90428. * and provide callbacks for the I/O.
  90429. *
  90430. * This function should be called after FLAC__stream_decoder_new() and
  90431. * FLAC__stream_decoder_set_*() but before any of the
  90432. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90433. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90434. * if initialization succeeded.
  90435. *
  90436. * \param decoder An uninitialized decoder instance.
  90437. * \param filename The name of the file to decode from. The file will
  90438. * be opened with fopen(). Use \c NULL to decode from
  90439. * \c stdin. Note that \c stdin is not seekable.
  90440. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90441. * pointer must not be \c NULL.
  90442. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90443. * pointer may be \c NULL if the callback is not
  90444. * desired.
  90445. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90446. * pointer must not be \c NULL.
  90447. * \param client_data This value will be supplied to callbacks in their
  90448. * \a client_data argument.
  90449. * \assert
  90450. * \code decoder != NULL \endcode
  90451. * \retval FLAC__StreamDecoderInitStatus
  90452. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90453. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90454. */
  90455. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90456. FLAC__StreamDecoder *decoder,
  90457. const char *filename,
  90458. FLAC__StreamDecoderWriteCallback write_callback,
  90459. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90460. FLAC__StreamDecoderErrorCallback error_callback,
  90461. void *client_data
  90462. );
  90463. /** Initialize the decoder instance to decode Ogg FLAC files.
  90464. *
  90465. * This flavor of initialization sets up the decoder to decode from a plain
  90466. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90467. * example, with Unicode filenames on Windows), you must use
  90468. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90469. * and provide callbacks for the I/O.
  90470. *
  90471. * This function should be called after FLAC__stream_decoder_new() and
  90472. * FLAC__stream_decoder_set_*() but before any of the
  90473. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90474. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90475. * if initialization succeeded.
  90476. *
  90477. * \note Support for Ogg FLAC in the library is optional. If this
  90478. * library has been built without support for Ogg FLAC, this function
  90479. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90480. *
  90481. * \param decoder An uninitialized decoder instance.
  90482. * \param filename The name of the file to decode from. The file will
  90483. * be opened with fopen(). Use \c NULL to decode from
  90484. * \c stdin. Note that \c stdin is not seekable.
  90485. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90486. * pointer must not be \c NULL.
  90487. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90488. * pointer may be \c NULL if the callback is not
  90489. * desired.
  90490. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90491. * pointer must not be \c NULL.
  90492. * \param client_data This value will be supplied to callbacks in their
  90493. * \a client_data argument.
  90494. * \assert
  90495. * \code decoder != NULL \endcode
  90496. * \retval FLAC__StreamDecoderInitStatus
  90497. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90498. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90499. */
  90500. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90501. FLAC__StreamDecoder *decoder,
  90502. const char *filename,
  90503. FLAC__StreamDecoderWriteCallback write_callback,
  90504. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90505. FLAC__StreamDecoderErrorCallback error_callback,
  90506. void *client_data
  90507. );
  90508. /** Finish the decoding process.
  90509. * Flushes the decoding buffer, releases resources, resets the decoder
  90510. * settings to their defaults, and returns the decoder state to
  90511. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90512. *
  90513. * In the event of a prematurely-terminated decode, it is not strictly
  90514. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90515. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90516. * with a FLAC__stream_decoder_finish().
  90517. *
  90518. * \param decoder An uninitialized decoder instance.
  90519. * \assert
  90520. * \code decoder != NULL \endcode
  90521. * \retval FLAC__bool
  90522. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90523. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90524. * signature does not match the one computed by the decoder; else
  90525. * \c true.
  90526. */
  90527. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90528. /** Flush the stream input.
  90529. * The decoder's input buffer will be cleared and the state set to
  90530. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90531. * off MD5 checking.
  90532. *
  90533. * \param decoder A decoder instance.
  90534. * \assert
  90535. * \code decoder != NULL \endcode
  90536. * \retval FLAC__bool
  90537. * \c true if successful, else \c false if a memory allocation
  90538. * error occurs (in which case the state will be set to
  90539. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90540. */
  90541. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90542. /** Reset the decoding process.
  90543. * The decoder's input buffer will be cleared and the state set to
  90544. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90545. * FLAC__stream_decoder_finish() except that the settings are
  90546. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90547. * before decoding again. MD5 checking will be restored to its original
  90548. * setting.
  90549. *
  90550. * If the decoder is seekable, or was initialized with
  90551. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90552. * the decoder will also attempt to seek to the beginning of the file.
  90553. * If this rewind fails, this function will return \c false. It follows
  90554. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90555. * \c stdin.
  90556. *
  90557. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90558. * and is not seekable (i.e. no seek callback was provided or the seek
  90559. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90560. * is the duty of the client to start feeding data from the beginning of
  90561. * the stream on the next FLAC__stream_decoder_process() or
  90562. * FLAC__stream_decoder_process_interleaved() call.
  90563. *
  90564. * \param decoder A decoder instance.
  90565. * \assert
  90566. * \code decoder != NULL \endcode
  90567. * \retval FLAC__bool
  90568. * \c true if successful, else \c false if a memory allocation occurs
  90569. * (in which case the state will be set to
  90570. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90571. * occurs (the state will be unchanged).
  90572. */
  90573. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90574. /** Decode one metadata block or audio frame.
  90575. * This version instructs the decoder to decode a either a single metadata
  90576. * block or a single frame and stop, unless the callbacks return a fatal
  90577. * error or the read callback returns
  90578. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90579. *
  90580. * As the decoder needs more input it will call the read callback.
  90581. * Depending on what was decoded, the metadata or write callback will be
  90582. * called with the decoded metadata block or audio frame.
  90583. *
  90584. * Unless there is a fatal read error or end of stream, this function
  90585. * will return once one whole frame is decoded. In other words, if the
  90586. * stream is not synchronized or points to a corrupt frame header, the
  90587. * decoder will continue to try and resync until it gets to a valid
  90588. * frame, then decode one frame, then return. If the decoder points to
  90589. * a frame whose frame CRC in the frame footer does not match the
  90590. * computed frame CRC, this function will issue a
  90591. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90592. * error callback, and return, having decoded one complete, although
  90593. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90594. * correct length to the write callback.)
  90595. *
  90596. * \param decoder An initialized decoder instance.
  90597. * \assert
  90598. * \code decoder != NULL \endcode
  90599. * \retval FLAC__bool
  90600. * \c false if any fatal read, write, or memory allocation error
  90601. * occurred (meaning decoding must stop), else \c true; for more
  90602. * information about the decoder, check the decoder state with
  90603. * FLAC__stream_decoder_get_state().
  90604. */
  90605. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90606. /** Decode until the end of the metadata.
  90607. * This version instructs the decoder to decode from the current position
  90608. * and continue until all the metadata has been read, or until the
  90609. * callbacks return a fatal error or the read callback returns
  90610. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90611. *
  90612. * As the decoder needs more input it will call the read callback.
  90613. * As each metadata block is decoded, the metadata callback will be called
  90614. * with the decoded metadata.
  90615. *
  90616. * \param decoder An initialized decoder instance.
  90617. * \assert
  90618. * \code decoder != NULL \endcode
  90619. * \retval FLAC__bool
  90620. * \c false if any fatal read, write, or memory allocation error
  90621. * occurred (meaning decoding must stop), else \c true; for more
  90622. * information about the decoder, check the decoder state with
  90623. * FLAC__stream_decoder_get_state().
  90624. */
  90625. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90626. /** Decode until the end of the stream.
  90627. * This version instructs the decoder to decode from the current position
  90628. * and continue until the end of stream (the read callback returns
  90629. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90630. * callbacks return a fatal error.
  90631. *
  90632. * As the decoder needs more input it will call the read callback.
  90633. * As each metadata block and frame is decoded, the metadata or write
  90634. * callback will be called with the decoded metadata or frame.
  90635. *
  90636. * \param decoder An initialized decoder instance.
  90637. * \assert
  90638. * \code decoder != NULL \endcode
  90639. * \retval FLAC__bool
  90640. * \c false if any fatal read, write, or memory allocation error
  90641. * occurred (meaning decoding must stop), else \c true; for more
  90642. * information about the decoder, check the decoder state with
  90643. * FLAC__stream_decoder_get_state().
  90644. */
  90645. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90646. /** Skip one audio frame.
  90647. * This version instructs the decoder to 'skip' a single frame and stop,
  90648. * unless the callbacks return a fatal error or the read callback returns
  90649. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90650. *
  90651. * The decoding flow is the same as what occurs when
  90652. * FLAC__stream_decoder_process_single() is called to process an audio
  90653. * frame, except that this function does not decode the parsed data into
  90654. * PCM or call the write callback. The integrity of the frame is still
  90655. * checked the same way as in the other process functions.
  90656. *
  90657. * This function will return once one whole frame is skipped, in the
  90658. * same way that FLAC__stream_decoder_process_single() will return once
  90659. * one whole frame is decoded.
  90660. *
  90661. * This function can be used in more quickly determining FLAC frame
  90662. * boundaries when decoding of the actual data is not needed, for
  90663. * example when an application is separating a FLAC stream into frames
  90664. * for editing or storing in a container. To do this, the application
  90665. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90666. * to the next frame, then use
  90667. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90668. * boundary.
  90669. *
  90670. * This function should only be called when the stream has advanced
  90671. * past all the metadata, otherwise it will return \c false.
  90672. *
  90673. * \param decoder An initialized decoder instance not in a metadata
  90674. * state.
  90675. * \assert
  90676. * \code decoder != NULL \endcode
  90677. * \retval FLAC__bool
  90678. * \c false if any fatal read, write, or memory allocation error
  90679. * occurred (meaning decoding must stop), or if the decoder
  90680. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90681. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90682. * information about the decoder, check the decoder state with
  90683. * FLAC__stream_decoder_get_state().
  90684. */
  90685. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90686. /** Flush the input and seek to an absolute sample.
  90687. * Decoding will resume at the given sample. Note that because of
  90688. * this, the next write callback may contain a partial block. The
  90689. * client must support seeking the input or this function will fail
  90690. * and return \c false. Furthermore, if the decoder state is
  90691. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90692. * with FLAC__stream_decoder_flush() or reset with
  90693. * FLAC__stream_decoder_reset() before decoding can continue.
  90694. *
  90695. * \param decoder A decoder instance.
  90696. * \param sample The target sample number to seek to.
  90697. * \assert
  90698. * \code decoder != NULL \endcode
  90699. * \retval FLAC__bool
  90700. * \c true if successful, else \c false.
  90701. */
  90702. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90703. /* \} */
  90704. #ifdef __cplusplus
  90705. }
  90706. #endif
  90707. #endif
  90708. /*** End of inlined file: stream_decoder.h ***/
  90709. /*** Start of inlined file: stream_encoder.h ***/
  90710. #ifndef FLAC__STREAM_ENCODER_H
  90711. #define FLAC__STREAM_ENCODER_H
  90712. #include <stdio.h> /* for FILE */
  90713. #ifdef __cplusplus
  90714. extern "C" {
  90715. #endif
  90716. /** \file include/FLAC/stream_encoder.h
  90717. *
  90718. * \brief
  90719. * This module contains the functions which implement the stream
  90720. * encoder.
  90721. *
  90722. * See the detailed documentation in the
  90723. * \link flac_stream_encoder stream encoder \endlink module.
  90724. */
  90725. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90726. * \ingroup flac
  90727. *
  90728. * \brief
  90729. * This module describes the encoder layers provided by libFLAC.
  90730. *
  90731. * The stream encoder can be used to encode complete streams either to the
  90732. * client via callbacks, or directly to a file, depending on how it is
  90733. * initialized. When encoding via callbacks, the client provides a write
  90734. * callback which will be called whenever FLAC data is ready to be written.
  90735. * If the client also supplies a seek callback, the encoder will also
  90736. * automatically handle the writing back of metadata discovered while
  90737. * encoding, like stream info, seek points offsets, etc. When encoding to
  90738. * a file, the client needs only supply a filename or open \c FILE* and an
  90739. * optional progress callback for periodic notification of progress; the
  90740. * write and seek callbacks are supplied internally. For more info see the
  90741. * \link flac_stream_encoder stream encoder \endlink module.
  90742. */
  90743. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90744. * \ingroup flac_encoder
  90745. *
  90746. * \brief
  90747. * This module contains the functions which implement the stream
  90748. * encoder.
  90749. *
  90750. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90751. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90752. *
  90753. * The basic usage of this encoder is as follows:
  90754. * - The program creates an instance of an encoder using
  90755. * FLAC__stream_encoder_new().
  90756. * - The program overrides the default settings using
  90757. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90758. * functions should be called:
  90759. * - FLAC__stream_encoder_set_channels()
  90760. * - FLAC__stream_encoder_set_bits_per_sample()
  90761. * - FLAC__stream_encoder_set_sample_rate()
  90762. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90763. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90764. * - If the application wants to control the compression level or set its own
  90765. * metadata, then the following should also be called:
  90766. * - FLAC__stream_encoder_set_compression_level()
  90767. * - FLAC__stream_encoder_set_verify()
  90768. * - FLAC__stream_encoder_set_metadata()
  90769. * - The rest of the set functions should only be called if the client needs
  90770. * exact control over how the audio is compressed; thorough understanding
  90771. * of the FLAC format is necessary to achieve good results.
  90772. * - The program initializes the instance to validate the settings and
  90773. * prepare for encoding using
  90774. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90775. * or FLAC__stream_encoder_init_file() for native FLAC
  90776. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90777. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90778. * - The program calls FLAC__stream_encoder_process() or
  90779. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90780. * subsequently calls the callbacks when there is encoder data ready
  90781. * to be written.
  90782. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90783. * which causes the encoder to encode any data still in its input pipe,
  90784. * update the metadata with the final encoding statistics if output
  90785. * seeking is possible, and finally reset the encoder to the
  90786. * uninitialized state.
  90787. * - The instance may be used again or deleted with
  90788. * FLAC__stream_encoder_delete().
  90789. *
  90790. * In more detail, the stream encoder functions similarly to the
  90791. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90792. * callbacks and more options. Typically the client will create a new
  90793. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90794. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90795. * calling one of the FLAC__stream_encoder_init_*() functions.
  90796. *
  90797. * Unlike the decoders, the stream encoder has many options that can
  90798. * affect the speed and compression ratio. When setting these parameters
  90799. * you should have some basic knowledge of the format (see the
  90800. * <A HREF="../documentation.html#format">user-level documentation</A>
  90801. * or the <A HREF="../format.html">formal description</A>). The
  90802. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90803. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90804. * functions will do this, so make sure to pay attention to the state
  90805. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90806. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90807. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90808. * the constructor.
  90809. *
  90810. * There are three initialization functions for native FLAC, one for
  90811. * setting up the encoder to encode FLAC data to the client via
  90812. * callbacks, and two for encoding directly to a file.
  90813. *
  90814. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90815. * You must also supply a write callback which will be called anytime
  90816. * there is raw encoded data to write. If the client can seek the output
  90817. * it is best to also supply seek and tell callbacks, as this allows the
  90818. * encoder to go back after encoding is finished to write back
  90819. * information that was collected while encoding, like seek point offsets,
  90820. * frame sizes, etc.
  90821. *
  90822. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90823. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90824. * filename or open \c FILE*; the encoder will handle all the callbacks
  90825. * internally. You may also supply a progress callback for periodic
  90826. * notification of the encoding progress.
  90827. *
  90828. * There are three similarly-named init functions for encoding to Ogg
  90829. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90830. * library has been built with Ogg support.
  90831. *
  90832. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90833. * call the write callback several times, once with the \c fLaC signature,
  90834. * and once for each encoded metadata block. Note that for Ogg FLAC
  90835. * encoding you will usually get at least twice the number of callbacks than
  90836. * with native FLAC, one for the Ogg page header and one for the page body.
  90837. *
  90838. * After initializing the instance, the client may feed audio data to the
  90839. * encoder in one of two ways:
  90840. *
  90841. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90842. * will pass an array of pointers to buffers, one for each channel, to
  90843. * the encoder, each of the same length. The samples need not be
  90844. * block-aligned, but each channel should have the same number of samples.
  90845. * - Channel interleaved, through
  90846. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90847. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90848. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90849. * Again, the samples need not be block-aligned but they must be
  90850. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90851. * the last value channelN_sampleM.
  90852. *
  90853. * Note that for either process call, each sample in the buffers should be a
  90854. * signed integer, right-justified to the resolution set by
  90855. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90856. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90857. *
  90858. * When the client is finished encoding data, it calls
  90859. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90860. * data still in its input pipe, and call the metadata callback with the
  90861. * final encoding statistics. Then the instance may be deleted with
  90862. * FLAC__stream_encoder_delete() or initialized again to encode another
  90863. * stream.
  90864. *
  90865. * For programs that write their own metadata, but that do not know the
  90866. * actual metadata until after encoding, it is advantageous to instruct
  90867. * the encoder to write a PADDING block of the correct size, so that
  90868. * instead of rewriting the whole stream after encoding, the program can
  90869. * just overwrite the PADDING block. If only the maximum size of the
  90870. * metadata is known, the program can write a slightly larger padding
  90871. * block, then split it after encoding.
  90872. *
  90873. * Make sure you understand how lengths are calculated. All FLAC metadata
  90874. * blocks have a 4 byte header which contains the type and length. This
  90875. * length does not include the 4 bytes of the header. See the format page
  90876. * for the specification of metadata blocks and their lengths.
  90877. *
  90878. * \note
  90879. * If you are writing the FLAC data to a file via callbacks, make sure it
  90880. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90881. * after the first encoding pass, the encoder will try to seek back to the
  90882. * beginning of the stream, to the STREAMINFO block, to write some data
  90883. * there. (If using FLAC__stream_encoder_init*_file() or
  90884. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90885. *
  90886. * \note
  90887. * The "set" functions may only be called when the encoder is in the
  90888. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90889. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90890. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90891. * return \c true, otherwise \c false.
  90892. *
  90893. * \note
  90894. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90895. * defaults.
  90896. *
  90897. * \{
  90898. */
  90899. /** State values for a FLAC__StreamEncoder.
  90900. *
  90901. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90902. *
  90903. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90904. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90905. * must be deleted with FLAC__stream_encoder_delete().
  90906. */
  90907. typedef enum {
  90908. FLAC__STREAM_ENCODER_OK = 0,
  90909. /**< The encoder is in the normal OK state and samples can be processed. */
  90910. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90911. /**< The encoder is in the uninitialized state; one of the
  90912. * FLAC__stream_encoder_init_*() functions must be called before samples
  90913. * can be processed.
  90914. */
  90915. FLAC__STREAM_ENCODER_OGG_ERROR,
  90916. /**< An error occurred in the underlying Ogg layer. */
  90917. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90918. /**< An error occurred in the underlying verify stream decoder;
  90919. * check FLAC__stream_encoder_get_verify_decoder_state().
  90920. */
  90921. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90922. /**< The verify decoder detected a mismatch between the original
  90923. * audio signal and the decoded audio signal.
  90924. */
  90925. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90926. /**< One of the callbacks returned a fatal error. */
  90927. FLAC__STREAM_ENCODER_IO_ERROR,
  90928. /**< An I/O error occurred while opening/reading/writing a file.
  90929. * Check \c errno.
  90930. */
  90931. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90932. /**< An error occurred while writing the stream; usually, the
  90933. * write_callback returned an error.
  90934. */
  90935. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90936. /**< Memory allocation failed. */
  90937. } FLAC__StreamEncoderState;
  90938. /** Maps a FLAC__StreamEncoderState to a C string.
  90939. *
  90940. * Using a FLAC__StreamEncoderState as the index to this array
  90941. * will give the string equivalent. The contents should not be modified.
  90942. */
  90943. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90944. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90945. */
  90946. typedef enum {
  90947. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90948. /**< Initialization was successful. */
  90949. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90950. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90951. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90952. /**< The library was not compiled with support for the given container
  90953. * format.
  90954. */
  90955. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90956. /**< A required callback was not supplied. */
  90957. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90958. /**< The encoder has an invalid setting for number of channels. */
  90959. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90960. /**< The encoder has an invalid setting for bits-per-sample.
  90961. * FLAC supports 4-32 bps but the reference encoder currently supports
  90962. * only up to 24 bps.
  90963. */
  90964. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90965. /**< The encoder has an invalid setting for the input sample rate. */
  90966. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90967. /**< The encoder has an invalid setting for the block size. */
  90968. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90969. /**< The encoder has an invalid setting for the maximum LPC order. */
  90970. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90971. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90972. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90973. /**< The specified block size is less than the maximum LPC order. */
  90974. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90975. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90976. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90977. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90978. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90979. * - One of the metadata blocks contains an undefined type
  90980. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90981. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90982. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90983. */
  90984. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90985. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90986. * already initialized, usually because
  90987. * FLAC__stream_encoder_finish() was not called.
  90988. */
  90989. } FLAC__StreamEncoderInitStatus;
  90990. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90991. *
  90992. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90993. * will give the string equivalent. The contents should not be modified.
  90994. */
  90995. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90996. /** Return values for the FLAC__StreamEncoder read callback.
  90997. */
  90998. typedef enum {
  90999. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91000. /**< The read was OK and decoding can continue. */
  91001. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91002. /**< The read was attempted at the end of the stream. */
  91003. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91004. /**< An unrecoverable error occurred. */
  91005. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91006. /**< Client does not support reading back from the output. */
  91007. } FLAC__StreamEncoderReadStatus;
  91008. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91009. *
  91010. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91011. * will give the string equivalent. The contents should not be modified.
  91012. */
  91013. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91014. /** Return values for the FLAC__StreamEncoder write callback.
  91015. */
  91016. typedef enum {
  91017. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91018. /**< The write was OK and encoding can continue. */
  91019. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91020. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91021. } FLAC__StreamEncoderWriteStatus;
  91022. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91023. *
  91024. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91025. * will give the string equivalent. The contents should not be modified.
  91026. */
  91027. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91028. /** Return values for the FLAC__StreamEncoder seek callback.
  91029. */
  91030. typedef enum {
  91031. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91032. /**< The seek was OK and encoding can continue. */
  91033. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91034. /**< An unrecoverable error occurred. */
  91035. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91036. /**< Client does not support seeking. */
  91037. } FLAC__StreamEncoderSeekStatus;
  91038. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91039. *
  91040. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91041. * will give the string equivalent. The contents should not be modified.
  91042. */
  91043. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91044. /** Return values for the FLAC__StreamEncoder tell callback.
  91045. */
  91046. typedef enum {
  91047. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91048. /**< The tell was OK and encoding can continue. */
  91049. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91050. /**< An unrecoverable error occurred. */
  91051. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91052. /**< Client does not support seeking. */
  91053. } FLAC__StreamEncoderTellStatus;
  91054. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91055. *
  91056. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91057. * will give the string equivalent. The contents should not be modified.
  91058. */
  91059. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91060. /***********************************************************************
  91061. *
  91062. * class FLAC__StreamEncoder
  91063. *
  91064. ***********************************************************************/
  91065. struct FLAC__StreamEncoderProtected;
  91066. struct FLAC__StreamEncoderPrivate;
  91067. /** The opaque structure definition for the stream encoder type.
  91068. * See the \link flac_stream_encoder stream encoder module \endlink
  91069. * for a detailed description.
  91070. */
  91071. typedef struct {
  91072. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91073. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91074. } FLAC__StreamEncoder;
  91075. /** Signature for the read callback.
  91076. *
  91077. * A function pointer matching this signature must be passed to
  91078. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91079. * The supplied function will be called when the encoder needs to read back
  91080. * encoded data. This happens during the metadata callback, when the encoder
  91081. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91082. * while encoding. The address of the buffer to be filled is supplied, along
  91083. * with the number of bytes the buffer can hold. The callback may choose to
  91084. * supply less data and modify the byte count but must be careful not to
  91085. * overflow the buffer. The callback then returns a status code chosen from
  91086. * FLAC__StreamEncoderReadStatus.
  91087. *
  91088. * Here is an example of a read callback for stdio streams:
  91089. * \code
  91090. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91091. * {
  91092. * FILE *file = ((MyClientData*)client_data)->file;
  91093. * if(*bytes > 0) {
  91094. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91095. * if(ferror(file))
  91096. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91097. * else if(*bytes == 0)
  91098. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91099. * else
  91100. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91101. * }
  91102. * else
  91103. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91104. * }
  91105. * \endcode
  91106. *
  91107. * \note In general, FLAC__StreamEncoder functions which change the
  91108. * state should not be called on the \a encoder while in the callback.
  91109. *
  91110. * \param encoder The encoder instance calling the callback.
  91111. * \param buffer A pointer to a location for the callee to store
  91112. * data to be encoded.
  91113. * \param bytes A pointer to the size of the buffer. On entry
  91114. * to the callback, it contains the maximum number
  91115. * of bytes that may be stored in \a buffer. The
  91116. * callee must set it to the actual number of bytes
  91117. * stored (0 in case of error or end-of-stream) before
  91118. * returning.
  91119. * \param client_data The callee's client data set through
  91120. * FLAC__stream_encoder_set_client_data().
  91121. * \retval FLAC__StreamEncoderReadStatus
  91122. * The callee's return status.
  91123. */
  91124. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91125. /** Signature for the write callback.
  91126. *
  91127. * A function pointer matching this signature must be passed to
  91128. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91129. * by the encoder anytime there is raw encoded data ready to write. It may
  91130. * include metadata mixed with encoded audio frames and the data is not
  91131. * guaranteed to be aligned on frame or metadata block boundaries.
  91132. *
  91133. * The only duty of the callback is to write out the \a bytes worth of data
  91134. * in \a buffer to the current position in the output stream. The arguments
  91135. * \a samples and \a current_frame are purely informational. If \a samples
  91136. * is greater than \c 0, then \a current_frame will hold the current frame
  91137. * number that is being written; otherwise it indicates that the write
  91138. * callback is being called to write metadata.
  91139. *
  91140. * \note
  91141. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91142. * write callback will be called twice when writing each audio
  91143. * frame; once for the page header, and once for the page body.
  91144. * When writing the page header, the \a samples argument to the
  91145. * write callback will be \c 0.
  91146. *
  91147. * \note In general, FLAC__StreamEncoder functions which change the
  91148. * state should not be called on the \a encoder while in the callback.
  91149. *
  91150. * \param encoder The encoder instance calling the callback.
  91151. * \param buffer An array of encoded data of length \a bytes.
  91152. * \param bytes The byte length of \a buffer.
  91153. * \param samples The number of samples encoded by \a buffer.
  91154. * \c 0 has a special meaning; see above.
  91155. * \param current_frame The number of the current frame being encoded.
  91156. * \param client_data The callee's client data set through
  91157. * FLAC__stream_encoder_init_*().
  91158. * \retval FLAC__StreamEncoderWriteStatus
  91159. * The callee's return status.
  91160. */
  91161. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91162. /** Signature for the seek callback.
  91163. *
  91164. * A function pointer matching this signature may be passed to
  91165. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91166. * when the encoder needs to seek the output stream. The encoder will pass
  91167. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91168. *
  91169. * Here is an example of a seek callback for stdio streams:
  91170. * \code
  91171. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91172. * {
  91173. * FILE *file = ((MyClientData*)client_data)->file;
  91174. * if(file == stdin)
  91175. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91176. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91177. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91178. * else
  91179. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91180. * }
  91181. * \endcode
  91182. *
  91183. * \note In general, FLAC__StreamEncoder functions which change the
  91184. * state should not be called on the \a encoder while in the callback.
  91185. *
  91186. * \param encoder The encoder instance calling the callback.
  91187. * \param absolute_byte_offset The offset from the beginning of the stream
  91188. * to seek to.
  91189. * \param client_data The callee's client data set through
  91190. * FLAC__stream_encoder_init_*().
  91191. * \retval FLAC__StreamEncoderSeekStatus
  91192. * The callee's return status.
  91193. */
  91194. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91195. /** Signature for the tell callback.
  91196. *
  91197. * A function pointer matching this signature may be passed to
  91198. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91199. * when the encoder needs to know the current position of the output stream.
  91200. *
  91201. * \warning
  91202. * The callback must return the true current byte offset of the output to
  91203. * which the encoder is writing. If you are buffering the output, make
  91204. * sure and take this into account. If you are writing directly to a
  91205. * FILE* from your write callback, ftell() is sufficient. If you are
  91206. * writing directly to a file descriptor from your write callback, you
  91207. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91208. * these points to rewrite metadata after encoding.
  91209. *
  91210. * Here is an example of a tell callback for stdio streams:
  91211. * \code
  91212. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91213. * {
  91214. * FILE *file = ((MyClientData*)client_data)->file;
  91215. * off_t pos;
  91216. * if(file == stdin)
  91217. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91218. * else if((pos = ftello(file)) < 0)
  91219. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91220. * else {
  91221. * *absolute_byte_offset = (FLAC__uint64)pos;
  91222. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91223. * }
  91224. * }
  91225. * \endcode
  91226. *
  91227. * \note In general, FLAC__StreamEncoder functions which change the
  91228. * state should not be called on the \a encoder while in the callback.
  91229. *
  91230. * \param encoder The encoder instance calling the callback.
  91231. * \param absolute_byte_offset The address at which to store the current
  91232. * position of the output.
  91233. * \param client_data The callee's client data set through
  91234. * FLAC__stream_encoder_init_*().
  91235. * \retval FLAC__StreamEncoderTellStatus
  91236. * The callee's return status.
  91237. */
  91238. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91239. /** Signature for the metadata callback.
  91240. *
  91241. * A function pointer matching this signature may be passed to
  91242. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91243. * once at the end of encoding with the populated STREAMINFO structure. This
  91244. * is so the client can seek back to the beginning of the file and write the
  91245. * STREAMINFO block with the correct statistics after encoding (like
  91246. * minimum/maximum frame size and total samples).
  91247. *
  91248. * \note In general, FLAC__StreamEncoder functions which change the
  91249. * state should not be called on the \a encoder while in the callback.
  91250. *
  91251. * \param encoder The encoder instance calling the callback.
  91252. * \param metadata The final populated STREAMINFO block.
  91253. * \param client_data The callee's client data set through
  91254. * FLAC__stream_encoder_init_*().
  91255. */
  91256. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91257. /** Signature for the progress callback.
  91258. *
  91259. * A function pointer matching this signature may be passed to
  91260. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91261. * The supplied function will be called when the encoder has finished
  91262. * writing a frame. The \c total_frames_estimate argument to the
  91263. * callback will be based on the value from
  91264. * FLAC__stream_encoder_set_total_samples_estimate().
  91265. *
  91266. * \note In general, FLAC__StreamEncoder functions which change the
  91267. * state should not be called on the \a encoder while in the callback.
  91268. *
  91269. * \param encoder The encoder instance calling the callback.
  91270. * \param bytes_written Bytes written so far.
  91271. * \param samples_written Samples written so far.
  91272. * \param frames_written Frames written so far.
  91273. * \param total_frames_estimate The estimate of the total number of
  91274. * frames to be written.
  91275. * \param client_data The callee's client data set through
  91276. * FLAC__stream_encoder_init_*().
  91277. */
  91278. 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);
  91279. /***********************************************************************
  91280. *
  91281. * Class constructor/destructor
  91282. *
  91283. ***********************************************************************/
  91284. /** Create a new stream encoder instance. The instance is created with
  91285. * default settings; see the individual FLAC__stream_encoder_set_*()
  91286. * functions for each setting's default.
  91287. *
  91288. * \retval FLAC__StreamEncoder*
  91289. * \c NULL if there was an error allocating memory, else the new instance.
  91290. */
  91291. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91292. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91293. *
  91294. * \param encoder A pointer to an existing encoder.
  91295. * \assert
  91296. * \code encoder != NULL \endcode
  91297. */
  91298. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91299. /***********************************************************************
  91300. *
  91301. * Public class method prototypes
  91302. *
  91303. ***********************************************************************/
  91304. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91305. *
  91306. * \note
  91307. * This does not need to be set for native FLAC encoding.
  91308. *
  91309. * \note
  91310. * It is recommended to set a serial number explicitly as the default of '0'
  91311. * may collide with other streams.
  91312. *
  91313. * \default \c 0
  91314. * \param encoder An encoder instance to set.
  91315. * \param serial_number See above.
  91316. * \assert
  91317. * \code encoder != NULL \endcode
  91318. * \retval FLAC__bool
  91319. * \c false if the encoder is already initialized, else \c true.
  91320. */
  91321. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91322. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91323. * encoded output by feeding it through an internal decoder and comparing
  91324. * the original signal against the decoded signal. If a mismatch occurs,
  91325. * the process call will return \c false. Note that this will slow the
  91326. * encoding process by the extra time required for decoding and comparison.
  91327. *
  91328. * \default \c false
  91329. * \param encoder An encoder instance to set.
  91330. * \param value Flag value (see above).
  91331. * \assert
  91332. * \code encoder != NULL \endcode
  91333. * \retval FLAC__bool
  91334. * \c false if the encoder is already initialized, else \c true.
  91335. */
  91336. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91337. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91338. * the encoder will comply with the Subset and will check the
  91339. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91340. * comply. If \c false, the settings may take advantage of the full
  91341. * range that the format allows.
  91342. *
  91343. * Make sure you know what it entails before setting this to \c false.
  91344. *
  91345. * \default \c true
  91346. * \param encoder An encoder instance to set.
  91347. * \param value Flag value (see above).
  91348. * \assert
  91349. * \code encoder != NULL \endcode
  91350. * \retval FLAC__bool
  91351. * \c false if the encoder is already initialized, else \c true.
  91352. */
  91353. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91354. /** Set the number of channels to be encoded.
  91355. *
  91356. * \default \c 2
  91357. * \param encoder An encoder instance to set.
  91358. * \param value See above.
  91359. * \assert
  91360. * \code encoder != NULL \endcode
  91361. * \retval FLAC__bool
  91362. * \c false if the encoder is already initialized, else \c true.
  91363. */
  91364. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91365. /** Set the sample resolution of the input to be encoded.
  91366. *
  91367. * \warning
  91368. * Do not feed the encoder data that is wider than the value you
  91369. * set here or you will generate an invalid stream.
  91370. *
  91371. * \default \c 16
  91372. * \param encoder An encoder instance to set.
  91373. * \param value See above.
  91374. * \assert
  91375. * \code encoder != NULL \endcode
  91376. * \retval FLAC__bool
  91377. * \c false if the encoder is already initialized, else \c true.
  91378. */
  91379. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91380. /** Set the sample rate (in Hz) of the input to be encoded.
  91381. *
  91382. * \default \c 44100
  91383. * \param encoder An encoder instance to set.
  91384. * \param value See above.
  91385. * \assert
  91386. * \code encoder != NULL \endcode
  91387. * \retval FLAC__bool
  91388. * \c false if the encoder is already initialized, else \c true.
  91389. */
  91390. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91391. /** Set the compression level
  91392. *
  91393. * The compression level is roughly proportional to the amount of effort
  91394. * the encoder expends to compress the file. A higher level usually
  91395. * means more computation but higher compression. The default level is
  91396. * suitable for most applications.
  91397. *
  91398. * Currently the levels range from \c 0 (fastest, least compression) to
  91399. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91400. * treated as \c 8.
  91401. *
  91402. * This function automatically calls the following other \c _set_
  91403. * functions with appropriate values, so the client does not need to
  91404. * unless it specifically wants to override them:
  91405. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91406. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91407. * - FLAC__stream_encoder_set_apodization()
  91408. * - FLAC__stream_encoder_set_max_lpc_order()
  91409. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91410. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91411. * - FLAC__stream_encoder_set_do_escape_coding()
  91412. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91413. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91414. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91415. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91416. *
  91417. * The actual values set for each level are:
  91418. * <table>
  91419. * <tr>
  91420. * <td><b>level</b><td>
  91421. * <td>do mid-side stereo<td>
  91422. * <td>loose mid-side stereo<td>
  91423. * <td>apodization<td>
  91424. * <td>max lpc order<td>
  91425. * <td>qlp coeff precision<td>
  91426. * <td>qlp coeff prec search<td>
  91427. * <td>escape coding<td>
  91428. * <td>exhaustive model search<td>
  91429. * <td>min residual partition order<td>
  91430. * <td>max residual partition order<td>
  91431. * <td>rice parameter search dist<td>
  91432. * </tr>
  91433. * <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>
  91434. * <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>
  91435. * <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>
  91436. * <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>
  91437. * <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>
  91438. * <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>
  91439. * <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>
  91440. * <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>
  91441. * <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>
  91442. * </table>
  91443. *
  91444. * \default \c 5
  91445. * \param encoder An encoder instance to set.
  91446. * \param value See above.
  91447. * \assert
  91448. * \code encoder != NULL \endcode
  91449. * \retval FLAC__bool
  91450. * \c false if the encoder is already initialized, else \c true.
  91451. */
  91452. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91453. /** Set the blocksize to use while encoding.
  91454. *
  91455. * The number of samples to use per frame. Use \c 0 to let the encoder
  91456. * estimate a blocksize; this is usually best.
  91457. *
  91458. * \default \c 0
  91459. * \param encoder An encoder instance to set.
  91460. * \param value See above.
  91461. * \assert
  91462. * \code encoder != NULL \endcode
  91463. * \retval FLAC__bool
  91464. * \c false if the encoder is already initialized, else \c true.
  91465. */
  91466. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91467. /** Set to \c true to enable mid-side encoding on stereo input. The
  91468. * number of channels must be 2 for this to have any effect. Set to
  91469. * \c false to use only independent channel coding.
  91470. *
  91471. * \default \c false
  91472. * \param encoder An encoder instance to set.
  91473. * \param value Flag value (see above).
  91474. * \assert
  91475. * \code encoder != NULL \endcode
  91476. * \retval FLAC__bool
  91477. * \c false if the encoder is already initialized, else \c true.
  91478. */
  91479. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91480. /** Set to \c true to enable adaptive switching between mid-side and
  91481. * left-right encoding on stereo input. Set to \c false to use
  91482. * exhaustive searching. Setting this to \c true requires
  91483. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91484. * \c true in order to have any effect.
  91485. *
  91486. * \default \c false
  91487. * \param encoder An encoder instance to set.
  91488. * \param value Flag value (see above).
  91489. * \assert
  91490. * \code encoder != NULL \endcode
  91491. * \retval FLAC__bool
  91492. * \c false if the encoder is already initialized, else \c true.
  91493. */
  91494. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91495. /** Sets the apodization function(s) the encoder will use when windowing
  91496. * audio data for LPC analysis.
  91497. *
  91498. * The \a specification is a plain ASCII string which specifies exactly
  91499. * which functions to use. There may be more than one (up to 32),
  91500. * separated by \c ';' characters. Some functions take one or more
  91501. * comma-separated arguments in parentheses.
  91502. *
  91503. * The available functions are \c bartlett, \c bartlett_hann,
  91504. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91505. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91506. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91507. *
  91508. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91509. * (0<STDDEV<=0.5).
  91510. *
  91511. * For \c tukey(P), P specifies the fraction of the window that is
  91512. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91513. * corresponds to \c hann.
  91514. *
  91515. * Example specifications are \c "blackman" or
  91516. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91517. *
  91518. * Any function that is specified erroneously is silently dropped. Up
  91519. * to 32 functions are kept, the rest are dropped. If the specification
  91520. * is empty the encoder defaults to \c "tukey(0.5)".
  91521. *
  91522. * When more than one function is specified, then for every subframe the
  91523. * encoder will try each of them separately and choose the window that
  91524. * results in the smallest compressed subframe.
  91525. *
  91526. * Note that each function specified causes the encoder to occupy a
  91527. * floating point array in which to store the window.
  91528. *
  91529. * \default \c "tukey(0.5)"
  91530. * \param encoder An encoder instance to set.
  91531. * \param specification See above.
  91532. * \assert
  91533. * \code encoder != NULL \endcode
  91534. * \code specification != NULL \endcode
  91535. * \retval FLAC__bool
  91536. * \c false if the encoder is already initialized, else \c true.
  91537. */
  91538. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91539. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91540. *
  91541. * \default \c 0
  91542. * \param encoder An encoder instance to set.
  91543. * \param value See above.
  91544. * \assert
  91545. * \code encoder != NULL \endcode
  91546. * \retval FLAC__bool
  91547. * \c false if the encoder is already initialized, else \c true.
  91548. */
  91549. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91550. /** Set the precision, in bits, of the quantized linear predictor
  91551. * coefficients, or \c 0 to let the encoder select it based on the
  91552. * blocksize.
  91553. *
  91554. * \note
  91555. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91556. * be less than 32.
  91557. *
  91558. * \default \c 0
  91559. * \param encoder An encoder instance to set.
  91560. * \param value See above.
  91561. * \assert
  91562. * \code encoder != NULL \endcode
  91563. * \retval FLAC__bool
  91564. * \c false if the encoder is already initialized, else \c true.
  91565. */
  91566. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91567. /** Set to \c false to use only the specified quantized linear predictor
  91568. * coefficient precision, or \c true to search neighboring precision
  91569. * values and use the best one.
  91570. *
  91571. * \default \c false
  91572. * \param encoder An encoder instance to set.
  91573. * \param value See above.
  91574. * \assert
  91575. * \code encoder != NULL \endcode
  91576. * \retval FLAC__bool
  91577. * \c false if the encoder is already initialized, else \c true.
  91578. */
  91579. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91580. /** Deprecated. Setting this value has no effect.
  91581. *
  91582. * \default \c false
  91583. * \param encoder An encoder instance to set.
  91584. * \param value See above.
  91585. * \assert
  91586. * \code encoder != NULL \endcode
  91587. * \retval FLAC__bool
  91588. * \c false if the encoder is already initialized, else \c true.
  91589. */
  91590. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91591. /** Set to \c false to let the encoder estimate the best model order
  91592. * based on the residual signal energy, or \c true to force the
  91593. * encoder to evaluate all order models and select the best.
  91594. *
  91595. * \default \c false
  91596. * \param encoder An encoder instance to set.
  91597. * \param value See above.
  91598. * \assert
  91599. * \code encoder != NULL \endcode
  91600. * \retval FLAC__bool
  91601. * \c false if the encoder is already initialized, else \c true.
  91602. */
  91603. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91604. /** Set the minimum partition order to search when coding the residual.
  91605. * This is used in tandem with
  91606. * FLAC__stream_encoder_set_max_residual_partition_order().
  91607. *
  91608. * The partition order determines the context size in the residual.
  91609. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91610. *
  91611. * Set both min and max values to \c 0 to force a single context,
  91612. * whose Rice parameter is based on the residual signal variance.
  91613. * Otherwise, set a min and max order, and the encoder will search
  91614. * all orders, using the mean of each context for its Rice parameter,
  91615. * and use the best.
  91616. *
  91617. * \default \c 0
  91618. * \param encoder An encoder instance to set.
  91619. * \param value See above.
  91620. * \assert
  91621. * \code encoder != NULL \endcode
  91622. * \retval FLAC__bool
  91623. * \c false if the encoder is already initialized, else \c true.
  91624. */
  91625. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91626. /** Set the maximum partition order to search when coding the residual.
  91627. * This is used in tandem with
  91628. * FLAC__stream_encoder_set_min_residual_partition_order().
  91629. *
  91630. * The partition order determines the context size in the residual.
  91631. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91632. *
  91633. * Set both min and max values to \c 0 to force a single context,
  91634. * whose Rice parameter is based on the residual signal variance.
  91635. * Otherwise, set a min and max order, and the encoder will search
  91636. * all orders, using the mean of each context for its Rice parameter,
  91637. * and use the best.
  91638. *
  91639. * \default \c 0
  91640. * \param encoder An encoder instance to set.
  91641. * \param value See above.
  91642. * \assert
  91643. * \code encoder != NULL \endcode
  91644. * \retval FLAC__bool
  91645. * \c false if the encoder is already initialized, else \c true.
  91646. */
  91647. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91648. /** Deprecated. Setting this value has no effect.
  91649. *
  91650. * \default \c 0
  91651. * \param encoder An encoder instance to set.
  91652. * \param value See above.
  91653. * \assert
  91654. * \code encoder != NULL \endcode
  91655. * \retval FLAC__bool
  91656. * \c false if the encoder is already initialized, else \c true.
  91657. */
  91658. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91659. /** Set an estimate of the total samples that will be encoded.
  91660. * This is merely an estimate and may be set to \c 0 if unknown.
  91661. * This value will be written to the STREAMINFO block before encoding,
  91662. * and can remove the need for the caller to rewrite the value later
  91663. * if the value is known before encoding.
  91664. *
  91665. * \default \c 0
  91666. * \param encoder An encoder instance to set.
  91667. * \param value See above.
  91668. * \assert
  91669. * \code encoder != NULL \endcode
  91670. * \retval FLAC__bool
  91671. * \c false if the encoder is already initialized, else \c true.
  91672. */
  91673. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91674. /** Set the metadata blocks to be emitted to the stream before encoding.
  91675. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91676. * array of pointers to metadata blocks. The array is non-const since
  91677. * the encoder may need to change the \a is_last flag inside them, and
  91678. * in some cases update seek point offsets. Otherwise, the encoder will
  91679. * not modify or free the blocks. It is up to the caller to free the
  91680. * metadata blocks after encoding finishes.
  91681. *
  91682. * \note
  91683. * The encoder stores only copies of the pointers in the \a metadata array;
  91684. * the metadata blocks themselves must survive at least until after
  91685. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91686. *
  91687. * \note
  91688. * The STREAMINFO block is always written and no STREAMINFO block may
  91689. * occur in the supplied array.
  91690. *
  91691. * \note
  91692. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91693. * in the \a metadata array, but the client has specified that it does not
  91694. * support seeking, then the SEEKTABLE will be written verbatim. However
  91695. * by itself this is not very useful as the client will not know the stream
  91696. * offsets for the seekpoints ahead of time. In order to get a proper
  91697. * seektable the client must support seeking. See next note.
  91698. *
  91699. * \note
  91700. * SEEKTABLE blocks are handled specially. Since you will not know
  91701. * the values for the seek point stream offsets, you should pass in
  91702. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91703. * required sample numbers (or placeholder points), with \c 0 for the
  91704. * \a frame_samples and \a stream_offset fields for each point. If the
  91705. * client has specified that it supports seeking by providing a seek
  91706. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91707. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91708. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91709. * then while it is encoding the encoder will fill the stream offsets in
  91710. * for you and when encoding is finished, it will seek back and write the
  91711. * real values into the SEEKTABLE block in the stream. There are helper
  91712. * routines for manipulating seektable template blocks; see metadata.h:
  91713. * FLAC__metadata_object_seektable_template_*(). If the client does
  91714. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91715. * will slow down or remove the ability to seek in the FLAC stream.
  91716. *
  91717. * \note
  91718. * The encoder instance \b will modify the first \c SEEKTABLE block
  91719. * as it transforms the template to a valid seektable while encoding,
  91720. * but it is still up to the caller to free all metadata blocks after
  91721. * encoding.
  91722. *
  91723. * \note
  91724. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91725. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91726. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91727. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91728. * block is present in the \a metadata array, libFLAC will write an
  91729. * empty one, containing only the vendor string.
  91730. *
  91731. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91732. * the second metadata block of the stream. The encoder already supplies
  91733. * the STREAMINFO block automatically. If \a metadata does not contain a
  91734. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91735. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91736. * first, the init function will reorder \a metadata by moving the
  91737. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91738. * blocks will remain as they were.
  91739. *
  91740. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91741. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91742. * return \c false.
  91743. *
  91744. * \default \c NULL, 0
  91745. * \param encoder An encoder instance to set.
  91746. * \param metadata See above.
  91747. * \param num_blocks See above.
  91748. * \assert
  91749. * \code encoder != NULL \endcode
  91750. * \retval FLAC__bool
  91751. * \c false if the encoder is already initialized, else \c true.
  91752. * \c false if the encoder is already initialized, or if
  91753. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91754. */
  91755. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91756. /** Get the current encoder state.
  91757. *
  91758. * \param encoder An encoder instance to query.
  91759. * \assert
  91760. * \code encoder != NULL \endcode
  91761. * \retval FLAC__StreamEncoderState
  91762. * The current encoder state.
  91763. */
  91764. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91765. /** Get the state of the verify stream decoder.
  91766. * Useful when the stream encoder state is
  91767. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91768. *
  91769. * \param encoder An encoder instance to query.
  91770. * \assert
  91771. * \code encoder != NULL \endcode
  91772. * \retval FLAC__StreamDecoderState
  91773. * The verify stream decoder state.
  91774. */
  91775. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91776. /** Get the current encoder state as a C string.
  91777. * This version automatically resolves
  91778. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91779. * verify decoder's state.
  91780. *
  91781. * \param encoder A encoder instance to query.
  91782. * \assert
  91783. * \code encoder != NULL \endcode
  91784. * \retval const char *
  91785. * The encoder state as a C string. Do not modify the contents.
  91786. */
  91787. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91788. /** Get relevant values about the nature of a verify decoder error.
  91789. * Useful when the stream encoder state is
  91790. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91791. * be addresses in which the stats will be returned, or NULL if value
  91792. * is not desired.
  91793. *
  91794. * \param encoder An encoder instance to query.
  91795. * \param absolute_sample The absolute sample number of the mismatch.
  91796. * \param frame_number The number of the frame in which the mismatch occurred.
  91797. * \param channel The channel in which the mismatch occurred.
  91798. * \param sample The number of the sample (relative to the frame) in
  91799. * which the mismatch occurred.
  91800. * \param expected The expected value for the sample in question.
  91801. * \param got The actual value returned by the decoder.
  91802. * \assert
  91803. * \code encoder != NULL \endcode
  91804. */
  91805. 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);
  91806. /** Get the "verify" flag.
  91807. *
  91808. * \param encoder An encoder instance to query.
  91809. * \assert
  91810. * \code encoder != NULL \endcode
  91811. * \retval FLAC__bool
  91812. * See FLAC__stream_encoder_set_verify().
  91813. */
  91814. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91815. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91816. *
  91817. * \param encoder An encoder instance to query.
  91818. * \assert
  91819. * \code encoder != NULL \endcode
  91820. * \retval FLAC__bool
  91821. * See FLAC__stream_encoder_set_streamable_subset().
  91822. */
  91823. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91824. /** Get the number of input channels being processed.
  91825. *
  91826. * \param encoder An encoder instance to query.
  91827. * \assert
  91828. * \code encoder != NULL \endcode
  91829. * \retval unsigned
  91830. * See FLAC__stream_encoder_set_channels().
  91831. */
  91832. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91833. /** Get the input sample resolution setting.
  91834. *
  91835. * \param encoder An encoder instance to query.
  91836. * \assert
  91837. * \code encoder != NULL \endcode
  91838. * \retval unsigned
  91839. * See FLAC__stream_encoder_set_bits_per_sample().
  91840. */
  91841. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91842. /** Get the input sample rate setting.
  91843. *
  91844. * \param encoder An encoder instance to query.
  91845. * \assert
  91846. * \code encoder != NULL \endcode
  91847. * \retval unsigned
  91848. * See FLAC__stream_encoder_set_sample_rate().
  91849. */
  91850. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91851. /** Get the blocksize setting.
  91852. *
  91853. * \param encoder An encoder instance to query.
  91854. * \assert
  91855. * \code encoder != NULL \endcode
  91856. * \retval unsigned
  91857. * See FLAC__stream_encoder_set_blocksize().
  91858. */
  91859. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91860. /** Get the "mid/side stereo coding" flag.
  91861. *
  91862. * \param encoder An encoder instance to query.
  91863. * \assert
  91864. * \code encoder != NULL \endcode
  91865. * \retval FLAC__bool
  91866. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91867. */
  91868. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91869. /** Get the "adaptive mid/side switching" flag.
  91870. *
  91871. * \param encoder An encoder instance to query.
  91872. * \assert
  91873. * \code encoder != NULL \endcode
  91874. * \retval FLAC__bool
  91875. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91876. */
  91877. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91878. /** Get the maximum LPC order setting.
  91879. *
  91880. * \param encoder An encoder instance to query.
  91881. * \assert
  91882. * \code encoder != NULL \endcode
  91883. * \retval unsigned
  91884. * See FLAC__stream_encoder_set_max_lpc_order().
  91885. */
  91886. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91887. /** Get the quantized linear predictor coefficient precision setting.
  91888. *
  91889. * \param encoder An encoder instance to query.
  91890. * \assert
  91891. * \code encoder != NULL \endcode
  91892. * \retval unsigned
  91893. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91894. */
  91895. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91896. /** Get the qlp coefficient precision search flag.
  91897. *
  91898. * \param encoder An encoder instance to query.
  91899. * \assert
  91900. * \code encoder != NULL \endcode
  91901. * \retval FLAC__bool
  91902. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91903. */
  91904. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91905. /** Get the "escape coding" flag.
  91906. *
  91907. * \param encoder An encoder instance to query.
  91908. * \assert
  91909. * \code encoder != NULL \endcode
  91910. * \retval FLAC__bool
  91911. * See FLAC__stream_encoder_set_do_escape_coding().
  91912. */
  91913. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91914. /** Get the exhaustive model search flag.
  91915. *
  91916. * \param encoder An encoder instance to query.
  91917. * \assert
  91918. * \code encoder != NULL \endcode
  91919. * \retval FLAC__bool
  91920. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91921. */
  91922. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91923. /** Get the minimum residual partition order setting.
  91924. *
  91925. * \param encoder An encoder instance to query.
  91926. * \assert
  91927. * \code encoder != NULL \endcode
  91928. * \retval unsigned
  91929. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91930. */
  91931. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91932. /** Get maximum residual partition order setting.
  91933. *
  91934. * \param encoder An encoder instance to query.
  91935. * \assert
  91936. * \code encoder != NULL \endcode
  91937. * \retval unsigned
  91938. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91939. */
  91940. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91941. /** Get the Rice parameter search distance setting.
  91942. *
  91943. * \param encoder An encoder instance to query.
  91944. * \assert
  91945. * \code encoder != NULL \endcode
  91946. * \retval unsigned
  91947. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91948. */
  91949. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91950. /** Get the previously set estimate of the total samples to be encoded.
  91951. * The encoder merely mimics back the value given to
  91952. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91953. * other way of knowing how many samples the client will encode.
  91954. *
  91955. * \param encoder An encoder instance to set.
  91956. * \assert
  91957. * \code encoder != NULL \endcode
  91958. * \retval FLAC__uint64
  91959. * See FLAC__stream_encoder_get_total_samples_estimate().
  91960. */
  91961. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91962. /** Initialize the encoder instance to encode native FLAC streams.
  91963. *
  91964. * This flavor of initialization sets up the encoder to encode to a
  91965. * native FLAC stream. I/O is performed via callbacks to the client.
  91966. * For encoding to a plain file via filename or open \c FILE*,
  91967. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91968. * provide a simpler interface.
  91969. *
  91970. * This function should be called after FLAC__stream_encoder_new() and
  91971. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91972. * or FLAC__stream_encoder_process_interleaved().
  91973. * initialization succeeded.
  91974. *
  91975. * The call to FLAC__stream_encoder_init_stream() currently will also
  91976. * immediately call the write callback several times, once with the \c fLaC
  91977. * signature, and once for each encoded metadata block.
  91978. *
  91979. * \param encoder An uninitialized encoder instance.
  91980. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91981. * pointer must not be \c NULL.
  91982. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91983. * pointer may be \c NULL if seeking is not
  91984. * supported. The encoder uses seeking to go back
  91985. * and write some some stream statistics to the
  91986. * STREAMINFO block; this is recommended but not
  91987. * necessary to create a valid FLAC stream. If
  91988. * \a seek_callback is not \c NULL then a
  91989. * \a tell_callback must also be supplied.
  91990. * Alternatively, a dummy seek callback that just
  91991. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91992. * may also be supplied, all though this is slightly
  91993. * less efficient for the encoder.
  91994. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91995. * pointer may be \c NULL if seeking is not
  91996. * supported. If \a seek_callback is \c NULL then
  91997. * this argument will be ignored. If
  91998. * \a seek_callback is not \c NULL then a
  91999. * \a tell_callback must also be supplied.
  92000. * Alternatively, a dummy tell callback that just
  92001. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92002. * may also be supplied, all though this is slightly
  92003. * less efficient for the encoder.
  92004. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92005. * pointer may be \c NULL if the callback is not
  92006. * desired. If the client provides a seek callback,
  92007. * this function is not necessary as the encoder
  92008. * will automatically seek back and update the
  92009. * STREAMINFO block. It may also be \c NULL if the
  92010. * client does not support seeking, since it will
  92011. * have no way of going back to update the
  92012. * STREAMINFO. However the client can still supply
  92013. * a callback if it would like to know the details
  92014. * from the STREAMINFO.
  92015. * \param client_data This value will be supplied to callbacks in their
  92016. * \a client_data argument.
  92017. * \assert
  92018. * \code encoder != NULL \endcode
  92019. * \retval FLAC__StreamEncoderInitStatus
  92020. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92021. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92022. */
  92023. 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);
  92024. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92025. *
  92026. * This flavor of initialization sets up the encoder to encode to a FLAC
  92027. * stream in an Ogg container. I/O is performed via callbacks to the
  92028. * client. For encoding to a plain file via filename or open \c FILE*,
  92029. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92030. * provide a simpler interface.
  92031. *
  92032. * This function should be called after FLAC__stream_encoder_new() and
  92033. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92034. * or FLAC__stream_encoder_process_interleaved().
  92035. * initialization succeeded.
  92036. *
  92037. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92038. * immediately call the write callback several times to write the metadata
  92039. * packets.
  92040. *
  92041. * \param encoder An uninitialized encoder instance.
  92042. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92043. * pointer must not be \c NULL if \a seek_callback
  92044. * is non-NULL since they are both needed to be
  92045. * able to write data back to the Ogg FLAC stream
  92046. * in the post-encode phase.
  92047. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92048. * pointer must not be \c NULL.
  92049. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92050. * pointer may be \c NULL if seeking is not
  92051. * supported. The encoder uses seeking to go back
  92052. * and write some some stream statistics to the
  92053. * STREAMINFO block; this is recommended but not
  92054. * necessary to create a valid FLAC stream. If
  92055. * \a seek_callback is not \c NULL then a
  92056. * \a tell_callback must also be supplied.
  92057. * Alternatively, a dummy seek callback that just
  92058. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92059. * may also be supplied, all though this is slightly
  92060. * less efficient for the encoder.
  92061. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92062. * pointer may be \c NULL if seeking is not
  92063. * supported. If \a seek_callback is \c NULL then
  92064. * this argument will be ignored. If
  92065. * \a seek_callback is not \c NULL then a
  92066. * \a tell_callback must also be supplied.
  92067. * Alternatively, a dummy tell callback that just
  92068. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92069. * may also be supplied, all though this is slightly
  92070. * less efficient for the encoder.
  92071. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92072. * pointer may be \c NULL if the callback is not
  92073. * desired. If the client provides a seek callback,
  92074. * this function is not necessary as the encoder
  92075. * will automatically seek back and update the
  92076. * STREAMINFO block. It may also be \c NULL if the
  92077. * client does not support seeking, since it will
  92078. * have no way of going back to update the
  92079. * STREAMINFO. However the client can still supply
  92080. * a callback if it would like to know the details
  92081. * from the STREAMINFO.
  92082. * \param client_data This value will be supplied to callbacks in their
  92083. * \a client_data argument.
  92084. * \assert
  92085. * \code encoder != NULL \endcode
  92086. * \retval FLAC__StreamEncoderInitStatus
  92087. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92088. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92089. */
  92090. 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);
  92091. /** Initialize the encoder instance to encode native FLAC files.
  92092. *
  92093. * This flavor of initialization sets up the encoder to encode to a
  92094. * plain native FLAC file. For non-stdio streams, you must use
  92095. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92096. *
  92097. * This function should be called after FLAC__stream_encoder_new() and
  92098. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92099. * or FLAC__stream_encoder_process_interleaved().
  92100. * initialization succeeded.
  92101. *
  92102. * \param encoder An uninitialized encoder instance.
  92103. * \param file An open file. The file should have been opened
  92104. * with mode \c "w+b" and rewound. The file
  92105. * becomes owned by the encoder and should not be
  92106. * manipulated by the client while encoding.
  92107. * Unless \a file is \c stdout, it will be closed
  92108. * when FLAC__stream_encoder_finish() is called.
  92109. * Note however that a proper SEEKTABLE cannot be
  92110. * created when encoding to \c stdout since it is
  92111. * not seekable.
  92112. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92113. * pointer may be \c NULL if the callback is not
  92114. * desired.
  92115. * \param client_data This value will be supplied to callbacks in their
  92116. * \a client_data argument.
  92117. * \assert
  92118. * \code encoder != NULL \endcode
  92119. * \code file != NULL \endcode
  92120. * \retval FLAC__StreamEncoderInitStatus
  92121. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92122. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92123. */
  92124. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92125. /** Initialize the encoder instance to encode Ogg FLAC files.
  92126. *
  92127. * This flavor of initialization sets up the encoder to encode to a
  92128. * plain Ogg FLAC file. For non-stdio streams, you must use
  92129. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92130. *
  92131. * This function should be called after FLAC__stream_encoder_new() and
  92132. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92133. * or FLAC__stream_encoder_process_interleaved().
  92134. * initialization succeeded.
  92135. *
  92136. * \param encoder An uninitialized encoder instance.
  92137. * \param file An open file. The file should have been opened
  92138. * with mode \c "w+b" and rewound. The file
  92139. * becomes owned by the encoder and should not be
  92140. * manipulated by the client while encoding.
  92141. * Unless \a file is \c stdout, it will be closed
  92142. * when FLAC__stream_encoder_finish() is called.
  92143. * Note however that a proper SEEKTABLE cannot be
  92144. * created when encoding to \c stdout since it is
  92145. * not seekable.
  92146. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92147. * pointer may be \c NULL if the callback is not
  92148. * desired.
  92149. * \param client_data This value will be supplied to callbacks in their
  92150. * \a client_data argument.
  92151. * \assert
  92152. * \code encoder != NULL \endcode
  92153. * \code file != NULL \endcode
  92154. * \retval FLAC__StreamEncoderInitStatus
  92155. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92156. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92157. */
  92158. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92159. /** Initialize the encoder instance to encode native FLAC files.
  92160. *
  92161. * This flavor of initialization sets up the encoder to encode to a plain
  92162. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92163. * with Unicode filenames on Windows), you must use
  92164. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92165. * and provide callbacks for the I/O.
  92166. *
  92167. * This function should be called after FLAC__stream_encoder_new() and
  92168. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92169. * or FLAC__stream_encoder_process_interleaved().
  92170. * initialization succeeded.
  92171. *
  92172. * \param encoder An uninitialized encoder instance.
  92173. * \param filename The name of the file to encode to. The file will
  92174. * be opened with fopen(). Use \c NULL to encode to
  92175. * \c stdout. Note however that a proper SEEKTABLE
  92176. * cannot be created when encoding to \c stdout since
  92177. * it is not seekable.
  92178. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92179. * pointer may be \c NULL if the callback is not
  92180. * desired.
  92181. * \param client_data This value will be supplied to callbacks in their
  92182. * \a client_data argument.
  92183. * \assert
  92184. * \code encoder != NULL \endcode
  92185. * \retval FLAC__StreamEncoderInitStatus
  92186. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92187. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92188. */
  92189. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92190. /** Initialize the encoder instance to encode Ogg FLAC files.
  92191. *
  92192. * This flavor of initialization sets up the encoder to encode to a plain
  92193. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92194. * with Unicode filenames on Windows), you must use
  92195. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92196. * and provide callbacks for the I/O.
  92197. *
  92198. * This function should be called after FLAC__stream_encoder_new() and
  92199. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92200. * or FLAC__stream_encoder_process_interleaved().
  92201. * initialization succeeded.
  92202. *
  92203. * \param encoder An uninitialized encoder instance.
  92204. * \param filename The name of the file to encode to. The file will
  92205. * be opened with fopen(). Use \c NULL to encode to
  92206. * \c stdout. Note however that a proper SEEKTABLE
  92207. * cannot be created when encoding to \c stdout since
  92208. * it is not seekable.
  92209. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92210. * pointer may be \c NULL if the callback is not
  92211. * desired.
  92212. * \param client_data This value will be supplied to callbacks in their
  92213. * \a client_data argument.
  92214. * \assert
  92215. * \code encoder != NULL \endcode
  92216. * \retval FLAC__StreamEncoderInitStatus
  92217. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92218. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92219. */
  92220. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92221. /** Finish the encoding process.
  92222. * Flushes the encoding buffer, releases resources, resets the encoder
  92223. * settings to their defaults, and returns the encoder state to
  92224. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92225. * one or more write callbacks before returning, and will generate
  92226. * a metadata callback.
  92227. *
  92228. * Note that in the course of processing the last frame, errors can
  92229. * occur, so the caller should be sure to check the return value to
  92230. * ensure the file was encoded properly.
  92231. *
  92232. * In the event of a prematurely-terminated encode, it is not strictly
  92233. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92234. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92235. * with a FLAC__stream_encoder_finish().
  92236. *
  92237. * \param encoder An uninitialized encoder instance.
  92238. * \assert
  92239. * \code encoder != NULL \endcode
  92240. * \retval FLAC__bool
  92241. * \c false if an error occurred processing the last frame; or if verify
  92242. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92243. * verify mismatch; else \c true. If \c false, caller should check the
  92244. * state with FLAC__stream_encoder_get_state() for more information
  92245. * about the error.
  92246. */
  92247. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92248. /** Submit data for encoding.
  92249. * This version allows you to supply the input data via an array of
  92250. * pointers, each pointer pointing to an array of \a samples samples
  92251. * representing one channel. The samples need not be block-aligned,
  92252. * but each channel should have the same number of samples. Each sample
  92253. * should be a signed integer, right-justified to the resolution set by
  92254. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92255. * resolution is 16 bits per sample, the samples should all be in the
  92256. * range [-32768,32767].
  92257. *
  92258. * For applications where channel order is important, channels must
  92259. * follow the order as described in the
  92260. * <A HREF="../format.html#frame_header">frame header</A>.
  92261. *
  92262. * \param encoder An initialized encoder instance in the OK state.
  92263. * \param buffer An array of pointers to each channel's signal.
  92264. * \param samples The number of samples in one channel.
  92265. * \assert
  92266. * \code encoder != NULL \endcode
  92267. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92268. * \retval FLAC__bool
  92269. * \c true if successful, else \c false; in this case, check the
  92270. * encoder state with FLAC__stream_encoder_get_state() to see what
  92271. * went wrong.
  92272. */
  92273. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92274. /** Submit data for encoding.
  92275. * This version allows you to supply the input data where the channels
  92276. * are interleaved into a single array (i.e. channel0_sample0,
  92277. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92278. * The samples need not be block-aligned but they must be
  92279. * sample-aligned, i.e. the first value should be channel0_sample0
  92280. * and the last value channelN_sampleM. Each sample should be a signed
  92281. * integer, right-justified to the resolution set by
  92282. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92283. * resolution is 16 bits per sample, the samples should all be in the
  92284. * range [-32768,32767].
  92285. *
  92286. * For applications where channel order is important, channels must
  92287. * follow the order as described in the
  92288. * <A HREF="../format.html#frame_header">frame header</A>.
  92289. *
  92290. * \param encoder An initialized encoder instance in the OK state.
  92291. * \param buffer An array of channel-interleaved data (see above).
  92292. * \param samples The number of samples in one channel, the same as for
  92293. * FLAC__stream_encoder_process(). For example, if
  92294. * encoding two channels, \c 1000 \a samples corresponds
  92295. * to a \a buffer of 2000 values.
  92296. * \assert
  92297. * \code encoder != NULL \endcode
  92298. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92299. * \retval FLAC__bool
  92300. * \c true if successful, else \c false; in this case, check the
  92301. * encoder state with FLAC__stream_encoder_get_state() to see what
  92302. * went wrong.
  92303. */
  92304. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92305. /* \} */
  92306. #ifdef __cplusplus
  92307. }
  92308. #endif
  92309. #endif
  92310. /*** End of inlined file: stream_encoder.h ***/
  92311. #ifdef _MSC_VER
  92312. /* OPT: an MSVC built-in would be better */
  92313. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92314. {
  92315. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92316. return (x>>16) | (x<<16);
  92317. }
  92318. #endif
  92319. #if defined(_MSC_VER) && defined(_X86_)
  92320. /* OPT: an MSVC built-in would be better */
  92321. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92322. {
  92323. __asm {
  92324. mov edx, start
  92325. mov ecx, len
  92326. test ecx, ecx
  92327. loop1:
  92328. jz done1
  92329. mov eax, [edx]
  92330. bswap eax
  92331. mov [edx], eax
  92332. add edx, 4
  92333. dec ecx
  92334. jmp short loop1
  92335. done1:
  92336. }
  92337. }
  92338. #endif
  92339. /** \mainpage
  92340. *
  92341. * \section intro Introduction
  92342. *
  92343. * This is the documentation for the FLAC C and C++ APIs. It is
  92344. * highly interconnected; this introduction should give you a top
  92345. * level idea of the structure and how to find the information you
  92346. * need. As a prerequisite you should have at least a basic
  92347. * knowledge of the FLAC format, documented
  92348. * <A HREF="../format.html">here</A>.
  92349. *
  92350. * \section c_api FLAC C API
  92351. *
  92352. * The FLAC C API is the interface to libFLAC, a set of structures
  92353. * describing the components of FLAC streams, and functions for
  92354. * encoding and decoding streams, as well as manipulating FLAC
  92355. * metadata in files. The public include files will be installed
  92356. * in your include area (for example /usr/include/FLAC/...).
  92357. *
  92358. * By writing a little code and linking against libFLAC, it is
  92359. * relatively easy to add FLAC support to another program. The
  92360. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92361. * Complete source code of libFLAC as well as the command-line
  92362. * encoder and plugins is available and is a useful source of
  92363. * examples.
  92364. *
  92365. * Aside from encoders and decoders, libFLAC provides a powerful
  92366. * metadata interface for manipulating metadata in FLAC files. It
  92367. * allows the user to add, delete, and modify FLAC metadata blocks
  92368. * and it can automatically take advantage of PADDING blocks to avoid
  92369. * rewriting the entire FLAC file when changing the size of the
  92370. * metadata.
  92371. *
  92372. * libFLAC usually only requires the standard C library and C math
  92373. * library. In particular, threading is not used so there is no
  92374. * dependency on a thread library. However, libFLAC does not use
  92375. * global variables and should be thread-safe.
  92376. *
  92377. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92378. * However the metadata editing interfaces currently have limited
  92379. * read-only support for Ogg FLAC files.
  92380. *
  92381. * \section cpp_api FLAC C++ API
  92382. *
  92383. * The FLAC C++ API is a set of classes that encapsulate the
  92384. * structures and functions in libFLAC. They provide slightly more
  92385. * functionality with respect to metadata but are otherwise
  92386. * equivalent. For the most part, they share the same usage as
  92387. * their counterparts in libFLAC, and the FLAC C API documentation
  92388. * can be used as a supplement. The public include files
  92389. * for the C++ API will be installed in your include area (for
  92390. * example /usr/include/FLAC++/...).
  92391. *
  92392. * libFLAC++ is also licensed under
  92393. * <A HREF="../license.html">Xiph's BSD license</A>.
  92394. *
  92395. * \section getting_started Getting Started
  92396. *
  92397. * A good starting point for learning the API is to browse through
  92398. * the <A HREF="modules.html">modules</A>. Modules are logical
  92399. * groupings of related functions or classes, which correspond roughly
  92400. * to header files or sections of header files. Each module includes a
  92401. * detailed description of the general usage of its functions or
  92402. * classes.
  92403. *
  92404. * From there you can go on to look at the documentation of
  92405. * individual functions. You can see different views of the individual
  92406. * functions through the links in top bar across this page.
  92407. *
  92408. * If you prefer a more hands-on approach, you can jump right to some
  92409. * <A HREF="../documentation_example_code.html">example code</A>.
  92410. *
  92411. * \section porting_guide Porting Guide
  92412. *
  92413. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92414. * has been introduced which gives detailed instructions on how to
  92415. * port your code to newer versions of FLAC.
  92416. *
  92417. * \section embedded_developers Embedded Developers
  92418. *
  92419. * libFLAC has grown larger over time as more functionality has been
  92420. * included, but much of it may be unnecessary for a particular embedded
  92421. * implementation. Unused parts may be pruned by some simple editing of
  92422. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92423. * metadata interface are all independent from each other.
  92424. *
  92425. * It is easiest to just describe the dependencies:
  92426. *
  92427. * - All modules depend on the \link flac_format Format \endlink module.
  92428. * - The decoders and encoders depend on the bitbuffer.
  92429. * - The decoder is independent of the encoder. The encoder uses the
  92430. * decoder because of the verify feature, but this can be removed if
  92431. * not needed.
  92432. * - Parts of the metadata interface require the stream decoder (but not
  92433. * the encoder).
  92434. * - Ogg support is selectable through the compile time macro
  92435. * \c FLAC__HAS_OGG.
  92436. *
  92437. * For example, if your application only requires the stream decoder, no
  92438. * encoder, and no metadata interface, you can remove the stream encoder
  92439. * and the metadata interface, which will greatly reduce the size of the
  92440. * library.
  92441. *
  92442. * Also, there are several places in the libFLAC code with comments marked
  92443. * with "OPT:" where a #define can be changed to enable code that might be
  92444. * faster on a specific platform. Experimenting with these can yield faster
  92445. * binaries.
  92446. */
  92447. /** \defgroup porting Porting Guide for New Versions
  92448. *
  92449. * This module describes differences in the library interfaces from
  92450. * version to version. It assists in the porting of code that uses
  92451. * the libraries to newer versions of FLAC.
  92452. *
  92453. * One simple facility for making porting easier that has been added
  92454. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92455. * library's includes (e.g. \c include/FLAC/export.h). The
  92456. * \c #defines mirror the libraries'
  92457. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92458. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92459. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92460. * These can be used to support multiple versions of an API during the
  92461. * transition phase, e.g.
  92462. *
  92463. * \code
  92464. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92465. * legacy code
  92466. * #else
  92467. * new code
  92468. * #endif
  92469. * \endcode
  92470. *
  92471. * The the source will work for multiple versions and the legacy code can
  92472. * easily be removed when the transition is complete.
  92473. *
  92474. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92475. * include/FLAC/export.h), which can be used to determine whether or not
  92476. * the library has been compiled with support for Ogg FLAC. This is
  92477. * simpler than trying to call an Ogg init function and catching the
  92478. * error.
  92479. */
  92480. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92481. * \ingroup porting
  92482. *
  92483. * \brief
  92484. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92485. *
  92486. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92487. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92488. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92489. * decoding layers and three encoding layers have been merged into a
  92490. * single stream decoder and stream encoder. That is, the functionality
  92491. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92492. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92493. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92494. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92495. * is there is now a single API that can be used to encode or decode
  92496. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92497. * on both seekable and non-seekable streams.
  92498. *
  92499. * Instead of creating an encoder or decoder of a certain layer, now the
  92500. * client will always create a FLAC__StreamEncoder or
  92501. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92502. * initialization function. For example, for the decoder,
  92503. * FLAC__stream_decoder_init() has been replaced by
  92504. * FLAC__stream_decoder_init_stream(). This init function takes
  92505. * callbacks for the I/O, and the seeking callbacks are optional. This
  92506. * allows the client to use the same object for seekable and
  92507. * non-seekable streams. For decoding a FLAC file directly, the client
  92508. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92509. * and fewer callbacks; most of the other callbacks are supplied
  92510. * internally. For situations where fopen()ing by filename is not
  92511. * possible (e.g. Unicode filenames on Windows) the client can instead
  92512. * open the file itself and supply the FILE* to
  92513. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92514. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92515. * Since the callbacks and client data are now passed to the init
  92516. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92517. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92518. * rest of the calls to the decoder are the same as before.
  92519. *
  92520. * There are counterpart init functions for Ogg FLAC, e.g.
  92521. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92522. * and callbacks are the same as for native FLAC.
  92523. *
  92524. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92525. * been set up like so:
  92526. *
  92527. * \code
  92528. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92529. * if(decoder == NULL) do_something;
  92530. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92531. * [... other settings ...]
  92532. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92533. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92534. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92535. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92536. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92537. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92538. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92539. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92540. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92541. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92542. * \endcode
  92543. *
  92544. * In FLAC 1.1.3 it is like this:
  92545. *
  92546. * \code
  92547. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92548. * if(decoder == NULL) do_something;
  92549. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92550. * [... other settings ...]
  92551. * if(FLAC__stream_decoder_init_stream(
  92552. * decoder,
  92553. * my_read_callback,
  92554. * my_seek_callback, // or NULL
  92555. * my_tell_callback, // or NULL
  92556. * my_length_callback, // or NULL
  92557. * my_eof_callback, // or NULL
  92558. * my_write_callback,
  92559. * my_metadata_callback, // or NULL
  92560. * my_error_callback,
  92561. * my_client_data
  92562. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92563. * \endcode
  92564. *
  92565. * or you could do;
  92566. *
  92567. * \code
  92568. * [...]
  92569. * FILE *file = fopen("somefile.flac","rb");
  92570. * if(file == NULL) do_somthing;
  92571. * if(FLAC__stream_decoder_init_FILE(
  92572. * decoder,
  92573. * file,
  92574. * my_write_callback,
  92575. * my_metadata_callback, // or NULL
  92576. * my_error_callback,
  92577. * my_client_data
  92578. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92579. * \endcode
  92580. *
  92581. * or just:
  92582. *
  92583. * \code
  92584. * [...]
  92585. * if(FLAC__stream_decoder_init_file(
  92586. * decoder,
  92587. * "somefile.flac",
  92588. * my_write_callback,
  92589. * my_metadata_callback, // or NULL
  92590. * my_error_callback,
  92591. * my_client_data
  92592. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92593. * \endcode
  92594. *
  92595. * Another small change to the decoder is in how it handles unparseable
  92596. * streams. Before, when the decoder found an unparseable stream
  92597. * (reserved for when the decoder encounters a stream from a future
  92598. * encoder that it can't parse), it changed the state to
  92599. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92600. * drops sync and calls the error callback with a new error code
  92601. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92602. * more robust. If your error callback does not discriminate on the the
  92603. * error state, your code does not need to be changed.
  92604. *
  92605. * The encoder now has a new setting:
  92606. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92607. * method used to window the data before LPC analysis. You only need to
  92608. * add a call to this function if the default is not suitable. There
  92609. * are also two new convenience functions that may be useful:
  92610. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92611. * FLAC__metadata_get_cuesheet().
  92612. *
  92613. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92614. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92615. * is now \c size_t instead of \c unsigned.
  92616. */
  92617. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92618. * \ingroup porting
  92619. *
  92620. * \brief
  92621. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92622. *
  92623. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92624. * There was a slight change in the implementation of
  92625. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92626. * of the \a metadata array of pointers so the client no longer needs
  92627. * to maintain it after the call. The objects themselves that are
  92628. * pointed to by the array are still not copied though and must be
  92629. * maintained until the call to FLAC__stream_encoder_finish().
  92630. */
  92631. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92632. * \ingroup porting
  92633. *
  92634. * \brief
  92635. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92636. *
  92637. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92638. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92639. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92640. *
  92641. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92642. * has changed to reflect the conversion of one of the reserved bits
  92643. * into active use. It used to be \c 2 and now is \c 1. However the
  92644. * FLAC frame header length has not changed, so to skip the proper
  92645. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92646. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92647. */
  92648. /** \defgroup flac FLAC C API
  92649. *
  92650. * The FLAC C API is the interface to libFLAC, a set of structures
  92651. * describing the components of FLAC streams, and functions for
  92652. * encoding and decoding streams, as well as manipulating FLAC
  92653. * metadata in files.
  92654. *
  92655. * You should start with the format components as all other modules
  92656. * are dependent on it.
  92657. */
  92658. #endif
  92659. /*** End of inlined file: all.h ***/
  92660. /*** Start of inlined file: bitmath.c ***/
  92661. /*** Start of inlined file: juce_FlacHeader.h ***/
  92662. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92663. // tasks..
  92664. #define VERSION "1.2.1"
  92665. #define FLAC__NO_DLL 1
  92666. #if JUCE_MSVC
  92667. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92668. #endif
  92669. #if JUCE_MAC
  92670. #define FLAC__SYS_DARWIN 1
  92671. #endif
  92672. /*** End of inlined file: juce_FlacHeader.h ***/
  92673. #if JUCE_USE_FLAC
  92674. #if HAVE_CONFIG_H
  92675. # include <config.h>
  92676. #endif
  92677. /*** Start of inlined file: bitmath.h ***/
  92678. #ifndef FLAC__PRIVATE__BITMATH_H
  92679. #define FLAC__PRIVATE__BITMATH_H
  92680. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92681. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92682. unsigned FLAC__bitmath_silog2(int v);
  92683. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92684. #endif
  92685. /*** End of inlined file: bitmath.h ***/
  92686. /* An example of what FLAC__bitmath_ilog2() computes:
  92687. *
  92688. * ilog2( 0) = assertion failure
  92689. * ilog2( 1) = 0
  92690. * ilog2( 2) = 1
  92691. * ilog2( 3) = 1
  92692. * ilog2( 4) = 2
  92693. * ilog2( 5) = 2
  92694. * ilog2( 6) = 2
  92695. * ilog2( 7) = 2
  92696. * ilog2( 8) = 3
  92697. * ilog2( 9) = 3
  92698. * ilog2(10) = 3
  92699. * ilog2(11) = 3
  92700. * ilog2(12) = 3
  92701. * ilog2(13) = 3
  92702. * ilog2(14) = 3
  92703. * ilog2(15) = 3
  92704. * ilog2(16) = 4
  92705. * ilog2(17) = 4
  92706. * ilog2(18) = 4
  92707. */
  92708. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92709. {
  92710. unsigned l = 0;
  92711. FLAC__ASSERT(v > 0);
  92712. while(v >>= 1)
  92713. l++;
  92714. return l;
  92715. }
  92716. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92717. {
  92718. unsigned l = 0;
  92719. FLAC__ASSERT(v > 0);
  92720. while(v >>= 1)
  92721. l++;
  92722. return l;
  92723. }
  92724. /* An example of what FLAC__bitmath_silog2() computes:
  92725. *
  92726. * silog2(-10) = 5
  92727. * silog2(- 9) = 5
  92728. * silog2(- 8) = 4
  92729. * silog2(- 7) = 4
  92730. * silog2(- 6) = 4
  92731. * silog2(- 5) = 4
  92732. * silog2(- 4) = 3
  92733. * silog2(- 3) = 3
  92734. * silog2(- 2) = 2
  92735. * silog2(- 1) = 2
  92736. * silog2( 0) = 0
  92737. * silog2( 1) = 2
  92738. * silog2( 2) = 3
  92739. * silog2( 3) = 3
  92740. * silog2( 4) = 4
  92741. * silog2( 5) = 4
  92742. * silog2( 6) = 4
  92743. * silog2( 7) = 4
  92744. * silog2( 8) = 5
  92745. * silog2( 9) = 5
  92746. * silog2( 10) = 5
  92747. */
  92748. unsigned FLAC__bitmath_silog2(int v)
  92749. {
  92750. while(1) {
  92751. if(v == 0) {
  92752. return 0;
  92753. }
  92754. else if(v > 0) {
  92755. unsigned l = 0;
  92756. while(v) {
  92757. l++;
  92758. v >>= 1;
  92759. }
  92760. return l+1;
  92761. }
  92762. else if(v == -1) {
  92763. return 2;
  92764. }
  92765. else {
  92766. v++;
  92767. v = -v;
  92768. }
  92769. }
  92770. }
  92771. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92772. {
  92773. while(1) {
  92774. if(v == 0) {
  92775. return 0;
  92776. }
  92777. else if(v > 0) {
  92778. unsigned l = 0;
  92779. while(v) {
  92780. l++;
  92781. v >>= 1;
  92782. }
  92783. return l+1;
  92784. }
  92785. else if(v == -1) {
  92786. return 2;
  92787. }
  92788. else {
  92789. v++;
  92790. v = -v;
  92791. }
  92792. }
  92793. }
  92794. #endif
  92795. /*** End of inlined file: bitmath.c ***/
  92796. /*** Start of inlined file: bitreader.c ***/
  92797. /*** Start of inlined file: juce_FlacHeader.h ***/
  92798. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92799. // tasks..
  92800. #define VERSION "1.2.1"
  92801. #define FLAC__NO_DLL 1
  92802. #if JUCE_MSVC
  92803. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92804. #endif
  92805. #if JUCE_MAC
  92806. #define FLAC__SYS_DARWIN 1
  92807. #endif
  92808. /*** End of inlined file: juce_FlacHeader.h ***/
  92809. #if JUCE_USE_FLAC
  92810. #if HAVE_CONFIG_H
  92811. # include <config.h>
  92812. #endif
  92813. #include <stdlib.h> /* for malloc() */
  92814. #include <string.h> /* for memcpy(), memset() */
  92815. #ifdef _MSC_VER
  92816. #include <winsock.h> /* for ntohl() */
  92817. #elif defined FLAC__SYS_DARWIN
  92818. #include <machine/endian.h> /* for ntohl() */
  92819. #elif defined __MINGW32__
  92820. #include <winsock.h> /* for ntohl() */
  92821. #else
  92822. #include <netinet/in.h> /* for ntohl() */
  92823. #endif
  92824. /*** Start of inlined file: bitreader.h ***/
  92825. #ifndef FLAC__PRIVATE__BITREADER_H
  92826. #define FLAC__PRIVATE__BITREADER_H
  92827. #include <stdio.h> /* for FILE */
  92828. /*** Start of inlined file: cpu.h ***/
  92829. #ifndef FLAC__PRIVATE__CPU_H
  92830. #define FLAC__PRIVATE__CPU_H
  92831. #ifdef HAVE_CONFIG_H
  92832. #include <config.h>
  92833. #endif
  92834. typedef enum {
  92835. FLAC__CPUINFO_TYPE_IA32,
  92836. FLAC__CPUINFO_TYPE_PPC,
  92837. FLAC__CPUINFO_TYPE_UNKNOWN
  92838. } FLAC__CPUInfo_Type;
  92839. typedef struct {
  92840. FLAC__bool cpuid;
  92841. FLAC__bool bswap;
  92842. FLAC__bool cmov;
  92843. FLAC__bool mmx;
  92844. FLAC__bool fxsr;
  92845. FLAC__bool sse;
  92846. FLAC__bool sse2;
  92847. FLAC__bool sse3;
  92848. FLAC__bool ssse3;
  92849. FLAC__bool _3dnow;
  92850. FLAC__bool ext3dnow;
  92851. FLAC__bool extmmx;
  92852. } FLAC__CPUInfo_IA32;
  92853. typedef struct {
  92854. FLAC__bool altivec;
  92855. FLAC__bool ppc64;
  92856. } FLAC__CPUInfo_PPC;
  92857. typedef struct {
  92858. FLAC__bool use_asm;
  92859. FLAC__CPUInfo_Type type;
  92860. union {
  92861. FLAC__CPUInfo_IA32 ia32;
  92862. FLAC__CPUInfo_PPC ppc;
  92863. } data;
  92864. } FLAC__CPUInfo;
  92865. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92866. #ifndef FLAC__NO_ASM
  92867. #ifdef FLAC__CPU_IA32
  92868. #ifdef FLAC__HAS_NASM
  92869. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92870. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92871. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92872. #endif
  92873. #endif
  92874. #endif
  92875. #endif
  92876. /*** End of inlined file: cpu.h ***/
  92877. /*
  92878. * opaque structure definition
  92879. */
  92880. struct FLAC__BitReader;
  92881. typedef struct FLAC__BitReader FLAC__BitReader;
  92882. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92883. /*
  92884. * construction, deletion, initialization, etc functions
  92885. */
  92886. FLAC__BitReader *FLAC__bitreader_new(void);
  92887. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92888. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92889. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92890. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92891. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92892. /*
  92893. * CRC functions
  92894. */
  92895. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92896. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92897. /*
  92898. * info functions
  92899. */
  92900. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92901. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92902. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92903. /*
  92904. * read functions
  92905. */
  92906. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92907. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92908. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92909. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92910. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92911. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92912. 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! */
  92913. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92914. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92915. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92916. #ifndef FLAC__NO_ASM
  92917. # ifdef FLAC__CPU_IA32
  92918. # ifdef FLAC__HAS_NASM
  92919. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92920. # endif
  92921. # endif
  92922. #endif
  92923. #if 0 /* UNUSED */
  92924. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92925. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92926. #endif
  92927. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92928. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92929. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92930. #endif
  92931. /*** End of inlined file: bitreader.h ***/
  92932. /*** Start of inlined file: crc.h ***/
  92933. #ifndef FLAC__PRIVATE__CRC_H
  92934. #define FLAC__PRIVATE__CRC_H
  92935. /* 8 bit CRC generator, MSB shifted first
  92936. ** polynomial = x^8 + x^2 + x^1 + x^0
  92937. ** init = 0
  92938. */
  92939. extern FLAC__byte const FLAC__crc8_table[256];
  92940. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92941. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92942. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92943. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92944. /* 16 bit CRC generator, MSB shifted first
  92945. ** polynomial = x^16 + x^15 + x^2 + x^0
  92946. ** init = 0
  92947. */
  92948. extern unsigned FLAC__crc16_table[256];
  92949. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92950. /* this alternate may be faster on some systems/compilers */
  92951. #if 0
  92952. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92953. #endif
  92954. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92955. #endif
  92956. /*** End of inlined file: crc.h ***/
  92957. /* Things should be fastest when this matches the machine word size */
  92958. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92959. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92960. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92961. typedef FLAC__uint32 brword;
  92962. #define FLAC__BYTES_PER_WORD 4
  92963. #define FLAC__BITS_PER_WORD 32
  92964. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92965. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92966. #if WORDS_BIGENDIAN
  92967. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92968. #else
  92969. #if defined (_MSC_VER) && defined (_X86_)
  92970. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92971. #else
  92972. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92973. #endif
  92974. #endif
  92975. /* counts the # of zero MSBs in a word */
  92976. #define COUNT_ZERO_MSBS(word) ( \
  92977. (word) <= 0xffff ? \
  92978. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92979. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92980. )
  92981. /* this alternate might be slightly faster on some systems/compilers: */
  92982. #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])) )
  92983. /*
  92984. * This should be at least twice as large as the largest number of words
  92985. * required to represent any 'number' (in any encoding) you are going to
  92986. * read. With FLAC this is on the order of maybe a few hundred bits.
  92987. * If the buffer is smaller than that, the decoder won't be able to read
  92988. * in a whole number that is in a variable length encoding (e.g. Rice).
  92989. * But to be practical it should be at least 1K bytes.
  92990. *
  92991. * Increase this number to decrease the number of read callbacks, at the
  92992. * expense of using more memory. Or decrease for the reverse effect,
  92993. * keeping in mind the limit from the first paragraph. The optimal size
  92994. * also depends on the CPU cache size and other factors; some twiddling
  92995. * may be necessary to squeeze out the best performance.
  92996. */
  92997. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92998. static const unsigned char byte_to_unary_table[] = {
  92999. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93000. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93001. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93002. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93003. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93004. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93005. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93006. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93015. };
  93016. #ifdef min
  93017. #undef min
  93018. #endif
  93019. #define min(x,y) ((x)<(y)?(x):(y))
  93020. #ifdef max
  93021. #undef max
  93022. #endif
  93023. #define max(x,y) ((x)>(y)?(x):(y))
  93024. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93025. #ifdef _MSC_VER
  93026. #define FLAC__U64L(x) x
  93027. #else
  93028. #define FLAC__U64L(x) x##LLU
  93029. #endif
  93030. #ifndef FLaC__INLINE
  93031. #define FLaC__INLINE
  93032. #endif
  93033. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93034. struct FLAC__BitReader {
  93035. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93036. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93037. brword *buffer;
  93038. unsigned capacity; /* in words */
  93039. unsigned words; /* # of completed words in buffer */
  93040. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93041. unsigned consumed_words; /* #words ... */
  93042. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93043. unsigned read_crc16; /* the running frame CRC */
  93044. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93045. FLAC__BitReaderReadCallback read_callback;
  93046. void *client_data;
  93047. FLAC__CPUInfo cpu_info;
  93048. };
  93049. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93050. {
  93051. register unsigned crc = br->read_crc16;
  93052. #if FLAC__BYTES_PER_WORD == 4
  93053. switch(br->crc16_align) {
  93054. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93055. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93056. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93057. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93058. }
  93059. #elif FLAC__BYTES_PER_WORD == 8
  93060. switch(br->crc16_align) {
  93061. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93062. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93063. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93064. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93065. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93066. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93067. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93068. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93069. }
  93070. #else
  93071. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93072. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93073. br->read_crc16 = crc;
  93074. #endif
  93075. br->crc16_align = 0;
  93076. }
  93077. /* would be static except it needs to be called by asm routines */
  93078. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93079. {
  93080. unsigned start, end;
  93081. size_t bytes;
  93082. FLAC__byte *target;
  93083. /* first shift the unconsumed buffer data toward the front as much as possible */
  93084. if(br->consumed_words > 0) {
  93085. start = br->consumed_words;
  93086. end = br->words + (br->bytes? 1:0);
  93087. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93088. br->words -= start;
  93089. br->consumed_words = 0;
  93090. }
  93091. /*
  93092. * set the target for reading, taking into account word alignment and endianness
  93093. */
  93094. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93095. if(bytes == 0)
  93096. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93097. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93098. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93099. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93100. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93101. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93102. * ^^-------target, bytes=3
  93103. * on LE machines, have to byteswap the odd tail word so nothing is
  93104. * overwritten:
  93105. */
  93106. #if WORDS_BIGENDIAN
  93107. #else
  93108. if(br->bytes)
  93109. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93110. #endif
  93111. /* now it looks like:
  93112. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93113. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93114. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93115. * ^^-------target, bytes=3
  93116. */
  93117. /* read in the data; note that the callback may return a smaller number of bytes */
  93118. if(!br->read_callback(target, &bytes, br->client_data))
  93119. return false;
  93120. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93121. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93122. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93123. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93124. * now have to byteswap on LE machines:
  93125. */
  93126. #if WORDS_BIGENDIAN
  93127. #else
  93128. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93129. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93130. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93131. start = br->words;
  93132. local_swap32_block_(br->buffer + start, end - start);
  93133. }
  93134. else
  93135. # endif
  93136. for(start = br->words; start < end; start++)
  93137. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93138. #endif
  93139. /* now it looks like:
  93140. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93141. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93142. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93143. * finally we'll update the reader values:
  93144. */
  93145. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93146. br->words = end / FLAC__BYTES_PER_WORD;
  93147. br->bytes = end % FLAC__BYTES_PER_WORD;
  93148. return true;
  93149. }
  93150. /***********************************************************************
  93151. *
  93152. * Class constructor/destructor
  93153. *
  93154. ***********************************************************************/
  93155. FLAC__BitReader *FLAC__bitreader_new(void)
  93156. {
  93157. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93158. /* calloc() implies:
  93159. memset(br, 0, sizeof(FLAC__BitReader));
  93160. br->buffer = 0;
  93161. br->capacity = 0;
  93162. br->words = br->bytes = 0;
  93163. br->consumed_words = br->consumed_bits = 0;
  93164. br->read_callback = 0;
  93165. br->client_data = 0;
  93166. */
  93167. return br;
  93168. }
  93169. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93170. {
  93171. FLAC__ASSERT(0 != br);
  93172. FLAC__bitreader_free(br);
  93173. free(br);
  93174. }
  93175. /***********************************************************************
  93176. *
  93177. * Public class methods
  93178. *
  93179. ***********************************************************************/
  93180. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93181. {
  93182. FLAC__ASSERT(0 != br);
  93183. br->words = br->bytes = 0;
  93184. br->consumed_words = br->consumed_bits = 0;
  93185. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93186. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93187. if(br->buffer == 0)
  93188. return false;
  93189. br->read_callback = rcb;
  93190. br->client_data = cd;
  93191. br->cpu_info = cpu;
  93192. return true;
  93193. }
  93194. void FLAC__bitreader_free(FLAC__BitReader *br)
  93195. {
  93196. FLAC__ASSERT(0 != br);
  93197. if(0 != br->buffer)
  93198. free(br->buffer);
  93199. br->buffer = 0;
  93200. br->capacity = 0;
  93201. br->words = br->bytes = 0;
  93202. br->consumed_words = br->consumed_bits = 0;
  93203. br->read_callback = 0;
  93204. br->client_data = 0;
  93205. }
  93206. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93207. {
  93208. br->words = br->bytes = 0;
  93209. br->consumed_words = br->consumed_bits = 0;
  93210. return true;
  93211. }
  93212. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93213. {
  93214. unsigned i, j;
  93215. if(br == 0) {
  93216. fprintf(out, "bitreader is NULL\n");
  93217. }
  93218. else {
  93219. 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);
  93220. for(i = 0; i < br->words; i++) {
  93221. fprintf(out, "%08X: ", i);
  93222. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93223. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93224. fprintf(out, ".");
  93225. else
  93226. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93227. fprintf(out, "\n");
  93228. }
  93229. if(br->bytes > 0) {
  93230. fprintf(out, "%08X: ", i);
  93231. for(j = 0; j < br->bytes*8; j++)
  93232. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93233. fprintf(out, ".");
  93234. else
  93235. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93236. fprintf(out, "\n");
  93237. }
  93238. }
  93239. }
  93240. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93241. {
  93242. FLAC__ASSERT(0 != br);
  93243. FLAC__ASSERT(0 != br->buffer);
  93244. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93245. br->read_crc16 = (unsigned)seed;
  93246. br->crc16_align = br->consumed_bits;
  93247. }
  93248. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93249. {
  93250. FLAC__ASSERT(0 != br);
  93251. FLAC__ASSERT(0 != br->buffer);
  93252. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93253. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93254. /* CRC any tail bytes in a partially-consumed word */
  93255. if(br->consumed_bits) {
  93256. const brword tail = br->buffer[br->consumed_words];
  93257. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93258. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93259. }
  93260. return br->read_crc16;
  93261. }
  93262. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93263. {
  93264. return ((br->consumed_bits & 7) == 0);
  93265. }
  93266. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93267. {
  93268. return 8 - (br->consumed_bits & 7);
  93269. }
  93270. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93271. {
  93272. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93273. }
  93274. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93275. {
  93276. FLAC__ASSERT(0 != br);
  93277. FLAC__ASSERT(0 != br->buffer);
  93278. FLAC__ASSERT(bits <= 32);
  93279. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93280. FLAC__ASSERT(br->consumed_words <= br->words);
  93281. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93282. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93283. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93284. *val = 0;
  93285. return true;
  93286. }
  93287. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93288. if(!bitreader_read_from_client_(br))
  93289. return false;
  93290. }
  93291. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93292. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93293. if(br->consumed_bits) {
  93294. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93295. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93296. const brword word = br->buffer[br->consumed_words];
  93297. if(bits < n) {
  93298. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93299. br->consumed_bits += bits;
  93300. return true;
  93301. }
  93302. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93303. bits -= n;
  93304. crc16_update_word_(br, word);
  93305. br->consumed_words++;
  93306. br->consumed_bits = 0;
  93307. 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 */
  93308. *val <<= bits;
  93309. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93310. br->consumed_bits = bits;
  93311. }
  93312. return true;
  93313. }
  93314. else {
  93315. const brword word = br->buffer[br->consumed_words];
  93316. if(bits < FLAC__BITS_PER_WORD) {
  93317. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93318. br->consumed_bits = bits;
  93319. return true;
  93320. }
  93321. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93322. *val = word;
  93323. crc16_update_word_(br, word);
  93324. br->consumed_words++;
  93325. return true;
  93326. }
  93327. }
  93328. else {
  93329. /* in this case we're starting our read at a partial tail word;
  93330. * the reader has guaranteed that we have at least 'bits' bits
  93331. * available to read, which makes this case simpler.
  93332. */
  93333. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93334. if(br->consumed_bits) {
  93335. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93336. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93337. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93338. br->consumed_bits += bits;
  93339. return true;
  93340. }
  93341. else {
  93342. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93343. br->consumed_bits += bits;
  93344. return true;
  93345. }
  93346. }
  93347. }
  93348. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93349. {
  93350. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93351. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93352. return false;
  93353. /* sign-extend: */
  93354. *val <<= (32-bits);
  93355. *val >>= (32-bits);
  93356. return true;
  93357. }
  93358. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93359. {
  93360. FLAC__uint32 hi, lo;
  93361. if(bits > 32) {
  93362. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93363. return false;
  93364. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93365. return false;
  93366. *val = hi;
  93367. *val <<= 32;
  93368. *val |= lo;
  93369. }
  93370. else {
  93371. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93372. return false;
  93373. *val = lo;
  93374. }
  93375. return true;
  93376. }
  93377. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93378. {
  93379. FLAC__uint32 x8, x32 = 0;
  93380. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93381. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93382. return false;
  93383. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93384. return false;
  93385. x32 |= (x8 << 8);
  93386. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93387. return false;
  93388. x32 |= (x8 << 16);
  93389. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93390. return false;
  93391. x32 |= (x8 << 24);
  93392. *val = x32;
  93393. return true;
  93394. }
  93395. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93396. {
  93397. /*
  93398. * OPT: a faster implementation is possible but probably not that useful
  93399. * since this is only called a couple of times in the metadata readers.
  93400. */
  93401. FLAC__ASSERT(0 != br);
  93402. FLAC__ASSERT(0 != br->buffer);
  93403. if(bits > 0) {
  93404. const unsigned n = br->consumed_bits & 7;
  93405. unsigned m;
  93406. FLAC__uint32 x;
  93407. if(n != 0) {
  93408. m = min(8-n, bits);
  93409. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93410. return false;
  93411. bits -= m;
  93412. }
  93413. m = bits / 8;
  93414. if(m > 0) {
  93415. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93416. return false;
  93417. bits %= 8;
  93418. }
  93419. if(bits > 0) {
  93420. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93421. return false;
  93422. }
  93423. }
  93424. return true;
  93425. }
  93426. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93427. {
  93428. FLAC__uint32 x;
  93429. FLAC__ASSERT(0 != br);
  93430. FLAC__ASSERT(0 != br->buffer);
  93431. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93432. /* step 1: skip over partial head word to get word aligned */
  93433. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93434. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93435. return false;
  93436. nvals--;
  93437. }
  93438. if(0 == nvals)
  93439. return true;
  93440. /* step 2: skip whole words in chunks */
  93441. while(nvals >= FLAC__BYTES_PER_WORD) {
  93442. if(br->consumed_words < br->words) {
  93443. br->consumed_words++;
  93444. nvals -= FLAC__BYTES_PER_WORD;
  93445. }
  93446. else if(!bitreader_read_from_client_(br))
  93447. return false;
  93448. }
  93449. /* step 3: skip any remainder from partial tail bytes */
  93450. while(nvals) {
  93451. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93452. return false;
  93453. nvals--;
  93454. }
  93455. return true;
  93456. }
  93457. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93458. {
  93459. FLAC__uint32 x;
  93460. FLAC__ASSERT(0 != br);
  93461. FLAC__ASSERT(0 != br->buffer);
  93462. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93463. /* step 1: read from partial head word to get word aligned */
  93464. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93465. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93466. return false;
  93467. *val++ = (FLAC__byte)x;
  93468. nvals--;
  93469. }
  93470. if(0 == nvals)
  93471. return true;
  93472. /* step 2: read whole words in chunks */
  93473. while(nvals >= FLAC__BYTES_PER_WORD) {
  93474. if(br->consumed_words < br->words) {
  93475. const brword word = br->buffer[br->consumed_words++];
  93476. #if FLAC__BYTES_PER_WORD == 4
  93477. val[0] = (FLAC__byte)(word >> 24);
  93478. val[1] = (FLAC__byte)(word >> 16);
  93479. val[2] = (FLAC__byte)(word >> 8);
  93480. val[3] = (FLAC__byte)word;
  93481. #elif FLAC__BYTES_PER_WORD == 8
  93482. val[0] = (FLAC__byte)(word >> 56);
  93483. val[1] = (FLAC__byte)(word >> 48);
  93484. val[2] = (FLAC__byte)(word >> 40);
  93485. val[3] = (FLAC__byte)(word >> 32);
  93486. val[4] = (FLAC__byte)(word >> 24);
  93487. val[5] = (FLAC__byte)(word >> 16);
  93488. val[6] = (FLAC__byte)(word >> 8);
  93489. val[7] = (FLAC__byte)word;
  93490. #else
  93491. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93492. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93493. #endif
  93494. val += FLAC__BYTES_PER_WORD;
  93495. nvals -= FLAC__BYTES_PER_WORD;
  93496. }
  93497. else if(!bitreader_read_from_client_(br))
  93498. return false;
  93499. }
  93500. /* step 3: read any remainder from partial tail bytes */
  93501. while(nvals) {
  93502. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93503. return false;
  93504. *val++ = (FLAC__byte)x;
  93505. nvals--;
  93506. }
  93507. return true;
  93508. }
  93509. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93510. #if 0 /* slow but readable version */
  93511. {
  93512. unsigned bit;
  93513. FLAC__ASSERT(0 != br);
  93514. FLAC__ASSERT(0 != br->buffer);
  93515. *val = 0;
  93516. while(1) {
  93517. if(!FLAC__bitreader_read_bit(br, &bit))
  93518. return false;
  93519. if(bit)
  93520. break;
  93521. else
  93522. *val++;
  93523. }
  93524. return true;
  93525. }
  93526. #else
  93527. {
  93528. unsigned i;
  93529. FLAC__ASSERT(0 != br);
  93530. FLAC__ASSERT(0 != br->buffer);
  93531. *val = 0;
  93532. while(1) {
  93533. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93534. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93535. if(b) {
  93536. i = COUNT_ZERO_MSBS(b);
  93537. *val += i;
  93538. i++;
  93539. br->consumed_bits += i;
  93540. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93541. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93542. br->consumed_words++;
  93543. br->consumed_bits = 0;
  93544. }
  93545. return true;
  93546. }
  93547. else {
  93548. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93549. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93550. br->consumed_words++;
  93551. br->consumed_bits = 0;
  93552. /* didn't find stop bit yet, have to keep going... */
  93553. }
  93554. }
  93555. /* at this point we've eaten up all the whole words; have to try
  93556. * reading through any tail bytes before calling the read callback.
  93557. * this is a repeat of the above logic adjusted for the fact we
  93558. * don't have a whole word. note though if the client is feeding
  93559. * us data a byte at a time (unlikely), br->consumed_bits may not
  93560. * be zero.
  93561. */
  93562. if(br->bytes) {
  93563. const unsigned end = br->bytes * 8;
  93564. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93565. if(b) {
  93566. i = COUNT_ZERO_MSBS(b);
  93567. *val += i;
  93568. i++;
  93569. br->consumed_bits += i;
  93570. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93571. return true;
  93572. }
  93573. else {
  93574. *val += end - br->consumed_bits;
  93575. br->consumed_bits += end;
  93576. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93577. /* didn't find stop bit yet, have to keep going... */
  93578. }
  93579. }
  93580. if(!bitreader_read_from_client_(br))
  93581. return false;
  93582. }
  93583. }
  93584. #endif
  93585. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93586. {
  93587. FLAC__uint32 lsbs = 0, msbs = 0;
  93588. unsigned uval;
  93589. FLAC__ASSERT(0 != br);
  93590. FLAC__ASSERT(0 != br->buffer);
  93591. FLAC__ASSERT(parameter <= 31);
  93592. /* read the unary MSBs and end bit */
  93593. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93594. return false;
  93595. /* read the binary LSBs */
  93596. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93597. return false;
  93598. /* compose the value */
  93599. uval = (msbs << parameter) | lsbs;
  93600. if(uval & 1)
  93601. *val = -((int)(uval >> 1)) - 1;
  93602. else
  93603. *val = (int)(uval >> 1);
  93604. return true;
  93605. }
  93606. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93607. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93608. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93609. /* OPT: possibly faster version for use with MSVC */
  93610. #ifdef _MSC_VER
  93611. {
  93612. unsigned i;
  93613. unsigned uval = 0;
  93614. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93615. /* try and get br->consumed_words and br->consumed_bits into register;
  93616. * must remember to flush them back to *br before calling other
  93617. * bitwriter functions that use them, and before returning */
  93618. register unsigned cwords;
  93619. register unsigned cbits;
  93620. FLAC__ASSERT(0 != br);
  93621. FLAC__ASSERT(0 != br->buffer);
  93622. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93623. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93624. FLAC__ASSERT(parameter < 32);
  93625. /* 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 */
  93626. if(nvals == 0)
  93627. return true;
  93628. cbits = br->consumed_bits;
  93629. cwords = br->consumed_words;
  93630. while(1) {
  93631. /* read unary part */
  93632. while(1) {
  93633. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93634. brword b = br->buffer[cwords] << cbits;
  93635. if(b) {
  93636. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93637. __asm {
  93638. bsr eax, b
  93639. not eax
  93640. and eax, 31
  93641. mov i, eax
  93642. }
  93643. #else
  93644. i = COUNT_ZERO_MSBS(b);
  93645. #endif
  93646. uval += i;
  93647. bits = parameter;
  93648. i++;
  93649. cbits += i;
  93650. if(cbits == FLAC__BITS_PER_WORD) {
  93651. crc16_update_word_(br, br->buffer[cwords]);
  93652. cwords++;
  93653. cbits = 0;
  93654. }
  93655. goto break1;
  93656. }
  93657. else {
  93658. uval += FLAC__BITS_PER_WORD - cbits;
  93659. crc16_update_word_(br, br->buffer[cwords]);
  93660. cwords++;
  93661. cbits = 0;
  93662. /* didn't find stop bit yet, have to keep going... */
  93663. }
  93664. }
  93665. /* at this point we've eaten up all the whole words; have to try
  93666. * reading through any tail bytes before calling the read callback.
  93667. * this is a repeat of the above logic adjusted for the fact we
  93668. * don't have a whole word. note though if the client is feeding
  93669. * us data a byte at a time (unlikely), br->consumed_bits may not
  93670. * be zero.
  93671. */
  93672. if(br->bytes) {
  93673. const unsigned end = br->bytes * 8;
  93674. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93675. if(b) {
  93676. i = COUNT_ZERO_MSBS(b);
  93677. uval += i;
  93678. bits = parameter;
  93679. i++;
  93680. cbits += i;
  93681. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93682. goto break1;
  93683. }
  93684. else {
  93685. uval += end - cbits;
  93686. cbits += end;
  93687. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93688. /* didn't find stop bit yet, have to keep going... */
  93689. }
  93690. }
  93691. /* flush registers and read; bitreader_read_from_client_() does
  93692. * not touch br->consumed_bits at all but we still need to set
  93693. * it in case it fails and we have to return false.
  93694. */
  93695. br->consumed_bits = cbits;
  93696. br->consumed_words = cwords;
  93697. if(!bitreader_read_from_client_(br))
  93698. return false;
  93699. cwords = br->consumed_words;
  93700. }
  93701. break1:
  93702. /* read binary part */
  93703. FLAC__ASSERT(cwords <= br->words);
  93704. if(bits) {
  93705. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93706. /* flush registers and read; bitreader_read_from_client_() does
  93707. * not touch br->consumed_bits at all but we still need to set
  93708. * it in case it fails and we have to return false.
  93709. */
  93710. br->consumed_bits = cbits;
  93711. br->consumed_words = cwords;
  93712. if(!bitreader_read_from_client_(br))
  93713. return false;
  93714. cwords = br->consumed_words;
  93715. }
  93716. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93717. if(cbits) {
  93718. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93719. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93720. const brword word = br->buffer[cwords];
  93721. if(bits < n) {
  93722. uval <<= bits;
  93723. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93724. cbits += bits;
  93725. goto break2;
  93726. }
  93727. uval <<= n;
  93728. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93729. bits -= n;
  93730. crc16_update_word_(br, word);
  93731. cwords++;
  93732. cbits = 0;
  93733. 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 */
  93734. uval <<= bits;
  93735. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93736. cbits = bits;
  93737. }
  93738. goto break2;
  93739. }
  93740. else {
  93741. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93742. uval <<= bits;
  93743. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93744. cbits = bits;
  93745. goto break2;
  93746. }
  93747. }
  93748. else {
  93749. /* in this case we're starting our read at a partial tail word;
  93750. * the reader has guaranteed that we have at least 'bits' bits
  93751. * available to read, which makes this case simpler.
  93752. */
  93753. uval <<= bits;
  93754. if(cbits) {
  93755. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93756. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93757. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93758. cbits += bits;
  93759. goto break2;
  93760. }
  93761. else {
  93762. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93763. cbits += bits;
  93764. goto break2;
  93765. }
  93766. }
  93767. }
  93768. break2:
  93769. /* compose the value */
  93770. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93771. /* are we done? */
  93772. --nvals;
  93773. if(nvals == 0) {
  93774. br->consumed_bits = cbits;
  93775. br->consumed_words = cwords;
  93776. return true;
  93777. }
  93778. uval = 0;
  93779. ++vals;
  93780. }
  93781. }
  93782. #else
  93783. {
  93784. unsigned i;
  93785. unsigned uval = 0;
  93786. /* try and get br->consumed_words and br->consumed_bits into register;
  93787. * must remember to flush them back to *br before calling other
  93788. * bitwriter functions that use them, and before returning */
  93789. register unsigned cwords;
  93790. register unsigned cbits;
  93791. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93792. FLAC__ASSERT(0 != br);
  93793. FLAC__ASSERT(0 != br->buffer);
  93794. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93795. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93796. FLAC__ASSERT(parameter < 32);
  93797. /* 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 */
  93798. if(nvals == 0)
  93799. return true;
  93800. cbits = br->consumed_bits;
  93801. cwords = br->consumed_words;
  93802. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93803. while(1) {
  93804. /* read unary part */
  93805. while(1) {
  93806. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93807. brword b = br->buffer[cwords] << cbits;
  93808. if(b) {
  93809. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93810. asm volatile (
  93811. "bsrl %1, %0;"
  93812. "notl %0;"
  93813. "andl $31, %0;"
  93814. : "=r"(i)
  93815. : "r"(b)
  93816. );
  93817. #else
  93818. i = COUNT_ZERO_MSBS(b);
  93819. #endif
  93820. uval += i;
  93821. cbits += i;
  93822. cbits++; /* skip over stop bit */
  93823. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93824. crc16_update_word_(br, br->buffer[cwords]);
  93825. cwords++;
  93826. cbits = 0;
  93827. }
  93828. goto break1;
  93829. }
  93830. else {
  93831. uval += FLAC__BITS_PER_WORD - cbits;
  93832. crc16_update_word_(br, br->buffer[cwords]);
  93833. cwords++;
  93834. cbits = 0;
  93835. /* didn't find stop bit yet, have to keep going... */
  93836. }
  93837. }
  93838. /* at this point we've eaten up all the whole words; have to try
  93839. * reading through any tail bytes before calling the read callback.
  93840. * this is a repeat of the above logic adjusted for the fact we
  93841. * don't have a whole word. note though if the client is feeding
  93842. * us data a byte at a time (unlikely), br->consumed_bits may not
  93843. * be zero.
  93844. */
  93845. if(br->bytes) {
  93846. const unsigned end = br->bytes * 8;
  93847. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93848. if(b) {
  93849. i = COUNT_ZERO_MSBS(b);
  93850. uval += i;
  93851. cbits += i;
  93852. cbits++; /* skip over stop bit */
  93853. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93854. goto break1;
  93855. }
  93856. else {
  93857. uval += end - cbits;
  93858. cbits += end;
  93859. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93860. /* didn't find stop bit yet, have to keep going... */
  93861. }
  93862. }
  93863. /* flush registers and read; bitreader_read_from_client_() does
  93864. * not touch br->consumed_bits at all but we still need to set
  93865. * it in case it fails and we have to return false.
  93866. */
  93867. br->consumed_bits = cbits;
  93868. br->consumed_words = cwords;
  93869. if(!bitreader_read_from_client_(br))
  93870. return false;
  93871. cwords = br->consumed_words;
  93872. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93873. /* + uval to offset our count by the # of unary bits already
  93874. * consumed before the read, because we will add these back
  93875. * in all at once at break1
  93876. */
  93877. }
  93878. break1:
  93879. ucbits -= uval;
  93880. ucbits--; /* account for stop bit */
  93881. /* read binary part */
  93882. FLAC__ASSERT(cwords <= br->words);
  93883. if(parameter) {
  93884. while(ucbits < parameter) {
  93885. /* flush registers and read; bitreader_read_from_client_() does
  93886. * not touch br->consumed_bits at all but we still need to set
  93887. * it in case it fails and we have to return false.
  93888. */
  93889. br->consumed_bits = cbits;
  93890. br->consumed_words = cwords;
  93891. if(!bitreader_read_from_client_(br))
  93892. return false;
  93893. cwords = br->consumed_words;
  93894. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93895. }
  93896. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93897. if(cbits) {
  93898. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93899. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93900. const brword word = br->buffer[cwords];
  93901. if(parameter < n) {
  93902. uval <<= parameter;
  93903. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93904. cbits += parameter;
  93905. }
  93906. else {
  93907. uval <<= n;
  93908. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93909. crc16_update_word_(br, word);
  93910. cwords++;
  93911. cbits = parameter - n;
  93912. 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 */
  93913. uval <<= cbits;
  93914. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93915. }
  93916. }
  93917. }
  93918. else {
  93919. cbits = parameter;
  93920. uval <<= parameter;
  93921. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93922. }
  93923. }
  93924. else {
  93925. /* in this case we're starting our read at a partial tail word;
  93926. * the reader has guaranteed that we have at least 'parameter'
  93927. * bits available to read, which makes this case simpler.
  93928. */
  93929. uval <<= parameter;
  93930. if(cbits) {
  93931. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93932. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93933. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93934. cbits += parameter;
  93935. }
  93936. else {
  93937. cbits = parameter;
  93938. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93939. }
  93940. }
  93941. }
  93942. ucbits -= parameter;
  93943. /* compose the value */
  93944. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93945. /* are we done? */
  93946. --nvals;
  93947. if(nvals == 0) {
  93948. br->consumed_bits = cbits;
  93949. br->consumed_words = cwords;
  93950. return true;
  93951. }
  93952. uval = 0;
  93953. ++vals;
  93954. }
  93955. }
  93956. #endif
  93957. #if 0 /* UNUSED */
  93958. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93959. {
  93960. FLAC__uint32 lsbs = 0, msbs = 0;
  93961. unsigned bit, uval, k;
  93962. FLAC__ASSERT(0 != br);
  93963. FLAC__ASSERT(0 != br->buffer);
  93964. k = FLAC__bitmath_ilog2(parameter);
  93965. /* read the unary MSBs and end bit */
  93966. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93967. return false;
  93968. /* read the binary LSBs */
  93969. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93970. return false;
  93971. if(parameter == 1u<<k) {
  93972. /* compose the value */
  93973. uval = (msbs << k) | lsbs;
  93974. }
  93975. else {
  93976. unsigned d = (1 << (k+1)) - parameter;
  93977. if(lsbs >= d) {
  93978. if(!FLAC__bitreader_read_bit(br, &bit))
  93979. return false;
  93980. lsbs <<= 1;
  93981. lsbs |= bit;
  93982. lsbs -= d;
  93983. }
  93984. /* compose the value */
  93985. uval = msbs * parameter + lsbs;
  93986. }
  93987. /* unfold unsigned to signed */
  93988. if(uval & 1)
  93989. *val = -((int)(uval >> 1)) - 1;
  93990. else
  93991. *val = (int)(uval >> 1);
  93992. return true;
  93993. }
  93994. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93995. {
  93996. FLAC__uint32 lsbs, msbs = 0;
  93997. unsigned bit, k;
  93998. FLAC__ASSERT(0 != br);
  93999. FLAC__ASSERT(0 != br->buffer);
  94000. k = FLAC__bitmath_ilog2(parameter);
  94001. /* read the unary MSBs and end bit */
  94002. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94003. return false;
  94004. /* read the binary LSBs */
  94005. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94006. return false;
  94007. if(parameter == 1u<<k) {
  94008. /* compose the value */
  94009. *val = (msbs << k) | lsbs;
  94010. }
  94011. else {
  94012. unsigned d = (1 << (k+1)) - parameter;
  94013. if(lsbs >= d) {
  94014. if(!FLAC__bitreader_read_bit(br, &bit))
  94015. return false;
  94016. lsbs <<= 1;
  94017. lsbs |= bit;
  94018. lsbs -= d;
  94019. }
  94020. /* compose the value */
  94021. *val = msbs * parameter + lsbs;
  94022. }
  94023. return true;
  94024. }
  94025. #endif /* UNUSED */
  94026. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94027. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94028. {
  94029. FLAC__uint32 v = 0;
  94030. FLAC__uint32 x;
  94031. unsigned i;
  94032. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94033. return false;
  94034. if(raw)
  94035. raw[(*rawlen)++] = (FLAC__byte)x;
  94036. if(!(x & 0x80)) { /* 0xxxxxxx */
  94037. v = x;
  94038. i = 0;
  94039. }
  94040. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94041. v = x & 0x1F;
  94042. i = 1;
  94043. }
  94044. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94045. v = x & 0x0F;
  94046. i = 2;
  94047. }
  94048. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94049. v = x & 0x07;
  94050. i = 3;
  94051. }
  94052. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94053. v = x & 0x03;
  94054. i = 4;
  94055. }
  94056. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94057. v = x & 0x01;
  94058. i = 5;
  94059. }
  94060. else {
  94061. *val = 0xffffffff;
  94062. return true;
  94063. }
  94064. for( ; i; i--) {
  94065. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94066. return false;
  94067. if(raw)
  94068. raw[(*rawlen)++] = (FLAC__byte)x;
  94069. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94070. *val = 0xffffffff;
  94071. return true;
  94072. }
  94073. v <<= 6;
  94074. v |= (x & 0x3F);
  94075. }
  94076. *val = v;
  94077. return true;
  94078. }
  94079. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94080. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94081. {
  94082. FLAC__uint64 v = 0;
  94083. FLAC__uint32 x;
  94084. unsigned i;
  94085. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94086. return false;
  94087. if(raw)
  94088. raw[(*rawlen)++] = (FLAC__byte)x;
  94089. if(!(x & 0x80)) { /* 0xxxxxxx */
  94090. v = x;
  94091. i = 0;
  94092. }
  94093. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94094. v = x & 0x1F;
  94095. i = 1;
  94096. }
  94097. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94098. v = x & 0x0F;
  94099. i = 2;
  94100. }
  94101. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94102. v = x & 0x07;
  94103. i = 3;
  94104. }
  94105. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94106. v = x & 0x03;
  94107. i = 4;
  94108. }
  94109. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94110. v = x & 0x01;
  94111. i = 5;
  94112. }
  94113. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94114. v = 0;
  94115. i = 6;
  94116. }
  94117. else {
  94118. *val = FLAC__U64L(0xffffffffffffffff);
  94119. return true;
  94120. }
  94121. for( ; i; i--) {
  94122. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94123. return false;
  94124. if(raw)
  94125. raw[(*rawlen)++] = (FLAC__byte)x;
  94126. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94127. *val = FLAC__U64L(0xffffffffffffffff);
  94128. return true;
  94129. }
  94130. v <<= 6;
  94131. v |= (x & 0x3F);
  94132. }
  94133. *val = v;
  94134. return true;
  94135. }
  94136. #endif
  94137. /*** End of inlined file: bitreader.c ***/
  94138. /*** Start of inlined file: bitwriter.c ***/
  94139. /*** Start of inlined file: juce_FlacHeader.h ***/
  94140. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94141. // tasks..
  94142. #define VERSION "1.2.1"
  94143. #define FLAC__NO_DLL 1
  94144. #if JUCE_MSVC
  94145. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94146. #endif
  94147. #if JUCE_MAC
  94148. #define FLAC__SYS_DARWIN 1
  94149. #endif
  94150. /*** End of inlined file: juce_FlacHeader.h ***/
  94151. #if JUCE_USE_FLAC
  94152. #if HAVE_CONFIG_H
  94153. # include <config.h>
  94154. #endif
  94155. #include <stdlib.h> /* for malloc() */
  94156. #include <string.h> /* for memcpy(), memset() */
  94157. #ifdef _MSC_VER
  94158. #include <winsock.h> /* for ntohl() */
  94159. #elif defined FLAC__SYS_DARWIN
  94160. #include <machine/endian.h> /* for ntohl() */
  94161. #elif defined __MINGW32__
  94162. #include <winsock.h> /* for ntohl() */
  94163. #else
  94164. #include <netinet/in.h> /* for ntohl() */
  94165. #endif
  94166. #if 0 /* UNUSED */
  94167. #endif
  94168. /*** Start of inlined file: bitwriter.h ***/
  94169. #ifndef FLAC__PRIVATE__BITWRITER_H
  94170. #define FLAC__PRIVATE__BITWRITER_H
  94171. #include <stdio.h> /* for FILE */
  94172. /*
  94173. * opaque structure definition
  94174. */
  94175. struct FLAC__BitWriter;
  94176. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94177. /*
  94178. * construction, deletion, initialization, etc functions
  94179. */
  94180. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94181. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94182. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94183. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94184. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94185. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94186. /*
  94187. * CRC functions
  94188. *
  94189. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94190. */
  94191. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94192. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94193. /*
  94194. * info functions
  94195. */
  94196. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94197. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94198. /*
  94199. * direct buffer access
  94200. *
  94201. * there may be no calls on the bitwriter between get and release.
  94202. * the bitwriter continues to own the returned buffer.
  94203. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94204. */
  94205. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94206. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94207. /*
  94208. * write functions
  94209. */
  94210. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94211. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94212. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94213. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94214. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94215. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94216. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94217. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94218. #if 0 /* UNUSED */
  94219. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94220. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94221. #endif
  94222. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94223. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94224. #if 0 /* UNUSED */
  94225. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94226. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94227. #endif
  94228. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94229. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94230. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94231. #endif
  94232. /*** End of inlined file: bitwriter.h ***/
  94233. /*** Start of inlined file: alloc.h ***/
  94234. #ifndef FLAC__SHARE__ALLOC_H
  94235. #define FLAC__SHARE__ALLOC_H
  94236. #if HAVE_CONFIG_H
  94237. # include <config.h>
  94238. #endif
  94239. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94240. * before #including this file, otherwise SIZE_MAX might not be defined
  94241. */
  94242. #include <limits.h> /* for SIZE_MAX */
  94243. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94244. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94245. #endif
  94246. #include <stdlib.h> /* for size_t, malloc(), etc */
  94247. #ifndef SIZE_MAX
  94248. # ifndef SIZE_T_MAX
  94249. # ifdef _MSC_VER
  94250. # define SIZE_T_MAX UINT_MAX
  94251. # else
  94252. # error
  94253. # endif
  94254. # endif
  94255. # define SIZE_MAX SIZE_T_MAX
  94256. #endif
  94257. #ifndef FLaC__INLINE
  94258. #define FLaC__INLINE
  94259. #endif
  94260. /* avoid malloc()ing 0 bytes, see:
  94261. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94262. */
  94263. static FLaC__INLINE void *safe_malloc_(size_t size)
  94264. {
  94265. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94266. if(!size)
  94267. size++;
  94268. return malloc(size);
  94269. }
  94270. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94271. {
  94272. if(!nmemb || !size)
  94273. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94274. return calloc(nmemb, size);
  94275. }
  94276. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94277. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94278. {
  94279. size2 += size1;
  94280. if(size2 < size1)
  94281. return 0;
  94282. return safe_malloc_(size2);
  94283. }
  94284. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94285. {
  94286. size2 += size1;
  94287. if(size2 < size1)
  94288. return 0;
  94289. size3 += size2;
  94290. if(size3 < size2)
  94291. return 0;
  94292. return safe_malloc_(size3);
  94293. }
  94294. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94295. {
  94296. size2 += size1;
  94297. if(size2 < size1)
  94298. return 0;
  94299. size3 += size2;
  94300. if(size3 < size2)
  94301. return 0;
  94302. size4 += size3;
  94303. if(size4 < size3)
  94304. return 0;
  94305. return safe_malloc_(size4);
  94306. }
  94307. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94308. #if 0
  94309. needs support for cases where sizeof(size_t) != 4
  94310. {
  94311. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94312. if(sizeof(size_t) == 4) {
  94313. if ((double)size1 * (double)size2 < 4294967296.0)
  94314. return malloc(size1*size2);
  94315. }
  94316. return 0;
  94317. }
  94318. #else
  94319. /* better? */
  94320. {
  94321. if(!size1 || !size2)
  94322. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94323. if(size1 > SIZE_MAX / size2)
  94324. return 0;
  94325. return malloc(size1*size2);
  94326. }
  94327. #endif
  94328. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94329. {
  94330. if(!size1 || !size2 || !size3)
  94331. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94332. if(size1 > SIZE_MAX / size2)
  94333. return 0;
  94334. size1 *= size2;
  94335. if(size1 > SIZE_MAX / size3)
  94336. return 0;
  94337. return malloc(size1*size3);
  94338. }
  94339. /* size1*size2 + size3 */
  94340. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94341. {
  94342. if(!size1 || !size2)
  94343. return safe_malloc_(size3);
  94344. if(size1 > SIZE_MAX / size2)
  94345. return 0;
  94346. return safe_malloc_add_2op_(size1*size2, size3);
  94347. }
  94348. /* size1 * (size2 + size3) */
  94349. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94350. {
  94351. if(!size1 || (!size2 && !size3))
  94352. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94353. size2 += size3;
  94354. if(size2 < size3)
  94355. return 0;
  94356. return safe_malloc_mul_2op_(size1, size2);
  94357. }
  94358. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94359. {
  94360. size2 += size1;
  94361. if(size2 < size1)
  94362. return 0;
  94363. return realloc(ptr, size2);
  94364. }
  94365. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94366. {
  94367. size2 += size1;
  94368. if(size2 < size1)
  94369. return 0;
  94370. size3 += size2;
  94371. if(size3 < size2)
  94372. return 0;
  94373. return realloc(ptr, size3);
  94374. }
  94375. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94376. {
  94377. size2 += size1;
  94378. if(size2 < size1)
  94379. return 0;
  94380. size3 += size2;
  94381. if(size3 < size2)
  94382. return 0;
  94383. size4 += size3;
  94384. if(size4 < size3)
  94385. return 0;
  94386. return realloc(ptr, size4);
  94387. }
  94388. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94389. {
  94390. if(!size1 || !size2)
  94391. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94392. if(size1 > SIZE_MAX / size2)
  94393. return 0;
  94394. return realloc(ptr, size1*size2);
  94395. }
  94396. /* size1 * (size2 + size3) */
  94397. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94398. {
  94399. if(!size1 || (!size2 && !size3))
  94400. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94401. size2 += size3;
  94402. if(size2 < size3)
  94403. return 0;
  94404. return safe_realloc_mul_2op_(ptr, size1, size2);
  94405. }
  94406. #endif
  94407. /*** End of inlined file: alloc.h ***/
  94408. /* Things should be fastest when this matches the machine word size */
  94409. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94410. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94411. typedef FLAC__uint32 bwword;
  94412. #define FLAC__BYTES_PER_WORD 4
  94413. #define FLAC__BITS_PER_WORD 32
  94414. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94415. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94416. #if WORDS_BIGENDIAN
  94417. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94418. #else
  94419. #ifdef _MSC_VER
  94420. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94421. #else
  94422. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94423. #endif
  94424. #endif
  94425. /*
  94426. * The default capacity here doesn't matter too much. The buffer always grows
  94427. * to hold whatever is written to it. Usually the encoder will stop adding at
  94428. * a frame or metadata block, then write that out and clear the buffer for the
  94429. * next one.
  94430. */
  94431. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94432. /* When growing, increment 4K at a time */
  94433. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94434. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94435. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94436. #ifdef min
  94437. #undef min
  94438. #endif
  94439. #define min(x,y) ((x)<(y)?(x):(y))
  94440. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94441. #ifdef _MSC_VER
  94442. #define FLAC__U64L(x) x
  94443. #else
  94444. #define FLAC__U64L(x) x##LLU
  94445. #endif
  94446. #ifndef FLaC__INLINE
  94447. #define FLaC__INLINE
  94448. #endif
  94449. struct FLAC__BitWriter {
  94450. bwword *buffer;
  94451. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94452. unsigned capacity; /* capacity of buffer in words */
  94453. unsigned words; /* # of complete words in buffer */
  94454. unsigned bits; /* # of used bits in accum */
  94455. };
  94456. /* * WATCHOUT: The current implementation only grows the buffer. */
  94457. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94458. {
  94459. unsigned new_capacity;
  94460. bwword *new_buffer;
  94461. FLAC__ASSERT(0 != bw);
  94462. FLAC__ASSERT(0 != bw->buffer);
  94463. /* calculate total words needed to store 'bits_to_add' additional bits */
  94464. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94465. /* it's possible (due to pessimism in the growth estimation that
  94466. * leads to this call) that we don't actually need to grow
  94467. */
  94468. if(bw->capacity >= new_capacity)
  94469. return true;
  94470. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94471. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94472. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94473. /* make sure we got everything right */
  94474. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94475. FLAC__ASSERT(new_capacity > bw->capacity);
  94476. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94477. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94478. if(new_buffer == 0)
  94479. return false;
  94480. bw->buffer = new_buffer;
  94481. bw->capacity = new_capacity;
  94482. return true;
  94483. }
  94484. /***********************************************************************
  94485. *
  94486. * Class constructor/destructor
  94487. *
  94488. ***********************************************************************/
  94489. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94490. {
  94491. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94492. /* note that calloc() sets all members to 0 for us */
  94493. return bw;
  94494. }
  94495. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94496. {
  94497. FLAC__ASSERT(0 != bw);
  94498. FLAC__bitwriter_free(bw);
  94499. free(bw);
  94500. }
  94501. /***********************************************************************
  94502. *
  94503. * Public class methods
  94504. *
  94505. ***********************************************************************/
  94506. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94507. {
  94508. FLAC__ASSERT(0 != bw);
  94509. bw->words = bw->bits = 0;
  94510. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94511. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94512. if(bw->buffer == 0)
  94513. return false;
  94514. return true;
  94515. }
  94516. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94517. {
  94518. FLAC__ASSERT(0 != bw);
  94519. if(0 != bw->buffer)
  94520. free(bw->buffer);
  94521. bw->buffer = 0;
  94522. bw->capacity = 0;
  94523. bw->words = bw->bits = 0;
  94524. }
  94525. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94526. {
  94527. bw->words = bw->bits = 0;
  94528. }
  94529. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94530. {
  94531. unsigned i, j;
  94532. if(bw == 0) {
  94533. fprintf(out, "bitwriter is NULL\n");
  94534. }
  94535. else {
  94536. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94537. for(i = 0; i < bw->words; i++) {
  94538. fprintf(out, "%08X: ", i);
  94539. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94540. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94541. fprintf(out, "\n");
  94542. }
  94543. if(bw->bits > 0) {
  94544. fprintf(out, "%08X: ", i);
  94545. for(j = 0; j < bw->bits; j++)
  94546. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94547. fprintf(out, "\n");
  94548. }
  94549. }
  94550. }
  94551. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94552. {
  94553. const FLAC__byte *buffer;
  94554. size_t bytes;
  94555. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94556. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94557. return false;
  94558. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94559. FLAC__bitwriter_release_buffer(bw);
  94560. return true;
  94561. }
  94562. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94563. {
  94564. const FLAC__byte *buffer;
  94565. size_t bytes;
  94566. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94567. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94568. return false;
  94569. *crc = FLAC__crc8(buffer, bytes);
  94570. FLAC__bitwriter_release_buffer(bw);
  94571. return true;
  94572. }
  94573. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94574. {
  94575. return ((bw->bits & 7) == 0);
  94576. }
  94577. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94578. {
  94579. return FLAC__TOTAL_BITS(bw);
  94580. }
  94581. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94582. {
  94583. FLAC__ASSERT((bw->bits & 7) == 0);
  94584. /* double protection */
  94585. if(bw->bits & 7)
  94586. return false;
  94587. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94588. if(bw->bits) {
  94589. FLAC__ASSERT(bw->words <= bw->capacity);
  94590. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94591. return false;
  94592. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94593. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94594. }
  94595. /* now we can just return what we have */
  94596. *buffer = (FLAC__byte*)bw->buffer;
  94597. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94598. return true;
  94599. }
  94600. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94601. {
  94602. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94603. * get-mode' flag could be added everywhere and then cleared here
  94604. */
  94605. (void)bw;
  94606. }
  94607. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94608. {
  94609. unsigned n;
  94610. FLAC__ASSERT(0 != bw);
  94611. FLAC__ASSERT(0 != bw->buffer);
  94612. if(bits == 0)
  94613. return true;
  94614. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94615. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94616. return false;
  94617. /* first part gets to word alignment */
  94618. if(bw->bits) {
  94619. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94620. bw->accum <<= n;
  94621. bits -= n;
  94622. bw->bits += n;
  94623. if(bw->bits == FLAC__BITS_PER_WORD) {
  94624. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94625. bw->bits = 0;
  94626. }
  94627. else
  94628. return true;
  94629. }
  94630. /* do whole words */
  94631. while(bits >= FLAC__BITS_PER_WORD) {
  94632. bw->buffer[bw->words++] = 0;
  94633. bits -= FLAC__BITS_PER_WORD;
  94634. }
  94635. /* do any leftovers */
  94636. if(bits > 0) {
  94637. bw->accum = 0;
  94638. bw->bits = bits;
  94639. }
  94640. return true;
  94641. }
  94642. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94643. {
  94644. register unsigned left;
  94645. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94646. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94647. FLAC__ASSERT(0 != bw);
  94648. FLAC__ASSERT(0 != bw->buffer);
  94649. FLAC__ASSERT(bits <= 32);
  94650. if(bits == 0)
  94651. return true;
  94652. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94653. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94654. return false;
  94655. left = FLAC__BITS_PER_WORD - bw->bits;
  94656. if(bits < left) {
  94657. bw->accum <<= bits;
  94658. bw->accum |= val;
  94659. bw->bits += bits;
  94660. }
  94661. 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 */
  94662. bw->accum <<= left;
  94663. bw->accum |= val >> (bw->bits = bits - left);
  94664. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94665. bw->accum = val;
  94666. }
  94667. else {
  94668. bw->accum = val;
  94669. bw->bits = 0;
  94670. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94671. }
  94672. return true;
  94673. }
  94674. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94675. {
  94676. /* zero-out unused bits */
  94677. if(bits < 32)
  94678. val &= (~(0xffffffff << bits));
  94679. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94680. }
  94681. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94682. {
  94683. /* this could be a little faster but it's not used for much */
  94684. if(bits > 32) {
  94685. return
  94686. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94687. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94688. }
  94689. else
  94690. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94691. }
  94692. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94693. {
  94694. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94695. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94696. return false;
  94697. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94698. return false;
  94699. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94700. return false;
  94701. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94702. return false;
  94703. return true;
  94704. }
  94705. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94706. {
  94707. unsigned i;
  94708. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94709. for(i = 0; i < nvals; i++) {
  94710. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94711. return false;
  94712. }
  94713. return true;
  94714. }
  94715. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94716. {
  94717. if(val < 32)
  94718. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94719. else
  94720. return
  94721. FLAC__bitwriter_write_zeroes(bw, val) &&
  94722. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94723. }
  94724. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94725. {
  94726. FLAC__uint32 uval;
  94727. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94728. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94729. uval = (val<<1) ^ (val>>31);
  94730. return 1 + parameter + (uval >> parameter);
  94731. }
  94732. #if 0 /* UNUSED */
  94733. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94734. {
  94735. unsigned bits, msbs, uval;
  94736. unsigned k;
  94737. FLAC__ASSERT(parameter > 0);
  94738. /* fold signed to unsigned */
  94739. if(val < 0)
  94740. uval = (unsigned)(((-(++val)) << 1) + 1);
  94741. else
  94742. uval = (unsigned)(val << 1);
  94743. k = FLAC__bitmath_ilog2(parameter);
  94744. if(parameter == 1u<<k) {
  94745. FLAC__ASSERT(k <= 30);
  94746. msbs = uval >> k;
  94747. bits = 1 + k + msbs;
  94748. }
  94749. else {
  94750. unsigned q, r, d;
  94751. d = (1 << (k+1)) - parameter;
  94752. q = uval / parameter;
  94753. r = uval - (q * parameter);
  94754. bits = 1 + q + k;
  94755. if(r >= d)
  94756. bits++;
  94757. }
  94758. return bits;
  94759. }
  94760. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94761. {
  94762. unsigned bits, msbs;
  94763. unsigned k;
  94764. FLAC__ASSERT(parameter > 0);
  94765. k = FLAC__bitmath_ilog2(parameter);
  94766. if(parameter == 1u<<k) {
  94767. FLAC__ASSERT(k <= 30);
  94768. msbs = uval >> k;
  94769. bits = 1 + k + msbs;
  94770. }
  94771. else {
  94772. unsigned q, r, d;
  94773. d = (1 << (k+1)) - parameter;
  94774. q = uval / parameter;
  94775. r = uval - (q * parameter);
  94776. bits = 1 + q + k;
  94777. if(r >= d)
  94778. bits++;
  94779. }
  94780. return bits;
  94781. }
  94782. #endif /* UNUSED */
  94783. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94784. {
  94785. unsigned total_bits, interesting_bits, msbs;
  94786. FLAC__uint32 uval, pattern;
  94787. FLAC__ASSERT(0 != bw);
  94788. FLAC__ASSERT(0 != bw->buffer);
  94789. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94790. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94791. uval = (val<<1) ^ (val>>31);
  94792. msbs = uval >> parameter;
  94793. interesting_bits = 1 + parameter;
  94794. total_bits = interesting_bits + msbs;
  94795. pattern = 1 << parameter; /* the unary end bit */
  94796. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94797. if(total_bits <= 32)
  94798. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94799. else
  94800. return
  94801. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94802. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94803. }
  94804. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94805. {
  94806. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94807. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94808. FLAC__uint32 uval;
  94809. unsigned left;
  94810. const unsigned lsbits = 1 + parameter;
  94811. unsigned msbits;
  94812. FLAC__ASSERT(0 != bw);
  94813. FLAC__ASSERT(0 != bw->buffer);
  94814. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94815. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94816. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94817. while(nvals) {
  94818. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94819. uval = (*vals<<1) ^ (*vals>>31);
  94820. msbits = uval >> parameter;
  94821. #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) */
  94822. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94823. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94824. bw->bits = bw->bits + msbits + lsbits;
  94825. uval |= mask1; /* set stop bit */
  94826. uval &= mask2; /* mask off unused top bits */
  94827. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94828. bw->accum <<= msbits;
  94829. bw->accum <<= lsbits;
  94830. bw->accum |= uval;
  94831. if(bw->bits == FLAC__BITS_PER_WORD) {
  94832. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94833. bw->bits = 0;
  94834. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94835. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94836. FLAC__ASSERT(bw->capacity == bw->words);
  94837. return false;
  94838. }
  94839. }
  94840. }
  94841. else {
  94842. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94843. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94844. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94845. bw->bits = bw->bits + msbits + lsbits;
  94846. uval |= mask1; /* set stop bit */
  94847. uval &= mask2; /* mask off unused top bits */
  94848. bw->accum <<= msbits + lsbits;
  94849. bw->accum |= uval;
  94850. }
  94851. else {
  94852. #endif
  94853. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94854. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94855. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94856. return false;
  94857. if(msbits) {
  94858. /* first part gets to word alignment */
  94859. if(bw->bits) {
  94860. left = FLAC__BITS_PER_WORD - bw->bits;
  94861. if(msbits < left) {
  94862. bw->accum <<= msbits;
  94863. bw->bits += msbits;
  94864. goto break1;
  94865. }
  94866. else {
  94867. bw->accum <<= left;
  94868. msbits -= left;
  94869. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94870. bw->bits = 0;
  94871. }
  94872. }
  94873. /* do whole words */
  94874. while(msbits >= FLAC__BITS_PER_WORD) {
  94875. bw->buffer[bw->words++] = 0;
  94876. msbits -= FLAC__BITS_PER_WORD;
  94877. }
  94878. /* do any leftovers */
  94879. if(msbits > 0) {
  94880. bw->accum = 0;
  94881. bw->bits = msbits;
  94882. }
  94883. }
  94884. break1:
  94885. uval |= mask1; /* set stop bit */
  94886. uval &= mask2; /* mask off unused top bits */
  94887. left = FLAC__BITS_PER_WORD - bw->bits;
  94888. if(lsbits < left) {
  94889. bw->accum <<= lsbits;
  94890. bw->accum |= uval;
  94891. bw->bits += lsbits;
  94892. }
  94893. else {
  94894. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94895. * be > lsbits (because of previous assertions) so it would have
  94896. * triggered the (lsbits<left) case above.
  94897. */
  94898. FLAC__ASSERT(bw->bits);
  94899. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94900. bw->accum <<= left;
  94901. bw->accum |= uval >> (bw->bits = lsbits - left);
  94902. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94903. bw->accum = uval;
  94904. }
  94905. #if 1
  94906. }
  94907. #endif
  94908. vals++;
  94909. nvals--;
  94910. }
  94911. return true;
  94912. }
  94913. #if 0 /* UNUSED */
  94914. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94915. {
  94916. unsigned total_bits, msbs, uval;
  94917. unsigned k;
  94918. FLAC__ASSERT(0 != bw);
  94919. FLAC__ASSERT(0 != bw->buffer);
  94920. FLAC__ASSERT(parameter > 0);
  94921. /* fold signed to unsigned */
  94922. if(val < 0)
  94923. uval = (unsigned)(((-(++val)) << 1) + 1);
  94924. else
  94925. uval = (unsigned)(val << 1);
  94926. k = FLAC__bitmath_ilog2(parameter);
  94927. if(parameter == 1u<<k) {
  94928. unsigned pattern;
  94929. FLAC__ASSERT(k <= 30);
  94930. msbs = uval >> k;
  94931. total_bits = 1 + k + msbs;
  94932. pattern = 1 << k; /* the unary end bit */
  94933. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94934. if(total_bits <= 32) {
  94935. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94936. return false;
  94937. }
  94938. else {
  94939. /* write the unary MSBs */
  94940. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94941. return false;
  94942. /* write the unary end bit and binary LSBs */
  94943. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94944. return false;
  94945. }
  94946. }
  94947. else {
  94948. unsigned q, r, d;
  94949. d = (1 << (k+1)) - parameter;
  94950. q = uval / parameter;
  94951. r = uval - (q * parameter);
  94952. /* write the unary MSBs */
  94953. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94954. return false;
  94955. /* write the unary end bit */
  94956. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94957. return false;
  94958. /* write the binary LSBs */
  94959. if(r >= d) {
  94960. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94961. return false;
  94962. }
  94963. else {
  94964. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94965. return false;
  94966. }
  94967. }
  94968. return true;
  94969. }
  94970. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94971. {
  94972. unsigned total_bits, msbs;
  94973. unsigned k;
  94974. FLAC__ASSERT(0 != bw);
  94975. FLAC__ASSERT(0 != bw->buffer);
  94976. FLAC__ASSERT(parameter > 0);
  94977. k = FLAC__bitmath_ilog2(parameter);
  94978. if(parameter == 1u<<k) {
  94979. unsigned pattern;
  94980. FLAC__ASSERT(k <= 30);
  94981. msbs = uval >> k;
  94982. total_bits = 1 + k + msbs;
  94983. pattern = 1 << k; /* the unary end bit */
  94984. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94985. if(total_bits <= 32) {
  94986. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94987. return false;
  94988. }
  94989. else {
  94990. /* write the unary MSBs */
  94991. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94992. return false;
  94993. /* write the unary end bit and binary LSBs */
  94994. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94995. return false;
  94996. }
  94997. }
  94998. else {
  94999. unsigned q, r, d;
  95000. d = (1 << (k+1)) - parameter;
  95001. q = uval / parameter;
  95002. r = uval - (q * parameter);
  95003. /* write the unary MSBs */
  95004. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95005. return false;
  95006. /* write the unary end bit */
  95007. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95008. return false;
  95009. /* write the binary LSBs */
  95010. if(r >= d) {
  95011. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95012. return false;
  95013. }
  95014. else {
  95015. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95016. return false;
  95017. }
  95018. }
  95019. return true;
  95020. }
  95021. #endif /* UNUSED */
  95022. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95023. {
  95024. FLAC__bool ok = 1;
  95025. FLAC__ASSERT(0 != bw);
  95026. FLAC__ASSERT(0 != bw->buffer);
  95027. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95028. if(val < 0x80) {
  95029. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95030. }
  95031. else if(val < 0x800) {
  95032. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95033. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95034. }
  95035. else if(val < 0x10000) {
  95036. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95037. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95038. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95039. }
  95040. else if(val < 0x200000) {
  95041. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95042. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95043. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95044. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95045. }
  95046. else if(val < 0x4000000) {
  95047. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95048. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95049. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95050. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95051. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95052. }
  95053. else {
  95054. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95055. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95056. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95057. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95058. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95059. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95060. }
  95061. return ok;
  95062. }
  95063. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95064. {
  95065. FLAC__bool ok = 1;
  95066. FLAC__ASSERT(0 != bw);
  95067. FLAC__ASSERT(0 != bw->buffer);
  95068. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95069. if(val < 0x80) {
  95070. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95071. }
  95072. else if(val < 0x800) {
  95073. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95074. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95075. }
  95076. else if(val < 0x10000) {
  95077. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95078. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95079. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95080. }
  95081. else if(val < 0x200000) {
  95082. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95083. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95084. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95085. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95086. }
  95087. else if(val < 0x4000000) {
  95088. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95089. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95090. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95091. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95092. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95093. }
  95094. else if(val < 0x80000000) {
  95095. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95096. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95097. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95098. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95099. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95100. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95101. }
  95102. else {
  95103. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95104. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95105. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95106. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95107. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95108. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95109. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95110. }
  95111. return ok;
  95112. }
  95113. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95114. {
  95115. /* 0-pad to byte boundary */
  95116. if(bw->bits & 7u)
  95117. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95118. else
  95119. return true;
  95120. }
  95121. #endif
  95122. /*** End of inlined file: bitwriter.c ***/
  95123. /*** Start of inlined file: cpu.c ***/
  95124. /*** Start of inlined file: juce_FlacHeader.h ***/
  95125. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95126. // tasks..
  95127. #define VERSION "1.2.1"
  95128. #define FLAC__NO_DLL 1
  95129. #if JUCE_MSVC
  95130. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95131. #endif
  95132. #if JUCE_MAC
  95133. #define FLAC__SYS_DARWIN 1
  95134. #endif
  95135. /*** End of inlined file: juce_FlacHeader.h ***/
  95136. #if JUCE_USE_FLAC
  95137. #if HAVE_CONFIG_H
  95138. # include <config.h>
  95139. #endif
  95140. #include <stdlib.h>
  95141. #include <stdio.h>
  95142. #if defined FLAC__CPU_IA32
  95143. # include <signal.h>
  95144. #elif defined FLAC__CPU_PPC
  95145. # if !defined FLAC__NO_ASM
  95146. # if defined FLAC__SYS_DARWIN
  95147. # include <sys/sysctl.h>
  95148. # include <mach/mach.h>
  95149. # include <mach/mach_host.h>
  95150. # include <mach/host_info.h>
  95151. # include <mach/machine.h>
  95152. # ifndef CPU_SUBTYPE_POWERPC_970
  95153. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95154. # endif
  95155. # else /* FLAC__SYS_DARWIN */
  95156. # include <signal.h>
  95157. # include <setjmp.h>
  95158. static sigjmp_buf jmpbuf;
  95159. static volatile sig_atomic_t canjump = 0;
  95160. static void sigill_handler (int sig)
  95161. {
  95162. if (!canjump) {
  95163. signal (sig, SIG_DFL);
  95164. raise (sig);
  95165. }
  95166. canjump = 0;
  95167. siglongjmp (jmpbuf, 1);
  95168. }
  95169. # endif /* FLAC__SYS_DARWIN */
  95170. # endif /* FLAC__NO_ASM */
  95171. #endif /* FLAC__CPU_PPC */
  95172. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95173. #include <sys/param.h>
  95174. #include <sys/sysctl.h>
  95175. #include <machine/cpu.h>
  95176. #endif
  95177. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95178. #include <sys/types.h>
  95179. #include <sys/sysctl.h>
  95180. #endif
  95181. #if defined(__APPLE__)
  95182. /* how to get sysctlbyname()? */
  95183. #endif
  95184. /* these are flags in EDX of CPUID AX=00000001 */
  95185. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95186. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95187. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95188. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95189. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95190. /* these are flags in ECX of CPUID AX=00000001 */
  95191. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95192. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95193. /* these are flags in EDX of CPUID AX=80000001 */
  95194. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95195. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95196. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95197. /*
  95198. * Extra stuff needed for detection of OS support for SSE on IA-32
  95199. */
  95200. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95201. # if defined(__linux__)
  95202. /*
  95203. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95204. * modify the return address to jump over the offending SSE instruction
  95205. * and also the operation following it that indicates the instruction
  95206. * executed successfully. In this way we use no global variables and
  95207. * stay thread-safe.
  95208. *
  95209. * 3 + 3 + 6:
  95210. * 3 bytes for "xorps xmm0,xmm0"
  95211. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95212. * 6 bytes extra in case our estimate is wrong
  95213. * 12 bytes puts us in the NOP "landing zone"
  95214. */
  95215. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95216. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95217. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95218. {
  95219. (void)signal;
  95220. sc.eip += 3 + 3 + 6;
  95221. }
  95222. # else
  95223. # include <sys/ucontext.h>
  95224. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95225. {
  95226. (void)signal, (void)si;
  95227. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95228. }
  95229. # endif
  95230. # elif defined(_MSC_VER)
  95231. # include <windows.h>
  95232. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95233. # ifdef USE_TRY_CATCH_FLAVOR
  95234. # else
  95235. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95236. {
  95237. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95238. ep->ContextRecord->Eip += 3 + 3 + 6;
  95239. return EXCEPTION_CONTINUE_EXECUTION;
  95240. }
  95241. return EXCEPTION_CONTINUE_SEARCH;
  95242. }
  95243. # endif
  95244. # endif
  95245. #endif
  95246. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95247. {
  95248. /*
  95249. * IA32-specific
  95250. */
  95251. #ifdef FLAC__CPU_IA32
  95252. info->type = FLAC__CPUINFO_TYPE_IA32;
  95253. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95254. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95255. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95256. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95257. info->data.ia32.cmov = false;
  95258. info->data.ia32.mmx = false;
  95259. info->data.ia32.fxsr = false;
  95260. info->data.ia32.sse = false;
  95261. info->data.ia32.sse2 = false;
  95262. info->data.ia32.sse3 = false;
  95263. info->data.ia32.ssse3 = false;
  95264. info->data.ia32._3dnow = false;
  95265. info->data.ia32.ext3dnow = false;
  95266. info->data.ia32.extmmx = false;
  95267. if(info->data.ia32.cpuid) {
  95268. /* http://www.sandpile.org/ia32/cpuid.htm */
  95269. FLAC__uint32 flags_edx, flags_ecx;
  95270. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95271. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95272. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95273. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95274. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95275. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95276. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95277. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95278. #ifdef FLAC__USE_3DNOW
  95279. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95280. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95281. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95282. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95283. #else
  95284. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95285. #endif
  95286. #ifdef DEBUG
  95287. fprintf(stderr, "CPU info (IA-32):\n");
  95288. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95289. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95290. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95291. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95292. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95293. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95294. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95295. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95296. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95297. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95298. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95299. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95300. #endif
  95301. /*
  95302. * now have to check for OS support of SSE/SSE2
  95303. */
  95304. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95305. #if defined FLAC__NO_SSE_OS
  95306. /* assume user knows better than us; turn it off */
  95307. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95308. #elif defined FLAC__SSE_OS
  95309. /* assume user knows better than us; leave as detected above */
  95310. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95311. int sse = 0;
  95312. size_t len;
  95313. /* at least one of these must work: */
  95314. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95315. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95316. if(!sse)
  95317. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95318. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95319. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95320. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95321. size_t len = sizeof(val);
  95322. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95323. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95324. else { /* double-check SSE2 */
  95325. mib[1] = CPU_SSE2;
  95326. len = sizeof(val);
  95327. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95328. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95329. }
  95330. # else
  95331. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95332. # endif
  95333. #elif defined(__linux__)
  95334. int sse = 0;
  95335. struct sigaction sigill_save;
  95336. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95337. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95338. #else
  95339. struct sigaction sigill_sse;
  95340. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95341. __sigemptyset(&sigill_sse.sa_mask);
  95342. 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 */
  95343. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95344. #endif
  95345. {
  95346. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95347. /* see sigill_handler_sse_os() for an explanation of the following: */
  95348. asm volatile (
  95349. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95350. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95351. "incl %0\n\t" /* SIGILL handler will jump over this */
  95352. /* landing zone */
  95353. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95354. "nop\n\t"
  95355. "nop\n\t"
  95356. "nop\n\t"
  95357. "nop\n\t"
  95358. "nop\n\t"
  95359. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95360. "nop\n\t"
  95361. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95362. : "=r"(sse)
  95363. : "r"(sse)
  95364. );
  95365. sigaction(SIGILL, &sigill_save, NULL);
  95366. }
  95367. if(!sse)
  95368. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95369. #elif defined(_MSC_VER)
  95370. # ifdef USE_TRY_CATCH_FLAVOR
  95371. _try {
  95372. __asm {
  95373. # if _MSC_VER <= 1200
  95374. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95375. _emit 0x0F
  95376. _emit 0x57
  95377. _emit 0xC0
  95378. # else
  95379. xorps xmm0,xmm0
  95380. # endif
  95381. }
  95382. }
  95383. _except(EXCEPTION_EXECUTE_HANDLER) {
  95384. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95385. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95386. }
  95387. # else
  95388. int sse = 0;
  95389. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95390. /* see GCC version above for explanation */
  95391. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95392. /* http://www.codeproject.com/cpp/gccasm.asp */
  95393. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95394. __asm {
  95395. # if _MSC_VER <= 1200
  95396. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95397. _emit 0x0F
  95398. _emit 0x57
  95399. _emit 0xC0
  95400. # else
  95401. xorps xmm0,xmm0
  95402. # endif
  95403. inc sse
  95404. nop
  95405. nop
  95406. nop
  95407. nop
  95408. nop
  95409. nop
  95410. nop
  95411. nop
  95412. nop
  95413. }
  95414. SetUnhandledExceptionFilter(save);
  95415. if(!sse)
  95416. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95417. # endif
  95418. #else
  95419. /* no way to test, disable to be safe */
  95420. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95421. #endif
  95422. #ifdef DEBUG
  95423. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95424. #endif
  95425. }
  95426. }
  95427. #else
  95428. info->use_asm = false;
  95429. #endif
  95430. /*
  95431. * PPC-specific
  95432. */
  95433. #elif defined FLAC__CPU_PPC
  95434. info->type = FLAC__CPUINFO_TYPE_PPC;
  95435. # if !defined FLAC__NO_ASM
  95436. info->use_asm = true;
  95437. # ifdef FLAC__USE_ALTIVEC
  95438. # if defined FLAC__SYS_DARWIN
  95439. {
  95440. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95441. size_t len = sizeof(val);
  95442. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95443. }
  95444. {
  95445. host_basic_info_data_t hostInfo;
  95446. mach_msg_type_number_t infoCount;
  95447. infoCount = HOST_BASIC_INFO_COUNT;
  95448. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95449. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95450. }
  95451. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95452. {
  95453. /* no Darwin, do it the brute-force way */
  95454. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95455. info->data.ppc.altivec = 0;
  95456. info->data.ppc.ppc64 = 0;
  95457. signal (SIGILL, sigill_handler);
  95458. canjump = 0;
  95459. if (!sigsetjmp (jmpbuf, 1)) {
  95460. canjump = 1;
  95461. asm volatile (
  95462. "mtspr 256, %0\n\t"
  95463. "vand %%v0, %%v0, %%v0"
  95464. :
  95465. : "r" (-1)
  95466. );
  95467. info->data.ppc.altivec = 1;
  95468. }
  95469. canjump = 0;
  95470. if (!sigsetjmp (jmpbuf, 1)) {
  95471. int x = 0;
  95472. canjump = 1;
  95473. /* PPC64 hardware implements the cntlzd instruction */
  95474. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95475. info->data.ppc.ppc64 = 1;
  95476. }
  95477. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95478. }
  95479. # endif
  95480. # else /* !FLAC__USE_ALTIVEC */
  95481. info->data.ppc.altivec = 0;
  95482. info->data.ppc.ppc64 = 0;
  95483. # endif
  95484. # else
  95485. info->use_asm = false;
  95486. # endif
  95487. /*
  95488. * unknown CPI
  95489. */
  95490. #else
  95491. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95492. info->use_asm = false;
  95493. #endif
  95494. }
  95495. #endif
  95496. /*** End of inlined file: cpu.c ***/
  95497. /*** Start of inlined file: crc.c ***/
  95498. /*** Start of inlined file: juce_FlacHeader.h ***/
  95499. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95500. // tasks..
  95501. #define VERSION "1.2.1"
  95502. #define FLAC__NO_DLL 1
  95503. #if JUCE_MSVC
  95504. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95505. #endif
  95506. #if JUCE_MAC
  95507. #define FLAC__SYS_DARWIN 1
  95508. #endif
  95509. /*** End of inlined file: juce_FlacHeader.h ***/
  95510. #if JUCE_USE_FLAC
  95511. #if HAVE_CONFIG_H
  95512. # include <config.h>
  95513. #endif
  95514. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95515. FLAC__byte const FLAC__crc8_table[256] = {
  95516. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95517. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95518. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95519. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95520. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95521. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95522. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95523. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95524. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95525. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95526. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95527. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95528. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95529. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95530. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95531. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95532. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95533. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95534. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95535. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95536. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95537. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95538. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95539. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95540. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95541. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95542. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95543. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95544. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95545. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95546. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95547. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95548. };
  95549. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95550. unsigned FLAC__crc16_table[256] = {
  95551. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95552. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95553. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95554. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95555. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95556. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95557. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95558. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95559. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95560. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95561. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95562. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95563. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95564. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95565. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95566. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95567. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95568. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95569. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95570. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95571. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95572. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95573. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95574. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95575. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95576. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95577. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95578. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95579. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95580. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95581. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95582. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95583. };
  95584. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95585. {
  95586. *crc = FLAC__crc8_table[*crc ^ data];
  95587. }
  95588. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95589. {
  95590. while(len--)
  95591. *crc = FLAC__crc8_table[*crc ^ *data++];
  95592. }
  95593. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95594. {
  95595. FLAC__uint8 crc = 0;
  95596. while(len--)
  95597. crc = FLAC__crc8_table[crc ^ *data++];
  95598. return crc;
  95599. }
  95600. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95601. {
  95602. unsigned crc = 0;
  95603. while(len--)
  95604. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95605. return crc;
  95606. }
  95607. #endif
  95608. /*** End of inlined file: crc.c ***/
  95609. /*** Start of inlined file: fixed.c ***/
  95610. /*** Start of inlined file: juce_FlacHeader.h ***/
  95611. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95612. // tasks..
  95613. #define VERSION "1.2.1"
  95614. #define FLAC__NO_DLL 1
  95615. #if JUCE_MSVC
  95616. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95617. #endif
  95618. #if JUCE_MAC
  95619. #define FLAC__SYS_DARWIN 1
  95620. #endif
  95621. /*** End of inlined file: juce_FlacHeader.h ***/
  95622. #if JUCE_USE_FLAC
  95623. #if HAVE_CONFIG_H
  95624. # include <config.h>
  95625. #endif
  95626. #include <math.h>
  95627. #include <string.h>
  95628. /*** Start of inlined file: fixed.h ***/
  95629. #ifndef FLAC__PRIVATE__FIXED_H
  95630. #define FLAC__PRIVATE__FIXED_H
  95631. #ifdef HAVE_CONFIG_H
  95632. #include <config.h>
  95633. #endif
  95634. /*** Start of inlined file: float.h ***/
  95635. #ifndef FLAC__PRIVATE__FLOAT_H
  95636. #define FLAC__PRIVATE__FLOAT_H
  95637. #ifdef HAVE_CONFIG_H
  95638. #include <config.h>
  95639. #endif
  95640. /*
  95641. * These typedefs make it easier to ensure that integer versions of
  95642. * the library really only contain integer operations. All the code
  95643. * in libFLAC should use FLAC__float and FLAC__double in place of
  95644. * float and double, and be protected by checks of the macro
  95645. * FLAC__INTEGER_ONLY_LIBRARY.
  95646. *
  95647. * FLAC__real is the basic floating point type used in LPC analysis.
  95648. */
  95649. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95650. typedef double FLAC__double;
  95651. typedef float FLAC__float;
  95652. /*
  95653. * WATCHOUT: changing FLAC__real will change the signatures of many
  95654. * functions that have assembly language equivalents and break them.
  95655. */
  95656. typedef float FLAC__real;
  95657. #else
  95658. /*
  95659. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95660. * for the integer part and lower 16 bits for the fractional part.
  95661. */
  95662. typedef FLAC__int32 FLAC__fixedpoint;
  95663. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95664. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95665. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95666. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95667. extern const FLAC__fixedpoint FLAC__FP_E;
  95668. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95669. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95670. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95671. /*
  95672. * FLAC__fixedpoint_log2()
  95673. * --------------------------------------------------------------------
  95674. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95675. * algorithm by Knuth for x >= 1.0
  95676. *
  95677. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95678. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95679. *
  95680. * 'precision' roughly limits the number of iterations that are done;
  95681. * use (unsigned)(-1) for maximum precision.
  95682. *
  95683. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95684. * function will punt and return 0.
  95685. *
  95686. * The return value will also have 'fracbits' fractional bits.
  95687. */
  95688. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95689. #endif
  95690. #endif
  95691. /*** End of inlined file: float.h ***/
  95692. /*** Start of inlined file: format.h ***/
  95693. #ifndef FLAC__PRIVATE__FORMAT_H
  95694. #define FLAC__PRIVATE__FORMAT_H
  95695. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95696. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95697. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95698. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95699. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95700. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95701. #endif
  95702. /*** End of inlined file: format.h ***/
  95703. /*
  95704. * FLAC__fixed_compute_best_predictor()
  95705. * --------------------------------------------------------------------
  95706. * Compute the best fixed predictor and the expected bits-per-sample
  95707. * of the residual signal for each order. The _wide() version uses
  95708. * 64-bit integers which is statistically necessary when bits-per-
  95709. * sample + log2(blocksize) > 30
  95710. *
  95711. * IN data[0,data_len-1]
  95712. * IN data_len
  95713. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95714. */
  95715. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95716. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95717. # ifndef FLAC__NO_ASM
  95718. # ifdef FLAC__CPU_IA32
  95719. # ifdef FLAC__HAS_NASM
  95720. 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]);
  95721. # endif
  95722. # endif
  95723. # endif
  95724. 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]);
  95725. #else
  95726. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95727. 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]);
  95728. #endif
  95729. /*
  95730. * FLAC__fixed_compute_residual()
  95731. * --------------------------------------------------------------------
  95732. * Compute the residual signal obtained from sutracting the predicted
  95733. * signal from the original.
  95734. *
  95735. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95736. * IN data_len length of original signal
  95737. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95738. * OUT residual[0,data_len-1] residual signal
  95739. */
  95740. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95741. /*
  95742. * FLAC__fixed_restore_signal()
  95743. * --------------------------------------------------------------------
  95744. * Restore the original signal by summing the residual and the
  95745. * predictor.
  95746. *
  95747. * IN residual[0,data_len-1] residual signal
  95748. * IN data_len length of original signal
  95749. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95750. * *** IMPORTANT: the caller must pass in the historical samples:
  95751. * IN data[-order,-1] previously-reconstructed historical samples
  95752. * OUT data[0,data_len-1] original signal
  95753. */
  95754. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95755. #endif
  95756. /*** End of inlined file: fixed.h ***/
  95757. #ifndef M_LN2
  95758. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95759. #define M_LN2 0.69314718055994530942
  95760. #endif
  95761. #ifdef min
  95762. #undef min
  95763. #endif
  95764. #define min(x,y) ((x) < (y)? (x) : (y))
  95765. #ifdef local_abs
  95766. #undef local_abs
  95767. #endif
  95768. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95769. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95770. /* rbps stands for residual bits per sample
  95771. *
  95772. * (ln(2) * err)
  95773. * rbps = log (-----------)
  95774. * 2 ( n )
  95775. */
  95776. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95777. {
  95778. FLAC__uint32 rbps;
  95779. unsigned bits; /* the number of bits required to represent a number */
  95780. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95781. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95782. FLAC__ASSERT(err > 0);
  95783. FLAC__ASSERT(n > 0);
  95784. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95785. if(err <= n)
  95786. return 0;
  95787. /*
  95788. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95789. * These allow us later to know we won't lose too much precision in the
  95790. * fixed-point division (err<<fracbits)/n.
  95791. */
  95792. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95793. err <<= fracbits;
  95794. err /= n;
  95795. /* err now holds err/n with fracbits fractional bits */
  95796. /*
  95797. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95798. * our purposes.
  95799. */
  95800. FLAC__ASSERT(err > 0);
  95801. bits = FLAC__bitmath_ilog2(err)+1;
  95802. if(bits > 16) {
  95803. err >>= (bits-16);
  95804. fracbits -= (bits-16);
  95805. }
  95806. rbps = (FLAC__uint32)err;
  95807. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95808. rbps *= FLAC__FP_LN2;
  95809. fracbits += 16;
  95810. FLAC__ASSERT(fracbits >= 0);
  95811. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95812. {
  95813. const int f = fracbits & 3;
  95814. if(f) {
  95815. rbps >>= f;
  95816. fracbits -= f;
  95817. }
  95818. }
  95819. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95820. if(rbps == 0)
  95821. return 0;
  95822. /*
  95823. * The return value must have 16 fractional bits. Since the whole part
  95824. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95825. * must be >= -3, these assertion allows us to be able to shift rbps
  95826. * left if necessary to get 16 fracbits without losing any bits of the
  95827. * whole part of rbps.
  95828. *
  95829. * There is a slight chance due to accumulated error that the whole part
  95830. * will require 6 bits, so we use 6 in the assertion. Really though as
  95831. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95832. */
  95833. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95834. FLAC__ASSERT(fracbits >= -3);
  95835. /* now shift the decimal point into place */
  95836. if(fracbits < 16)
  95837. return rbps << (16-fracbits);
  95838. else if(fracbits > 16)
  95839. return rbps >> (fracbits-16);
  95840. else
  95841. return rbps;
  95842. }
  95843. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95844. {
  95845. FLAC__uint32 rbps;
  95846. unsigned bits; /* the number of bits required to represent a number */
  95847. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95848. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95849. FLAC__ASSERT(err > 0);
  95850. FLAC__ASSERT(n > 0);
  95851. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95852. if(err <= n)
  95853. return 0;
  95854. /*
  95855. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95856. * These allow us later to know we won't lose too much precision in the
  95857. * fixed-point division (err<<fracbits)/n.
  95858. */
  95859. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95860. err <<= fracbits;
  95861. err /= n;
  95862. /* err now holds err/n with fracbits fractional bits */
  95863. /*
  95864. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95865. * our purposes.
  95866. */
  95867. FLAC__ASSERT(err > 0);
  95868. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95869. if(bits > 16) {
  95870. err >>= (bits-16);
  95871. fracbits -= (bits-16);
  95872. }
  95873. rbps = (FLAC__uint32)err;
  95874. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95875. rbps *= FLAC__FP_LN2;
  95876. fracbits += 16;
  95877. FLAC__ASSERT(fracbits >= 0);
  95878. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95879. {
  95880. const int f = fracbits & 3;
  95881. if(f) {
  95882. rbps >>= f;
  95883. fracbits -= f;
  95884. }
  95885. }
  95886. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95887. if(rbps == 0)
  95888. return 0;
  95889. /*
  95890. * The return value must have 16 fractional bits. Since the whole part
  95891. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95892. * must be >= -3, these assertion allows us to be able to shift rbps
  95893. * left if necessary to get 16 fracbits without losing any bits of the
  95894. * whole part of rbps.
  95895. *
  95896. * There is a slight chance due to accumulated error that the whole part
  95897. * will require 6 bits, so we use 6 in the assertion. Really though as
  95898. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95899. */
  95900. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95901. FLAC__ASSERT(fracbits >= -3);
  95902. /* now shift the decimal point into place */
  95903. if(fracbits < 16)
  95904. return rbps << (16-fracbits);
  95905. else if(fracbits > 16)
  95906. return rbps >> (fracbits-16);
  95907. else
  95908. return rbps;
  95909. }
  95910. #endif
  95911. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95912. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95913. #else
  95914. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95915. #endif
  95916. {
  95917. FLAC__int32 last_error_0 = data[-1];
  95918. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95919. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95920. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95921. FLAC__int32 error, save;
  95922. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95923. unsigned i, order;
  95924. for(i = 0; i < data_len; i++) {
  95925. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95926. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95927. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95928. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95929. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95930. }
  95931. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95932. order = 0;
  95933. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95934. order = 1;
  95935. else if(total_error_2 < min(total_error_3, total_error_4))
  95936. order = 2;
  95937. else if(total_error_3 < total_error_4)
  95938. order = 3;
  95939. else
  95940. order = 4;
  95941. /* Estimate the expected number of bits per residual signal sample. */
  95942. /* 'total_error*' is linearly related to the variance of the residual */
  95943. /* signal, so we use it directly to compute E(|x|) */
  95944. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95945. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95946. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95947. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95948. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95949. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95950. 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);
  95951. 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);
  95952. 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);
  95953. 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);
  95954. 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);
  95955. #else
  95956. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95957. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95958. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95959. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95960. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95961. #endif
  95962. return order;
  95963. }
  95964. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95965. 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])
  95966. #else
  95967. 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])
  95968. #endif
  95969. {
  95970. FLAC__int32 last_error_0 = data[-1];
  95971. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95972. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95973. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95974. FLAC__int32 error, save;
  95975. /* total_error_* are 64-bits to avoid overflow when encoding
  95976. * erratic signals when the bits-per-sample and blocksize are
  95977. * large.
  95978. */
  95979. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95980. unsigned i, order;
  95981. for(i = 0; i < data_len; i++) {
  95982. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95983. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95984. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95985. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95986. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95987. }
  95988. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95989. order = 0;
  95990. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95991. order = 1;
  95992. else if(total_error_2 < min(total_error_3, total_error_4))
  95993. order = 2;
  95994. else if(total_error_3 < total_error_4)
  95995. order = 3;
  95996. else
  95997. order = 4;
  95998. /* Estimate the expected number of bits per residual signal sample. */
  95999. /* 'total_error*' is linearly related to the variance of the residual */
  96000. /* signal, so we use it directly to compute E(|x|) */
  96001. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96002. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96003. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96004. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96005. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96006. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96007. #if defined _MSC_VER || defined __MINGW32__
  96008. /* with MSVC you have to spoon feed it the casting */
  96009. 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);
  96010. 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);
  96011. 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);
  96012. 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);
  96013. 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);
  96014. #else
  96015. 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);
  96016. 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);
  96017. 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);
  96018. 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);
  96019. 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);
  96020. #endif
  96021. #else
  96022. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96023. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96024. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96025. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96026. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96027. #endif
  96028. return order;
  96029. }
  96030. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96031. {
  96032. const int idata_len = (int)data_len;
  96033. int i;
  96034. switch(order) {
  96035. case 0:
  96036. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96037. memcpy(residual, data, sizeof(residual[0])*data_len);
  96038. break;
  96039. case 1:
  96040. for(i = 0; i < idata_len; i++)
  96041. residual[i] = data[i] - data[i-1];
  96042. break;
  96043. case 2:
  96044. for(i = 0; i < idata_len; i++)
  96045. #if 1 /* OPT: may be faster with some compilers on some systems */
  96046. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96047. #else
  96048. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96049. #endif
  96050. break;
  96051. case 3:
  96052. for(i = 0; i < idata_len; i++)
  96053. #if 1 /* OPT: may be faster with some compilers on some systems */
  96054. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96055. #else
  96056. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96057. #endif
  96058. break;
  96059. case 4:
  96060. for(i = 0; i < idata_len; i++)
  96061. #if 1 /* OPT: may be faster with some compilers on some systems */
  96062. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96063. #else
  96064. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96065. #endif
  96066. break;
  96067. default:
  96068. FLAC__ASSERT(0);
  96069. }
  96070. }
  96071. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96072. {
  96073. int i, idata_len = (int)data_len;
  96074. switch(order) {
  96075. case 0:
  96076. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96077. memcpy(data, residual, sizeof(residual[0])*data_len);
  96078. break;
  96079. case 1:
  96080. for(i = 0; i < idata_len; i++)
  96081. data[i] = residual[i] + data[i-1];
  96082. break;
  96083. case 2:
  96084. for(i = 0; i < idata_len; i++)
  96085. #if 1 /* OPT: may be faster with some compilers on some systems */
  96086. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96087. #else
  96088. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96089. #endif
  96090. break;
  96091. case 3:
  96092. for(i = 0; i < idata_len; i++)
  96093. #if 1 /* OPT: may be faster with some compilers on some systems */
  96094. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96095. #else
  96096. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96097. #endif
  96098. break;
  96099. case 4:
  96100. for(i = 0; i < idata_len; i++)
  96101. #if 1 /* OPT: may be faster with some compilers on some systems */
  96102. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96103. #else
  96104. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96105. #endif
  96106. break;
  96107. default:
  96108. FLAC__ASSERT(0);
  96109. }
  96110. }
  96111. #endif
  96112. /*** End of inlined file: fixed.c ***/
  96113. /*** Start of inlined file: float.c ***/
  96114. /*** Start of inlined file: juce_FlacHeader.h ***/
  96115. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96116. // tasks..
  96117. #define VERSION "1.2.1"
  96118. #define FLAC__NO_DLL 1
  96119. #if JUCE_MSVC
  96120. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96121. #endif
  96122. #if JUCE_MAC
  96123. #define FLAC__SYS_DARWIN 1
  96124. #endif
  96125. /*** End of inlined file: juce_FlacHeader.h ***/
  96126. #if JUCE_USE_FLAC
  96127. #if HAVE_CONFIG_H
  96128. # include <config.h>
  96129. #endif
  96130. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96131. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96132. #ifdef _MSC_VER
  96133. #define FLAC__U64L(x) x
  96134. #else
  96135. #define FLAC__U64L(x) x##LLU
  96136. #endif
  96137. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96138. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96139. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96140. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96141. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96142. /* Lookup tables for Knuth's logarithm algorithm */
  96143. #define LOG2_LOOKUP_PRECISION 16
  96144. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96145. {
  96146. /*
  96147. * 0 fraction bits
  96148. */
  96149. /* undefined */ 0x00000000,
  96150. /* lg(2/1) = */ 0x00000001,
  96151. /* lg(4/3) = */ 0x00000000,
  96152. /* lg(8/7) = */ 0x00000000,
  96153. /* lg(16/15) = */ 0x00000000,
  96154. /* lg(32/31) = */ 0x00000000,
  96155. /* lg(64/63) = */ 0x00000000,
  96156. /* lg(128/127) = */ 0x00000000,
  96157. /* lg(256/255) = */ 0x00000000,
  96158. /* lg(512/511) = */ 0x00000000,
  96159. /* lg(1024/1023) = */ 0x00000000,
  96160. /* lg(2048/2047) = */ 0x00000000,
  96161. /* lg(4096/4095) = */ 0x00000000,
  96162. /* lg(8192/8191) = */ 0x00000000,
  96163. /* lg(16384/16383) = */ 0x00000000,
  96164. /* lg(32768/32767) = */ 0x00000000
  96165. },
  96166. {
  96167. /*
  96168. * 4 fraction bits
  96169. */
  96170. /* undefined */ 0x00000000,
  96171. /* lg(2/1) = */ 0x00000010,
  96172. /* lg(4/3) = */ 0x00000007,
  96173. /* lg(8/7) = */ 0x00000003,
  96174. /* lg(16/15) = */ 0x00000001,
  96175. /* lg(32/31) = */ 0x00000001,
  96176. /* lg(64/63) = */ 0x00000000,
  96177. /* lg(128/127) = */ 0x00000000,
  96178. /* lg(256/255) = */ 0x00000000,
  96179. /* lg(512/511) = */ 0x00000000,
  96180. /* lg(1024/1023) = */ 0x00000000,
  96181. /* lg(2048/2047) = */ 0x00000000,
  96182. /* lg(4096/4095) = */ 0x00000000,
  96183. /* lg(8192/8191) = */ 0x00000000,
  96184. /* lg(16384/16383) = */ 0x00000000,
  96185. /* lg(32768/32767) = */ 0x00000000
  96186. },
  96187. {
  96188. /*
  96189. * 8 fraction bits
  96190. */
  96191. /* undefined */ 0x00000000,
  96192. /* lg(2/1) = */ 0x00000100,
  96193. /* lg(4/3) = */ 0x0000006a,
  96194. /* lg(8/7) = */ 0x00000031,
  96195. /* lg(16/15) = */ 0x00000018,
  96196. /* lg(32/31) = */ 0x0000000c,
  96197. /* lg(64/63) = */ 0x00000006,
  96198. /* lg(128/127) = */ 0x00000003,
  96199. /* lg(256/255) = */ 0x00000001,
  96200. /* lg(512/511) = */ 0x00000001,
  96201. /* lg(1024/1023) = */ 0x00000000,
  96202. /* lg(2048/2047) = */ 0x00000000,
  96203. /* lg(4096/4095) = */ 0x00000000,
  96204. /* lg(8192/8191) = */ 0x00000000,
  96205. /* lg(16384/16383) = */ 0x00000000,
  96206. /* lg(32768/32767) = */ 0x00000000
  96207. },
  96208. {
  96209. /*
  96210. * 12 fraction bits
  96211. */
  96212. /* undefined */ 0x00000000,
  96213. /* lg(2/1) = */ 0x00001000,
  96214. /* lg(4/3) = */ 0x000006a4,
  96215. /* lg(8/7) = */ 0x00000315,
  96216. /* lg(16/15) = */ 0x0000017d,
  96217. /* lg(32/31) = */ 0x000000bc,
  96218. /* lg(64/63) = */ 0x0000005d,
  96219. /* lg(128/127) = */ 0x0000002e,
  96220. /* lg(256/255) = */ 0x00000017,
  96221. /* lg(512/511) = */ 0x0000000c,
  96222. /* lg(1024/1023) = */ 0x00000006,
  96223. /* lg(2048/2047) = */ 0x00000003,
  96224. /* lg(4096/4095) = */ 0x00000001,
  96225. /* lg(8192/8191) = */ 0x00000001,
  96226. /* lg(16384/16383) = */ 0x00000000,
  96227. /* lg(32768/32767) = */ 0x00000000
  96228. },
  96229. {
  96230. /*
  96231. * 16 fraction bits
  96232. */
  96233. /* undefined */ 0x00000000,
  96234. /* lg(2/1) = */ 0x00010000,
  96235. /* lg(4/3) = */ 0x00006a40,
  96236. /* lg(8/7) = */ 0x00003151,
  96237. /* lg(16/15) = */ 0x000017d6,
  96238. /* lg(32/31) = */ 0x00000bba,
  96239. /* lg(64/63) = */ 0x000005d1,
  96240. /* lg(128/127) = */ 0x000002e6,
  96241. /* lg(256/255) = */ 0x00000172,
  96242. /* lg(512/511) = */ 0x000000b9,
  96243. /* lg(1024/1023) = */ 0x0000005c,
  96244. /* lg(2048/2047) = */ 0x0000002e,
  96245. /* lg(4096/4095) = */ 0x00000017,
  96246. /* lg(8192/8191) = */ 0x0000000c,
  96247. /* lg(16384/16383) = */ 0x00000006,
  96248. /* lg(32768/32767) = */ 0x00000003
  96249. },
  96250. {
  96251. /*
  96252. * 20 fraction bits
  96253. */
  96254. /* undefined */ 0x00000000,
  96255. /* lg(2/1) = */ 0x00100000,
  96256. /* lg(4/3) = */ 0x0006a3fe,
  96257. /* lg(8/7) = */ 0x00031513,
  96258. /* lg(16/15) = */ 0x00017d60,
  96259. /* lg(32/31) = */ 0x0000bb9d,
  96260. /* lg(64/63) = */ 0x00005d10,
  96261. /* lg(128/127) = */ 0x00002e59,
  96262. /* lg(256/255) = */ 0x00001721,
  96263. /* lg(512/511) = */ 0x00000b8e,
  96264. /* lg(1024/1023) = */ 0x000005c6,
  96265. /* lg(2048/2047) = */ 0x000002e3,
  96266. /* lg(4096/4095) = */ 0x00000171,
  96267. /* lg(8192/8191) = */ 0x000000b9,
  96268. /* lg(16384/16383) = */ 0x0000005c,
  96269. /* lg(32768/32767) = */ 0x0000002e
  96270. },
  96271. {
  96272. /*
  96273. * 24 fraction bits
  96274. */
  96275. /* undefined */ 0x00000000,
  96276. /* lg(2/1) = */ 0x01000000,
  96277. /* lg(4/3) = */ 0x006a3fe6,
  96278. /* lg(8/7) = */ 0x00315130,
  96279. /* lg(16/15) = */ 0x0017d605,
  96280. /* lg(32/31) = */ 0x000bb9ca,
  96281. /* lg(64/63) = */ 0x0005d0fc,
  96282. /* lg(128/127) = */ 0x0002e58f,
  96283. /* lg(256/255) = */ 0x0001720e,
  96284. /* lg(512/511) = */ 0x0000b8d8,
  96285. /* lg(1024/1023) = */ 0x00005c61,
  96286. /* lg(2048/2047) = */ 0x00002e2d,
  96287. /* lg(4096/4095) = */ 0x00001716,
  96288. /* lg(8192/8191) = */ 0x00000b8b,
  96289. /* lg(16384/16383) = */ 0x000005c5,
  96290. /* lg(32768/32767) = */ 0x000002e3
  96291. },
  96292. {
  96293. /*
  96294. * 28 fraction bits
  96295. */
  96296. /* undefined */ 0x00000000,
  96297. /* lg(2/1) = */ 0x10000000,
  96298. /* lg(4/3) = */ 0x06a3fe5c,
  96299. /* lg(8/7) = */ 0x03151301,
  96300. /* lg(16/15) = */ 0x017d6049,
  96301. /* lg(32/31) = */ 0x00bb9ca6,
  96302. /* lg(64/63) = */ 0x005d0fba,
  96303. /* lg(128/127) = */ 0x002e58f7,
  96304. /* lg(256/255) = */ 0x001720da,
  96305. /* lg(512/511) = */ 0x000b8d87,
  96306. /* lg(1024/1023) = */ 0x0005c60b,
  96307. /* lg(2048/2047) = */ 0x0002e2d7,
  96308. /* lg(4096/4095) = */ 0x00017160,
  96309. /* lg(8192/8191) = */ 0x0000b8ad,
  96310. /* lg(16384/16383) = */ 0x00005c56,
  96311. /* lg(32768/32767) = */ 0x00002e2b
  96312. }
  96313. };
  96314. #if 0
  96315. static const FLAC__uint64 log2_lookup_wide[] = {
  96316. {
  96317. /*
  96318. * 32 fraction bits
  96319. */
  96320. /* undefined */ 0x00000000,
  96321. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96322. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96323. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96324. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96325. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96326. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96327. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96328. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96329. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96330. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96331. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96332. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96333. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96334. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96335. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96336. },
  96337. {
  96338. /*
  96339. * 48 fraction bits
  96340. */
  96341. /* undefined */ 0x00000000,
  96342. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96343. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96344. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96345. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96346. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96347. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96348. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96349. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96350. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96351. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96352. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96353. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96354. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96355. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96356. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96357. }
  96358. };
  96359. #endif
  96360. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96361. {
  96362. const FLAC__uint32 ONE = (1u << fracbits);
  96363. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96364. FLAC__ASSERT(fracbits < 32);
  96365. FLAC__ASSERT((fracbits & 0x3) == 0);
  96366. if(x < ONE)
  96367. return 0;
  96368. if(precision > LOG2_LOOKUP_PRECISION)
  96369. precision = LOG2_LOOKUP_PRECISION;
  96370. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96371. {
  96372. FLAC__uint32 y = 0;
  96373. FLAC__uint32 z = x >> 1, k = 1;
  96374. while (x > ONE && k < precision) {
  96375. if (x - z >= ONE) {
  96376. x -= z;
  96377. z = x >> k;
  96378. y += table[k];
  96379. }
  96380. else {
  96381. z >>= 1;
  96382. k++;
  96383. }
  96384. }
  96385. return y;
  96386. }
  96387. }
  96388. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96389. #endif
  96390. /*** End of inlined file: float.c ***/
  96391. /*** Start of inlined file: format.c ***/
  96392. /*** Start of inlined file: juce_FlacHeader.h ***/
  96393. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96394. // tasks..
  96395. #define VERSION "1.2.1"
  96396. #define FLAC__NO_DLL 1
  96397. #if JUCE_MSVC
  96398. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96399. #endif
  96400. #if JUCE_MAC
  96401. #define FLAC__SYS_DARWIN 1
  96402. #endif
  96403. /*** End of inlined file: juce_FlacHeader.h ***/
  96404. #if JUCE_USE_FLAC
  96405. #if HAVE_CONFIG_H
  96406. # include <config.h>
  96407. #endif
  96408. #include <stdio.h>
  96409. #include <stdlib.h> /* for qsort() */
  96410. #include <string.h> /* for memset() */
  96411. #ifndef FLaC__INLINE
  96412. #define FLaC__INLINE
  96413. #endif
  96414. #ifdef min
  96415. #undef min
  96416. #endif
  96417. #define min(a,b) ((a)<(b)?(a):(b))
  96418. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96419. #ifdef _MSC_VER
  96420. #define FLAC__U64L(x) x
  96421. #else
  96422. #define FLAC__U64L(x) x##LLU
  96423. #endif
  96424. /* VERSION should come from configure */
  96425. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96426. ;
  96427. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96428. /* yet one more hack because of MSVC6: */
  96429. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96430. #else
  96431. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96432. #endif
  96433. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96434. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96435. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96436. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96437. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96438. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96439. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96440. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96441. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96442. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96443. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96444. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96445. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96446. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96447. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96448. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96449. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96450. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96451. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96452. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96453. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96454. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96455. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96456. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96457. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96458. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96459. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96460. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96461. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96462. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96463. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96464. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96465. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96466. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96467. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96468. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96469. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96470. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96471. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96472. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96473. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96474. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96475. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96476. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96477. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96478. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96479. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96480. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96481. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96482. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96483. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96484. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96485. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96486. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96487. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96488. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96489. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96490. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96491. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96492. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96493. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96494. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96495. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96496. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96497. "PARTITIONED_RICE",
  96498. "PARTITIONED_RICE2"
  96499. };
  96500. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96501. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96502. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96503. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96504. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96505. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96506. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96507. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96508. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96509. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96510. "CONSTANT",
  96511. "VERBATIM",
  96512. "FIXED",
  96513. "LPC"
  96514. };
  96515. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96516. "INDEPENDENT",
  96517. "LEFT_SIDE",
  96518. "RIGHT_SIDE",
  96519. "MID_SIDE"
  96520. };
  96521. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96522. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96523. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96524. };
  96525. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96526. "STREAMINFO",
  96527. "PADDING",
  96528. "APPLICATION",
  96529. "SEEKTABLE",
  96530. "VORBIS_COMMENT",
  96531. "CUESHEET",
  96532. "PICTURE"
  96533. };
  96534. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96535. "Other",
  96536. "32x32 pixels 'file icon' (PNG only)",
  96537. "Other file icon",
  96538. "Cover (front)",
  96539. "Cover (back)",
  96540. "Leaflet page",
  96541. "Media (e.g. label side of CD)",
  96542. "Lead artist/lead performer/soloist",
  96543. "Artist/performer",
  96544. "Conductor",
  96545. "Band/Orchestra",
  96546. "Composer",
  96547. "Lyricist/text writer",
  96548. "Recording Location",
  96549. "During recording",
  96550. "During performance",
  96551. "Movie/video screen capture",
  96552. "A bright coloured fish",
  96553. "Illustration",
  96554. "Band/artist logotype",
  96555. "Publisher/Studio logotype"
  96556. };
  96557. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96558. {
  96559. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96560. return false;
  96561. }
  96562. else
  96563. return true;
  96564. }
  96565. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96566. {
  96567. if(
  96568. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96569. (
  96570. sample_rate >= (1u << 16) &&
  96571. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96572. )
  96573. ) {
  96574. return false;
  96575. }
  96576. else
  96577. return true;
  96578. }
  96579. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96580. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96581. {
  96582. unsigned i;
  96583. FLAC__uint64 prev_sample_number = 0;
  96584. FLAC__bool got_prev = false;
  96585. FLAC__ASSERT(0 != seek_table);
  96586. for(i = 0; i < seek_table->num_points; i++) {
  96587. if(got_prev) {
  96588. if(
  96589. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96590. seek_table->points[i].sample_number <= prev_sample_number
  96591. )
  96592. return false;
  96593. }
  96594. prev_sample_number = seek_table->points[i].sample_number;
  96595. got_prev = true;
  96596. }
  96597. return true;
  96598. }
  96599. /* used as the sort predicate for qsort() */
  96600. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96601. {
  96602. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96603. if(l->sample_number == r->sample_number)
  96604. return 0;
  96605. else if(l->sample_number < r->sample_number)
  96606. return -1;
  96607. else
  96608. return 1;
  96609. }
  96610. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96611. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96612. {
  96613. unsigned i, j;
  96614. FLAC__bool first;
  96615. FLAC__ASSERT(0 != seek_table);
  96616. /* sort the seekpoints */
  96617. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96618. /* uniquify the seekpoints */
  96619. first = true;
  96620. for(i = j = 0; i < seek_table->num_points; i++) {
  96621. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96622. if(!first) {
  96623. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96624. continue;
  96625. }
  96626. }
  96627. first = false;
  96628. seek_table->points[j++] = seek_table->points[i];
  96629. }
  96630. for(i = j; i < seek_table->num_points; i++) {
  96631. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96632. seek_table->points[i].stream_offset = 0;
  96633. seek_table->points[i].frame_samples = 0;
  96634. }
  96635. return j;
  96636. }
  96637. /*
  96638. * also disallows non-shortest-form encodings, c.f.
  96639. * http://www.unicode.org/versions/corrigendum1.html
  96640. * and a more clear explanation at the end of this section:
  96641. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96642. */
  96643. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96644. {
  96645. FLAC__ASSERT(0 != utf8);
  96646. if ((utf8[0] & 0x80) == 0) {
  96647. return 1;
  96648. }
  96649. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96650. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96651. return 0;
  96652. return 2;
  96653. }
  96654. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96655. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96656. return 0;
  96657. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96658. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96659. return 0;
  96660. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96661. return 0;
  96662. return 3;
  96663. }
  96664. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96665. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96666. return 0;
  96667. return 4;
  96668. }
  96669. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96670. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96671. return 0;
  96672. return 5;
  96673. }
  96674. 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) {
  96675. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96676. return 0;
  96677. return 6;
  96678. }
  96679. else {
  96680. return 0;
  96681. }
  96682. }
  96683. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96684. {
  96685. char c;
  96686. for(c = *name; c; c = *(++name))
  96687. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96688. return false;
  96689. return true;
  96690. }
  96691. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96692. {
  96693. if(length == (unsigned)(-1)) {
  96694. while(*value) {
  96695. unsigned n = utf8len_(value);
  96696. if(n == 0)
  96697. return false;
  96698. value += n;
  96699. }
  96700. }
  96701. else {
  96702. const FLAC__byte *end = value + length;
  96703. while(value < end) {
  96704. unsigned n = utf8len_(value);
  96705. if(n == 0)
  96706. return false;
  96707. value += n;
  96708. }
  96709. if(value != end)
  96710. return false;
  96711. }
  96712. return true;
  96713. }
  96714. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96715. {
  96716. const FLAC__byte *s, *end;
  96717. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96718. if(*s < 0x20 || *s > 0x7D)
  96719. return false;
  96720. }
  96721. if(s == end)
  96722. return false;
  96723. s++; /* skip '=' */
  96724. while(s < end) {
  96725. unsigned n = utf8len_(s);
  96726. if(n == 0)
  96727. return false;
  96728. s += n;
  96729. }
  96730. if(s != end)
  96731. return false;
  96732. return true;
  96733. }
  96734. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96735. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96736. {
  96737. unsigned i, j;
  96738. if(check_cd_da_subset) {
  96739. if(cue_sheet->lead_in < 2 * 44100) {
  96740. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96741. return false;
  96742. }
  96743. if(cue_sheet->lead_in % 588 != 0) {
  96744. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96745. return false;
  96746. }
  96747. }
  96748. if(cue_sheet->num_tracks == 0) {
  96749. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96750. return false;
  96751. }
  96752. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96753. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96754. return false;
  96755. }
  96756. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96757. if(cue_sheet->tracks[i].number == 0) {
  96758. if(violation) *violation = "cue sheet may not have a track number 0";
  96759. return false;
  96760. }
  96761. if(check_cd_da_subset) {
  96762. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96763. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96764. return false;
  96765. }
  96766. }
  96767. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96768. if(violation) {
  96769. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96770. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96771. else
  96772. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96773. }
  96774. return false;
  96775. }
  96776. if(i < cue_sheet->num_tracks - 1) {
  96777. if(cue_sheet->tracks[i].num_indices == 0) {
  96778. if(violation) *violation = "cue sheet track must have at least one index point";
  96779. return false;
  96780. }
  96781. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96782. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96783. return false;
  96784. }
  96785. }
  96786. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96787. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96788. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96789. return false;
  96790. }
  96791. if(j > 0) {
  96792. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96793. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96794. return false;
  96795. }
  96796. }
  96797. }
  96798. }
  96799. return true;
  96800. }
  96801. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96802. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96803. {
  96804. char *p;
  96805. FLAC__byte *b;
  96806. for(p = picture->mime_type; *p; p++) {
  96807. if(*p < 0x20 || *p > 0x7e) {
  96808. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96809. return false;
  96810. }
  96811. }
  96812. for(b = picture->description; *b; ) {
  96813. unsigned n = utf8len_(b);
  96814. if(n == 0) {
  96815. if(violation) *violation = "description string must be valid UTF-8";
  96816. return false;
  96817. }
  96818. b += n;
  96819. }
  96820. return true;
  96821. }
  96822. /*
  96823. * These routines are private to libFLAC
  96824. */
  96825. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96826. {
  96827. return
  96828. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96829. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96830. blocksize,
  96831. predictor_order
  96832. );
  96833. }
  96834. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96835. {
  96836. unsigned max_rice_partition_order = 0;
  96837. while(!(blocksize & 1)) {
  96838. max_rice_partition_order++;
  96839. blocksize >>= 1;
  96840. }
  96841. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96842. }
  96843. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96844. {
  96845. unsigned max_rice_partition_order = limit;
  96846. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96847. max_rice_partition_order--;
  96848. FLAC__ASSERT(
  96849. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96850. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96851. );
  96852. return max_rice_partition_order;
  96853. }
  96854. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96855. {
  96856. FLAC__ASSERT(0 != object);
  96857. object->parameters = 0;
  96858. object->raw_bits = 0;
  96859. object->capacity_by_order = 0;
  96860. }
  96861. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96862. {
  96863. FLAC__ASSERT(0 != object);
  96864. if(0 != object->parameters)
  96865. free(object->parameters);
  96866. if(0 != object->raw_bits)
  96867. free(object->raw_bits);
  96868. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96869. }
  96870. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96871. {
  96872. FLAC__ASSERT(0 != object);
  96873. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96874. if(object->capacity_by_order < max_partition_order) {
  96875. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96876. return false;
  96877. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96878. return false;
  96879. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96880. object->capacity_by_order = max_partition_order;
  96881. }
  96882. return true;
  96883. }
  96884. #endif
  96885. /*** End of inlined file: format.c ***/
  96886. /*** Start of inlined file: lpc_flac.c ***/
  96887. /*** Start of inlined file: juce_FlacHeader.h ***/
  96888. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96889. // tasks..
  96890. #define VERSION "1.2.1"
  96891. #define FLAC__NO_DLL 1
  96892. #if JUCE_MSVC
  96893. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96894. #endif
  96895. #if JUCE_MAC
  96896. #define FLAC__SYS_DARWIN 1
  96897. #endif
  96898. /*** End of inlined file: juce_FlacHeader.h ***/
  96899. #if JUCE_USE_FLAC
  96900. #if HAVE_CONFIG_H
  96901. # include <config.h>
  96902. #endif
  96903. #include <math.h>
  96904. /*** Start of inlined file: lpc.h ***/
  96905. #ifndef FLAC__PRIVATE__LPC_H
  96906. #define FLAC__PRIVATE__LPC_H
  96907. #ifdef HAVE_CONFIG_H
  96908. #include <config.h>
  96909. #endif
  96910. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96911. /*
  96912. * FLAC__lpc_window_data()
  96913. * --------------------------------------------------------------------
  96914. * Applies the given window to the data.
  96915. * OPT: asm implementation
  96916. *
  96917. * IN in[0,data_len-1]
  96918. * IN window[0,data_len-1]
  96919. * OUT out[0,lag-1]
  96920. * IN data_len
  96921. */
  96922. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96923. /*
  96924. * FLAC__lpc_compute_autocorrelation()
  96925. * --------------------------------------------------------------------
  96926. * Compute the autocorrelation for lags between 0 and lag-1.
  96927. * Assumes data[] outside of [0,data_len-1] == 0.
  96928. * Asserts that lag > 0.
  96929. *
  96930. * IN data[0,data_len-1]
  96931. * IN data_len
  96932. * IN 0 < lag <= data_len
  96933. * OUT autoc[0,lag-1]
  96934. */
  96935. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96936. #ifndef FLAC__NO_ASM
  96937. # ifdef FLAC__CPU_IA32
  96938. # ifdef FLAC__HAS_NASM
  96939. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96940. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96941. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96942. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96943. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96944. # endif
  96945. # endif
  96946. #endif
  96947. /*
  96948. * FLAC__lpc_compute_lp_coefficients()
  96949. * --------------------------------------------------------------------
  96950. * Computes LP coefficients for orders 1..max_order.
  96951. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96952. * and there is no point in calculating a predictor.
  96953. *
  96954. * IN autoc[0,max_order] autocorrelation values
  96955. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96956. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96957. * *** IMPORTANT:
  96958. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96959. * OUT error[0,max_order-1] error for each order (more
  96960. * specifically, the variance of
  96961. * the error signal times # of
  96962. * samples in the signal)
  96963. *
  96964. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96965. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96966. * in lp_coeff[7][0,7], etc.
  96967. */
  96968. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96969. /*
  96970. * FLAC__lpc_quantize_coefficients()
  96971. * --------------------------------------------------------------------
  96972. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96973. * must be less than 32 (sizeof(FLAC__int32)*8).
  96974. *
  96975. * IN lp_coeff[0,order-1] LP coefficients
  96976. * IN order LP order
  96977. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96978. * desired precision (in bits, including sign
  96979. * bit) of largest coefficient
  96980. * OUT qlp_coeff[0,order-1] quantized coefficients
  96981. * OUT shift # of bits to shift right to get approximated
  96982. * LP coefficients. NOTE: could be negative.
  96983. * RETURN 0 => quantization OK
  96984. * 1 => coefficients require too much shifting for *shift to
  96985. * fit in the LPC subframe header. 'shift' is unset.
  96986. * 2 => coefficients are all zero, which is bad. 'shift' is
  96987. * unset.
  96988. */
  96989. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96990. /*
  96991. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96992. * --------------------------------------------------------------------
  96993. * Compute the residual signal obtained from sutracting the predicted
  96994. * signal from the original.
  96995. *
  96996. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96997. * IN data_len length of original signal
  96998. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96999. * IN order > 0 LP order
  97000. * IN lp_quantization quantization of LP coefficients in bits
  97001. * OUT residual[0,data_len-1] residual signal
  97002. */
  97003. 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[]);
  97004. 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[]);
  97005. #ifndef FLAC__NO_ASM
  97006. # ifdef FLAC__CPU_IA32
  97007. # ifdef FLAC__HAS_NASM
  97008. 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[]);
  97009. 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[]);
  97010. # endif
  97011. # endif
  97012. #endif
  97013. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97014. /*
  97015. * FLAC__lpc_restore_signal()
  97016. * --------------------------------------------------------------------
  97017. * Restore the original signal by summing the residual and the
  97018. * predictor.
  97019. *
  97020. * IN residual[0,data_len-1] residual signal
  97021. * IN data_len length of original signal
  97022. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97023. * IN order > 0 LP order
  97024. * IN lp_quantization quantization of LP coefficients in bits
  97025. * *** IMPORTANT: the caller must pass in the historical samples:
  97026. * IN data[-order,-1] previously-reconstructed historical samples
  97027. * OUT data[0,data_len-1] original signal
  97028. */
  97029. 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[]);
  97030. 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[]);
  97031. #ifndef FLAC__NO_ASM
  97032. # ifdef FLAC__CPU_IA32
  97033. # ifdef FLAC__HAS_NASM
  97034. 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[]);
  97035. 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[]);
  97036. # endif /* FLAC__HAS_NASM */
  97037. # elif defined FLAC__CPU_PPC
  97038. 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[]);
  97039. 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[]);
  97040. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97041. #endif /* FLAC__NO_ASM */
  97042. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97043. /*
  97044. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97045. * --------------------------------------------------------------------
  97046. * Compute the expected number of bits per residual signal sample
  97047. * based on the LP error (which is related to the residual variance).
  97048. *
  97049. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97050. * IN total_samples > 0 # of samples in residual signal
  97051. * RETURN expected bits per sample
  97052. */
  97053. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97054. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97055. /*
  97056. * FLAC__lpc_compute_best_order()
  97057. * --------------------------------------------------------------------
  97058. * Compute the best order from the array of signal errors returned
  97059. * during coefficient computation.
  97060. *
  97061. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97062. * IN max_order > 0 max LP order
  97063. * IN total_samples > 0 # of samples in residual signal
  97064. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97065. * (includes warmup sample size and quantized LP coefficient)
  97066. * RETURN [1,max_order] best order
  97067. */
  97068. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97069. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97070. #endif
  97071. /*** End of inlined file: lpc.h ***/
  97072. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97073. #include <stdio.h>
  97074. #endif
  97075. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97076. #ifndef M_LN2
  97077. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97078. #define M_LN2 0.69314718055994530942
  97079. #endif
  97080. /* OPT: #undef'ing this may improve the speed on some architectures */
  97081. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97082. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97083. {
  97084. unsigned i;
  97085. for(i = 0; i < data_len; i++)
  97086. out[i] = in[i] * window[i];
  97087. }
  97088. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97089. {
  97090. /* a readable, but slower, version */
  97091. #if 0
  97092. FLAC__real d;
  97093. unsigned i;
  97094. FLAC__ASSERT(lag > 0);
  97095. FLAC__ASSERT(lag <= data_len);
  97096. /*
  97097. * Technically we should subtract the mean first like so:
  97098. * for(i = 0; i < data_len; i++)
  97099. * data[i] -= mean;
  97100. * but it appears not to make enough of a difference to matter, and
  97101. * most signals are already closely centered around zero
  97102. */
  97103. while(lag--) {
  97104. for(i = lag, d = 0.0; i < data_len; i++)
  97105. d += data[i] * data[i - lag];
  97106. autoc[lag] = d;
  97107. }
  97108. #endif
  97109. /*
  97110. * this version tends to run faster because of better data locality
  97111. * ('data_len' is usually much larger than 'lag')
  97112. */
  97113. FLAC__real d;
  97114. unsigned sample, coeff;
  97115. const unsigned limit = data_len - lag;
  97116. FLAC__ASSERT(lag > 0);
  97117. FLAC__ASSERT(lag <= data_len);
  97118. for(coeff = 0; coeff < lag; coeff++)
  97119. autoc[coeff] = 0.0;
  97120. for(sample = 0; sample <= limit; sample++) {
  97121. d = data[sample];
  97122. for(coeff = 0; coeff < lag; coeff++)
  97123. autoc[coeff] += d * data[sample+coeff];
  97124. }
  97125. for(; sample < data_len; sample++) {
  97126. d = data[sample];
  97127. for(coeff = 0; coeff < data_len - sample; coeff++)
  97128. autoc[coeff] += d * data[sample+coeff];
  97129. }
  97130. }
  97131. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97132. {
  97133. unsigned i, j;
  97134. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97135. FLAC__ASSERT(0 != max_order);
  97136. FLAC__ASSERT(0 < *max_order);
  97137. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97138. FLAC__ASSERT(autoc[0] != 0.0);
  97139. err = autoc[0];
  97140. for(i = 0; i < *max_order; i++) {
  97141. /* Sum up this iteration's reflection coefficient. */
  97142. r = -autoc[i+1];
  97143. for(j = 0; j < i; j++)
  97144. r -= lpc[j] * autoc[i-j];
  97145. ref[i] = (r/=err);
  97146. /* Update LPC coefficients and total error. */
  97147. lpc[i]=r;
  97148. for(j = 0; j < (i>>1); j++) {
  97149. FLAC__double tmp = lpc[j];
  97150. lpc[j] += r * lpc[i-1-j];
  97151. lpc[i-1-j] += r * tmp;
  97152. }
  97153. if(i & 1)
  97154. lpc[j] += lpc[j] * r;
  97155. err *= (1.0 - r * r);
  97156. /* save this order */
  97157. for(j = 0; j <= i; j++)
  97158. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97159. error[i] = err;
  97160. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97161. if(err == 0.0) {
  97162. *max_order = i+1;
  97163. return;
  97164. }
  97165. }
  97166. }
  97167. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97168. {
  97169. unsigned i;
  97170. FLAC__double cmax;
  97171. FLAC__int32 qmax, qmin;
  97172. FLAC__ASSERT(precision > 0);
  97173. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97174. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97175. precision--;
  97176. qmax = 1 << precision;
  97177. qmin = -qmax;
  97178. qmax--;
  97179. /* calc cmax = max( |lp_coeff[i]| ) */
  97180. cmax = 0.0;
  97181. for(i = 0; i < order; i++) {
  97182. const FLAC__double d = fabs(lp_coeff[i]);
  97183. if(d > cmax)
  97184. cmax = d;
  97185. }
  97186. if(cmax <= 0.0) {
  97187. /* => coefficients are all 0, which means our constant-detect didn't work */
  97188. return 2;
  97189. }
  97190. else {
  97191. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97192. const int min_shiftlimit = -max_shiftlimit - 1;
  97193. int log2cmax;
  97194. (void)frexp(cmax, &log2cmax);
  97195. log2cmax--;
  97196. *shift = (int)precision - log2cmax - 1;
  97197. if(*shift > max_shiftlimit)
  97198. *shift = max_shiftlimit;
  97199. else if(*shift < min_shiftlimit)
  97200. return 1;
  97201. }
  97202. if(*shift >= 0) {
  97203. FLAC__double error = 0.0;
  97204. FLAC__int32 q;
  97205. for(i = 0; i < order; i++) {
  97206. error += lp_coeff[i] * (1 << *shift);
  97207. #if 1 /* unfortunately lround() is C99 */
  97208. if(error >= 0.0)
  97209. q = (FLAC__int32)(error + 0.5);
  97210. else
  97211. q = (FLAC__int32)(error - 0.5);
  97212. #else
  97213. q = lround(error);
  97214. #endif
  97215. #ifdef FLAC__OVERFLOW_DETECT
  97216. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97217. 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]);
  97218. else if(q < qmin)
  97219. 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]);
  97220. #endif
  97221. if(q > qmax)
  97222. q = qmax;
  97223. else if(q < qmin)
  97224. q = qmin;
  97225. error -= q;
  97226. qlp_coeff[i] = q;
  97227. }
  97228. }
  97229. /* negative shift is very rare but due to design flaw, negative shift is
  97230. * a NOP in the decoder, so it must be handled specially by scaling down
  97231. * coeffs
  97232. */
  97233. else {
  97234. const int nshift = -(*shift);
  97235. FLAC__double error = 0.0;
  97236. FLAC__int32 q;
  97237. #ifdef DEBUG
  97238. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97239. #endif
  97240. for(i = 0; i < order; i++) {
  97241. error += lp_coeff[i] / (1 << nshift);
  97242. #if 1 /* unfortunately lround() is C99 */
  97243. if(error >= 0.0)
  97244. q = (FLAC__int32)(error + 0.5);
  97245. else
  97246. q = (FLAC__int32)(error - 0.5);
  97247. #else
  97248. q = lround(error);
  97249. #endif
  97250. #ifdef FLAC__OVERFLOW_DETECT
  97251. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97252. 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]);
  97253. else if(q < qmin)
  97254. 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]);
  97255. #endif
  97256. if(q > qmax)
  97257. q = qmax;
  97258. else if(q < qmin)
  97259. q = qmin;
  97260. error -= q;
  97261. qlp_coeff[i] = q;
  97262. }
  97263. *shift = 0;
  97264. }
  97265. return 0;
  97266. }
  97267. 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[])
  97268. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97269. {
  97270. FLAC__int64 sumo;
  97271. unsigned i, j;
  97272. FLAC__int32 sum;
  97273. const FLAC__int32 *history;
  97274. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97275. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97276. for(i=0;i<order;i++)
  97277. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97278. fprintf(stderr,"\n");
  97279. #endif
  97280. FLAC__ASSERT(order > 0);
  97281. for(i = 0; i < data_len; i++) {
  97282. sumo = 0;
  97283. sum = 0;
  97284. history = data;
  97285. for(j = 0; j < order; j++) {
  97286. sum += qlp_coeff[j] * (*(--history));
  97287. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97288. #if defined _MSC_VER
  97289. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97290. 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);
  97291. #else
  97292. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97293. 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);
  97294. #endif
  97295. }
  97296. *(residual++) = *(data++) - (sum >> lp_quantization);
  97297. }
  97298. /* Here's a slower but clearer version:
  97299. for(i = 0; i < data_len; i++) {
  97300. sum = 0;
  97301. for(j = 0; j < order; j++)
  97302. sum += qlp_coeff[j] * data[i-j-1];
  97303. residual[i] = data[i] - (sum >> lp_quantization);
  97304. }
  97305. */
  97306. }
  97307. #else /* fully unrolled version for normal use */
  97308. {
  97309. int i;
  97310. FLAC__int32 sum;
  97311. FLAC__ASSERT(order > 0);
  97312. FLAC__ASSERT(order <= 32);
  97313. /*
  97314. * We do unique versions up to 12th order since that's the subset limit.
  97315. * Also they are roughly ordered to match frequency of occurrence to
  97316. * minimize branching.
  97317. */
  97318. if(order <= 12) {
  97319. if(order > 8) {
  97320. if(order > 10) {
  97321. if(order == 12) {
  97322. for(i = 0; i < (int)data_len; i++) {
  97323. sum = 0;
  97324. sum += qlp_coeff[11] * data[i-12];
  97325. sum += qlp_coeff[10] * data[i-11];
  97326. sum += qlp_coeff[9] * data[i-10];
  97327. sum += qlp_coeff[8] * data[i-9];
  97328. sum += qlp_coeff[7] * data[i-8];
  97329. sum += qlp_coeff[6] * data[i-7];
  97330. sum += qlp_coeff[5] * data[i-6];
  97331. sum += qlp_coeff[4] * data[i-5];
  97332. sum += qlp_coeff[3] * data[i-4];
  97333. sum += qlp_coeff[2] * data[i-3];
  97334. sum += qlp_coeff[1] * data[i-2];
  97335. sum += qlp_coeff[0] * data[i-1];
  97336. residual[i] = data[i] - (sum >> lp_quantization);
  97337. }
  97338. }
  97339. else { /* order == 11 */
  97340. for(i = 0; i < (int)data_len; i++) {
  97341. sum = 0;
  97342. sum += qlp_coeff[10] * data[i-11];
  97343. sum += qlp_coeff[9] * data[i-10];
  97344. sum += qlp_coeff[8] * data[i-9];
  97345. sum += qlp_coeff[7] * data[i-8];
  97346. sum += qlp_coeff[6] * data[i-7];
  97347. sum += qlp_coeff[5] * data[i-6];
  97348. sum += qlp_coeff[4] * data[i-5];
  97349. sum += qlp_coeff[3] * data[i-4];
  97350. sum += qlp_coeff[2] * data[i-3];
  97351. sum += qlp_coeff[1] * data[i-2];
  97352. sum += qlp_coeff[0] * data[i-1];
  97353. residual[i] = data[i] - (sum >> lp_quantization);
  97354. }
  97355. }
  97356. }
  97357. else {
  97358. if(order == 10) {
  97359. for(i = 0; i < (int)data_len; i++) {
  97360. sum = 0;
  97361. sum += qlp_coeff[9] * data[i-10];
  97362. sum += qlp_coeff[8] * data[i-9];
  97363. sum += qlp_coeff[7] * data[i-8];
  97364. sum += qlp_coeff[6] * data[i-7];
  97365. sum += qlp_coeff[5] * data[i-6];
  97366. sum += qlp_coeff[4] * data[i-5];
  97367. sum += qlp_coeff[3] * data[i-4];
  97368. sum += qlp_coeff[2] * data[i-3];
  97369. sum += qlp_coeff[1] * data[i-2];
  97370. sum += qlp_coeff[0] * data[i-1];
  97371. residual[i] = data[i] - (sum >> lp_quantization);
  97372. }
  97373. }
  97374. else { /* order == 9 */
  97375. for(i = 0; i < (int)data_len; i++) {
  97376. sum = 0;
  97377. sum += qlp_coeff[8] * data[i-9];
  97378. sum += qlp_coeff[7] * data[i-8];
  97379. sum += qlp_coeff[6] * data[i-7];
  97380. sum += qlp_coeff[5] * data[i-6];
  97381. sum += qlp_coeff[4] * data[i-5];
  97382. sum += qlp_coeff[3] * data[i-4];
  97383. sum += qlp_coeff[2] * data[i-3];
  97384. sum += qlp_coeff[1] * data[i-2];
  97385. sum += qlp_coeff[0] * data[i-1];
  97386. residual[i] = data[i] - (sum >> lp_quantization);
  97387. }
  97388. }
  97389. }
  97390. }
  97391. else if(order > 4) {
  97392. if(order > 6) {
  97393. if(order == 8) {
  97394. for(i = 0; i < (int)data_len; i++) {
  97395. sum = 0;
  97396. sum += qlp_coeff[7] * data[i-8];
  97397. sum += qlp_coeff[6] * data[i-7];
  97398. sum += qlp_coeff[5] * data[i-6];
  97399. sum += qlp_coeff[4] * data[i-5];
  97400. sum += qlp_coeff[3] * data[i-4];
  97401. sum += qlp_coeff[2] * data[i-3];
  97402. sum += qlp_coeff[1] * data[i-2];
  97403. sum += qlp_coeff[0] * data[i-1];
  97404. residual[i] = data[i] - (sum >> lp_quantization);
  97405. }
  97406. }
  97407. else { /* order == 7 */
  97408. for(i = 0; i < (int)data_len; i++) {
  97409. sum = 0;
  97410. sum += qlp_coeff[6] * data[i-7];
  97411. sum += qlp_coeff[5] * data[i-6];
  97412. sum += qlp_coeff[4] * data[i-5];
  97413. sum += qlp_coeff[3] * data[i-4];
  97414. sum += qlp_coeff[2] * data[i-3];
  97415. sum += qlp_coeff[1] * data[i-2];
  97416. sum += qlp_coeff[0] * data[i-1];
  97417. residual[i] = data[i] - (sum >> lp_quantization);
  97418. }
  97419. }
  97420. }
  97421. else {
  97422. if(order == 6) {
  97423. for(i = 0; i < (int)data_len; i++) {
  97424. sum = 0;
  97425. sum += qlp_coeff[5] * data[i-6];
  97426. sum += qlp_coeff[4] * data[i-5];
  97427. sum += qlp_coeff[3] * data[i-4];
  97428. sum += qlp_coeff[2] * data[i-3];
  97429. sum += qlp_coeff[1] * data[i-2];
  97430. sum += qlp_coeff[0] * data[i-1];
  97431. residual[i] = data[i] - (sum >> lp_quantization);
  97432. }
  97433. }
  97434. else { /* order == 5 */
  97435. for(i = 0; i < (int)data_len; i++) {
  97436. sum = 0;
  97437. sum += qlp_coeff[4] * data[i-5];
  97438. sum += qlp_coeff[3] * data[i-4];
  97439. sum += qlp_coeff[2] * data[i-3];
  97440. sum += qlp_coeff[1] * data[i-2];
  97441. sum += qlp_coeff[0] * data[i-1];
  97442. residual[i] = data[i] - (sum >> lp_quantization);
  97443. }
  97444. }
  97445. }
  97446. }
  97447. else {
  97448. if(order > 2) {
  97449. if(order == 4) {
  97450. for(i = 0; i < (int)data_len; i++) {
  97451. sum = 0;
  97452. sum += qlp_coeff[3] * data[i-4];
  97453. sum += qlp_coeff[2] * data[i-3];
  97454. sum += qlp_coeff[1] * data[i-2];
  97455. sum += qlp_coeff[0] * data[i-1];
  97456. residual[i] = data[i] - (sum >> lp_quantization);
  97457. }
  97458. }
  97459. else { /* order == 3 */
  97460. for(i = 0; i < (int)data_len; i++) {
  97461. sum = 0;
  97462. sum += qlp_coeff[2] * data[i-3];
  97463. sum += qlp_coeff[1] * data[i-2];
  97464. sum += qlp_coeff[0] * data[i-1];
  97465. residual[i] = data[i] - (sum >> lp_quantization);
  97466. }
  97467. }
  97468. }
  97469. else {
  97470. if(order == 2) {
  97471. for(i = 0; i < (int)data_len; i++) {
  97472. sum = 0;
  97473. sum += qlp_coeff[1] * data[i-2];
  97474. sum += qlp_coeff[0] * data[i-1];
  97475. residual[i] = data[i] - (sum >> lp_quantization);
  97476. }
  97477. }
  97478. else { /* order == 1 */
  97479. for(i = 0; i < (int)data_len; i++)
  97480. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97481. }
  97482. }
  97483. }
  97484. }
  97485. else { /* order > 12 */
  97486. for(i = 0; i < (int)data_len; i++) {
  97487. sum = 0;
  97488. switch(order) {
  97489. case 32: sum += qlp_coeff[31] * data[i-32];
  97490. case 31: sum += qlp_coeff[30] * data[i-31];
  97491. case 30: sum += qlp_coeff[29] * data[i-30];
  97492. case 29: sum += qlp_coeff[28] * data[i-29];
  97493. case 28: sum += qlp_coeff[27] * data[i-28];
  97494. case 27: sum += qlp_coeff[26] * data[i-27];
  97495. case 26: sum += qlp_coeff[25] * data[i-26];
  97496. case 25: sum += qlp_coeff[24] * data[i-25];
  97497. case 24: sum += qlp_coeff[23] * data[i-24];
  97498. case 23: sum += qlp_coeff[22] * data[i-23];
  97499. case 22: sum += qlp_coeff[21] * data[i-22];
  97500. case 21: sum += qlp_coeff[20] * data[i-21];
  97501. case 20: sum += qlp_coeff[19] * data[i-20];
  97502. case 19: sum += qlp_coeff[18] * data[i-19];
  97503. case 18: sum += qlp_coeff[17] * data[i-18];
  97504. case 17: sum += qlp_coeff[16] * data[i-17];
  97505. case 16: sum += qlp_coeff[15] * data[i-16];
  97506. case 15: sum += qlp_coeff[14] * data[i-15];
  97507. case 14: sum += qlp_coeff[13] * data[i-14];
  97508. case 13: sum += qlp_coeff[12] * data[i-13];
  97509. sum += qlp_coeff[11] * data[i-12];
  97510. sum += qlp_coeff[10] * data[i-11];
  97511. sum += qlp_coeff[ 9] * data[i-10];
  97512. sum += qlp_coeff[ 8] * data[i- 9];
  97513. sum += qlp_coeff[ 7] * data[i- 8];
  97514. sum += qlp_coeff[ 6] * data[i- 7];
  97515. sum += qlp_coeff[ 5] * data[i- 6];
  97516. sum += qlp_coeff[ 4] * data[i- 5];
  97517. sum += qlp_coeff[ 3] * data[i- 4];
  97518. sum += qlp_coeff[ 2] * data[i- 3];
  97519. sum += qlp_coeff[ 1] * data[i- 2];
  97520. sum += qlp_coeff[ 0] * data[i- 1];
  97521. }
  97522. residual[i] = data[i] - (sum >> lp_quantization);
  97523. }
  97524. }
  97525. }
  97526. #endif
  97527. 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[])
  97528. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97529. {
  97530. unsigned i, j;
  97531. FLAC__int64 sum;
  97532. const FLAC__int32 *history;
  97533. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97534. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97535. for(i=0;i<order;i++)
  97536. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97537. fprintf(stderr,"\n");
  97538. #endif
  97539. FLAC__ASSERT(order > 0);
  97540. for(i = 0; i < data_len; i++) {
  97541. sum = 0;
  97542. history = data;
  97543. for(j = 0; j < order; j++)
  97544. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97545. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97546. #if defined _MSC_VER
  97547. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97548. #else
  97549. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97550. #endif
  97551. break;
  97552. }
  97553. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97554. #if defined _MSC_VER
  97555. 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));
  97556. #else
  97557. 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)));
  97558. #endif
  97559. break;
  97560. }
  97561. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97562. }
  97563. }
  97564. #else /* fully unrolled version for normal use */
  97565. {
  97566. int i;
  97567. FLAC__int64 sum;
  97568. FLAC__ASSERT(order > 0);
  97569. FLAC__ASSERT(order <= 32);
  97570. /*
  97571. * We do unique versions up to 12th order since that's the subset limit.
  97572. * Also they are roughly ordered to match frequency of occurrence to
  97573. * minimize branching.
  97574. */
  97575. if(order <= 12) {
  97576. if(order > 8) {
  97577. if(order > 10) {
  97578. if(order == 12) {
  97579. for(i = 0; i < (int)data_len; i++) {
  97580. sum = 0;
  97581. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97582. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97583. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97584. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97585. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97586. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97587. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97588. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97589. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97590. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97591. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97592. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97593. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97594. }
  97595. }
  97596. else { /* order == 11 */
  97597. for(i = 0; i < (int)data_len; i++) {
  97598. sum = 0;
  97599. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97600. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97601. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97602. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97603. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97604. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97605. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97606. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97607. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97608. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97609. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97610. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97611. }
  97612. }
  97613. }
  97614. else {
  97615. if(order == 10) {
  97616. for(i = 0; i < (int)data_len; i++) {
  97617. sum = 0;
  97618. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97619. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97620. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97621. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97622. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97623. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97624. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97625. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97626. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97627. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97628. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97629. }
  97630. }
  97631. else { /* order == 9 */
  97632. for(i = 0; i < (int)data_len; i++) {
  97633. sum = 0;
  97634. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97635. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97636. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97637. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97638. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97639. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97640. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97641. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97642. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97643. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97644. }
  97645. }
  97646. }
  97647. }
  97648. else if(order > 4) {
  97649. if(order > 6) {
  97650. if(order == 8) {
  97651. for(i = 0; i < (int)data_len; i++) {
  97652. sum = 0;
  97653. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97654. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97655. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97656. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97657. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97658. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97659. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97660. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97661. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97662. }
  97663. }
  97664. else { /* order == 7 */
  97665. for(i = 0; i < (int)data_len; i++) {
  97666. sum = 0;
  97667. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97668. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97669. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97670. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97671. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97672. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97673. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97674. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97675. }
  97676. }
  97677. }
  97678. else {
  97679. if(order == 6) {
  97680. for(i = 0; i < (int)data_len; i++) {
  97681. sum = 0;
  97682. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97683. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97684. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97685. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97686. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97687. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97688. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97689. }
  97690. }
  97691. else { /* order == 5 */
  97692. for(i = 0; i < (int)data_len; i++) {
  97693. sum = 0;
  97694. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97695. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97696. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97697. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97698. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97699. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97700. }
  97701. }
  97702. }
  97703. }
  97704. else {
  97705. if(order > 2) {
  97706. if(order == 4) {
  97707. for(i = 0; i < (int)data_len; i++) {
  97708. sum = 0;
  97709. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97710. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97711. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97712. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97713. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97714. }
  97715. }
  97716. else { /* order == 3 */
  97717. for(i = 0; i < (int)data_len; i++) {
  97718. sum = 0;
  97719. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97720. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97721. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97722. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97723. }
  97724. }
  97725. }
  97726. else {
  97727. if(order == 2) {
  97728. for(i = 0; i < (int)data_len; i++) {
  97729. sum = 0;
  97730. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97731. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97732. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97733. }
  97734. }
  97735. else { /* order == 1 */
  97736. for(i = 0; i < (int)data_len; i++)
  97737. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97738. }
  97739. }
  97740. }
  97741. }
  97742. else { /* order > 12 */
  97743. for(i = 0; i < (int)data_len; i++) {
  97744. sum = 0;
  97745. switch(order) {
  97746. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97747. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97748. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97749. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97750. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97751. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97752. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97753. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97754. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97755. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97756. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97757. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97758. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97759. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97760. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97761. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97762. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97763. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97764. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97765. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97766. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97767. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97768. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97769. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97770. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97771. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97772. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97773. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97774. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97775. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97776. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97777. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97778. }
  97779. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97780. }
  97781. }
  97782. }
  97783. #endif
  97784. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97785. 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[])
  97786. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97787. {
  97788. FLAC__int64 sumo;
  97789. unsigned i, j;
  97790. FLAC__int32 sum;
  97791. const FLAC__int32 *r = residual, *history;
  97792. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97793. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97794. for(i=0;i<order;i++)
  97795. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97796. fprintf(stderr,"\n");
  97797. #endif
  97798. FLAC__ASSERT(order > 0);
  97799. for(i = 0; i < data_len; i++) {
  97800. sumo = 0;
  97801. sum = 0;
  97802. history = data;
  97803. for(j = 0; j < order; j++) {
  97804. sum += qlp_coeff[j] * (*(--history));
  97805. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97806. #if defined _MSC_VER
  97807. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97808. 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);
  97809. #else
  97810. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97811. 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);
  97812. #endif
  97813. }
  97814. *(data++) = *(r++) + (sum >> lp_quantization);
  97815. }
  97816. /* Here's a slower but clearer version:
  97817. for(i = 0; i < data_len; i++) {
  97818. sum = 0;
  97819. for(j = 0; j < order; j++)
  97820. sum += qlp_coeff[j] * data[i-j-1];
  97821. data[i] = residual[i] + (sum >> lp_quantization);
  97822. }
  97823. */
  97824. }
  97825. #else /* fully unrolled version for normal use */
  97826. {
  97827. int i;
  97828. FLAC__int32 sum;
  97829. FLAC__ASSERT(order > 0);
  97830. FLAC__ASSERT(order <= 32);
  97831. /*
  97832. * We do unique versions up to 12th order since that's the subset limit.
  97833. * Also they are roughly ordered to match frequency of occurrence to
  97834. * minimize branching.
  97835. */
  97836. if(order <= 12) {
  97837. if(order > 8) {
  97838. if(order > 10) {
  97839. if(order == 12) {
  97840. for(i = 0; i < (int)data_len; i++) {
  97841. sum = 0;
  97842. sum += qlp_coeff[11] * data[i-12];
  97843. sum += qlp_coeff[10] * data[i-11];
  97844. sum += qlp_coeff[9] * data[i-10];
  97845. sum += qlp_coeff[8] * data[i-9];
  97846. sum += qlp_coeff[7] * data[i-8];
  97847. sum += qlp_coeff[6] * data[i-7];
  97848. sum += qlp_coeff[5] * data[i-6];
  97849. sum += qlp_coeff[4] * data[i-5];
  97850. sum += qlp_coeff[3] * data[i-4];
  97851. sum += qlp_coeff[2] * data[i-3];
  97852. sum += qlp_coeff[1] * data[i-2];
  97853. sum += qlp_coeff[0] * data[i-1];
  97854. data[i] = residual[i] + (sum >> lp_quantization);
  97855. }
  97856. }
  97857. else { /* order == 11 */
  97858. for(i = 0; i < (int)data_len; i++) {
  97859. sum = 0;
  97860. sum += qlp_coeff[10] * data[i-11];
  97861. sum += qlp_coeff[9] * data[i-10];
  97862. sum += qlp_coeff[8] * data[i-9];
  97863. sum += qlp_coeff[7] * data[i-8];
  97864. sum += qlp_coeff[6] * data[i-7];
  97865. sum += qlp_coeff[5] * data[i-6];
  97866. sum += qlp_coeff[4] * data[i-5];
  97867. sum += qlp_coeff[3] * data[i-4];
  97868. sum += qlp_coeff[2] * data[i-3];
  97869. sum += qlp_coeff[1] * data[i-2];
  97870. sum += qlp_coeff[0] * data[i-1];
  97871. data[i] = residual[i] + (sum >> lp_quantization);
  97872. }
  97873. }
  97874. }
  97875. else {
  97876. if(order == 10) {
  97877. for(i = 0; i < (int)data_len; i++) {
  97878. sum = 0;
  97879. sum += qlp_coeff[9] * data[i-10];
  97880. sum += qlp_coeff[8] * data[i-9];
  97881. sum += qlp_coeff[7] * data[i-8];
  97882. sum += qlp_coeff[6] * data[i-7];
  97883. sum += qlp_coeff[5] * data[i-6];
  97884. sum += qlp_coeff[4] * data[i-5];
  97885. sum += qlp_coeff[3] * data[i-4];
  97886. sum += qlp_coeff[2] * data[i-3];
  97887. sum += qlp_coeff[1] * data[i-2];
  97888. sum += qlp_coeff[0] * data[i-1];
  97889. data[i] = residual[i] + (sum >> lp_quantization);
  97890. }
  97891. }
  97892. else { /* order == 9 */
  97893. for(i = 0; i < (int)data_len; i++) {
  97894. sum = 0;
  97895. sum += qlp_coeff[8] * data[i-9];
  97896. sum += qlp_coeff[7] * data[i-8];
  97897. sum += qlp_coeff[6] * data[i-7];
  97898. sum += qlp_coeff[5] * data[i-6];
  97899. sum += qlp_coeff[4] * data[i-5];
  97900. sum += qlp_coeff[3] * data[i-4];
  97901. sum += qlp_coeff[2] * data[i-3];
  97902. sum += qlp_coeff[1] * data[i-2];
  97903. sum += qlp_coeff[0] * data[i-1];
  97904. data[i] = residual[i] + (sum >> lp_quantization);
  97905. }
  97906. }
  97907. }
  97908. }
  97909. else if(order > 4) {
  97910. if(order > 6) {
  97911. if(order == 8) {
  97912. for(i = 0; i < (int)data_len; i++) {
  97913. sum = 0;
  97914. sum += qlp_coeff[7] * data[i-8];
  97915. sum += qlp_coeff[6] * data[i-7];
  97916. sum += qlp_coeff[5] * data[i-6];
  97917. sum += qlp_coeff[4] * data[i-5];
  97918. sum += qlp_coeff[3] * data[i-4];
  97919. sum += qlp_coeff[2] * data[i-3];
  97920. sum += qlp_coeff[1] * data[i-2];
  97921. sum += qlp_coeff[0] * data[i-1];
  97922. data[i] = residual[i] + (sum >> lp_quantization);
  97923. }
  97924. }
  97925. else { /* order == 7 */
  97926. for(i = 0; i < (int)data_len; i++) {
  97927. sum = 0;
  97928. sum += qlp_coeff[6] * data[i-7];
  97929. sum += qlp_coeff[5] * data[i-6];
  97930. sum += qlp_coeff[4] * data[i-5];
  97931. sum += qlp_coeff[3] * data[i-4];
  97932. sum += qlp_coeff[2] * data[i-3];
  97933. sum += qlp_coeff[1] * data[i-2];
  97934. sum += qlp_coeff[0] * data[i-1];
  97935. data[i] = residual[i] + (sum >> lp_quantization);
  97936. }
  97937. }
  97938. }
  97939. else {
  97940. if(order == 6) {
  97941. for(i = 0; i < (int)data_len; i++) {
  97942. sum = 0;
  97943. sum += qlp_coeff[5] * data[i-6];
  97944. sum += qlp_coeff[4] * data[i-5];
  97945. sum += qlp_coeff[3] * data[i-4];
  97946. sum += qlp_coeff[2] * data[i-3];
  97947. sum += qlp_coeff[1] * data[i-2];
  97948. sum += qlp_coeff[0] * data[i-1];
  97949. data[i] = residual[i] + (sum >> lp_quantization);
  97950. }
  97951. }
  97952. else { /* order == 5 */
  97953. for(i = 0; i < (int)data_len; i++) {
  97954. sum = 0;
  97955. sum += qlp_coeff[4] * data[i-5];
  97956. sum += qlp_coeff[3] * data[i-4];
  97957. sum += qlp_coeff[2] * data[i-3];
  97958. sum += qlp_coeff[1] * data[i-2];
  97959. sum += qlp_coeff[0] * data[i-1];
  97960. data[i] = residual[i] + (sum >> lp_quantization);
  97961. }
  97962. }
  97963. }
  97964. }
  97965. else {
  97966. if(order > 2) {
  97967. if(order == 4) {
  97968. for(i = 0; i < (int)data_len; i++) {
  97969. sum = 0;
  97970. sum += qlp_coeff[3] * data[i-4];
  97971. sum += qlp_coeff[2] * data[i-3];
  97972. sum += qlp_coeff[1] * data[i-2];
  97973. sum += qlp_coeff[0] * data[i-1];
  97974. data[i] = residual[i] + (sum >> lp_quantization);
  97975. }
  97976. }
  97977. else { /* order == 3 */
  97978. for(i = 0; i < (int)data_len; i++) {
  97979. sum = 0;
  97980. sum += qlp_coeff[2] * data[i-3];
  97981. sum += qlp_coeff[1] * data[i-2];
  97982. sum += qlp_coeff[0] * data[i-1];
  97983. data[i] = residual[i] + (sum >> lp_quantization);
  97984. }
  97985. }
  97986. }
  97987. else {
  97988. if(order == 2) {
  97989. for(i = 0; i < (int)data_len; i++) {
  97990. sum = 0;
  97991. sum += qlp_coeff[1] * data[i-2];
  97992. sum += qlp_coeff[0] * data[i-1];
  97993. data[i] = residual[i] + (sum >> lp_quantization);
  97994. }
  97995. }
  97996. else { /* order == 1 */
  97997. for(i = 0; i < (int)data_len; i++)
  97998. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97999. }
  98000. }
  98001. }
  98002. }
  98003. else { /* order > 12 */
  98004. for(i = 0; i < (int)data_len; i++) {
  98005. sum = 0;
  98006. switch(order) {
  98007. case 32: sum += qlp_coeff[31] * data[i-32];
  98008. case 31: sum += qlp_coeff[30] * data[i-31];
  98009. case 30: sum += qlp_coeff[29] * data[i-30];
  98010. case 29: sum += qlp_coeff[28] * data[i-29];
  98011. case 28: sum += qlp_coeff[27] * data[i-28];
  98012. case 27: sum += qlp_coeff[26] * data[i-27];
  98013. case 26: sum += qlp_coeff[25] * data[i-26];
  98014. case 25: sum += qlp_coeff[24] * data[i-25];
  98015. case 24: sum += qlp_coeff[23] * data[i-24];
  98016. case 23: sum += qlp_coeff[22] * data[i-23];
  98017. case 22: sum += qlp_coeff[21] * data[i-22];
  98018. case 21: sum += qlp_coeff[20] * data[i-21];
  98019. case 20: sum += qlp_coeff[19] * data[i-20];
  98020. case 19: sum += qlp_coeff[18] * data[i-19];
  98021. case 18: sum += qlp_coeff[17] * data[i-18];
  98022. case 17: sum += qlp_coeff[16] * data[i-17];
  98023. case 16: sum += qlp_coeff[15] * data[i-16];
  98024. case 15: sum += qlp_coeff[14] * data[i-15];
  98025. case 14: sum += qlp_coeff[13] * data[i-14];
  98026. case 13: sum += qlp_coeff[12] * data[i-13];
  98027. sum += qlp_coeff[11] * data[i-12];
  98028. sum += qlp_coeff[10] * data[i-11];
  98029. sum += qlp_coeff[ 9] * data[i-10];
  98030. sum += qlp_coeff[ 8] * data[i- 9];
  98031. sum += qlp_coeff[ 7] * data[i- 8];
  98032. sum += qlp_coeff[ 6] * data[i- 7];
  98033. sum += qlp_coeff[ 5] * data[i- 6];
  98034. sum += qlp_coeff[ 4] * data[i- 5];
  98035. sum += qlp_coeff[ 3] * data[i- 4];
  98036. sum += qlp_coeff[ 2] * data[i- 3];
  98037. sum += qlp_coeff[ 1] * data[i- 2];
  98038. sum += qlp_coeff[ 0] * data[i- 1];
  98039. }
  98040. data[i] = residual[i] + (sum >> lp_quantization);
  98041. }
  98042. }
  98043. }
  98044. #endif
  98045. 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[])
  98046. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98047. {
  98048. unsigned i, j;
  98049. FLAC__int64 sum;
  98050. const FLAC__int32 *r = residual, *history;
  98051. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98052. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98053. for(i=0;i<order;i++)
  98054. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98055. fprintf(stderr,"\n");
  98056. #endif
  98057. FLAC__ASSERT(order > 0);
  98058. for(i = 0; i < data_len; i++) {
  98059. sum = 0;
  98060. history = data;
  98061. for(j = 0; j < order; j++)
  98062. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98063. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98064. #ifdef _MSC_VER
  98065. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98066. #else
  98067. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98068. #endif
  98069. break;
  98070. }
  98071. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98072. #ifdef _MSC_VER
  98073. 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));
  98074. #else
  98075. 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)));
  98076. #endif
  98077. break;
  98078. }
  98079. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98080. }
  98081. }
  98082. #else /* fully unrolled version for normal use */
  98083. {
  98084. int i;
  98085. FLAC__int64 sum;
  98086. FLAC__ASSERT(order > 0);
  98087. FLAC__ASSERT(order <= 32);
  98088. /*
  98089. * We do unique versions up to 12th order since that's the subset limit.
  98090. * Also they are roughly ordered to match frequency of occurrence to
  98091. * minimize branching.
  98092. */
  98093. if(order <= 12) {
  98094. if(order > 8) {
  98095. if(order > 10) {
  98096. if(order == 12) {
  98097. for(i = 0; i < (int)data_len; i++) {
  98098. sum = 0;
  98099. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98100. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98101. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98102. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98103. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98104. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98105. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98106. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98107. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98108. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98109. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98110. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98111. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98112. }
  98113. }
  98114. else { /* order == 11 */
  98115. for(i = 0; i < (int)data_len; i++) {
  98116. sum = 0;
  98117. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98118. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98119. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98120. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98121. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98122. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98123. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98124. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98125. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98126. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98127. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98128. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98129. }
  98130. }
  98131. }
  98132. else {
  98133. if(order == 10) {
  98134. for(i = 0; i < (int)data_len; i++) {
  98135. sum = 0;
  98136. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98137. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98138. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98139. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98140. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98141. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98142. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98143. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98144. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98145. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98146. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98147. }
  98148. }
  98149. else { /* order == 9 */
  98150. for(i = 0; i < (int)data_len; i++) {
  98151. sum = 0;
  98152. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98153. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98154. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98155. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98156. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98157. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98158. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98159. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98160. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98161. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98162. }
  98163. }
  98164. }
  98165. }
  98166. else if(order > 4) {
  98167. if(order > 6) {
  98168. if(order == 8) {
  98169. for(i = 0; i < (int)data_len; i++) {
  98170. sum = 0;
  98171. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98172. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98173. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98174. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98175. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98176. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98177. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98178. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98179. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98180. }
  98181. }
  98182. else { /* order == 7 */
  98183. for(i = 0; i < (int)data_len; i++) {
  98184. sum = 0;
  98185. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98186. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98187. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98188. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98189. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98190. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98191. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98192. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98193. }
  98194. }
  98195. }
  98196. else {
  98197. if(order == 6) {
  98198. for(i = 0; i < (int)data_len; i++) {
  98199. sum = 0;
  98200. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98201. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98202. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98203. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98204. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98205. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98206. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98207. }
  98208. }
  98209. else { /* order == 5 */
  98210. for(i = 0; i < (int)data_len; i++) {
  98211. sum = 0;
  98212. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98213. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98214. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98215. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98216. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98217. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98218. }
  98219. }
  98220. }
  98221. }
  98222. else {
  98223. if(order > 2) {
  98224. if(order == 4) {
  98225. for(i = 0; i < (int)data_len; i++) {
  98226. sum = 0;
  98227. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98228. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98229. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98230. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98231. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98232. }
  98233. }
  98234. else { /* order == 3 */
  98235. for(i = 0; i < (int)data_len; i++) {
  98236. sum = 0;
  98237. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98238. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98239. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98240. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98241. }
  98242. }
  98243. }
  98244. else {
  98245. if(order == 2) {
  98246. for(i = 0; i < (int)data_len; i++) {
  98247. sum = 0;
  98248. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98249. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98250. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98251. }
  98252. }
  98253. else { /* order == 1 */
  98254. for(i = 0; i < (int)data_len; i++)
  98255. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98256. }
  98257. }
  98258. }
  98259. }
  98260. else { /* order > 12 */
  98261. for(i = 0; i < (int)data_len; i++) {
  98262. sum = 0;
  98263. switch(order) {
  98264. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98265. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98266. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98267. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98268. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98269. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98270. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98271. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98272. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98273. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98274. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98275. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98276. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98277. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98278. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98279. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98280. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98281. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98282. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98283. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98284. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98285. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98286. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98287. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98288. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98289. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98290. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98291. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98292. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98293. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98294. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98295. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98296. }
  98297. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98298. }
  98299. }
  98300. }
  98301. #endif
  98302. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98303. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98304. {
  98305. FLAC__double error_scale;
  98306. FLAC__ASSERT(total_samples > 0);
  98307. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98308. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98309. }
  98310. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98311. {
  98312. if(lpc_error > 0.0) {
  98313. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98314. if(bps >= 0.0)
  98315. return bps;
  98316. else
  98317. return 0.0;
  98318. }
  98319. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98320. return 1e32;
  98321. }
  98322. else {
  98323. return 0.0;
  98324. }
  98325. }
  98326. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98327. {
  98328. 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 */
  98329. FLAC__double bits, best_bits, error_scale;
  98330. FLAC__ASSERT(max_order > 0);
  98331. FLAC__ASSERT(total_samples > 0);
  98332. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98333. best_index = 0;
  98334. best_bits = (unsigned)(-1);
  98335. for(index = 0, order = 1; index < max_order; index++, order++) {
  98336. 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);
  98337. if(bits < best_bits) {
  98338. best_index = index;
  98339. best_bits = bits;
  98340. }
  98341. }
  98342. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98343. }
  98344. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98345. #endif
  98346. /*** End of inlined file: lpc_flac.c ***/
  98347. /*** Start of inlined file: md5.c ***/
  98348. /*** Start of inlined file: juce_FlacHeader.h ***/
  98349. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98350. // tasks..
  98351. #define VERSION "1.2.1"
  98352. #define FLAC__NO_DLL 1
  98353. #if JUCE_MSVC
  98354. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98355. #endif
  98356. #if JUCE_MAC
  98357. #define FLAC__SYS_DARWIN 1
  98358. #endif
  98359. /*** End of inlined file: juce_FlacHeader.h ***/
  98360. #if JUCE_USE_FLAC
  98361. #if HAVE_CONFIG_H
  98362. # include <config.h>
  98363. #endif
  98364. #include <stdlib.h> /* for malloc() */
  98365. #include <string.h> /* for memcpy() */
  98366. /*** Start of inlined file: md5.h ***/
  98367. #ifndef FLAC__PRIVATE__MD5_H
  98368. #define FLAC__PRIVATE__MD5_H
  98369. /*
  98370. * This is the header file for the MD5 message-digest algorithm.
  98371. * The algorithm is due to Ron Rivest. This code was
  98372. * written by Colin Plumb in 1993, no copyright is claimed.
  98373. * This code is in the public domain; do with it what you wish.
  98374. *
  98375. * Equivalent code is available from RSA Data Security, Inc.
  98376. * This code has been tested against that, and is equivalent,
  98377. * except that you don't need to include two pages of legalese
  98378. * with every copy.
  98379. *
  98380. * To compute the message digest of a chunk of bytes, declare an
  98381. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98382. * needed on buffers full of bytes, and then call MD5Final, which
  98383. * will fill a supplied 16-byte array with the digest.
  98384. *
  98385. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98386. * header definitions; now uses stuff from dpkg's config.h
  98387. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98388. * Still in the public domain.
  98389. *
  98390. * Josh Coalson: made some changes to integrate with libFLAC.
  98391. * Still in the public domain, with no warranty.
  98392. */
  98393. typedef struct {
  98394. FLAC__uint32 in[16];
  98395. FLAC__uint32 buf[4];
  98396. FLAC__uint32 bytes[2];
  98397. FLAC__byte *internal_buf;
  98398. size_t capacity;
  98399. } FLAC__MD5Context;
  98400. void FLAC__MD5Init(FLAC__MD5Context *context);
  98401. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98402. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98403. #endif
  98404. /*** End of inlined file: md5.h ***/
  98405. #ifndef FLaC__INLINE
  98406. #define FLaC__INLINE
  98407. #endif
  98408. /*
  98409. * This code implements the MD5 message-digest algorithm.
  98410. * The algorithm is due to Ron Rivest. This code was
  98411. * written by Colin Plumb in 1993, no copyright is claimed.
  98412. * This code is in the public domain; do with it what you wish.
  98413. *
  98414. * Equivalent code is available from RSA Data Security, Inc.
  98415. * This code has been tested against that, and is equivalent,
  98416. * except that you don't need to include two pages of legalese
  98417. * with every copy.
  98418. *
  98419. * To compute the message digest of a chunk of bytes, declare an
  98420. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98421. * needed on buffers full of bytes, and then call MD5Final, which
  98422. * will fill a supplied 16-byte array with the digest.
  98423. *
  98424. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98425. * definitions; now uses stuff from dpkg's config.h.
  98426. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98427. * Still in the public domain.
  98428. *
  98429. * Josh Coalson: made some changes to integrate with libFLAC.
  98430. * Still in the public domain.
  98431. */
  98432. /* The four core functions - F1 is optimized somewhat */
  98433. /* #define F1(x, y, z) (x & y | ~x & z) */
  98434. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98435. #define F2(x, y, z) F1(z, x, y)
  98436. #define F3(x, y, z) (x ^ y ^ z)
  98437. #define F4(x, y, z) (y ^ (x | ~z))
  98438. /* This is the central step in the MD5 algorithm. */
  98439. #define MD5STEP(f,w,x,y,z,in,s) \
  98440. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98441. /*
  98442. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98443. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98444. * the data and converts bytes into longwords for this routine.
  98445. */
  98446. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98447. {
  98448. register FLAC__uint32 a, b, c, d;
  98449. a = buf[0];
  98450. b = buf[1];
  98451. c = buf[2];
  98452. d = buf[3];
  98453. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98454. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98455. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98456. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98457. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98458. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98459. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98460. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98461. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98462. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98463. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98464. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98465. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98466. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98467. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98468. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98469. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98470. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98471. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98472. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98473. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98474. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98475. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98476. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98477. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98478. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98479. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98480. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98481. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98482. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98483. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98484. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98485. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98486. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98487. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98488. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98489. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98490. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98491. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98492. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98493. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98494. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98495. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98496. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98497. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98498. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98499. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98500. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98501. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98502. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98503. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98504. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98505. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98506. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98507. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98508. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98509. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98510. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98511. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98512. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98513. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98514. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98515. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98516. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98517. buf[0] += a;
  98518. buf[1] += b;
  98519. buf[2] += c;
  98520. buf[3] += d;
  98521. }
  98522. #if WORDS_BIGENDIAN
  98523. //@@@@@@ OPT: use bswap/intrinsics
  98524. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98525. {
  98526. register FLAC__uint32 x;
  98527. do {
  98528. x = *buf;
  98529. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98530. *buf++ = (x >> 16) | (x << 16);
  98531. } while (--words);
  98532. }
  98533. static void byteSwapX16(FLAC__uint32 *buf)
  98534. {
  98535. register FLAC__uint32 x;
  98536. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98537. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98538. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98539. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98540. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98541. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98542. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98543. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98544. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98545. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98546. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98547. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98548. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98549. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98550. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98551. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98552. }
  98553. #else
  98554. #define byteSwap(buf, words)
  98555. #define byteSwapX16(buf)
  98556. #endif
  98557. /*
  98558. * Update context to reflect the concatenation of another buffer full
  98559. * of bytes.
  98560. */
  98561. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98562. {
  98563. FLAC__uint32 t;
  98564. /* Update byte count */
  98565. t = ctx->bytes[0];
  98566. if ((ctx->bytes[0] = t + len) < t)
  98567. ctx->bytes[1]++; /* Carry from low to high */
  98568. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98569. if (t > len) {
  98570. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98571. return;
  98572. }
  98573. /* First chunk is an odd size */
  98574. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98575. byteSwapX16(ctx->in);
  98576. FLAC__MD5Transform(ctx->buf, ctx->in);
  98577. buf += t;
  98578. len -= t;
  98579. /* Process data in 64-byte chunks */
  98580. while (len >= 64) {
  98581. memcpy(ctx->in, buf, 64);
  98582. byteSwapX16(ctx->in);
  98583. FLAC__MD5Transform(ctx->buf, ctx->in);
  98584. buf += 64;
  98585. len -= 64;
  98586. }
  98587. /* Handle any remaining bytes of data. */
  98588. memcpy(ctx->in, buf, len);
  98589. }
  98590. /*
  98591. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98592. * initialization constants.
  98593. */
  98594. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98595. {
  98596. ctx->buf[0] = 0x67452301;
  98597. ctx->buf[1] = 0xefcdab89;
  98598. ctx->buf[2] = 0x98badcfe;
  98599. ctx->buf[3] = 0x10325476;
  98600. ctx->bytes[0] = 0;
  98601. ctx->bytes[1] = 0;
  98602. ctx->internal_buf = 0;
  98603. ctx->capacity = 0;
  98604. }
  98605. /*
  98606. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98607. * 1 0* (64-bit count of bits processed, MSB-first)
  98608. */
  98609. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98610. {
  98611. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98612. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98613. /* Set the first char of padding to 0x80. There is always room. */
  98614. *p++ = 0x80;
  98615. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98616. count = 56 - 1 - count;
  98617. if (count < 0) { /* Padding forces an extra block */
  98618. memset(p, 0, count + 8);
  98619. byteSwapX16(ctx->in);
  98620. FLAC__MD5Transform(ctx->buf, ctx->in);
  98621. p = (FLAC__byte *)ctx->in;
  98622. count = 56;
  98623. }
  98624. memset(p, 0, count);
  98625. byteSwap(ctx->in, 14);
  98626. /* Append length in bits and transform */
  98627. ctx->in[14] = ctx->bytes[0] << 3;
  98628. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98629. FLAC__MD5Transform(ctx->buf, ctx->in);
  98630. byteSwap(ctx->buf, 4);
  98631. memcpy(digest, ctx->buf, 16);
  98632. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98633. if(0 != ctx->internal_buf) {
  98634. free(ctx->internal_buf);
  98635. ctx->internal_buf = 0;
  98636. ctx->capacity = 0;
  98637. }
  98638. }
  98639. /*
  98640. * Convert the incoming audio signal to a byte stream
  98641. */
  98642. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98643. {
  98644. unsigned channel, sample;
  98645. register FLAC__int32 a_word;
  98646. register FLAC__byte *buf_ = buf;
  98647. #if WORDS_BIGENDIAN
  98648. #else
  98649. if(channels == 2 && bytes_per_sample == 2) {
  98650. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98651. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98652. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98653. *buf1_ = (FLAC__int16)signal[1][sample];
  98654. }
  98655. else if(channels == 1 && bytes_per_sample == 2) {
  98656. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98657. for(sample = 0; sample < samples; sample++)
  98658. *buf1_++ = (FLAC__int16)signal[0][sample];
  98659. }
  98660. else
  98661. #endif
  98662. if(bytes_per_sample == 2) {
  98663. if(channels == 2) {
  98664. for(sample = 0; sample < samples; sample++) {
  98665. a_word = signal[0][sample];
  98666. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98667. *buf_++ = (FLAC__byte)a_word;
  98668. a_word = signal[1][sample];
  98669. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98670. *buf_++ = (FLAC__byte)a_word;
  98671. }
  98672. }
  98673. else if(channels == 1) {
  98674. for(sample = 0; sample < samples; sample++) {
  98675. a_word = signal[0][sample];
  98676. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98677. *buf_++ = (FLAC__byte)a_word;
  98678. }
  98679. }
  98680. else {
  98681. for(sample = 0; sample < samples; sample++) {
  98682. for(channel = 0; channel < channels; channel++) {
  98683. a_word = signal[channel][sample];
  98684. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98685. *buf_++ = (FLAC__byte)a_word;
  98686. }
  98687. }
  98688. }
  98689. }
  98690. else if(bytes_per_sample == 3) {
  98691. if(channels == 2) {
  98692. for(sample = 0; sample < samples; sample++) {
  98693. a_word = signal[0][sample];
  98694. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98695. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98696. *buf_++ = (FLAC__byte)a_word;
  98697. a_word = signal[1][sample];
  98698. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98699. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98700. *buf_++ = (FLAC__byte)a_word;
  98701. }
  98702. }
  98703. else if(channels == 1) {
  98704. for(sample = 0; sample < samples; sample++) {
  98705. a_word = signal[0][sample];
  98706. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98707. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98708. *buf_++ = (FLAC__byte)a_word;
  98709. }
  98710. }
  98711. else {
  98712. for(sample = 0; sample < samples; sample++) {
  98713. for(channel = 0; channel < channels; channel++) {
  98714. a_word = signal[channel][sample];
  98715. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98716. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98717. *buf_++ = (FLAC__byte)a_word;
  98718. }
  98719. }
  98720. }
  98721. }
  98722. else if(bytes_per_sample == 1) {
  98723. if(channels == 2) {
  98724. for(sample = 0; sample < samples; sample++) {
  98725. a_word = signal[0][sample];
  98726. *buf_++ = (FLAC__byte)a_word;
  98727. a_word = signal[1][sample];
  98728. *buf_++ = (FLAC__byte)a_word;
  98729. }
  98730. }
  98731. else if(channels == 1) {
  98732. for(sample = 0; sample < samples; sample++) {
  98733. a_word = signal[0][sample];
  98734. *buf_++ = (FLAC__byte)a_word;
  98735. }
  98736. }
  98737. else {
  98738. for(sample = 0; sample < samples; sample++) {
  98739. for(channel = 0; channel < channels; channel++) {
  98740. a_word = signal[channel][sample];
  98741. *buf_++ = (FLAC__byte)a_word;
  98742. }
  98743. }
  98744. }
  98745. }
  98746. else { /* bytes_per_sample == 4, maybe optimize more later */
  98747. for(sample = 0; sample < samples; sample++) {
  98748. for(channel = 0; channel < channels; channel++) {
  98749. a_word = signal[channel][sample];
  98750. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98751. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98752. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98753. *buf_++ = (FLAC__byte)a_word;
  98754. }
  98755. }
  98756. }
  98757. }
  98758. /*
  98759. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98760. */
  98761. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98762. {
  98763. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98764. /* overflow check */
  98765. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98766. return false;
  98767. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98768. return false;
  98769. if(ctx->capacity < bytes_needed) {
  98770. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98771. if(0 == tmp) {
  98772. free(ctx->internal_buf);
  98773. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98774. return false;
  98775. }
  98776. ctx->internal_buf = tmp;
  98777. ctx->capacity = bytes_needed;
  98778. }
  98779. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98780. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98781. return true;
  98782. }
  98783. #endif
  98784. /*** End of inlined file: md5.c ***/
  98785. /*** Start of inlined file: memory.c ***/
  98786. /*** Start of inlined file: juce_FlacHeader.h ***/
  98787. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98788. // tasks..
  98789. #define VERSION "1.2.1"
  98790. #define FLAC__NO_DLL 1
  98791. #if JUCE_MSVC
  98792. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98793. #endif
  98794. #if JUCE_MAC
  98795. #define FLAC__SYS_DARWIN 1
  98796. #endif
  98797. /*** End of inlined file: juce_FlacHeader.h ***/
  98798. #if JUCE_USE_FLAC
  98799. #if HAVE_CONFIG_H
  98800. # include <config.h>
  98801. #endif
  98802. /*** Start of inlined file: memory.h ***/
  98803. #ifndef FLAC__PRIVATE__MEMORY_H
  98804. #define FLAC__PRIVATE__MEMORY_H
  98805. #ifdef HAVE_CONFIG_H
  98806. #include <config.h>
  98807. #endif
  98808. #include <stdlib.h> /* for size_t */
  98809. /* Returns the unaligned address returned by malloc.
  98810. * Use free() on this address to deallocate.
  98811. */
  98812. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98813. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98814. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98815. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98816. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98817. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98818. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98819. #endif
  98820. #endif
  98821. /*** End of inlined file: memory.h ***/
  98822. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98823. {
  98824. void *x;
  98825. FLAC__ASSERT(0 != aligned_address);
  98826. #ifdef FLAC__ALIGN_MALLOC_DATA
  98827. /* align on 32-byte (256-bit) boundary */
  98828. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98829. #ifdef SIZEOF_VOIDP
  98830. #if SIZEOF_VOIDP == 4
  98831. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98832. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98833. #elif SIZEOF_VOIDP == 8
  98834. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98835. #else
  98836. # error Unsupported sizeof(void*)
  98837. #endif
  98838. #else
  98839. /* there's got to be a better way to do this right for all archs */
  98840. if(sizeof(void*) == sizeof(unsigned))
  98841. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98842. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98843. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98844. else
  98845. return 0;
  98846. #endif
  98847. #else
  98848. x = safe_malloc_(bytes);
  98849. *aligned_address = x;
  98850. #endif
  98851. return x;
  98852. }
  98853. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98854. {
  98855. FLAC__int32 *pu; /* unaligned pointer */
  98856. union { /* union needed to comply with C99 pointer aliasing rules */
  98857. FLAC__int32 *pa; /* aligned pointer */
  98858. void *pv; /* aligned pointer alias */
  98859. } u;
  98860. FLAC__ASSERT(elements > 0);
  98861. FLAC__ASSERT(0 != unaligned_pointer);
  98862. FLAC__ASSERT(0 != aligned_pointer);
  98863. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98864. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98865. if(0 == pu) {
  98866. return false;
  98867. }
  98868. else {
  98869. if(*unaligned_pointer != 0)
  98870. free(*unaligned_pointer);
  98871. *unaligned_pointer = pu;
  98872. *aligned_pointer = u.pa;
  98873. return true;
  98874. }
  98875. }
  98876. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98877. {
  98878. FLAC__uint32 *pu; /* unaligned pointer */
  98879. union { /* union needed to comply with C99 pointer aliasing rules */
  98880. FLAC__uint32 *pa; /* aligned pointer */
  98881. void *pv; /* aligned pointer alias */
  98882. } u;
  98883. FLAC__ASSERT(elements > 0);
  98884. FLAC__ASSERT(0 != unaligned_pointer);
  98885. FLAC__ASSERT(0 != aligned_pointer);
  98886. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98887. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98888. if(0 == pu) {
  98889. return false;
  98890. }
  98891. else {
  98892. if(*unaligned_pointer != 0)
  98893. free(*unaligned_pointer);
  98894. *unaligned_pointer = pu;
  98895. *aligned_pointer = u.pa;
  98896. return true;
  98897. }
  98898. }
  98899. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98900. {
  98901. FLAC__uint64 *pu; /* unaligned pointer */
  98902. union { /* union needed to comply with C99 pointer aliasing rules */
  98903. FLAC__uint64 *pa; /* aligned pointer */
  98904. void *pv; /* aligned pointer alias */
  98905. } u;
  98906. FLAC__ASSERT(elements > 0);
  98907. FLAC__ASSERT(0 != unaligned_pointer);
  98908. FLAC__ASSERT(0 != aligned_pointer);
  98909. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98910. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98911. if(0 == pu) {
  98912. return false;
  98913. }
  98914. else {
  98915. if(*unaligned_pointer != 0)
  98916. free(*unaligned_pointer);
  98917. *unaligned_pointer = pu;
  98918. *aligned_pointer = u.pa;
  98919. return true;
  98920. }
  98921. }
  98922. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98923. {
  98924. unsigned *pu; /* unaligned pointer */
  98925. union { /* union needed to comply with C99 pointer aliasing rules */
  98926. unsigned *pa; /* aligned pointer */
  98927. void *pv; /* aligned pointer alias */
  98928. } u;
  98929. FLAC__ASSERT(elements > 0);
  98930. FLAC__ASSERT(0 != unaligned_pointer);
  98931. FLAC__ASSERT(0 != aligned_pointer);
  98932. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98933. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98934. if(0 == pu) {
  98935. return false;
  98936. }
  98937. else {
  98938. if(*unaligned_pointer != 0)
  98939. free(*unaligned_pointer);
  98940. *unaligned_pointer = pu;
  98941. *aligned_pointer = u.pa;
  98942. return true;
  98943. }
  98944. }
  98945. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98946. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98947. {
  98948. FLAC__real *pu; /* unaligned pointer */
  98949. union { /* union needed to comply with C99 pointer aliasing rules */
  98950. FLAC__real *pa; /* aligned pointer */
  98951. void *pv; /* aligned pointer alias */
  98952. } u;
  98953. FLAC__ASSERT(elements > 0);
  98954. FLAC__ASSERT(0 != unaligned_pointer);
  98955. FLAC__ASSERT(0 != aligned_pointer);
  98956. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98957. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98958. if(0 == pu) {
  98959. return false;
  98960. }
  98961. else {
  98962. if(*unaligned_pointer != 0)
  98963. free(*unaligned_pointer);
  98964. *unaligned_pointer = pu;
  98965. *aligned_pointer = u.pa;
  98966. return true;
  98967. }
  98968. }
  98969. #endif
  98970. #endif
  98971. /*** End of inlined file: memory.c ***/
  98972. /*** Start of inlined file: stream_decoder.c ***/
  98973. /*** Start of inlined file: juce_FlacHeader.h ***/
  98974. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98975. // tasks..
  98976. #define VERSION "1.2.1"
  98977. #define FLAC__NO_DLL 1
  98978. #if JUCE_MSVC
  98979. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98980. #endif
  98981. #if JUCE_MAC
  98982. #define FLAC__SYS_DARWIN 1
  98983. #endif
  98984. /*** End of inlined file: juce_FlacHeader.h ***/
  98985. #if JUCE_USE_FLAC
  98986. #if HAVE_CONFIG_H
  98987. # include <config.h>
  98988. #endif
  98989. #if defined _MSC_VER || defined __MINGW32__
  98990. #include <io.h> /* for _setmode() */
  98991. #include <fcntl.h> /* for _O_BINARY */
  98992. #endif
  98993. #if defined __CYGWIN__ || defined __EMX__
  98994. #include <io.h> /* for setmode(), O_BINARY */
  98995. #include <fcntl.h> /* for _O_BINARY */
  98996. #endif
  98997. #include <stdio.h>
  98998. #include <stdlib.h> /* for malloc() */
  98999. #include <string.h> /* for memset/memcpy() */
  99000. #include <sys/stat.h> /* for stat() */
  99001. #include <sys/types.h> /* for off_t */
  99002. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99003. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99004. #define fseeko fseek
  99005. #define ftello ftell
  99006. #endif
  99007. #endif
  99008. /*** Start of inlined file: stream_decoder.h ***/
  99009. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99010. #define FLAC__PROTECTED__STREAM_DECODER_H
  99011. #if FLAC__HAS_OGG
  99012. #include "include/private/ogg_decoder_aspect.h"
  99013. #endif
  99014. typedef struct FLAC__StreamDecoderProtected {
  99015. FLAC__StreamDecoderState state;
  99016. unsigned channels;
  99017. FLAC__ChannelAssignment channel_assignment;
  99018. unsigned bits_per_sample;
  99019. unsigned sample_rate; /* in Hz */
  99020. unsigned blocksize; /* in samples (per channel) */
  99021. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99022. #if FLAC__HAS_OGG
  99023. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99024. #endif
  99025. } FLAC__StreamDecoderProtected;
  99026. /*
  99027. * return the number of input bytes consumed
  99028. */
  99029. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99030. #endif
  99031. /*** End of inlined file: stream_decoder.h ***/
  99032. #ifdef max
  99033. #undef max
  99034. #endif
  99035. #define max(a,b) ((a)>(b)?(a):(b))
  99036. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99037. #ifdef _MSC_VER
  99038. #define FLAC__U64L(x) x
  99039. #else
  99040. #define FLAC__U64L(x) x##LLU
  99041. #endif
  99042. /* technically this should be in an "export.c" but this is convenient enough */
  99043. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99044. #if FLAC__HAS_OGG
  99045. 1
  99046. #else
  99047. 0
  99048. #endif
  99049. ;
  99050. /***********************************************************************
  99051. *
  99052. * Private static data
  99053. *
  99054. ***********************************************************************/
  99055. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99056. /***********************************************************************
  99057. *
  99058. * Private class method prototypes
  99059. *
  99060. ***********************************************************************/
  99061. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99062. static FILE *get_binary_stdin_(void);
  99063. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99064. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99065. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99066. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99067. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99068. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99069. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99070. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99071. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99072. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99073. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99074. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99075. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99076. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99077. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99078. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99079. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99080. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99081. 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);
  99082. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99083. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99084. #if FLAC__HAS_OGG
  99085. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99086. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99087. #endif
  99088. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99089. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99090. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99091. #if FLAC__HAS_OGG
  99092. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99093. #endif
  99094. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99095. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99096. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99097. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99098. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99099. /***********************************************************************
  99100. *
  99101. * Private class data
  99102. *
  99103. ***********************************************************************/
  99104. typedef struct FLAC__StreamDecoderPrivate {
  99105. #if FLAC__HAS_OGG
  99106. FLAC__bool is_ogg;
  99107. #endif
  99108. FLAC__StreamDecoderReadCallback read_callback;
  99109. FLAC__StreamDecoderSeekCallback seek_callback;
  99110. FLAC__StreamDecoderTellCallback tell_callback;
  99111. FLAC__StreamDecoderLengthCallback length_callback;
  99112. FLAC__StreamDecoderEofCallback eof_callback;
  99113. FLAC__StreamDecoderWriteCallback write_callback;
  99114. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99115. FLAC__StreamDecoderErrorCallback error_callback;
  99116. /* generic 32-bit datapath: */
  99117. 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[]);
  99118. /* generic 64-bit datapath: */
  99119. 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[]);
  99120. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99121. 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[]);
  99122. /* 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: */
  99123. 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[]);
  99124. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99125. void *client_data;
  99126. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99127. FLAC__BitReader *input;
  99128. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99129. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99130. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99131. unsigned output_capacity, output_channels;
  99132. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99133. FLAC__uint64 samples_decoded;
  99134. FLAC__bool has_stream_info, has_seek_table;
  99135. FLAC__StreamMetadata stream_info;
  99136. FLAC__StreamMetadata seek_table;
  99137. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99138. FLAC__byte *metadata_filter_ids;
  99139. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99140. FLAC__Frame frame;
  99141. FLAC__bool cached; /* true if there is a byte in lookahead */
  99142. FLAC__CPUInfo cpuinfo;
  99143. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99144. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99145. /* unaligned (original) pointers to allocated data */
  99146. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99147. 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 */
  99148. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99149. FLAC__bool is_seeking;
  99150. FLAC__MD5Context md5context;
  99151. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99152. /* (the rest of these are only used for seeking) */
  99153. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99154. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99155. FLAC__uint64 target_sample;
  99156. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99157. #if FLAC__HAS_OGG
  99158. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99159. #endif
  99160. } FLAC__StreamDecoderPrivate;
  99161. /***********************************************************************
  99162. *
  99163. * Public static class data
  99164. *
  99165. ***********************************************************************/
  99166. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99167. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99168. "FLAC__STREAM_DECODER_READ_METADATA",
  99169. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99170. "FLAC__STREAM_DECODER_READ_FRAME",
  99171. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99172. "FLAC__STREAM_DECODER_OGG_ERROR",
  99173. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99174. "FLAC__STREAM_DECODER_ABORTED",
  99175. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99176. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99177. };
  99178. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99179. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99180. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99181. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99182. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99183. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99184. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99185. };
  99186. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99187. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99188. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99189. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99190. };
  99191. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99192. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99193. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99194. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99195. };
  99196. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99197. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99198. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99199. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99200. };
  99201. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99202. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99203. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99204. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99205. };
  99206. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99207. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99208. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99209. };
  99210. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99211. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99212. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99213. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99214. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99215. };
  99216. /***********************************************************************
  99217. *
  99218. * Class constructor/destructor
  99219. *
  99220. ***********************************************************************/
  99221. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99222. {
  99223. FLAC__StreamDecoder *decoder;
  99224. unsigned i;
  99225. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99226. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99227. if(decoder == 0) {
  99228. return 0;
  99229. }
  99230. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99231. if(decoder->protected_ == 0) {
  99232. free(decoder);
  99233. return 0;
  99234. }
  99235. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99236. if(decoder->private_ == 0) {
  99237. free(decoder->protected_);
  99238. free(decoder);
  99239. return 0;
  99240. }
  99241. decoder->private_->input = FLAC__bitreader_new();
  99242. if(decoder->private_->input == 0) {
  99243. free(decoder->private_);
  99244. free(decoder->protected_);
  99245. free(decoder);
  99246. return 0;
  99247. }
  99248. decoder->private_->metadata_filter_ids_capacity = 16;
  99249. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99250. FLAC__bitreader_delete(decoder->private_->input);
  99251. free(decoder->private_);
  99252. free(decoder->protected_);
  99253. free(decoder);
  99254. return 0;
  99255. }
  99256. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99257. decoder->private_->output[i] = 0;
  99258. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99259. }
  99260. decoder->private_->output_capacity = 0;
  99261. decoder->private_->output_channels = 0;
  99262. decoder->private_->has_seek_table = false;
  99263. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99264. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99265. decoder->private_->file = 0;
  99266. set_defaults_dec(decoder);
  99267. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99268. return decoder;
  99269. }
  99270. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99271. {
  99272. unsigned i;
  99273. FLAC__ASSERT(0 != decoder);
  99274. FLAC__ASSERT(0 != decoder->protected_);
  99275. FLAC__ASSERT(0 != decoder->private_);
  99276. FLAC__ASSERT(0 != decoder->private_->input);
  99277. (void)FLAC__stream_decoder_finish(decoder);
  99278. if(0 != decoder->private_->metadata_filter_ids)
  99279. free(decoder->private_->metadata_filter_ids);
  99280. FLAC__bitreader_delete(decoder->private_->input);
  99281. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99282. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99283. free(decoder->private_);
  99284. free(decoder->protected_);
  99285. free(decoder);
  99286. }
  99287. /***********************************************************************
  99288. *
  99289. * Public class methods
  99290. *
  99291. ***********************************************************************/
  99292. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99293. FLAC__StreamDecoder *decoder,
  99294. FLAC__StreamDecoderReadCallback read_callback,
  99295. FLAC__StreamDecoderSeekCallback seek_callback,
  99296. FLAC__StreamDecoderTellCallback tell_callback,
  99297. FLAC__StreamDecoderLengthCallback length_callback,
  99298. FLAC__StreamDecoderEofCallback eof_callback,
  99299. FLAC__StreamDecoderWriteCallback write_callback,
  99300. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99301. FLAC__StreamDecoderErrorCallback error_callback,
  99302. void *client_data,
  99303. FLAC__bool is_ogg
  99304. )
  99305. {
  99306. FLAC__ASSERT(0 != decoder);
  99307. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99308. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99309. #if !FLAC__HAS_OGG
  99310. if(is_ogg)
  99311. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99312. #endif
  99313. if(
  99314. 0 == read_callback ||
  99315. 0 == write_callback ||
  99316. 0 == error_callback ||
  99317. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99318. )
  99319. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99320. #if FLAC__HAS_OGG
  99321. decoder->private_->is_ogg = is_ogg;
  99322. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99323. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99324. #endif
  99325. /*
  99326. * get the CPU info and set the function pointers
  99327. */
  99328. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99329. /* first default to the non-asm routines */
  99330. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99331. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99332. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99333. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99334. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99335. /* now override with asm where appropriate */
  99336. #ifndef FLAC__NO_ASM
  99337. if(decoder->private_->cpuinfo.use_asm) {
  99338. #ifdef FLAC__CPU_IA32
  99339. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99340. #ifdef FLAC__HAS_NASM
  99341. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99342. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99343. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99344. #endif
  99345. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99346. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99347. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99348. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99349. }
  99350. else {
  99351. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99352. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99353. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99354. }
  99355. #endif
  99356. #elif defined FLAC__CPU_PPC
  99357. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99358. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99359. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99360. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99361. }
  99362. #endif
  99363. }
  99364. #endif
  99365. /* from here on, errors are fatal */
  99366. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99367. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99368. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99369. }
  99370. decoder->private_->read_callback = read_callback;
  99371. decoder->private_->seek_callback = seek_callback;
  99372. decoder->private_->tell_callback = tell_callback;
  99373. decoder->private_->length_callback = length_callback;
  99374. decoder->private_->eof_callback = eof_callback;
  99375. decoder->private_->write_callback = write_callback;
  99376. decoder->private_->metadata_callback = metadata_callback;
  99377. decoder->private_->error_callback = error_callback;
  99378. decoder->private_->client_data = client_data;
  99379. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99380. decoder->private_->samples_decoded = 0;
  99381. decoder->private_->has_stream_info = false;
  99382. decoder->private_->cached = false;
  99383. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99384. decoder->private_->is_seeking = false;
  99385. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99386. if(!FLAC__stream_decoder_reset(decoder)) {
  99387. /* above call sets the state for us */
  99388. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99389. }
  99390. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99391. }
  99392. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99393. FLAC__StreamDecoder *decoder,
  99394. FLAC__StreamDecoderReadCallback read_callback,
  99395. FLAC__StreamDecoderSeekCallback seek_callback,
  99396. FLAC__StreamDecoderTellCallback tell_callback,
  99397. FLAC__StreamDecoderLengthCallback length_callback,
  99398. FLAC__StreamDecoderEofCallback eof_callback,
  99399. FLAC__StreamDecoderWriteCallback write_callback,
  99400. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99401. FLAC__StreamDecoderErrorCallback error_callback,
  99402. void *client_data
  99403. )
  99404. {
  99405. return init_stream_internal_dec(
  99406. decoder,
  99407. read_callback,
  99408. seek_callback,
  99409. tell_callback,
  99410. length_callback,
  99411. eof_callback,
  99412. write_callback,
  99413. metadata_callback,
  99414. error_callback,
  99415. client_data,
  99416. /*is_ogg=*/false
  99417. );
  99418. }
  99419. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99420. FLAC__StreamDecoder *decoder,
  99421. FLAC__StreamDecoderReadCallback read_callback,
  99422. FLAC__StreamDecoderSeekCallback seek_callback,
  99423. FLAC__StreamDecoderTellCallback tell_callback,
  99424. FLAC__StreamDecoderLengthCallback length_callback,
  99425. FLAC__StreamDecoderEofCallback eof_callback,
  99426. FLAC__StreamDecoderWriteCallback write_callback,
  99427. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99428. FLAC__StreamDecoderErrorCallback error_callback,
  99429. void *client_data
  99430. )
  99431. {
  99432. return init_stream_internal_dec(
  99433. decoder,
  99434. read_callback,
  99435. seek_callback,
  99436. tell_callback,
  99437. length_callback,
  99438. eof_callback,
  99439. write_callback,
  99440. metadata_callback,
  99441. error_callback,
  99442. client_data,
  99443. /*is_ogg=*/true
  99444. );
  99445. }
  99446. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99447. FLAC__StreamDecoder *decoder,
  99448. FILE *file,
  99449. FLAC__StreamDecoderWriteCallback write_callback,
  99450. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99451. FLAC__StreamDecoderErrorCallback error_callback,
  99452. void *client_data,
  99453. FLAC__bool is_ogg
  99454. )
  99455. {
  99456. FLAC__ASSERT(0 != decoder);
  99457. FLAC__ASSERT(0 != file);
  99458. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99459. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99460. if(0 == write_callback || 0 == error_callback)
  99461. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99462. /*
  99463. * To make sure that our file does not go unclosed after an error, we
  99464. * must assign the FILE pointer before any further error can occur in
  99465. * this routine.
  99466. */
  99467. if(file == stdin)
  99468. file = get_binary_stdin_(); /* just to be safe */
  99469. decoder->private_->file = file;
  99470. return init_stream_internal_dec(
  99471. decoder,
  99472. file_read_callback_dec,
  99473. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99474. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99475. decoder->private_->file == stdin? 0: file_length_callback_,
  99476. file_eof_callback_,
  99477. write_callback,
  99478. metadata_callback,
  99479. error_callback,
  99480. client_data,
  99481. is_ogg
  99482. );
  99483. }
  99484. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99485. FLAC__StreamDecoder *decoder,
  99486. FILE *file,
  99487. FLAC__StreamDecoderWriteCallback write_callback,
  99488. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99489. FLAC__StreamDecoderErrorCallback error_callback,
  99490. void *client_data
  99491. )
  99492. {
  99493. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99494. }
  99495. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99496. FLAC__StreamDecoder *decoder,
  99497. FILE *file,
  99498. FLAC__StreamDecoderWriteCallback write_callback,
  99499. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99500. FLAC__StreamDecoderErrorCallback error_callback,
  99501. void *client_data
  99502. )
  99503. {
  99504. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99505. }
  99506. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99507. FLAC__StreamDecoder *decoder,
  99508. const char *filename,
  99509. FLAC__StreamDecoderWriteCallback write_callback,
  99510. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99511. FLAC__StreamDecoderErrorCallback error_callback,
  99512. void *client_data,
  99513. FLAC__bool is_ogg
  99514. )
  99515. {
  99516. FILE *file;
  99517. FLAC__ASSERT(0 != decoder);
  99518. /*
  99519. * To make sure that our file does not go unclosed after an error, we
  99520. * have to do the same entrance checks here that are later performed
  99521. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99522. */
  99523. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99524. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99525. if(0 == write_callback || 0 == error_callback)
  99526. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99527. file = filename? fopen(filename, "rb") : stdin;
  99528. if(0 == file)
  99529. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99530. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99531. }
  99532. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99533. FLAC__StreamDecoder *decoder,
  99534. const char *filename,
  99535. FLAC__StreamDecoderWriteCallback write_callback,
  99536. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99537. FLAC__StreamDecoderErrorCallback error_callback,
  99538. void *client_data
  99539. )
  99540. {
  99541. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99542. }
  99543. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99544. FLAC__StreamDecoder *decoder,
  99545. const char *filename,
  99546. FLAC__StreamDecoderWriteCallback write_callback,
  99547. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99548. FLAC__StreamDecoderErrorCallback error_callback,
  99549. void *client_data
  99550. )
  99551. {
  99552. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99553. }
  99554. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99555. {
  99556. FLAC__bool md5_failed = false;
  99557. unsigned i;
  99558. FLAC__ASSERT(0 != decoder);
  99559. FLAC__ASSERT(0 != decoder->private_);
  99560. FLAC__ASSERT(0 != decoder->protected_);
  99561. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99562. return true;
  99563. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99564. * always call FLAC__MD5Final()
  99565. */
  99566. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99567. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99568. free(decoder->private_->seek_table.data.seek_table.points);
  99569. decoder->private_->seek_table.data.seek_table.points = 0;
  99570. decoder->private_->has_seek_table = false;
  99571. }
  99572. FLAC__bitreader_free(decoder->private_->input);
  99573. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99574. /* WATCHOUT:
  99575. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99576. * output arrays have a buffer of up to 3 zeroes in front
  99577. * (at negative indices) for alignment purposes; we use 4
  99578. * to keep the data well-aligned.
  99579. */
  99580. if(0 != decoder->private_->output[i]) {
  99581. free(decoder->private_->output[i]-4);
  99582. decoder->private_->output[i] = 0;
  99583. }
  99584. if(0 != decoder->private_->residual_unaligned[i]) {
  99585. free(decoder->private_->residual_unaligned[i]);
  99586. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99587. }
  99588. }
  99589. decoder->private_->output_capacity = 0;
  99590. decoder->private_->output_channels = 0;
  99591. #if FLAC__HAS_OGG
  99592. if(decoder->private_->is_ogg)
  99593. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99594. #endif
  99595. if(0 != decoder->private_->file) {
  99596. if(decoder->private_->file != stdin)
  99597. fclose(decoder->private_->file);
  99598. decoder->private_->file = 0;
  99599. }
  99600. if(decoder->private_->do_md5_checking) {
  99601. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99602. md5_failed = true;
  99603. }
  99604. decoder->private_->is_seeking = false;
  99605. set_defaults_dec(decoder);
  99606. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99607. return !md5_failed;
  99608. }
  99609. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99610. {
  99611. FLAC__ASSERT(0 != decoder);
  99612. FLAC__ASSERT(0 != decoder->private_);
  99613. FLAC__ASSERT(0 != decoder->protected_);
  99614. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99615. return false;
  99616. #if FLAC__HAS_OGG
  99617. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99618. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99619. return true;
  99620. #else
  99621. (void)value;
  99622. return false;
  99623. #endif
  99624. }
  99625. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99626. {
  99627. FLAC__ASSERT(0 != decoder);
  99628. FLAC__ASSERT(0 != decoder->protected_);
  99629. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99630. return false;
  99631. decoder->protected_->md5_checking = value;
  99632. return true;
  99633. }
  99634. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99635. {
  99636. FLAC__ASSERT(0 != decoder);
  99637. FLAC__ASSERT(0 != decoder->private_);
  99638. FLAC__ASSERT(0 != decoder->protected_);
  99639. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99640. /* double protection */
  99641. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99642. return false;
  99643. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99644. return false;
  99645. decoder->private_->metadata_filter[type] = true;
  99646. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99647. decoder->private_->metadata_filter_ids_count = 0;
  99648. return true;
  99649. }
  99650. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99651. {
  99652. FLAC__ASSERT(0 != decoder);
  99653. FLAC__ASSERT(0 != decoder->private_);
  99654. FLAC__ASSERT(0 != decoder->protected_);
  99655. FLAC__ASSERT(0 != id);
  99656. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99657. return false;
  99658. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99659. return true;
  99660. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99661. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99662. 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))) {
  99663. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99664. return false;
  99665. }
  99666. decoder->private_->metadata_filter_ids_capacity *= 2;
  99667. }
  99668. 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));
  99669. decoder->private_->metadata_filter_ids_count++;
  99670. return true;
  99671. }
  99672. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99673. {
  99674. unsigned i;
  99675. FLAC__ASSERT(0 != decoder);
  99676. FLAC__ASSERT(0 != decoder->private_);
  99677. FLAC__ASSERT(0 != decoder->protected_);
  99678. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99679. return false;
  99680. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99681. decoder->private_->metadata_filter[i] = true;
  99682. decoder->private_->metadata_filter_ids_count = 0;
  99683. return true;
  99684. }
  99685. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99686. {
  99687. FLAC__ASSERT(0 != decoder);
  99688. FLAC__ASSERT(0 != decoder->private_);
  99689. FLAC__ASSERT(0 != decoder->protected_);
  99690. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99691. /* double protection */
  99692. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99693. return false;
  99694. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99695. return false;
  99696. decoder->private_->metadata_filter[type] = false;
  99697. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99698. decoder->private_->metadata_filter_ids_count = 0;
  99699. return true;
  99700. }
  99701. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99702. {
  99703. FLAC__ASSERT(0 != decoder);
  99704. FLAC__ASSERT(0 != decoder->private_);
  99705. FLAC__ASSERT(0 != decoder->protected_);
  99706. FLAC__ASSERT(0 != id);
  99707. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99708. return false;
  99709. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99710. return true;
  99711. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99712. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99713. 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))) {
  99714. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99715. return false;
  99716. }
  99717. decoder->private_->metadata_filter_ids_capacity *= 2;
  99718. }
  99719. 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));
  99720. decoder->private_->metadata_filter_ids_count++;
  99721. return true;
  99722. }
  99723. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99724. {
  99725. FLAC__ASSERT(0 != decoder);
  99726. FLAC__ASSERT(0 != decoder->private_);
  99727. FLAC__ASSERT(0 != decoder->protected_);
  99728. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99729. return false;
  99730. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99731. decoder->private_->metadata_filter_ids_count = 0;
  99732. return true;
  99733. }
  99734. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99735. {
  99736. FLAC__ASSERT(0 != decoder);
  99737. FLAC__ASSERT(0 != decoder->protected_);
  99738. return decoder->protected_->state;
  99739. }
  99740. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99741. {
  99742. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99743. }
  99744. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99745. {
  99746. FLAC__ASSERT(0 != decoder);
  99747. FLAC__ASSERT(0 != decoder->protected_);
  99748. return decoder->protected_->md5_checking;
  99749. }
  99750. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99751. {
  99752. FLAC__ASSERT(0 != decoder);
  99753. FLAC__ASSERT(0 != decoder->protected_);
  99754. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99755. }
  99756. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99757. {
  99758. FLAC__ASSERT(0 != decoder);
  99759. FLAC__ASSERT(0 != decoder->protected_);
  99760. return decoder->protected_->channels;
  99761. }
  99762. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99763. {
  99764. FLAC__ASSERT(0 != decoder);
  99765. FLAC__ASSERT(0 != decoder->protected_);
  99766. return decoder->protected_->channel_assignment;
  99767. }
  99768. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99769. {
  99770. FLAC__ASSERT(0 != decoder);
  99771. FLAC__ASSERT(0 != decoder->protected_);
  99772. return decoder->protected_->bits_per_sample;
  99773. }
  99774. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99775. {
  99776. FLAC__ASSERT(0 != decoder);
  99777. FLAC__ASSERT(0 != decoder->protected_);
  99778. return decoder->protected_->sample_rate;
  99779. }
  99780. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99781. {
  99782. FLAC__ASSERT(0 != decoder);
  99783. FLAC__ASSERT(0 != decoder->protected_);
  99784. return decoder->protected_->blocksize;
  99785. }
  99786. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99787. {
  99788. FLAC__ASSERT(0 != decoder);
  99789. FLAC__ASSERT(0 != decoder->private_);
  99790. FLAC__ASSERT(0 != position);
  99791. #if FLAC__HAS_OGG
  99792. if(decoder->private_->is_ogg)
  99793. return false;
  99794. #endif
  99795. if(0 == decoder->private_->tell_callback)
  99796. return false;
  99797. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99798. return false;
  99799. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99800. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99801. return false;
  99802. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99803. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99804. return true;
  99805. }
  99806. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99807. {
  99808. FLAC__ASSERT(0 != decoder);
  99809. FLAC__ASSERT(0 != decoder->private_);
  99810. FLAC__ASSERT(0 != decoder->protected_);
  99811. decoder->private_->samples_decoded = 0;
  99812. decoder->private_->do_md5_checking = false;
  99813. #if FLAC__HAS_OGG
  99814. if(decoder->private_->is_ogg)
  99815. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99816. #endif
  99817. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99818. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99819. return false;
  99820. }
  99821. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99822. return true;
  99823. }
  99824. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99825. {
  99826. FLAC__ASSERT(0 != decoder);
  99827. FLAC__ASSERT(0 != decoder->private_);
  99828. FLAC__ASSERT(0 != decoder->protected_);
  99829. if(!FLAC__stream_decoder_flush(decoder)) {
  99830. /* above call sets the state for us */
  99831. return false;
  99832. }
  99833. #if FLAC__HAS_OGG
  99834. /*@@@ could go in !internal_reset_hack block below */
  99835. if(decoder->private_->is_ogg)
  99836. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99837. #endif
  99838. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99839. * (internal_reset_hack) don't try to rewind since we are already at
  99840. * the beginning of the stream and don't want to fail if the input is
  99841. * not seekable.
  99842. */
  99843. if(!decoder->private_->internal_reset_hack) {
  99844. if(decoder->private_->file == stdin)
  99845. return false; /* can't rewind stdin, reset fails */
  99846. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99847. return false; /* seekable and seek fails, reset fails */
  99848. }
  99849. else
  99850. decoder->private_->internal_reset_hack = false;
  99851. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99852. decoder->private_->has_stream_info = false;
  99853. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99854. free(decoder->private_->seek_table.data.seek_table.points);
  99855. decoder->private_->seek_table.data.seek_table.points = 0;
  99856. decoder->private_->has_seek_table = false;
  99857. }
  99858. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99859. /*
  99860. * This goes in reset() and not flush() because according to the spec, a
  99861. * fixed-blocksize stream must stay that way through the whole stream.
  99862. */
  99863. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99864. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99865. * is because md5 checking may be turned on to start and then turned off if
  99866. * a seek occurs. So we init the context here and finalize it in
  99867. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99868. * properly.
  99869. */
  99870. FLAC__MD5Init(&decoder->private_->md5context);
  99871. decoder->private_->first_frame_offset = 0;
  99872. decoder->private_->unparseable_frame_count = 0;
  99873. return true;
  99874. }
  99875. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99876. {
  99877. FLAC__bool got_a_frame;
  99878. FLAC__ASSERT(0 != decoder);
  99879. FLAC__ASSERT(0 != decoder->protected_);
  99880. while(1) {
  99881. switch(decoder->protected_->state) {
  99882. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99883. if(!find_metadata_(decoder))
  99884. return false; /* above function sets the status for us */
  99885. break;
  99886. case FLAC__STREAM_DECODER_READ_METADATA:
  99887. if(!read_metadata_(decoder))
  99888. return false; /* above function sets the status for us */
  99889. else
  99890. return true;
  99891. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99892. if(!frame_sync_(decoder))
  99893. return true; /* above function sets the status for us */
  99894. break;
  99895. case FLAC__STREAM_DECODER_READ_FRAME:
  99896. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99897. return false; /* above function sets the status for us */
  99898. if(got_a_frame)
  99899. return true; /* above function sets the status for us */
  99900. break;
  99901. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99902. case FLAC__STREAM_DECODER_ABORTED:
  99903. return true;
  99904. default:
  99905. FLAC__ASSERT(0);
  99906. return false;
  99907. }
  99908. }
  99909. }
  99910. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99911. {
  99912. FLAC__ASSERT(0 != decoder);
  99913. FLAC__ASSERT(0 != decoder->protected_);
  99914. while(1) {
  99915. switch(decoder->protected_->state) {
  99916. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99917. if(!find_metadata_(decoder))
  99918. return false; /* above function sets the status for us */
  99919. break;
  99920. case FLAC__STREAM_DECODER_READ_METADATA:
  99921. if(!read_metadata_(decoder))
  99922. return false; /* above function sets the status for us */
  99923. break;
  99924. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99925. case FLAC__STREAM_DECODER_READ_FRAME:
  99926. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99927. case FLAC__STREAM_DECODER_ABORTED:
  99928. return true;
  99929. default:
  99930. FLAC__ASSERT(0);
  99931. return false;
  99932. }
  99933. }
  99934. }
  99935. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99936. {
  99937. FLAC__bool dummy;
  99938. FLAC__ASSERT(0 != decoder);
  99939. FLAC__ASSERT(0 != decoder->protected_);
  99940. while(1) {
  99941. switch(decoder->protected_->state) {
  99942. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99943. if(!find_metadata_(decoder))
  99944. return false; /* above function sets the status for us */
  99945. break;
  99946. case FLAC__STREAM_DECODER_READ_METADATA:
  99947. if(!read_metadata_(decoder))
  99948. return false; /* above function sets the status for us */
  99949. break;
  99950. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99951. if(!frame_sync_(decoder))
  99952. return true; /* above function sets the status for us */
  99953. break;
  99954. case FLAC__STREAM_DECODER_READ_FRAME:
  99955. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99956. return false; /* above function sets the status for us */
  99957. break;
  99958. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99959. case FLAC__STREAM_DECODER_ABORTED:
  99960. return true;
  99961. default:
  99962. FLAC__ASSERT(0);
  99963. return false;
  99964. }
  99965. }
  99966. }
  99967. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99968. {
  99969. FLAC__bool got_a_frame;
  99970. FLAC__ASSERT(0 != decoder);
  99971. FLAC__ASSERT(0 != decoder->protected_);
  99972. while(1) {
  99973. switch(decoder->protected_->state) {
  99974. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99975. case FLAC__STREAM_DECODER_READ_METADATA:
  99976. return false; /* above function sets the status for us */
  99977. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99978. if(!frame_sync_(decoder))
  99979. return true; /* above function sets the status for us */
  99980. break;
  99981. case FLAC__STREAM_DECODER_READ_FRAME:
  99982. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99983. return false; /* above function sets the status for us */
  99984. if(got_a_frame)
  99985. return true; /* above function sets the status for us */
  99986. break;
  99987. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99988. case FLAC__STREAM_DECODER_ABORTED:
  99989. return true;
  99990. default:
  99991. FLAC__ASSERT(0);
  99992. return false;
  99993. }
  99994. }
  99995. }
  99996. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99997. {
  99998. FLAC__uint64 length;
  99999. FLAC__ASSERT(0 != decoder);
  100000. if(
  100001. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100002. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100003. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100004. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100005. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100006. )
  100007. return false;
  100008. if(0 == decoder->private_->seek_callback)
  100009. return false;
  100010. FLAC__ASSERT(decoder->private_->seek_callback);
  100011. FLAC__ASSERT(decoder->private_->tell_callback);
  100012. FLAC__ASSERT(decoder->private_->length_callback);
  100013. FLAC__ASSERT(decoder->private_->eof_callback);
  100014. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100015. return false;
  100016. decoder->private_->is_seeking = true;
  100017. /* turn off md5 checking if a seek is attempted */
  100018. decoder->private_->do_md5_checking = false;
  100019. /* 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) */
  100020. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100021. decoder->private_->is_seeking = false;
  100022. return false;
  100023. }
  100024. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100025. if(
  100026. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100027. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100028. ) {
  100029. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100030. /* above call sets the state for us */
  100031. decoder->private_->is_seeking = false;
  100032. return false;
  100033. }
  100034. /* check this again in case we didn't know total_samples the first time */
  100035. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100036. decoder->private_->is_seeking = false;
  100037. return false;
  100038. }
  100039. }
  100040. {
  100041. const FLAC__bool ok =
  100042. #if FLAC__HAS_OGG
  100043. decoder->private_->is_ogg?
  100044. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100045. #endif
  100046. seek_to_absolute_sample_(decoder, length, sample)
  100047. ;
  100048. decoder->private_->is_seeking = false;
  100049. return ok;
  100050. }
  100051. }
  100052. /***********************************************************************
  100053. *
  100054. * Protected class methods
  100055. *
  100056. ***********************************************************************/
  100057. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100058. {
  100059. FLAC__ASSERT(0 != decoder);
  100060. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100061. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100062. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100063. }
  100064. /***********************************************************************
  100065. *
  100066. * Private class methods
  100067. *
  100068. ***********************************************************************/
  100069. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100070. {
  100071. #if FLAC__HAS_OGG
  100072. decoder->private_->is_ogg = false;
  100073. #endif
  100074. decoder->private_->read_callback = 0;
  100075. decoder->private_->seek_callback = 0;
  100076. decoder->private_->tell_callback = 0;
  100077. decoder->private_->length_callback = 0;
  100078. decoder->private_->eof_callback = 0;
  100079. decoder->private_->write_callback = 0;
  100080. decoder->private_->metadata_callback = 0;
  100081. decoder->private_->error_callback = 0;
  100082. decoder->private_->client_data = 0;
  100083. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100084. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100085. decoder->private_->metadata_filter_ids_count = 0;
  100086. decoder->protected_->md5_checking = false;
  100087. #if FLAC__HAS_OGG
  100088. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100089. #endif
  100090. }
  100091. /*
  100092. * This will forcibly set stdin to binary mode (for OSes that require it)
  100093. */
  100094. FILE *get_binary_stdin_(void)
  100095. {
  100096. /* if something breaks here it is probably due to the presence or
  100097. * absence of an underscore before the identifiers 'setmode',
  100098. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100099. */
  100100. #if defined _MSC_VER || defined __MINGW32__
  100101. _setmode(_fileno(stdin), _O_BINARY);
  100102. #elif defined __CYGWIN__
  100103. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100104. setmode(_fileno(stdin), _O_BINARY);
  100105. #elif defined __EMX__
  100106. setmode(fileno(stdin), O_BINARY);
  100107. #endif
  100108. return stdin;
  100109. }
  100110. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100111. {
  100112. unsigned i;
  100113. FLAC__int32 *tmp;
  100114. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100115. return true;
  100116. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100117. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100118. if(0 != decoder->private_->output[i]) {
  100119. free(decoder->private_->output[i]-4);
  100120. decoder->private_->output[i] = 0;
  100121. }
  100122. if(0 != decoder->private_->residual_unaligned[i]) {
  100123. free(decoder->private_->residual_unaligned[i]);
  100124. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100125. }
  100126. }
  100127. for(i = 0; i < channels; i++) {
  100128. /* WATCHOUT:
  100129. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100130. * output arrays have a buffer of up to 3 zeroes in front
  100131. * (at negative indices) for alignment purposes; we use 4
  100132. * to keep the data well-aligned.
  100133. */
  100134. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100135. if(tmp == 0) {
  100136. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100137. return false;
  100138. }
  100139. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100140. decoder->private_->output[i] = tmp + 4;
  100141. /* WATCHOUT:
  100142. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100143. */
  100144. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100145. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100146. return false;
  100147. }
  100148. }
  100149. decoder->private_->output_capacity = size;
  100150. decoder->private_->output_channels = channels;
  100151. return true;
  100152. }
  100153. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100154. {
  100155. size_t i;
  100156. FLAC__ASSERT(0 != decoder);
  100157. FLAC__ASSERT(0 != decoder->private_);
  100158. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100159. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100160. return true;
  100161. return false;
  100162. }
  100163. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100164. {
  100165. FLAC__uint32 x;
  100166. unsigned i, id_;
  100167. FLAC__bool first = true;
  100168. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100169. for(i = id_ = 0; i < 4; ) {
  100170. if(decoder->private_->cached) {
  100171. x = (FLAC__uint32)decoder->private_->lookahead;
  100172. decoder->private_->cached = false;
  100173. }
  100174. else {
  100175. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100176. return false; /* read_callback_ sets the state for us */
  100177. }
  100178. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100179. first = true;
  100180. i++;
  100181. id_ = 0;
  100182. continue;
  100183. }
  100184. if(x == ID3V2_TAG_[id_]) {
  100185. id_++;
  100186. i = 0;
  100187. if(id_ == 3) {
  100188. if(!skip_id3v2_tag_(decoder))
  100189. return false; /* skip_id3v2_tag_ sets the state for us */
  100190. }
  100191. continue;
  100192. }
  100193. id_ = 0;
  100194. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100195. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100196. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100197. return false; /* read_callback_ sets the state for us */
  100198. /* 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 */
  100199. /* else we have to check if the second byte is the end of a sync code */
  100200. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100201. decoder->private_->lookahead = (FLAC__byte)x;
  100202. decoder->private_->cached = true;
  100203. }
  100204. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100205. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100206. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100207. return true;
  100208. }
  100209. }
  100210. i = 0;
  100211. if(first) {
  100212. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100213. first = false;
  100214. }
  100215. }
  100216. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100217. return true;
  100218. }
  100219. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100220. {
  100221. FLAC__bool is_last;
  100222. FLAC__uint32 i, x, type, length;
  100223. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100224. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100225. return false; /* read_callback_ sets the state for us */
  100226. is_last = x? true : false;
  100227. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100228. return false; /* read_callback_ sets the state for us */
  100229. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100230. return false; /* read_callback_ sets the state for us */
  100231. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100232. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100233. return false;
  100234. decoder->private_->has_stream_info = true;
  100235. 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))
  100236. decoder->private_->do_md5_checking = false;
  100237. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100238. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100239. }
  100240. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100241. if(!read_metadata_seektable_(decoder, is_last, length))
  100242. return false;
  100243. decoder->private_->has_seek_table = true;
  100244. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100245. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100246. }
  100247. else {
  100248. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100249. unsigned real_length = length;
  100250. FLAC__StreamMetadata block;
  100251. block.is_last = is_last;
  100252. block.type = (FLAC__MetadataType)type;
  100253. block.length = length;
  100254. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100255. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100256. return false; /* read_callback_ sets the state for us */
  100257. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100258. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100259. return false;
  100260. }
  100261. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100262. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100263. skip_it = !skip_it;
  100264. }
  100265. if(skip_it) {
  100266. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100267. return false; /* read_callback_ sets the state for us */
  100268. }
  100269. else {
  100270. switch(type) {
  100271. case FLAC__METADATA_TYPE_PADDING:
  100272. /* skip the padding bytes */
  100273. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100274. return false; /* read_callback_ sets the state for us */
  100275. break;
  100276. case FLAC__METADATA_TYPE_APPLICATION:
  100277. /* remember, we read the ID already */
  100278. if(real_length > 0) {
  100279. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100280. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100281. return false;
  100282. }
  100283. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100284. return false; /* read_callback_ sets the state for us */
  100285. }
  100286. else
  100287. block.data.application.data = 0;
  100288. break;
  100289. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100290. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100291. return false;
  100292. break;
  100293. case FLAC__METADATA_TYPE_CUESHEET:
  100294. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100295. return false;
  100296. break;
  100297. case FLAC__METADATA_TYPE_PICTURE:
  100298. if(!read_metadata_picture_(decoder, &block.data.picture))
  100299. return false;
  100300. break;
  100301. case FLAC__METADATA_TYPE_STREAMINFO:
  100302. case FLAC__METADATA_TYPE_SEEKTABLE:
  100303. FLAC__ASSERT(0);
  100304. break;
  100305. default:
  100306. if(real_length > 0) {
  100307. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100308. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100309. return false;
  100310. }
  100311. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100312. return false; /* read_callback_ sets the state for us */
  100313. }
  100314. else
  100315. block.data.unknown.data = 0;
  100316. break;
  100317. }
  100318. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100319. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100320. /* now we have to free any malloc()ed data in the block */
  100321. switch(type) {
  100322. case FLAC__METADATA_TYPE_PADDING:
  100323. break;
  100324. case FLAC__METADATA_TYPE_APPLICATION:
  100325. if(0 != block.data.application.data)
  100326. free(block.data.application.data);
  100327. break;
  100328. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100329. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100330. free(block.data.vorbis_comment.vendor_string.entry);
  100331. if(block.data.vorbis_comment.num_comments > 0)
  100332. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100333. if(0 != block.data.vorbis_comment.comments[i].entry)
  100334. free(block.data.vorbis_comment.comments[i].entry);
  100335. if(0 != block.data.vorbis_comment.comments)
  100336. free(block.data.vorbis_comment.comments);
  100337. break;
  100338. case FLAC__METADATA_TYPE_CUESHEET:
  100339. if(block.data.cue_sheet.num_tracks > 0)
  100340. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100341. if(0 != block.data.cue_sheet.tracks[i].indices)
  100342. free(block.data.cue_sheet.tracks[i].indices);
  100343. if(0 != block.data.cue_sheet.tracks)
  100344. free(block.data.cue_sheet.tracks);
  100345. break;
  100346. case FLAC__METADATA_TYPE_PICTURE:
  100347. if(0 != block.data.picture.mime_type)
  100348. free(block.data.picture.mime_type);
  100349. if(0 != block.data.picture.description)
  100350. free(block.data.picture.description);
  100351. if(0 != block.data.picture.data)
  100352. free(block.data.picture.data);
  100353. break;
  100354. case FLAC__METADATA_TYPE_STREAMINFO:
  100355. case FLAC__METADATA_TYPE_SEEKTABLE:
  100356. FLAC__ASSERT(0);
  100357. default:
  100358. if(0 != block.data.unknown.data)
  100359. free(block.data.unknown.data);
  100360. break;
  100361. }
  100362. }
  100363. }
  100364. if(is_last) {
  100365. /* if this fails, it's OK, it's just a hint for the seek routine */
  100366. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100367. decoder->private_->first_frame_offset = 0;
  100368. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100369. }
  100370. return true;
  100371. }
  100372. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100373. {
  100374. FLAC__uint32 x;
  100375. unsigned bits, used_bits = 0;
  100376. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100377. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100378. decoder->private_->stream_info.is_last = is_last;
  100379. decoder->private_->stream_info.length = length;
  100380. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100381. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100382. return false; /* read_callback_ sets the state for us */
  100383. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100384. used_bits += bits;
  100385. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100386. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100387. return false; /* read_callback_ sets the state for us */
  100388. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100389. used_bits += bits;
  100390. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100391. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100392. return false; /* read_callback_ sets the state for us */
  100393. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100394. used_bits += bits;
  100395. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100396. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100397. return false; /* read_callback_ sets the state for us */
  100398. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100399. used_bits += bits;
  100400. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100401. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100402. return false; /* read_callback_ sets the state for us */
  100403. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100404. used_bits += bits;
  100405. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100406. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100407. return false; /* read_callback_ sets the state for us */
  100408. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100409. used_bits += bits;
  100410. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100411. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100412. return false; /* read_callback_ sets the state for us */
  100413. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100414. used_bits += bits;
  100415. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100416. 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))
  100417. return false; /* read_callback_ sets the state for us */
  100418. used_bits += bits;
  100419. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100420. return false; /* read_callback_ sets the state for us */
  100421. used_bits += 16*8;
  100422. /* skip the rest of the block */
  100423. FLAC__ASSERT(used_bits % 8 == 0);
  100424. length -= (used_bits / 8);
  100425. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100426. return false; /* read_callback_ sets the state for us */
  100427. return true;
  100428. }
  100429. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100430. {
  100431. FLAC__uint32 i, x;
  100432. FLAC__uint64 xx;
  100433. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100434. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100435. decoder->private_->seek_table.is_last = is_last;
  100436. decoder->private_->seek_table.length = length;
  100437. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100438. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100439. 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)))) {
  100440. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100441. return false;
  100442. }
  100443. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100444. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100445. return false; /* read_callback_ sets the state for us */
  100446. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100447. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100448. return false; /* read_callback_ sets the state for us */
  100449. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100450. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100451. return false; /* read_callback_ sets the state for us */
  100452. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100453. }
  100454. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100455. /* if there is a partial point left, skip over it */
  100456. if(length > 0) {
  100457. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100458. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100459. return false; /* read_callback_ sets the state for us */
  100460. }
  100461. return true;
  100462. }
  100463. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100464. {
  100465. FLAC__uint32 i;
  100466. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100467. /* read vendor string */
  100468. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100469. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100470. return false; /* read_callback_ sets the state for us */
  100471. if(obj->vendor_string.length > 0) {
  100472. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100473. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100474. return false;
  100475. }
  100476. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100477. return false; /* read_callback_ sets the state for us */
  100478. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100479. }
  100480. else
  100481. obj->vendor_string.entry = 0;
  100482. /* read num comments */
  100483. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100484. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100485. return false; /* read_callback_ sets the state for us */
  100486. /* read comments */
  100487. if(obj->num_comments > 0) {
  100488. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100489. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100490. return false;
  100491. }
  100492. for(i = 0; i < obj->num_comments; i++) {
  100493. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100494. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100495. return false; /* read_callback_ sets the state for us */
  100496. if(obj->comments[i].length > 0) {
  100497. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100498. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100499. return false;
  100500. }
  100501. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100502. return false; /* read_callback_ sets the state for us */
  100503. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100504. }
  100505. else
  100506. obj->comments[i].entry = 0;
  100507. }
  100508. }
  100509. else {
  100510. obj->comments = 0;
  100511. }
  100512. return true;
  100513. }
  100514. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100515. {
  100516. FLAC__uint32 i, j, x;
  100517. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100518. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100519. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100520. 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))
  100521. return false; /* read_callback_ sets the state for us */
  100522. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100523. return false; /* read_callback_ sets the state for us */
  100524. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100525. return false; /* read_callback_ sets the state for us */
  100526. obj->is_cd = x? true : false;
  100527. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100528. return false; /* read_callback_ sets the state for us */
  100529. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100530. return false; /* read_callback_ sets the state for us */
  100531. obj->num_tracks = x;
  100532. if(obj->num_tracks > 0) {
  100533. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100534. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100535. return false;
  100536. }
  100537. for(i = 0; i < obj->num_tracks; i++) {
  100538. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100539. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100540. return false; /* read_callback_ sets the state for us */
  100541. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100542. return false; /* read_callback_ sets the state for us */
  100543. track->number = (FLAC__byte)x;
  100544. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100545. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100546. return false; /* read_callback_ sets the state for us */
  100547. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100548. return false; /* read_callback_ sets the state for us */
  100549. track->type = x;
  100550. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100551. return false; /* read_callback_ sets the state for us */
  100552. track->pre_emphasis = x;
  100553. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100554. return false; /* read_callback_ sets the state for us */
  100555. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100556. return false; /* read_callback_ sets the state for us */
  100557. track->num_indices = (FLAC__byte)x;
  100558. if(track->num_indices > 0) {
  100559. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100560. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100561. return false;
  100562. }
  100563. for(j = 0; j < track->num_indices; j++) {
  100564. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100565. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100566. return false; /* read_callback_ sets the state for us */
  100567. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100568. return false; /* read_callback_ sets the state for us */
  100569. index->number = (FLAC__byte)x;
  100570. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100571. return false; /* read_callback_ sets the state for us */
  100572. }
  100573. }
  100574. }
  100575. }
  100576. return true;
  100577. }
  100578. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100579. {
  100580. FLAC__uint32 x;
  100581. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100582. /* read type */
  100583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100584. return false; /* read_callback_ sets the state for us */
  100585. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100586. /* read MIME type */
  100587. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100588. return false; /* read_callback_ sets the state for us */
  100589. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100590. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100591. return false;
  100592. }
  100593. if(x > 0) {
  100594. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100595. return false; /* read_callback_ sets the state for us */
  100596. }
  100597. obj->mime_type[x] = '\0';
  100598. /* read description */
  100599. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100600. return false; /* read_callback_ sets the state for us */
  100601. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100602. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100603. return false;
  100604. }
  100605. if(x > 0) {
  100606. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100607. return false; /* read_callback_ sets the state for us */
  100608. }
  100609. obj->description[x] = '\0';
  100610. /* read width */
  100611. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100612. return false; /* read_callback_ sets the state for us */
  100613. /* read height */
  100614. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100615. return false; /* read_callback_ sets the state for us */
  100616. /* read depth */
  100617. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100618. return false; /* read_callback_ sets the state for us */
  100619. /* read colors */
  100620. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100621. return false; /* read_callback_ sets the state for us */
  100622. /* read data */
  100623. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100624. return false; /* read_callback_ sets the state for us */
  100625. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100626. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100627. return false;
  100628. }
  100629. if(obj->data_length > 0) {
  100630. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100631. return false; /* read_callback_ sets the state for us */
  100632. }
  100633. return true;
  100634. }
  100635. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100636. {
  100637. FLAC__uint32 x;
  100638. unsigned i, skip;
  100639. /* skip the version and flags bytes */
  100640. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100641. return false; /* read_callback_ sets the state for us */
  100642. /* get the size (in bytes) to skip */
  100643. skip = 0;
  100644. for(i = 0; i < 4; i++) {
  100645. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100646. return false; /* read_callback_ sets the state for us */
  100647. skip <<= 7;
  100648. skip |= (x & 0x7f);
  100649. }
  100650. /* skip the rest of the tag */
  100651. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100652. return false; /* read_callback_ sets the state for us */
  100653. return true;
  100654. }
  100655. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100656. {
  100657. FLAC__uint32 x;
  100658. FLAC__bool first = true;
  100659. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100660. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100661. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100662. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100663. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100664. return true;
  100665. }
  100666. }
  100667. /* make sure we're byte aligned */
  100668. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100669. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100670. return false; /* read_callback_ sets the state for us */
  100671. }
  100672. while(1) {
  100673. if(decoder->private_->cached) {
  100674. x = (FLAC__uint32)decoder->private_->lookahead;
  100675. decoder->private_->cached = false;
  100676. }
  100677. else {
  100678. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100679. return false; /* read_callback_ sets the state for us */
  100680. }
  100681. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100682. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100683. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100684. return false; /* read_callback_ sets the state for us */
  100685. /* 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 */
  100686. /* else we have to check if the second byte is the end of a sync code */
  100687. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100688. decoder->private_->lookahead = (FLAC__byte)x;
  100689. decoder->private_->cached = true;
  100690. }
  100691. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100692. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100693. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100694. return true;
  100695. }
  100696. }
  100697. if(first) {
  100698. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100699. first = false;
  100700. }
  100701. }
  100702. return true;
  100703. }
  100704. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100705. {
  100706. unsigned channel;
  100707. unsigned i;
  100708. FLAC__int32 mid, side;
  100709. unsigned frame_crc; /* the one we calculate from the input stream */
  100710. FLAC__uint32 x;
  100711. *got_a_frame = false;
  100712. /* init the CRC */
  100713. frame_crc = 0;
  100714. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100715. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100716. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100717. if(!read_frame_header_(decoder))
  100718. return false;
  100719. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100720. return true;
  100721. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100722. return false;
  100723. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100724. /*
  100725. * first figure the correct bits-per-sample of the subframe
  100726. */
  100727. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100728. switch(decoder->private_->frame.header.channel_assignment) {
  100729. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100730. /* no adjustment needed */
  100731. break;
  100732. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100733. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100734. if(channel == 1)
  100735. bps++;
  100736. break;
  100737. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100738. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100739. if(channel == 0)
  100740. bps++;
  100741. break;
  100742. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100743. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100744. if(channel == 1)
  100745. bps++;
  100746. break;
  100747. default:
  100748. FLAC__ASSERT(0);
  100749. }
  100750. /*
  100751. * now read it
  100752. */
  100753. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100754. return false;
  100755. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100756. return true;
  100757. }
  100758. if(!read_zero_padding_(decoder))
  100759. return false;
  100760. 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) */
  100761. return true;
  100762. /*
  100763. * Read the frame CRC-16 from the footer and check
  100764. */
  100765. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100766. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100767. return false; /* read_callback_ sets the state for us */
  100768. if(frame_crc == x) {
  100769. if(do_full_decode) {
  100770. /* Undo any special channel coding */
  100771. switch(decoder->private_->frame.header.channel_assignment) {
  100772. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100773. /* do nothing */
  100774. break;
  100775. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100776. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100777. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100778. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100779. break;
  100780. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100781. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100782. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100783. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100784. break;
  100785. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100786. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100787. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100788. #if 1
  100789. mid = decoder->private_->output[0][i];
  100790. side = decoder->private_->output[1][i];
  100791. mid <<= 1;
  100792. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100793. decoder->private_->output[0][i] = (mid + side) >> 1;
  100794. decoder->private_->output[1][i] = (mid - side) >> 1;
  100795. #else
  100796. /* OPT: without 'side' temp variable */
  100797. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100798. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100799. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100800. #endif
  100801. }
  100802. break;
  100803. default:
  100804. FLAC__ASSERT(0);
  100805. break;
  100806. }
  100807. }
  100808. }
  100809. else {
  100810. /* Bad frame, emit error and zero the output signal */
  100811. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100812. if(do_full_decode) {
  100813. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100814. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100815. }
  100816. }
  100817. }
  100818. *got_a_frame = true;
  100819. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100820. if(decoder->private_->next_fixed_block_size)
  100821. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100822. /* put the latest values into the public section of the decoder instance */
  100823. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100824. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100825. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100826. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100827. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100828. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100829. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100830. /* write it */
  100831. if(do_full_decode) {
  100832. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100833. return false;
  100834. }
  100835. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100836. return true;
  100837. }
  100838. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100839. {
  100840. FLAC__uint32 x;
  100841. FLAC__uint64 xx;
  100842. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100843. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100844. unsigned raw_header_len;
  100845. FLAC__bool is_unparseable = false;
  100846. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100847. /* init the raw header with the saved bits from synchronization */
  100848. raw_header[0] = decoder->private_->header_warmup[0];
  100849. raw_header[1] = decoder->private_->header_warmup[1];
  100850. raw_header_len = 2;
  100851. /* check to make sure that reserved bit is 0 */
  100852. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100853. is_unparseable = true;
  100854. /*
  100855. * Note that along the way as we read the header, we look for a sync
  100856. * code inside. If we find one it would indicate that our original
  100857. * sync was bad since there cannot be a sync code in a valid header.
  100858. *
  100859. * Three kinds of things can go wrong when reading the frame header:
  100860. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100861. * If we don't find a sync code, it can end up looking like we read
  100862. * a valid but unparseable header, until getting to the frame header
  100863. * CRC. Even then we could get a false positive on the CRC.
  100864. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100865. * future encoder).
  100866. * 3) We may be on a damaged frame which appears valid but unparseable.
  100867. *
  100868. * For all these reasons, we try and read a complete frame header as
  100869. * long as it seems valid, even if unparseable, up until the frame
  100870. * header CRC.
  100871. */
  100872. /*
  100873. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100874. */
  100875. for(i = 0; i < 2; i++) {
  100876. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100877. return false; /* read_callback_ sets the state for us */
  100878. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100879. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100880. decoder->private_->lookahead = (FLAC__byte)x;
  100881. decoder->private_->cached = true;
  100882. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100883. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100884. return true;
  100885. }
  100886. raw_header[raw_header_len++] = (FLAC__byte)x;
  100887. }
  100888. switch(x = raw_header[2] >> 4) {
  100889. case 0:
  100890. is_unparseable = true;
  100891. break;
  100892. case 1:
  100893. decoder->private_->frame.header.blocksize = 192;
  100894. break;
  100895. case 2:
  100896. case 3:
  100897. case 4:
  100898. case 5:
  100899. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100900. break;
  100901. case 6:
  100902. case 7:
  100903. blocksize_hint = x;
  100904. break;
  100905. case 8:
  100906. case 9:
  100907. case 10:
  100908. case 11:
  100909. case 12:
  100910. case 13:
  100911. case 14:
  100912. case 15:
  100913. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100914. break;
  100915. default:
  100916. FLAC__ASSERT(0);
  100917. break;
  100918. }
  100919. switch(x = raw_header[2] & 0x0f) {
  100920. case 0:
  100921. if(decoder->private_->has_stream_info)
  100922. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100923. else
  100924. is_unparseable = true;
  100925. break;
  100926. case 1:
  100927. decoder->private_->frame.header.sample_rate = 88200;
  100928. break;
  100929. case 2:
  100930. decoder->private_->frame.header.sample_rate = 176400;
  100931. break;
  100932. case 3:
  100933. decoder->private_->frame.header.sample_rate = 192000;
  100934. break;
  100935. case 4:
  100936. decoder->private_->frame.header.sample_rate = 8000;
  100937. break;
  100938. case 5:
  100939. decoder->private_->frame.header.sample_rate = 16000;
  100940. break;
  100941. case 6:
  100942. decoder->private_->frame.header.sample_rate = 22050;
  100943. break;
  100944. case 7:
  100945. decoder->private_->frame.header.sample_rate = 24000;
  100946. break;
  100947. case 8:
  100948. decoder->private_->frame.header.sample_rate = 32000;
  100949. break;
  100950. case 9:
  100951. decoder->private_->frame.header.sample_rate = 44100;
  100952. break;
  100953. case 10:
  100954. decoder->private_->frame.header.sample_rate = 48000;
  100955. break;
  100956. case 11:
  100957. decoder->private_->frame.header.sample_rate = 96000;
  100958. break;
  100959. case 12:
  100960. case 13:
  100961. case 14:
  100962. sample_rate_hint = x;
  100963. break;
  100964. case 15:
  100965. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100966. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100967. return true;
  100968. default:
  100969. FLAC__ASSERT(0);
  100970. }
  100971. x = (unsigned)(raw_header[3] >> 4);
  100972. if(x & 8) {
  100973. decoder->private_->frame.header.channels = 2;
  100974. switch(x & 7) {
  100975. case 0:
  100976. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100977. break;
  100978. case 1:
  100979. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100980. break;
  100981. case 2:
  100982. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100983. break;
  100984. default:
  100985. is_unparseable = true;
  100986. break;
  100987. }
  100988. }
  100989. else {
  100990. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100991. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100992. }
  100993. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100994. case 0:
  100995. if(decoder->private_->has_stream_info)
  100996. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100997. else
  100998. is_unparseable = true;
  100999. break;
  101000. case 1:
  101001. decoder->private_->frame.header.bits_per_sample = 8;
  101002. break;
  101003. case 2:
  101004. decoder->private_->frame.header.bits_per_sample = 12;
  101005. break;
  101006. case 4:
  101007. decoder->private_->frame.header.bits_per_sample = 16;
  101008. break;
  101009. case 5:
  101010. decoder->private_->frame.header.bits_per_sample = 20;
  101011. break;
  101012. case 6:
  101013. decoder->private_->frame.header.bits_per_sample = 24;
  101014. break;
  101015. case 3:
  101016. case 7:
  101017. is_unparseable = true;
  101018. break;
  101019. default:
  101020. FLAC__ASSERT(0);
  101021. break;
  101022. }
  101023. /* check to make sure that reserved bit is 0 */
  101024. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101025. is_unparseable = true;
  101026. /* read the frame's starting sample number (or frame number as the case may be) */
  101027. if(
  101028. raw_header[1] & 0x01 ||
  101029. /*@@@ 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 */
  101030. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101031. ) { /* variable blocksize */
  101032. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101033. return false; /* read_callback_ sets the state for us */
  101034. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101035. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101036. decoder->private_->cached = true;
  101037. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101038. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101039. return true;
  101040. }
  101041. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101042. decoder->private_->frame.header.number.sample_number = xx;
  101043. }
  101044. else { /* fixed blocksize */
  101045. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101046. return false; /* read_callback_ sets the state for us */
  101047. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101048. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101049. decoder->private_->cached = true;
  101050. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101051. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101052. return true;
  101053. }
  101054. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101055. decoder->private_->frame.header.number.frame_number = x;
  101056. }
  101057. if(blocksize_hint) {
  101058. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101059. return false; /* read_callback_ sets the state for us */
  101060. raw_header[raw_header_len++] = (FLAC__byte)x;
  101061. if(blocksize_hint == 7) {
  101062. FLAC__uint32 _x;
  101063. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101064. return false; /* read_callback_ sets the state for us */
  101065. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101066. x = (x << 8) | _x;
  101067. }
  101068. decoder->private_->frame.header.blocksize = x+1;
  101069. }
  101070. if(sample_rate_hint) {
  101071. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101072. return false; /* read_callback_ sets the state for us */
  101073. raw_header[raw_header_len++] = (FLAC__byte)x;
  101074. if(sample_rate_hint != 12) {
  101075. FLAC__uint32 _x;
  101076. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101077. return false; /* read_callback_ sets the state for us */
  101078. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101079. x = (x << 8) | _x;
  101080. }
  101081. if(sample_rate_hint == 12)
  101082. decoder->private_->frame.header.sample_rate = x*1000;
  101083. else if(sample_rate_hint == 13)
  101084. decoder->private_->frame.header.sample_rate = x;
  101085. else
  101086. decoder->private_->frame.header.sample_rate = x*10;
  101087. }
  101088. /* read the CRC-8 byte */
  101089. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101090. return false; /* read_callback_ sets the state for us */
  101091. crc8 = (FLAC__byte)x;
  101092. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101093. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101094. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101095. return true;
  101096. }
  101097. /* calculate the sample number from the frame number if needed */
  101098. decoder->private_->next_fixed_block_size = 0;
  101099. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101100. x = decoder->private_->frame.header.number.frame_number;
  101101. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101102. if(decoder->private_->fixed_block_size)
  101103. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101104. else if(decoder->private_->has_stream_info) {
  101105. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101106. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101107. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101108. }
  101109. else
  101110. is_unparseable = true;
  101111. }
  101112. else if(x == 0) {
  101113. decoder->private_->frame.header.number.sample_number = 0;
  101114. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101115. }
  101116. else {
  101117. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101118. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101119. }
  101120. }
  101121. if(is_unparseable) {
  101122. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101123. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101124. return true;
  101125. }
  101126. return true;
  101127. }
  101128. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101129. {
  101130. FLAC__uint32 x;
  101131. FLAC__bool wasted_bits;
  101132. unsigned i;
  101133. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101134. return false; /* read_callback_ sets the state for us */
  101135. wasted_bits = (x & 1);
  101136. x &= 0xfe;
  101137. if(wasted_bits) {
  101138. unsigned u;
  101139. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101140. return false; /* read_callback_ sets the state for us */
  101141. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101142. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101143. }
  101144. else
  101145. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101146. /*
  101147. * Lots of magic numbers here
  101148. */
  101149. if(x & 0x80) {
  101150. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101151. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101152. return true;
  101153. }
  101154. else if(x == 0) {
  101155. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101156. return false;
  101157. }
  101158. else if(x == 2) {
  101159. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101160. return false;
  101161. }
  101162. else if(x < 16) {
  101163. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101164. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101165. return true;
  101166. }
  101167. else if(x <= 24) {
  101168. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101169. return false;
  101170. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101171. return true;
  101172. }
  101173. else if(x < 64) {
  101174. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101175. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101176. return true;
  101177. }
  101178. else {
  101179. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101180. return false;
  101181. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101182. return true;
  101183. }
  101184. if(wasted_bits && do_full_decode) {
  101185. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101186. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101187. decoder->private_->output[channel][i] <<= x;
  101188. }
  101189. return true;
  101190. }
  101191. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101192. {
  101193. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101194. FLAC__int32 x;
  101195. unsigned i;
  101196. FLAC__int32 *output = decoder->private_->output[channel];
  101197. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101198. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101199. return false; /* read_callback_ sets the state for us */
  101200. subframe->value = x;
  101201. /* decode the subframe */
  101202. if(do_full_decode) {
  101203. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101204. output[i] = x;
  101205. }
  101206. return true;
  101207. }
  101208. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101209. {
  101210. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101211. FLAC__int32 i32;
  101212. FLAC__uint32 u32;
  101213. unsigned u;
  101214. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101215. subframe->residual = decoder->private_->residual[channel];
  101216. subframe->order = order;
  101217. /* read warm-up samples */
  101218. for(u = 0; u < order; u++) {
  101219. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101220. return false; /* read_callback_ sets the state for us */
  101221. subframe->warmup[u] = i32;
  101222. }
  101223. /* read entropy coding method info */
  101224. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101225. return false; /* read_callback_ sets the state for us */
  101226. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101227. switch(subframe->entropy_coding_method.type) {
  101228. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101229. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101230. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101231. return false; /* read_callback_ sets the state for us */
  101232. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101233. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101234. break;
  101235. default:
  101236. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101237. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101238. return true;
  101239. }
  101240. /* read residual */
  101241. switch(subframe->entropy_coding_method.type) {
  101242. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101243. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101244. 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))
  101245. return false;
  101246. break;
  101247. default:
  101248. FLAC__ASSERT(0);
  101249. }
  101250. /* decode the subframe */
  101251. if(do_full_decode) {
  101252. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101253. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101254. }
  101255. return true;
  101256. }
  101257. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101258. {
  101259. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101260. FLAC__int32 i32;
  101261. FLAC__uint32 u32;
  101262. unsigned u;
  101263. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101264. subframe->residual = decoder->private_->residual[channel];
  101265. subframe->order = order;
  101266. /* read warm-up samples */
  101267. for(u = 0; u < order; u++) {
  101268. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101269. return false; /* read_callback_ sets the state for us */
  101270. subframe->warmup[u] = i32;
  101271. }
  101272. /* read qlp coeff precision */
  101273. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101274. return false; /* read_callback_ sets the state for us */
  101275. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101276. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101277. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101278. return true;
  101279. }
  101280. subframe->qlp_coeff_precision = u32+1;
  101281. /* read qlp shift */
  101282. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101283. return false; /* read_callback_ sets the state for us */
  101284. subframe->quantization_level = i32;
  101285. /* read quantized lp coefficiencts */
  101286. for(u = 0; u < order; u++) {
  101287. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101288. return false; /* read_callback_ sets the state for us */
  101289. subframe->qlp_coeff[u] = i32;
  101290. }
  101291. /* read entropy coding method info */
  101292. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101293. return false; /* read_callback_ sets the state for us */
  101294. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101295. switch(subframe->entropy_coding_method.type) {
  101296. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101297. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101298. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101299. return false; /* read_callback_ sets the state for us */
  101300. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101301. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101302. break;
  101303. default:
  101304. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101305. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101306. return true;
  101307. }
  101308. /* read residual */
  101309. switch(subframe->entropy_coding_method.type) {
  101310. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101311. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101312. 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))
  101313. return false;
  101314. break;
  101315. default:
  101316. FLAC__ASSERT(0);
  101317. }
  101318. /* decode the subframe */
  101319. if(do_full_decode) {
  101320. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101321. /*@@@@@@ technically not pessimistic enough, should be more like
  101322. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101323. */
  101324. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101325. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101326. if(order <= 8)
  101327. 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);
  101328. else
  101329. 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);
  101330. }
  101331. else
  101332. 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);
  101333. else
  101334. 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);
  101335. }
  101336. return true;
  101337. }
  101338. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101339. {
  101340. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101341. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101342. unsigned i;
  101343. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101344. subframe->data = residual;
  101345. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101346. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101347. return false; /* read_callback_ sets the state for us */
  101348. residual[i] = x;
  101349. }
  101350. /* decode the subframe */
  101351. if(do_full_decode)
  101352. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101353. return true;
  101354. }
  101355. 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)
  101356. {
  101357. FLAC__uint32 rice_parameter;
  101358. int i;
  101359. unsigned partition, sample, u;
  101360. const unsigned partitions = 1u << partition_order;
  101361. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101362. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101363. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101364. /* sanity checks */
  101365. if(partition_order == 0) {
  101366. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101367. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101368. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101369. return true;
  101370. }
  101371. }
  101372. else {
  101373. if(partition_samples < predictor_order) {
  101374. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101375. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101376. return true;
  101377. }
  101378. }
  101379. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101380. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101381. return false;
  101382. }
  101383. sample = 0;
  101384. for(partition = 0; partition < partitions; partition++) {
  101385. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101386. return false; /* read_callback_ sets the state for us */
  101387. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101388. if(rice_parameter < pesc) {
  101389. partitioned_rice_contents->raw_bits[partition] = 0;
  101390. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101391. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101392. return false; /* read_callback_ sets the state for us */
  101393. sample += u;
  101394. }
  101395. else {
  101396. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101397. return false; /* read_callback_ sets the state for us */
  101398. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101399. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101400. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101401. return false; /* read_callback_ sets the state for us */
  101402. residual[sample] = i;
  101403. }
  101404. }
  101405. }
  101406. return true;
  101407. }
  101408. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101409. {
  101410. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101411. FLAC__uint32 zero = 0;
  101412. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101413. return false; /* read_callback_ sets the state for us */
  101414. if(zero != 0) {
  101415. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101416. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101417. }
  101418. }
  101419. return true;
  101420. }
  101421. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101422. {
  101423. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101424. if(
  101425. #if FLAC__HAS_OGG
  101426. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101427. !decoder->private_->is_ogg &&
  101428. #endif
  101429. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101430. ) {
  101431. *bytes = 0;
  101432. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101433. return false;
  101434. }
  101435. else if(*bytes > 0) {
  101436. /* While seeking, it is possible for our seek to land in the
  101437. * middle of audio data that looks exactly like a frame header
  101438. * from a future version of an encoder. When that happens, our
  101439. * error callback will get an
  101440. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101441. * unparseable_frame_count. But there is a remote possibility
  101442. * that it is properly synced at such a "future-codec frame",
  101443. * so to make sure, we wait to see many "unparseable" errors in
  101444. * a row before bailing out.
  101445. */
  101446. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101447. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101448. return false;
  101449. }
  101450. else {
  101451. const FLAC__StreamDecoderReadStatus status =
  101452. #if FLAC__HAS_OGG
  101453. decoder->private_->is_ogg?
  101454. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101455. #endif
  101456. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101457. ;
  101458. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101459. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101460. return false;
  101461. }
  101462. else if(*bytes == 0) {
  101463. if(
  101464. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101465. (
  101466. #if FLAC__HAS_OGG
  101467. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101468. !decoder->private_->is_ogg &&
  101469. #endif
  101470. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101471. )
  101472. ) {
  101473. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101474. return false;
  101475. }
  101476. else
  101477. return true;
  101478. }
  101479. else
  101480. return true;
  101481. }
  101482. }
  101483. else {
  101484. /* abort to avoid a deadlock */
  101485. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101486. return false;
  101487. }
  101488. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101489. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101490. * and at the same time hit the end of the stream (for example, seeking
  101491. * to a point that is after the beginning of the last Ogg page). There
  101492. * is no way to report an Ogg sync loss through the callbacks (see note
  101493. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101494. * So to keep the decoder from stopping at this point we gate the call
  101495. * to the eof_callback and let the Ogg decoder aspect set the
  101496. * end-of-stream state when it is needed.
  101497. */
  101498. }
  101499. #if FLAC__HAS_OGG
  101500. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101501. {
  101502. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101503. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101504. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101505. /* we don't really have a way to handle lost sync via read
  101506. * callback so we'll let it pass and let the underlying
  101507. * FLAC decoder catch the error
  101508. */
  101509. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101510. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101511. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101512. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101513. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101514. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101515. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101516. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101517. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101518. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101519. default:
  101520. FLAC__ASSERT(0);
  101521. /* double protection */
  101522. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101523. }
  101524. }
  101525. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101526. {
  101527. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101528. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101529. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101530. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101531. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101532. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101533. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101534. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101535. default:
  101536. /* double protection: */
  101537. FLAC__ASSERT(0);
  101538. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101539. }
  101540. }
  101541. #endif
  101542. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101543. {
  101544. if(decoder->private_->is_seeking) {
  101545. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101546. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101547. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101548. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101549. #if FLAC__HAS_OGG
  101550. decoder->private_->got_a_frame = true;
  101551. #endif
  101552. decoder->private_->last_frame = *frame; /* save the frame */
  101553. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101554. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101555. /* kick out of seek mode */
  101556. decoder->private_->is_seeking = false;
  101557. /* shift out the samples before target_sample */
  101558. if(delta > 0) {
  101559. unsigned channel;
  101560. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101561. for(channel = 0; channel < frame->header.channels; channel++)
  101562. newbuffer[channel] = buffer[channel] + delta;
  101563. decoder->private_->last_frame.header.blocksize -= delta;
  101564. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101565. /* write the relevant samples */
  101566. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101567. }
  101568. else {
  101569. /* write the relevant samples */
  101570. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101571. }
  101572. }
  101573. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101574. }
  101575. /*
  101576. * If we never got STREAMINFO, turn off MD5 checking to save
  101577. * cycles since we don't have a sum to compare to anyway
  101578. */
  101579. if(!decoder->private_->has_stream_info)
  101580. decoder->private_->do_md5_checking = false;
  101581. if(decoder->private_->do_md5_checking) {
  101582. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101583. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101584. }
  101585. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101586. }
  101587. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101588. {
  101589. if(!decoder->private_->is_seeking)
  101590. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101591. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101592. decoder->private_->unparseable_frame_count++;
  101593. }
  101594. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101595. {
  101596. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101597. FLAC__int64 pos = -1;
  101598. int i;
  101599. unsigned approx_bytes_per_frame;
  101600. FLAC__bool first_seek = true;
  101601. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101602. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101603. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101604. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101605. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101606. /* take these from the current frame in case they've changed mid-stream */
  101607. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101608. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101609. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101610. /* use values from stream info if we didn't decode a frame */
  101611. if(channels == 0)
  101612. channels = decoder->private_->stream_info.data.stream_info.channels;
  101613. if(bps == 0)
  101614. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101615. /* we are just guessing here */
  101616. if(max_framesize > 0)
  101617. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101618. /*
  101619. * Check if it's a known fixed-blocksize stream. Note that though
  101620. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101621. * never get a STREAMINFO block when decoding so the value of
  101622. * min_blocksize might be zero.
  101623. */
  101624. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101625. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101626. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101627. }
  101628. else
  101629. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101630. /*
  101631. * First, we set an upper and lower bound on where in the
  101632. * stream we will search. For now we assume the worst case
  101633. * scenario, which is our best guess at the beginning of
  101634. * the first frame and end of the stream.
  101635. */
  101636. lower_bound = first_frame_offset;
  101637. lower_bound_sample = 0;
  101638. upper_bound = stream_length;
  101639. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101640. /*
  101641. * Now we refine the bounds if we have a seektable with
  101642. * suitable points. Note that according to the spec they
  101643. * must be ordered by ascending sample number.
  101644. *
  101645. * Note: to protect against invalid seek tables we will ignore points
  101646. * that have frame_samples==0 or sample_number>=total_samples
  101647. */
  101648. if(seek_table) {
  101649. FLAC__uint64 new_lower_bound = lower_bound;
  101650. FLAC__uint64 new_upper_bound = upper_bound;
  101651. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101652. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101653. /* find the closest seek point <= target_sample, if it exists */
  101654. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101655. if(
  101656. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101657. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101658. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101659. seek_table->points[i].sample_number <= target_sample
  101660. )
  101661. break;
  101662. }
  101663. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101664. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101665. new_lower_bound_sample = seek_table->points[i].sample_number;
  101666. }
  101667. /* find the closest seek point > target_sample, if it exists */
  101668. for(i = 0; i < (int)seek_table->num_points; i++) {
  101669. if(
  101670. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101671. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101672. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101673. seek_table->points[i].sample_number > target_sample
  101674. )
  101675. break;
  101676. }
  101677. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101678. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101679. new_upper_bound_sample = seek_table->points[i].sample_number;
  101680. }
  101681. /* final protection against unsorted seek tables; keep original values if bogus */
  101682. if(new_upper_bound >= new_lower_bound) {
  101683. lower_bound = new_lower_bound;
  101684. upper_bound = new_upper_bound;
  101685. lower_bound_sample = new_lower_bound_sample;
  101686. upper_bound_sample = new_upper_bound_sample;
  101687. }
  101688. }
  101689. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101690. /* there are 2 insidious ways that the following equality occurs, which
  101691. * we need to fix:
  101692. * 1) total_samples is 0 (unknown) and target_sample is 0
  101693. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101694. * exactly equal to the last seek point in the seek table; this
  101695. * means there is no seek point above it, and upper_bound_samples
  101696. * remains equal to the estimate (of target_samples) we made above
  101697. * in either case it does not hurt to move upper_bound_sample up by 1
  101698. */
  101699. if(upper_bound_sample == lower_bound_sample)
  101700. upper_bound_sample++;
  101701. decoder->private_->target_sample = target_sample;
  101702. while(1) {
  101703. /* check if the bounds are still ok */
  101704. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101705. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101706. return false;
  101707. }
  101708. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101709. #if defined _MSC_VER || defined __MINGW32__
  101710. /* with VC++ you have to spoon feed it the casting */
  101711. 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;
  101712. #else
  101713. 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;
  101714. #endif
  101715. #else
  101716. /* a little less accurate: */
  101717. if(upper_bound - lower_bound < 0xffffffff)
  101718. 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;
  101719. else /* @@@ WATCHOUT, ~2TB limit */
  101720. 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;
  101721. #endif
  101722. if(pos >= (FLAC__int64)upper_bound)
  101723. pos = (FLAC__int64)upper_bound - 1;
  101724. if(pos < (FLAC__int64)lower_bound)
  101725. pos = (FLAC__int64)lower_bound;
  101726. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101727. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101728. return false;
  101729. }
  101730. if(!FLAC__stream_decoder_flush(decoder)) {
  101731. /* above call sets the state for us */
  101732. return false;
  101733. }
  101734. /* Now we need to get a frame. First we need to reset our
  101735. * unparseable_frame_count; if we get too many unparseable
  101736. * frames in a row, the read callback will return
  101737. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101738. * FLAC__stream_decoder_process_single() to return false.
  101739. */
  101740. decoder->private_->unparseable_frame_count = 0;
  101741. if(!FLAC__stream_decoder_process_single(decoder)) {
  101742. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101743. return false;
  101744. }
  101745. /* our write callback will change the state when it gets to the target frame */
  101746. /* 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 */
  101747. #if 0
  101748. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101749. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101750. break;
  101751. #endif
  101752. if(!decoder->private_->is_seeking)
  101753. break;
  101754. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101755. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101756. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101757. if (pos == (FLAC__int64)lower_bound) {
  101758. /* can't move back any more than the first frame, something is fatally wrong */
  101759. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101760. return false;
  101761. }
  101762. /* our last move backwards wasn't big enough, try again */
  101763. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101764. continue;
  101765. }
  101766. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101767. first_seek = false;
  101768. /* make sure we are not seeking in corrupted stream */
  101769. if (this_frame_sample < lower_bound_sample) {
  101770. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101771. return false;
  101772. }
  101773. /* we need to narrow the search */
  101774. if(target_sample < this_frame_sample) {
  101775. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101776. /*@@@@@@ what will decode position be if at end of stream? */
  101777. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101778. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101779. return false;
  101780. }
  101781. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101782. }
  101783. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101784. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101785. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101786. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101787. return false;
  101788. }
  101789. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101790. }
  101791. }
  101792. return true;
  101793. }
  101794. #if FLAC__HAS_OGG
  101795. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101796. {
  101797. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101798. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101799. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101800. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101801. FLAC__bool did_a_seek;
  101802. unsigned iteration = 0;
  101803. /* In the first iterations, we will calculate the target byte position
  101804. * by the distance from the target sample to left_sample and
  101805. * right_sample (let's call it "proportional search"). After that, we
  101806. * will switch to binary search.
  101807. */
  101808. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101809. /* We will switch to a linear search once our current sample is less
  101810. * than this number of samples ahead of the target sample
  101811. */
  101812. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101813. /* If the total number of samples is unknown, use a large value, and
  101814. * force binary search immediately.
  101815. */
  101816. if(right_sample == 0) {
  101817. right_sample = (FLAC__uint64)(-1);
  101818. BINARY_SEARCH_AFTER_ITERATION = 0;
  101819. }
  101820. decoder->private_->target_sample = target_sample;
  101821. for( ; ; iteration++) {
  101822. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101823. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101824. pos = (right_pos + left_pos) / 2;
  101825. }
  101826. else {
  101827. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101828. #if defined _MSC_VER || defined __MINGW32__
  101829. /* with MSVC you have to spoon feed it the casting */
  101830. 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));
  101831. #else
  101832. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101833. #endif
  101834. #else
  101835. /* a little less accurate: */
  101836. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101837. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101838. else /* @@@ WATCHOUT, ~2TB limit */
  101839. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101840. #endif
  101841. /* @@@ TODO: might want to limit pos to some distance
  101842. * before EOF, to make sure we land before the last frame,
  101843. * thereby getting a this_frame_sample and so having a better
  101844. * estimate.
  101845. */
  101846. }
  101847. /* physical seek */
  101848. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101849. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101850. return false;
  101851. }
  101852. if(!FLAC__stream_decoder_flush(decoder)) {
  101853. /* above call sets the state for us */
  101854. return false;
  101855. }
  101856. did_a_seek = true;
  101857. }
  101858. else
  101859. did_a_seek = false;
  101860. decoder->private_->got_a_frame = false;
  101861. if(!FLAC__stream_decoder_process_single(decoder)) {
  101862. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101863. return false;
  101864. }
  101865. if(!decoder->private_->got_a_frame) {
  101866. if(did_a_seek) {
  101867. /* this can happen if we seek to a point after the last frame; we drop
  101868. * to binary search right away in this case to avoid any wasted
  101869. * iterations of proportional search.
  101870. */
  101871. right_pos = pos;
  101872. BINARY_SEARCH_AFTER_ITERATION = 0;
  101873. }
  101874. else {
  101875. /* this can probably only happen if total_samples is unknown and the
  101876. * target_sample is past the end of the stream
  101877. */
  101878. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101879. return false;
  101880. }
  101881. }
  101882. /* our write callback will change the state when it gets to the target frame */
  101883. else if(!decoder->private_->is_seeking) {
  101884. break;
  101885. }
  101886. else {
  101887. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101888. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101889. if (did_a_seek) {
  101890. if (this_frame_sample <= target_sample) {
  101891. /* The 'equal' case should not happen, since
  101892. * FLAC__stream_decoder_process_single()
  101893. * should recognize that it has hit the
  101894. * target sample and we would exit through
  101895. * the 'break' above.
  101896. */
  101897. FLAC__ASSERT(this_frame_sample != target_sample);
  101898. left_sample = this_frame_sample;
  101899. /* sanity check to avoid infinite loop */
  101900. if (left_pos == pos) {
  101901. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101902. return false;
  101903. }
  101904. left_pos = pos;
  101905. }
  101906. else if(this_frame_sample > target_sample) {
  101907. right_sample = this_frame_sample;
  101908. /* sanity check to avoid infinite loop */
  101909. if (right_pos == pos) {
  101910. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101911. return false;
  101912. }
  101913. right_pos = pos;
  101914. }
  101915. }
  101916. }
  101917. }
  101918. return true;
  101919. }
  101920. #endif
  101921. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101922. {
  101923. (void)client_data;
  101924. if(*bytes > 0) {
  101925. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101926. if(ferror(decoder->private_->file))
  101927. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101928. else if(*bytes == 0)
  101929. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101930. else
  101931. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101932. }
  101933. else
  101934. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101935. }
  101936. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101937. {
  101938. (void)client_data;
  101939. if(decoder->private_->file == stdin)
  101940. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101941. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101942. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101943. else
  101944. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101945. }
  101946. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101947. {
  101948. off_t pos;
  101949. (void)client_data;
  101950. if(decoder->private_->file == stdin)
  101951. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101952. else if((pos = ftello(decoder->private_->file)) < 0)
  101953. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101954. else {
  101955. *absolute_byte_offset = (FLAC__uint64)pos;
  101956. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101957. }
  101958. }
  101959. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101960. {
  101961. struct stat filestats;
  101962. (void)client_data;
  101963. if(decoder->private_->file == stdin)
  101964. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101965. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101966. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101967. else {
  101968. *stream_length = (FLAC__uint64)filestats.st_size;
  101969. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101970. }
  101971. }
  101972. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101973. {
  101974. (void)client_data;
  101975. return feof(decoder->private_->file)? true : false;
  101976. }
  101977. #endif
  101978. /*** End of inlined file: stream_decoder.c ***/
  101979. /*** Start of inlined file: stream_encoder.c ***/
  101980. /*** Start of inlined file: juce_FlacHeader.h ***/
  101981. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101982. // tasks..
  101983. #define VERSION "1.2.1"
  101984. #define FLAC__NO_DLL 1
  101985. #if JUCE_MSVC
  101986. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101987. #endif
  101988. #if JUCE_MAC
  101989. #define FLAC__SYS_DARWIN 1
  101990. #endif
  101991. /*** End of inlined file: juce_FlacHeader.h ***/
  101992. #if JUCE_USE_FLAC
  101993. #if HAVE_CONFIG_H
  101994. # include <config.h>
  101995. #endif
  101996. #if defined _MSC_VER || defined __MINGW32__
  101997. #include <io.h> /* for _setmode() */
  101998. #include <fcntl.h> /* for _O_BINARY */
  101999. #endif
  102000. #if defined __CYGWIN__ || defined __EMX__
  102001. #include <io.h> /* for setmode(), O_BINARY */
  102002. #include <fcntl.h> /* for _O_BINARY */
  102003. #endif
  102004. #include <limits.h>
  102005. #include <stdio.h>
  102006. #include <stdlib.h> /* for malloc() */
  102007. #include <string.h> /* for memcpy() */
  102008. #include <sys/types.h> /* for off_t */
  102009. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102010. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102011. #define fseeko fseek
  102012. #define ftello ftell
  102013. #endif
  102014. #endif
  102015. /*** Start of inlined file: stream_encoder.h ***/
  102016. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102017. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102018. #if FLAC__HAS_OGG
  102019. #include "private/ogg_encoder_aspect.h"
  102020. #endif
  102021. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102022. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102023. typedef enum {
  102024. FLAC__APODIZATION_BARTLETT,
  102025. FLAC__APODIZATION_BARTLETT_HANN,
  102026. FLAC__APODIZATION_BLACKMAN,
  102027. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102028. FLAC__APODIZATION_CONNES,
  102029. FLAC__APODIZATION_FLATTOP,
  102030. FLAC__APODIZATION_GAUSS,
  102031. FLAC__APODIZATION_HAMMING,
  102032. FLAC__APODIZATION_HANN,
  102033. FLAC__APODIZATION_KAISER_BESSEL,
  102034. FLAC__APODIZATION_NUTTALL,
  102035. FLAC__APODIZATION_RECTANGLE,
  102036. FLAC__APODIZATION_TRIANGLE,
  102037. FLAC__APODIZATION_TUKEY,
  102038. FLAC__APODIZATION_WELCH
  102039. } FLAC__ApodizationFunction;
  102040. typedef struct {
  102041. FLAC__ApodizationFunction type;
  102042. union {
  102043. struct {
  102044. FLAC__real stddev;
  102045. } gauss;
  102046. struct {
  102047. FLAC__real p;
  102048. } tukey;
  102049. } parameters;
  102050. } FLAC__ApodizationSpecification;
  102051. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102052. typedef struct FLAC__StreamEncoderProtected {
  102053. FLAC__StreamEncoderState state;
  102054. FLAC__bool verify;
  102055. FLAC__bool streamable_subset;
  102056. FLAC__bool do_md5;
  102057. FLAC__bool do_mid_side_stereo;
  102058. FLAC__bool loose_mid_side_stereo;
  102059. unsigned channels;
  102060. unsigned bits_per_sample;
  102061. unsigned sample_rate;
  102062. unsigned blocksize;
  102063. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102064. unsigned num_apodizations;
  102065. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102066. #endif
  102067. unsigned max_lpc_order;
  102068. unsigned qlp_coeff_precision;
  102069. FLAC__bool do_qlp_coeff_prec_search;
  102070. FLAC__bool do_exhaustive_model_search;
  102071. FLAC__bool do_escape_coding;
  102072. unsigned min_residual_partition_order;
  102073. unsigned max_residual_partition_order;
  102074. unsigned rice_parameter_search_dist;
  102075. FLAC__uint64 total_samples_estimate;
  102076. FLAC__StreamMetadata **metadata;
  102077. unsigned num_metadata_blocks;
  102078. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102079. #if FLAC__HAS_OGG
  102080. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102081. #endif
  102082. } FLAC__StreamEncoderProtected;
  102083. #endif
  102084. /*** End of inlined file: stream_encoder.h ***/
  102085. #if FLAC__HAS_OGG
  102086. #include "include/private/ogg_helper.h"
  102087. #include "include/private/ogg_mapping.h"
  102088. #endif
  102089. /*** Start of inlined file: stream_encoder_framing.h ***/
  102090. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102091. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102092. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102093. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102094. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102095. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102096. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102097. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102098. #endif
  102099. /*** End of inlined file: stream_encoder_framing.h ***/
  102100. /*** Start of inlined file: window.h ***/
  102101. #ifndef FLAC__PRIVATE__WINDOW_H
  102102. #define FLAC__PRIVATE__WINDOW_H
  102103. #ifdef HAVE_CONFIG_H
  102104. #include <config.h>
  102105. #endif
  102106. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102107. /*
  102108. * FLAC__window_*()
  102109. * --------------------------------------------------------------------
  102110. * Calculates window coefficients according to different apodization
  102111. * functions.
  102112. *
  102113. * OUT window[0,L-1]
  102114. * IN L (number of points in window)
  102115. */
  102116. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102117. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102118. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102119. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102120. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102121. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102122. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102123. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102124. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102125. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102126. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102127. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102128. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102129. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102130. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102131. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102132. #endif
  102133. /*** End of inlined file: window.h ***/
  102134. #ifndef FLaC__INLINE
  102135. #define FLaC__INLINE
  102136. #endif
  102137. #ifdef min
  102138. #undef min
  102139. #endif
  102140. #define min(x,y) ((x)<(y)?(x):(y))
  102141. #ifdef max
  102142. #undef max
  102143. #endif
  102144. #define max(x,y) ((x)>(y)?(x):(y))
  102145. /* Exact Rice codeword length calculation is off by default. The simple
  102146. * (and fast) estimation (of how many bits a residual value will be
  102147. * encoded with) in this encoder is very good, almost always yielding
  102148. * compression within 0.1% of exact calculation.
  102149. */
  102150. #undef EXACT_RICE_BITS_CALCULATION
  102151. /* Rice parameter searching is off by default. The simple (and fast)
  102152. * parameter estimation in this encoder is very good, almost always
  102153. * yielding compression within 0.1% of the optimal parameters.
  102154. */
  102155. #undef ENABLE_RICE_PARAMETER_SEARCH
  102156. typedef struct {
  102157. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102158. unsigned size; /* of each data[] in samples */
  102159. unsigned tail;
  102160. } verify_input_fifo;
  102161. typedef struct {
  102162. const FLAC__byte *data;
  102163. unsigned capacity;
  102164. unsigned bytes;
  102165. } verify_output;
  102166. typedef enum {
  102167. ENCODER_IN_MAGIC = 0,
  102168. ENCODER_IN_METADATA = 1,
  102169. ENCODER_IN_AUDIO = 2
  102170. } EncoderStateHint;
  102171. static struct CompressionLevels {
  102172. FLAC__bool do_mid_side_stereo;
  102173. FLAC__bool loose_mid_side_stereo;
  102174. unsigned max_lpc_order;
  102175. unsigned qlp_coeff_precision;
  102176. FLAC__bool do_qlp_coeff_prec_search;
  102177. FLAC__bool do_escape_coding;
  102178. FLAC__bool do_exhaustive_model_search;
  102179. unsigned min_residual_partition_order;
  102180. unsigned max_residual_partition_order;
  102181. unsigned rice_parameter_search_dist;
  102182. } compression_levels_[] = {
  102183. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102184. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102185. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102186. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102187. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102188. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102189. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102190. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102191. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102192. };
  102193. /***********************************************************************
  102194. *
  102195. * Private class method prototypes
  102196. *
  102197. ***********************************************************************/
  102198. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102199. static void free_(FLAC__StreamEncoder *encoder);
  102200. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102201. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102202. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102203. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102204. #if FLAC__HAS_OGG
  102205. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102206. #endif
  102207. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102208. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102209. static FLAC__bool process_subframe_(
  102210. FLAC__StreamEncoder *encoder,
  102211. unsigned min_partition_order,
  102212. unsigned max_partition_order,
  102213. const FLAC__FrameHeader *frame_header,
  102214. unsigned subframe_bps,
  102215. const FLAC__int32 integer_signal[],
  102216. FLAC__Subframe *subframe[2],
  102217. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102218. FLAC__int32 *residual[2],
  102219. unsigned *best_subframe,
  102220. unsigned *best_bits
  102221. );
  102222. static FLAC__bool add_subframe_(
  102223. FLAC__StreamEncoder *encoder,
  102224. unsigned blocksize,
  102225. unsigned subframe_bps,
  102226. const FLAC__Subframe *subframe,
  102227. FLAC__BitWriter *frame
  102228. );
  102229. static unsigned evaluate_constant_subframe_(
  102230. FLAC__StreamEncoder *encoder,
  102231. const FLAC__int32 signal,
  102232. unsigned blocksize,
  102233. unsigned subframe_bps,
  102234. FLAC__Subframe *subframe
  102235. );
  102236. static unsigned evaluate_fixed_subframe_(
  102237. FLAC__StreamEncoder *encoder,
  102238. const FLAC__int32 signal[],
  102239. FLAC__int32 residual[],
  102240. FLAC__uint64 abs_residual_partition_sums[],
  102241. unsigned raw_bits_per_partition[],
  102242. unsigned blocksize,
  102243. unsigned subframe_bps,
  102244. unsigned order,
  102245. unsigned rice_parameter,
  102246. unsigned rice_parameter_limit,
  102247. unsigned min_partition_order,
  102248. unsigned max_partition_order,
  102249. FLAC__bool do_escape_coding,
  102250. unsigned rice_parameter_search_dist,
  102251. FLAC__Subframe *subframe,
  102252. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102253. );
  102254. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102255. static unsigned evaluate_lpc_subframe_(
  102256. FLAC__StreamEncoder *encoder,
  102257. const FLAC__int32 signal[],
  102258. FLAC__int32 residual[],
  102259. FLAC__uint64 abs_residual_partition_sums[],
  102260. unsigned raw_bits_per_partition[],
  102261. const FLAC__real lp_coeff[],
  102262. unsigned blocksize,
  102263. unsigned subframe_bps,
  102264. unsigned order,
  102265. unsigned qlp_coeff_precision,
  102266. unsigned rice_parameter,
  102267. unsigned rice_parameter_limit,
  102268. unsigned min_partition_order,
  102269. unsigned max_partition_order,
  102270. FLAC__bool do_escape_coding,
  102271. unsigned rice_parameter_search_dist,
  102272. FLAC__Subframe *subframe,
  102273. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102274. );
  102275. #endif
  102276. static unsigned evaluate_verbatim_subframe_(
  102277. FLAC__StreamEncoder *encoder,
  102278. const FLAC__int32 signal[],
  102279. unsigned blocksize,
  102280. unsigned subframe_bps,
  102281. FLAC__Subframe *subframe
  102282. );
  102283. static unsigned find_best_partition_order_(
  102284. struct FLAC__StreamEncoderPrivate *private_,
  102285. const FLAC__int32 residual[],
  102286. FLAC__uint64 abs_residual_partition_sums[],
  102287. unsigned raw_bits_per_partition[],
  102288. unsigned residual_samples,
  102289. unsigned predictor_order,
  102290. unsigned rice_parameter,
  102291. unsigned rice_parameter_limit,
  102292. unsigned min_partition_order,
  102293. unsigned max_partition_order,
  102294. unsigned bps,
  102295. FLAC__bool do_escape_coding,
  102296. unsigned rice_parameter_search_dist,
  102297. FLAC__EntropyCodingMethod *best_ecm
  102298. );
  102299. static void precompute_partition_info_sums_(
  102300. const FLAC__int32 residual[],
  102301. FLAC__uint64 abs_residual_partition_sums[],
  102302. unsigned residual_samples,
  102303. unsigned predictor_order,
  102304. unsigned min_partition_order,
  102305. unsigned max_partition_order,
  102306. unsigned bps
  102307. );
  102308. static void precompute_partition_info_escapes_(
  102309. const FLAC__int32 residual[],
  102310. unsigned raw_bits_per_partition[],
  102311. unsigned residual_samples,
  102312. unsigned predictor_order,
  102313. unsigned min_partition_order,
  102314. unsigned max_partition_order
  102315. );
  102316. static FLAC__bool set_partitioned_rice_(
  102317. #ifdef EXACT_RICE_BITS_CALCULATION
  102318. const FLAC__int32 residual[],
  102319. #endif
  102320. const FLAC__uint64 abs_residual_partition_sums[],
  102321. const unsigned raw_bits_per_partition[],
  102322. const unsigned residual_samples,
  102323. const unsigned predictor_order,
  102324. const unsigned suggested_rice_parameter,
  102325. const unsigned rice_parameter_limit,
  102326. const unsigned rice_parameter_search_dist,
  102327. const unsigned partition_order,
  102328. const FLAC__bool search_for_escapes,
  102329. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102330. unsigned *bits
  102331. );
  102332. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102333. /* verify-related routines: */
  102334. static void append_to_verify_fifo_(
  102335. verify_input_fifo *fifo,
  102336. const FLAC__int32 * const input[],
  102337. unsigned input_offset,
  102338. unsigned channels,
  102339. unsigned wide_samples
  102340. );
  102341. static void append_to_verify_fifo_interleaved_(
  102342. verify_input_fifo *fifo,
  102343. const FLAC__int32 input[],
  102344. unsigned input_offset,
  102345. unsigned channels,
  102346. unsigned wide_samples
  102347. );
  102348. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102349. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102350. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102351. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102352. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102353. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102354. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102355. 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);
  102356. static FILE *get_binary_stdout_(void);
  102357. /***********************************************************************
  102358. *
  102359. * Private class data
  102360. *
  102361. ***********************************************************************/
  102362. typedef struct FLAC__StreamEncoderPrivate {
  102363. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102364. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102365. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102366. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102367. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102368. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102369. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102370. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102371. #endif
  102372. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102373. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102374. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102375. FLAC__int32 *residual_workspace_mid_side[2][2];
  102376. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102377. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102378. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102379. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102380. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102381. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102382. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102383. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102384. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102385. unsigned best_subframe_mid_side[2];
  102386. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102387. unsigned best_subframe_bits_mid_side[2];
  102388. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102389. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102390. FLAC__BitWriter *frame; /* the current frame being worked on */
  102391. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102392. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102393. FLAC__ChannelAssignment last_channel_assignment;
  102394. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102395. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102396. unsigned current_sample_number;
  102397. unsigned current_frame_number;
  102398. FLAC__MD5Context md5context;
  102399. FLAC__CPUInfo cpuinfo;
  102400. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102401. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102402. #else
  102403. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102404. #endif
  102405. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102406. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102407. 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[]);
  102408. 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[]);
  102409. 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[]);
  102410. #endif
  102411. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102412. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102413. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102414. FLAC__bool disable_constant_subframes;
  102415. FLAC__bool disable_fixed_subframes;
  102416. FLAC__bool disable_verbatim_subframes;
  102417. #if FLAC__HAS_OGG
  102418. FLAC__bool is_ogg;
  102419. #endif
  102420. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102421. FLAC__StreamEncoderSeekCallback seek_callback;
  102422. FLAC__StreamEncoderTellCallback tell_callback;
  102423. FLAC__StreamEncoderWriteCallback write_callback;
  102424. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102425. FLAC__StreamEncoderProgressCallback progress_callback;
  102426. void *client_data;
  102427. unsigned first_seekpoint_to_check;
  102428. FILE *file; /* only used when encoding to a file */
  102429. FLAC__uint64 bytes_written;
  102430. FLAC__uint64 samples_written;
  102431. unsigned frames_written;
  102432. unsigned total_frames_estimate;
  102433. /* unaligned (original) pointers to allocated data */
  102434. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102435. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102436. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102437. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102438. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102439. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102440. FLAC__real *windowed_signal_unaligned;
  102441. #endif
  102442. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102443. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102444. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102445. unsigned *raw_bits_per_partition_unaligned;
  102446. /*
  102447. * These fields have been moved here from private function local
  102448. * declarations merely to save stack space during encoding.
  102449. */
  102450. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102451. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102452. #endif
  102453. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102454. /*
  102455. * The data for the verify section
  102456. */
  102457. struct {
  102458. FLAC__StreamDecoder *decoder;
  102459. EncoderStateHint state_hint;
  102460. FLAC__bool needs_magic_hack;
  102461. verify_input_fifo input_fifo;
  102462. verify_output output;
  102463. struct {
  102464. FLAC__uint64 absolute_sample;
  102465. unsigned frame_number;
  102466. unsigned channel;
  102467. unsigned sample;
  102468. FLAC__int32 expected;
  102469. FLAC__int32 got;
  102470. } error_stats;
  102471. } verify;
  102472. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102473. } FLAC__StreamEncoderPrivate;
  102474. /***********************************************************************
  102475. *
  102476. * Public static class data
  102477. *
  102478. ***********************************************************************/
  102479. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102480. "FLAC__STREAM_ENCODER_OK",
  102481. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102482. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102483. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102484. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102485. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102486. "FLAC__STREAM_ENCODER_IO_ERROR",
  102487. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102488. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102489. };
  102490. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102491. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102492. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102493. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102494. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102495. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102496. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102497. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102498. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102499. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102500. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102501. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102502. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102503. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102504. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102505. };
  102506. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102507. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102508. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102509. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102510. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102511. };
  102512. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102513. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102514. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102515. };
  102516. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102517. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102518. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102519. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102520. };
  102521. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102522. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102523. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102524. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102525. };
  102526. /* Number of samples that will be overread to watch for end of stream. By
  102527. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102528. * always try to read blocksize+1 samples before encoding a block, so that
  102529. * even if the stream has a total sample count that is an integral multiple
  102530. * of the blocksize, we will still notice when we are encoding the last
  102531. * block. This is needed, for example, to correctly set the end-of-stream
  102532. * marker in Ogg FLAC.
  102533. *
  102534. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102535. * not really any reason to change it.
  102536. */
  102537. static const unsigned OVERREAD_ = 1;
  102538. /***********************************************************************
  102539. *
  102540. * Class constructor/destructor
  102541. *
  102542. */
  102543. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102544. {
  102545. FLAC__StreamEncoder *encoder;
  102546. unsigned i;
  102547. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102548. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102549. if(encoder == 0) {
  102550. return 0;
  102551. }
  102552. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102553. if(encoder->protected_ == 0) {
  102554. free(encoder);
  102555. return 0;
  102556. }
  102557. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102558. if(encoder->private_ == 0) {
  102559. free(encoder->protected_);
  102560. free(encoder);
  102561. return 0;
  102562. }
  102563. encoder->private_->frame = FLAC__bitwriter_new();
  102564. if(encoder->private_->frame == 0) {
  102565. free(encoder->private_);
  102566. free(encoder->protected_);
  102567. free(encoder);
  102568. return 0;
  102569. }
  102570. encoder->private_->file = 0;
  102571. set_defaults_enc(encoder);
  102572. encoder->private_->is_being_deleted = false;
  102573. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102574. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102575. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102576. }
  102577. for(i = 0; i < 2; i++) {
  102578. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102579. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102580. }
  102581. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102582. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102583. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102584. }
  102585. for(i = 0; i < 2; i++) {
  102586. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102587. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102588. }
  102589. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102590. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102591. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102592. }
  102593. for(i = 0; i < 2; i++) {
  102594. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102595. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102596. }
  102597. for(i = 0; i < 2; i++)
  102598. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102599. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102600. return encoder;
  102601. }
  102602. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102603. {
  102604. unsigned i;
  102605. FLAC__ASSERT(0 != encoder);
  102606. FLAC__ASSERT(0 != encoder->protected_);
  102607. FLAC__ASSERT(0 != encoder->private_);
  102608. FLAC__ASSERT(0 != encoder->private_->frame);
  102609. encoder->private_->is_being_deleted = true;
  102610. (void)FLAC__stream_encoder_finish(encoder);
  102611. if(0 != encoder->private_->verify.decoder)
  102612. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102613. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102614. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102615. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102616. }
  102617. for(i = 0; i < 2; i++) {
  102618. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102619. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102620. }
  102621. for(i = 0; i < 2; i++)
  102622. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102623. FLAC__bitwriter_delete(encoder->private_->frame);
  102624. free(encoder->private_);
  102625. free(encoder->protected_);
  102626. free(encoder);
  102627. }
  102628. /***********************************************************************
  102629. *
  102630. * Public class methods
  102631. *
  102632. ***********************************************************************/
  102633. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102634. FLAC__StreamEncoder *encoder,
  102635. FLAC__StreamEncoderReadCallback read_callback,
  102636. FLAC__StreamEncoderWriteCallback write_callback,
  102637. FLAC__StreamEncoderSeekCallback seek_callback,
  102638. FLAC__StreamEncoderTellCallback tell_callback,
  102639. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102640. void *client_data,
  102641. FLAC__bool is_ogg
  102642. )
  102643. {
  102644. unsigned i;
  102645. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102646. FLAC__ASSERT(0 != encoder);
  102647. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102648. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102649. #if !FLAC__HAS_OGG
  102650. if(is_ogg)
  102651. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102652. #endif
  102653. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102654. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102655. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102656. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102657. if(encoder->protected_->channels != 2) {
  102658. encoder->protected_->do_mid_side_stereo = false;
  102659. encoder->protected_->loose_mid_side_stereo = false;
  102660. }
  102661. else if(!encoder->protected_->do_mid_side_stereo)
  102662. encoder->protected_->loose_mid_side_stereo = false;
  102663. if(encoder->protected_->bits_per_sample >= 32)
  102664. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102665. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102666. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102667. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102668. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102669. if(encoder->protected_->blocksize == 0) {
  102670. if(encoder->protected_->max_lpc_order == 0)
  102671. encoder->protected_->blocksize = 1152;
  102672. else
  102673. encoder->protected_->blocksize = 4096;
  102674. }
  102675. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102676. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102677. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102678. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102679. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102680. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102681. if(encoder->protected_->qlp_coeff_precision == 0) {
  102682. if(encoder->protected_->bits_per_sample < 16) {
  102683. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102684. /* @@@ until then we'll make a guess */
  102685. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102686. }
  102687. else if(encoder->protected_->bits_per_sample == 16) {
  102688. if(encoder->protected_->blocksize <= 192)
  102689. encoder->protected_->qlp_coeff_precision = 7;
  102690. else if(encoder->protected_->blocksize <= 384)
  102691. encoder->protected_->qlp_coeff_precision = 8;
  102692. else if(encoder->protected_->blocksize <= 576)
  102693. encoder->protected_->qlp_coeff_precision = 9;
  102694. else if(encoder->protected_->blocksize <= 1152)
  102695. encoder->protected_->qlp_coeff_precision = 10;
  102696. else if(encoder->protected_->blocksize <= 2304)
  102697. encoder->protected_->qlp_coeff_precision = 11;
  102698. else if(encoder->protected_->blocksize <= 4608)
  102699. encoder->protected_->qlp_coeff_precision = 12;
  102700. else
  102701. encoder->protected_->qlp_coeff_precision = 13;
  102702. }
  102703. else {
  102704. if(encoder->protected_->blocksize <= 384)
  102705. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102706. else if(encoder->protected_->blocksize <= 1152)
  102707. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102708. else
  102709. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102710. }
  102711. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102712. }
  102713. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102714. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102715. if(encoder->protected_->streamable_subset) {
  102716. if(
  102717. encoder->protected_->blocksize != 192 &&
  102718. encoder->protected_->blocksize != 576 &&
  102719. encoder->protected_->blocksize != 1152 &&
  102720. encoder->protected_->blocksize != 2304 &&
  102721. encoder->protected_->blocksize != 4608 &&
  102722. encoder->protected_->blocksize != 256 &&
  102723. encoder->protected_->blocksize != 512 &&
  102724. encoder->protected_->blocksize != 1024 &&
  102725. encoder->protected_->blocksize != 2048 &&
  102726. encoder->protected_->blocksize != 4096 &&
  102727. encoder->protected_->blocksize != 8192 &&
  102728. encoder->protected_->blocksize != 16384
  102729. )
  102730. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102731. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102732. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102733. if(
  102734. encoder->protected_->bits_per_sample != 8 &&
  102735. encoder->protected_->bits_per_sample != 12 &&
  102736. encoder->protected_->bits_per_sample != 16 &&
  102737. encoder->protected_->bits_per_sample != 20 &&
  102738. encoder->protected_->bits_per_sample != 24
  102739. )
  102740. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102741. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102742. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102743. if(
  102744. encoder->protected_->sample_rate <= 48000 &&
  102745. (
  102746. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102747. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102748. )
  102749. ) {
  102750. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102751. }
  102752. }
  102753. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102754. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102755. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102756. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102757. #if FLAC__HAS_OGG
  102758. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102759. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102760. unsigned i;
  102761. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102762. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102763. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102764. for( ; i > 0; i--)
  102765. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102766. encoder->protected_->metadata[0] = vc;
  102767. break;
  102768. }
  102769. }
  102770. }
  102771. #endif
  102772. /* keep track of any SEEKTABLE block */
  102773. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102774. unsigned i;
  102775. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102776. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102777. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102778. break; /* take only the first one */
  102779. }
  102780. }
  102781. }
  102782. /* validate metadata */
  102783. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102784. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102785. metadata_has_seektable = false;
  102786. metadata_has_vorbis_comment = false;
  102787. metadata_picture_has_type1 = false;
  102788. metadata_picture_has_type2 = false;
  102789. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102790. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102791. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102792. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102793. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102794. if(metadata_has_seektable) /* only one is allowed */
  102795. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102796. metadata_has_seektable = true;
  102797. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102798. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102799. }
  102800. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102801. if(metadata_has_vorbis_comment) /* only one is allowed */
  102802. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102803. metadata_has_vorbis_comment = true;
  102804. }
  102805. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102806. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102807. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102808. }
  102809. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102810. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102811. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102812. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102813. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102814. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102815. metadata_picture_has_type1 = true;
  102816. /* standard icon must be 32x32 pixel PNG */
  102817. if(
  102818. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102819. (
  102820. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102821. m->data.picture.width != 32 ||
  102822. m->data.picture.height != 32
  102823. )
  102824. )
  102825. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102826. }
  102827. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102828. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102829. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102830. metadata_picture_has_type2 = true;
  102831. }
  102832. }
  102833. }
  102834. encoder->private_->input_capacity = 0;
  102835. for(i = 0; i < encoder->protected_->channels; i++) {
  102836. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102837. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102838. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102839. #endif
  102840. }
  102841. for(i = 0; i < 2; i++) {
  102842. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102843. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102844. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102845. #endif
  102846. }
  102847. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102848. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102849. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102850. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102851. #endif
  102852. for(i = 0; i < encoder->protected_->channels; i++) {
  102853. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102854. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102855. encoder->private_->best_subframe[i] = 0;
  102856. }
  102857. for(i = 0; i < 2; i++) {
  102858. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102859. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102860. encoder->private_->best_subframe_mid_side[i] = 0;
  102861. }
  102862. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102863. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102864. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102865. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102866. #else
  102867. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102868. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102869. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102870. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102871. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102872. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102873. 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);
  102874. #endif
  102875. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102876. encoder->private_->loose_mid_side_stereo_frames = 1;
  102877. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102878. encoder->private_->current_sample_number = 0;
  102879. encoder->private_->current_frame_number = 0;
  102880. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102881. 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? */
  102882. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102883. /*
  102884. * get the CPU info and set the function pointers
  102885. */
  102886. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102887. /* first default to the non-asm routines */
  102888. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102889. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102890. #endif
  102891. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102892. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102893. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102894. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102895. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102896. #endif
  102897. /* now override with asm where appropriate */
  102898. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102899. # ifndef FLAC__NO_ASM
  102900. if(encoder->private_->cpuinfo.use_asm) {
  102901. # ifdef FLAC__CPU_IA32
  102902. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102903. # ifdef FLAC__HAS_NASM
  102904. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102905. if(encoder->protected_->max_lpc_order < 4)
  102906. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102907. else if(encoder->protected_->max_lpc_order < 8)
  102908. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102909. else if(encoder->protected_->max_lpc_order < 12)
  102910. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102911. else
  102912. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102913. }
  102914. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102915. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102916. else
  102917. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102918. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102919. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102920. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102921. }
  102922. else {
  102923. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102924. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102925. }
  102926. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102927. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102928. # endif /* FLAC__HAS_NASM */
  102929. # endif /* FLAC__CPU_IA32 */
  102930. }
  102931. # endif /* !FLAC__NO_ASM */
  102932. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102933. /* finally override based on wide-ness if necessary */
  102934. if(encoder->private_->use_wide_by_block) {
  102935. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102936. }
  102937. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102938. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102939. #if FLAC__HAS_OGG
  102940. encoder->private_->is_ogg = is_ogg;
  102941. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102942. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102943. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102944. }
  102945. #endif
  102946. encoder->private_->read_callback = read_callback;
  102947. encoder->private_->write_callback = write_callback;
  102948. encoder->private_->seek_callback = seek_callback;
  102949. encoder->private_->tell_callback = tell_callback;
  102950. encoder->private_->metadata_callback = metadata_callback;
  102951. encoder->private_->client_data = client_data;
  102952. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102953. /* the above function sets the state for us in case of an error */
  102954. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102955. }
  102956. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102957. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102958. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102959. }
  102960. /*
  102961. * Set up the verify stuff if necessary
  102962. */
  102963. if(encoder->protected_->verify) {
  102964. /*
  102965. * First, set up the fifo which will hold the
  102966. * original signal to compare against
  102967. */
  102968. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102969. for(i = 0; i < encoder->protected_->channels; i++) {
  102970. 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))) {
  102971. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102972. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102973. }
  102974. }
  102975. encoder->private_->verify.input_fifo.tail = 0;
  102976. /*
  102977. * Now set up a stream decoder for verification
  102978. */
  102979. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102980. if(0 == encoder->private_->verify.decoder) {
  102981. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102982. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102983. }
  102984. 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) {
  102985. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102986. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102987. }
  102988. }
  102989. encoder->private_->verify.error_stats.absolute_sample = 0;
  102990. encoder->private_->verify.error_stats.frame_number = 0;
  102991. encoder->private_->verify.error_stats.channel = 0;
  102992. encoder->private_->verify.error_stats.sample = 0;
  102993. encoder->private_->verify.error_stats.expected = 0;
  102994. encoder->private_->verify.error_stats.got = 0;
  102995. /*
  102996. * These must be done before we write any metadata, because that
  102997. * calls the write_callback, which uses these values.
  102998. */
  102999. encoder->private_->first_seekpoint_to_check = 0;
  103000. encoder->private_->samples_written = 0;
  103001. encoder->protected_->streaminfo_offset = 0;
  103002. encoder->protected_->seektable_offset = 0;
  103003. encoder->protected_->audio_offset = 0;
  103004. /*
  103005. * write the stream header
  103006. */
  103007. if(encoder->protected_->verify)
  103008. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103009. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103010. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103011. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103012. }
  103013. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103014. /* the above function sets the state for us in case of an error */
  103015. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103016. }
  103017. /*
  103018. * write the STREAMINFO metadata block
  103019. */
  103020. if(encoder->protected_->verify)
  103021. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103022. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103023. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103024. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103025. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103026. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103027. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103028. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103029. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103030. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103031. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103032. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103033. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103034. if(encoder->protected_->do_md5)
  103035. FLAC__MD5Init(&encoder->private_->md5context);
  103036. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103037. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103038. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103039. }
  103040. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103041. /* the above function sets the state for us in case of an error */
  103042. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103043. }
  103044. /*
  103045. * Now that the STREAMINFO block is written, we can init this to an
  103046. * absurdly-high value...
  103047. */
  103048. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103049. /* ... and clear this to 0 */
  103050. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103051. /*
  103052. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103053. * if not, we will write an empty one (FLAC__add_metadata_block()
  103054. * automatically supplies the vendor string).
  103055. *
  103056. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103057. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103058. * true it will have already insured that the metadata list is properly
  103059. * ordered.)
  103060. */
  103061. if(!metadata_has_vorbis_comment) {
  103062. FLAC__StreamMetadata vorbis_comment;
  103063. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103064. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103065. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103066. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103067. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103068. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103069. vorbis_comment.data.vorbis_comment.comments = 0;
  103070. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103071. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103072. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103073. }
  103074. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103075. /* the above function sets the state for us in case of an error */
  103076. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103077. }
  103078. }
  103079. /*
  103080. * write the user's metadata blocks
  103081. */
  103082. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103083. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103084. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103085. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103086. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103087. }
  103088. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103089. /* the above function sets the state for us in case of an error */
  103090. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103091. }
  103092. }
  103093. /* now that all the metadata is written, we save the stream offset */
  103094. 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 */
  103095. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103096. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103097. }
  103098. if(encoder->protected_->verify)
  103099. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103100. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103101. }
  103102. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103103. FLAC__StreamEncoder *encoder,
  103104. FLAC__StreamEncoderWriteCallback write_callback,
  103105. FLAC__StreamEncoderSeekCallback seek_callback,
  103106. FLAC__StreamEncoderTellCallback tell_callback,
  103107. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103108. void *client_data
  103109. )
  103110. {
  103111. return init_stream_internal_enc(
  103112. encoder,
  103113. /*read_callback=*/0,
  103114. write_callback,
  103115. seek_callback,
  103116. tell_callback,
  103117. metadata_callback,
  103118. client_data,
  103119. /*is_ogg=*/false
  103120. );
  103121. }
  103122. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103123. FLAC__StreamEncoder *encoder,
  103124. FLAC__StreamEncoderReadCallback read_callback,
  103125. FLAC__StreamEncoderWriteCallback write_callback,
  103126. FLAC__StreamEncoderSeekCallback seek_callback,
  103127. FLAC__StreamEncoderTellCallback tell_callback,
  103128. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103129. void *client_data
  103130. )
  103131. {
  103132. return init_stream_internal_enc(
  103133. encoder,
  103134. read_callback,
  103135. write_callback,
  103136. seek_callback,
  103137. tell_callback,
  103138. metadata_callback,
  103139. client_data,
  103140. /*is_ogg=*/true
  103141. );
  103142. }
  103143. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103144. FLAC__StreamEncoder *encoder,
  103145. FILE *file,
  103146. FLAC__StreamEncoderProgressCallback progress_callback,
  103147. void *client_data,
  103148. FLAC__bool is_ogg
  103149. )
  103150. {
  103151. FLAC__StreamEncoderInitStatus init_status;
  103152. FLAC__ASSERT(0 != encoder);
  103153. FLAC__ASSERT(0 != file);
  103154. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103155. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103156. /* double protection */
  103157. if(file == 0) {
  103158. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103159. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103160. }
  103161. /*
  103162. * To make sure that our file does not go unclosed after an error, we
  103163. * must assign the FILE pointer before any further error can occur in
  103164. * this routine.
  103165. */
  103166. if(file == stdout)
  103167. file = get_binary_stdout_(); /* just to be safe */
  103168. encoder->private_->file = file;
  103169. encoder->private_->progress_callback = progress_callback;
  103170. encoder->private_->bytes_written = 0;
  103171. encoder->private_->samples_written = 0;
  103172. encoder->private_->frames_written = 0;
  103173. init_status = init_stream_internal_enc(
  103174. encoder,
  103175. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103176. file_write_callback_,
  103177. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103178. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103179. /*metadata_callback=*/0,
  103180. client_data,
  103181. is_ogg
  103182. );
  103183. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103184. /* the above function sets the state for us in case of an error */
  103185. return init_status;
  103186. }
  103187. {
  103188. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103189. FLAC__ASSERT(blocksize != 0);
  103190. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103191. }
  103192. return init_status;
  103193. }
  103194. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103195. FLAC__StreamEncoder *encoder,
  103196. FILE *file,
  103197. FLAC__StreamEncoderProgressCallback progress_callback,
  103198. void *client_data
  103199. )
  103200. {
  103201. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103202. }
  103203. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103204. FLAC__StreamEncoder *encoder,
  103205. FILE *file,
  103206. FLAC__StreamEncoderProgressCallback progress_callback,
  103207. void *client_data
  103208. )
  103209. {
  103210. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103211. }
  103212. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103213. FLAC__StreamEncoder *encoder,
  103214. const char *filename,
  103215. FLAC__StreamEncoderProgressCallback progress_callback,
  103216. void *client_data,
  103217. FLAC__bool is_ogg
  103218. )
  103219. {
  103220. FILE *file;
  103221. FLAC__ASSERT(0 != encoder);
  103222. /*
  103223. * To make sure that our file does not go unclosed after an error, we
  103224. * have to do the same entrance checks here that are later performed
  103225. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103226. */
  103227. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103228. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103229. file = filename? fopen(filename, "w+b") : stdout;
  103230. if(file == 0) {
  103231. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103232. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103233. }
  103234. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103235. }
  103236. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103237. FLAC__StreamEncoder *encoder,
  103238. const char *filename,
  103239. FLAC__StreamEncoderProgressCallback progress_callback,
  103240. void *client_data
  103241. )
  103242. {
  103243. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103244. }
  103245. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103246. FLAC__StreamEncoder *encoder,
  103247. const char *filename,
  103248. FLAC__StreamEncoderProgressCallback progress_callback,
  103249. void *client_data
  103250. )
  103251. {
  103252. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103253. }
  103254. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103255. {
  103256. FLAC__bool error = false;
  103257. FLAC__ASSERT(0 != encoder);
  103258. FLAC__ASSERT(0 != encoder->private_);
  103259. FLAC__ASSERT(0 != encoder->protected_);
  103260. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103261. return true;
  103262. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103263. if(encoder->private_->current_sample_number != 0) {
  103264. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103265. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103266. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103267. error = true;
  103268. }
  103269. }
  103270. if(encoder->protected_->do_md5)
  103271. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103272. if(!encoder->private_->is_being_deleted) {
  103273. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103274. if(encoder->private_->seek_callback) {
  103275. #if FLAC__HAS_OGG
  103276. if(encoder->private_->is_ogg)
  103277. update_ogg_metadata_(encoder);
  103278. else
  103279. #endif
  103280. update_metadata_(encoder);
  103281. /* check if an error occurred while updating metadata */
  103282. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103283. error = true;
  103284. }
  103285. if(encoder->private_->metadata_callback)
  103286. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103287. }
  103288. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103289. if(!error)
  103290. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103291. error = true;
  103292. }
  103293. }
  103294. if(0 != encoder->private_->file) {
  103295. if(encoder->private_->file != stdout)
  103296. fclose(encoder->private_->file);
  103297. encoder->private_->file = 0;
  103298. }
  103299. #if FLAC__HAS_OGG
  103300. if(encoder->private_->is_ogg)
  103301. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103302. #endif
  103303. free_(encoder);
  103304. set_defaults_enc(encoder);
  103305. if(!error)
  103306. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103307. return !error;
  103308. }
  103309. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103310. {
  103311. FLAC__ASSERT(0 != encoder);
  103312. FLAC__ASSERT(0 != encoder->private_);
  103313. FLAC__ASSERT(0 != encoder->protected_);
  103314. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103315. return false;
  103316. #if FLAC__HAS_OGG
  103317. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103318. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103319. return true;
  103320. #else
  103321. (void)value;
  103322. return false;
  103323. #endif
  103324. }
  103325. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103326. {
  103327. FLAC__ASSERT(0 != encoder);
  103328. FLAC__ASSERT(0 != encoder->private_);
  103329. FLAC__ASSERT(0 != encoder->protected_);
  103330. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103331. return false;
  103332. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103333. encoder->protected_->verify = value;
  103334. #endif
  103335. return true;
  103336. }
  103337. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103338. {
  103339. FLAC__ASSERT(0 != encoder);
  103340. FLAC__ASSERT(0 != encoder->private_);
  103341. FLAC__ASSERT(0 != encoder->protected_);
  103342. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103343. return false;
  103344. encoder->protected_->streamable_subset = value;
  103345. return true;
  103346. }
  103347. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103348. {
  103349. FLAC__ASSERT(0 != encoder);
  103350. FLAC__ASSERT(0 != encoder->private_);
  103351. FLAC__ASSERT(0 != encoder->protected_);
  103352. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103353. return false;
  103354. encoder->protected_->do_md5 = value;
  103355. return true;
  103356. }
  103357. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103358. {
  103359. FLAC__ASSERT(0 != encoder);
  103360. FLAC__ASSERT(0 != encoder->private_);
  103361. FLAC__ASSERT(0 != encoder->protected_);
  103362. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103363. return false;
  103364. encoder->protected_->channels = value;
  103365. return true;
  103366. }
  103367. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103368. {
  103369. FLAC__ASSERT(0 != encoder);
  103370. FLAC__ASSERT(0 != encoder->private_);
  103371. FLAC__ASSERT(0 != encoder->protected_);
  103372. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103373. return false;
  103374. encoder->protected_->bits_per_sample = value;
  103375. return true;
  103376. }
  103377. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103378. {
  103379. FLAC__ASSERT(0 != encoder);
  103380. FLAC__ASSERT(0 != encoder->private_);
  103381. FLAC__ASSERT(0 != encoder->protected_);
  103382. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103383. return false;
  103384. encoder->protected_->sample_rate = value;
  103385. return true;
  103386. }
  103387. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103388. {
  103389. FLAC__bool ok = true;
  103390. FLAC__ASSERT(0 != encoder);
  103391. FLAC__ASSERT(0 != encoder->private_);
  103392. FLAC__ASSERT(0 != encoder->protected_);
  103393. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103394. return false;
  103395. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103396. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103397. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103398. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103399. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103400. #if 0
  103401. /* was: */
  103402. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103403. /* but it's too hard to specify the string in a locale-specific way */
  103404. #else
  103405. encoder->protected_->num_apodizations = 1;
  103406. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103407. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103408. #endif
  103409. #endif
  103410. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103411. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103412. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103413. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103414. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103415. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103416. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103417. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103418. return ok;
  103419. }
  103420. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103421. {
  103422. FLAC__ASSERT(0 != encoder);
  103423. FLAC__ASSERT(0 != encoder->private_);
  103424. FLAC__ASSERT(0 != encoder->protected_);
  103425. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103426. return false;
  103427. encoder->protected_->blocksize = value;
  103428. return true;
  103429. }
  103430. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103431. {
  103432. FLAC__ASSERT(0 != encoder);
  103433. FLAC__ASSERT(0 != encoder->private_);
  103434. FLAC__ASSERT(0 != encoder->protected_);
  103435. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103436. return false;
  103437. encoder->protected_->do_mid_side_stereo = value;
  103438. return true;
  103439. }
  103440. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103441. {
  103442. FLAC__ASSERT(0 != encoder);
  103443. FLAC__ASSERT(0 != encoder->private_);
  103444. FLAC__ASSERT(0 != encoder->protected_);
  103445. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103446. return false;
  103447. encoder->protected_->loose_mid_side_stereo = value;
  103448. return true;
  103449. }
  103450. /*@@@@add to tests*/
  103451. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103452. {
  103453. FLAC__ASSERT(0 != encoder);
  103454. FLAC__ASSERT(0 != encoder->private_);
  103455. FLAC__ASSERT(0 != encoder->protected_);
  103456. FLAC__ASSERT(0 != specification);
  103457. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103458. return false;
  103459. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103460. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103461. #else
  103462. encoder->protected_->num_apodizations = 0;
  103463. while(1) {
  103464. const char *s = strchr(specification, ';');
  103465. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103466. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103467. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103468. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103469. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103470. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103471. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103472. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103473. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103474. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103475. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103476. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103477. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103478. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103479. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103480. if (stddev > 0.0 && stddev <= 0.5) {
  103481. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103482. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103483. }
  103484. }
  103485. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103486. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103487. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103488. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103489. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103490. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103491. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103492. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103493. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103494. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103495. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103496. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103497. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103498. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103499. if (p >= 0.0 && p <= 1.0) {
  103500. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103501. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103502. }
  103503. }
  103504. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103505. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103506. if (encoder->protected_->num_apodizations == 32)
  103507. break;
  103508. if (s)
  103509. specification = s+1;
  103510. else
  103511. break;
  103512. }
  103513. if(encoder->protected_->num_apodizations == 0) {
  103514. encoder->protected_->num_apodizations = 1;
  103515. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103516. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103517. }
  103518. #endif
  103519. return true;
  103520. }
  103521. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103522. {
  103523. FLAC__ASSERT(0 != encoder);
  103524. FLAC__ASSERT(0 != encoder->private_);
  103525. FLAC__ASSERT(0 != encoder->protected_);
  103526. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103527. return false;
  103528. encoder->protected_->max_lpc_order = value;
  103529. return true;
  103530. }
  103531. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103532. {
  103533. FLAC__ASSERT(0 != encoder);
  103534. FLAC__ASSERT(0 != encoder->private_);
  103535. FLAC__ASSERT(0 != encoder->protected_);
  103536. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103537. return false;
  103538. encoder->protected_->qlp_coeff_precision = value;
  103539. return true;
  103540. }
  103541. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103542. {
  103543. FLAC__ASSERT(0 != encoder);
  103544. FLAC__ASSERT(0 != encoder->private_);
  103545. FLAC__ASSERT(0 != encoder->protected_);
  103546. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103547. return false;
  103548. encoder->protected_->do_qlp_coeff_prec_search = value;
  103549. return true;
  103550. }
  103551. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103552. {
  103553. FLAC__ASSERT(0 != encoder);
  103554. FLAC__ASSERT(0 != encoder->private_);
  103555. FLAC__ASSERT(0 != encoder->protected_);
  103556. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103557. return false;
  103558. #if 0
  103559. /*@@@ deprecated: */
  103560. encoder->protected_->do_escape_coding = value;
  103561. #else
  103562. (void)value;
  103563. #endif
  103564. return true;
  103565. }
  103566. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103567. {
  103568. FLAC__ASSERT(0 != encoder);
  103569. FLAC__ASSERT(0 != encoder->private_);
  103570. FLAC__ASSERT(0 != encoder->protected_);
  103571. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103572. return false;
  103573. encoder->protected_->do_exhaustive_model_search = value;
  103574. return true;
  103575. }
  103576. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103577. {
  103578. FLAC__ASSERT(0 != encoder);
  103579. FLAC__ASSERT(0 != encoder->private_);
  103580. FLAC__ASSERT(0 != encoder->protected_);
  103581. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103582. return false;
  103583. encoder->protected_->min_residual_partition_order = value;
  103584. return true;
  103585. }
  103586. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103587. {
  103588. FLAC__ASSERT(0 != encoder);
  103589. FLAC__ASSERT(0 != encoder->private_);
  103590. FLAC__ASSERT(0 != encoder->protected_);
  103591. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103592. return false;
  103593. encoder->protected_->max_residual_partition_order = value;
  103594. return true;
  103595. }
  103596. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103597. {
  103598. FLAC__ASSERT(0 != encoder);
  103599. FLAC__ASSERT(0 != encoder->private_);
  103600. FLAC__ASSERT(0 != encoder->protected_);
  103601. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103602. return false;
  103603. #if 0
  103604. /*@@@ deprecated: */
  103605. encoder->protected_->rice_parameter_search_dist = value;
  103606. #else
  103607. (void)value;
  103608. #endif
  103609. return true;
  103610. }
  103611. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103612. {
  103613. FLAC__ASSERT(0 != encoder);
  103614. FLAC__ASSERT(0 != encoder->private_);
  103615. FLAC__ASSERT(0 != encoder->protected_);
  103616. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103617. return false;
  103618. encoder->protected_->total_samples_estimate = value;
  103619. return true;
  103620. }
  103621. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103622. {
  103623. FLAC__ASSERT(0 != encoder);
  103624. FLAC__ASSERT(0 != encoder->private_);
  103625. FLAC__ASSERT(0 != encoder->protected_);
  103626. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103627. return false;
  103628. if(0 == metadata)
  103629. num_blocks = 0;
  103630. if(0 == num_blocks)
  103631. metadata = 0;
  103632. /* realloc() does not do exactly what we want so... */
  103633. if(encoder->protected_->metadata) {
  103634. free(encoder->protected_->metadata);
  103635. encoder->protected_->metadata = 0;
  103636. encoder->protected_->num_metadata_blocks = 0;
  103637. }
  103638. if(num_blocks) {
  103639. FLAC__StreamMetadata **m;
  103640. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103641. return false;
  103642. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103643. encoder->protected_->metadata = m;
  103644. encoder->protected_->num_metadata_blocks = num_blocks;
  103645. }
  103646. #if FLAC__HAS_OGG
  103647. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103648. return false;
  103649. #endif
  103650. return true;
  103651. }
  103652. /*
  103653. * These three functions are not static, but not publically exposed in
  103654. * include/FLAC/ either. They are used by the test suite.
  103655. */
  103656. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103657. {
  103658. FLAC__ASSERT(0 != encoder);
  103659. FLAC__ASSERT(0 != encoder->private_);
  103660. FLAC__ASSERT(0 != encoder->protected_);
  103661. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103662. return false;
  103663. encoder->private_->disable_constant_subframes = value;
  103664. return true;
  103665. }
  103666. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103667. {
  103668. FLAC__ASSERT(0 != encoder);
  103669. FLAC__ASSERT(0 != encoder->private_);
  103670. FLAC__ASSERT(0 != encoder->protected_);
  103671. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103672. return false;
  103673. encoder->private_->disable_fixed_subframes = value;
  103674. return true;
  103675. }
  103676. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103677. {
  103678. FLAC__ASSERT(0 != encoder);
  103679. FLAC__ASSERT(0 != encoder->private_);
  103680. FLAC__ASSERT(0 != encoder->protected_);
  103681. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103682. return false;
  103683. encoder->private_->disable_verbatim_subframes = value;
  103684. return true;
  103685. }
  103686. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103687. {
  103688. FLAC__ASSERT(0 != encoder);
  103689. FLAC__ASSERT(0 != encoder->private_);
  103690. FLAC__ASSERT(0 != encoder->protected_);
  103691. return encoder->protected_->state;
  103692. }
  103693. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103694. {
  103695. FLAC__ASSERT(0 != encoder);
  103696. FLAC__ASSERT(0 != encoder->private_);
  103697. FLAC__ASSERT(0 != encoder->protected_);
  103698. if(encoder->protected_->verify)
  103699. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103700. else
  103701. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103702. }
  103703. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103704. {
  103705. FLAC__ASSERT(0 != encoder);
  103706. FLAC__ASSERT(0 != encoder->private_);
  103707. FLAC__ASSERT(0 != encoder->protected_);
  103708. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103709. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103710. else
  103711. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103712. }
  103713. 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)
  103714. {
  103715. FLAC__ASSERT(0 != encoder);
  103716. FLAC__ASSERT(0 != encoder->private_);
  103717. FLAC__ASSERT(0 != encoder->protected_);
  103718. if(0 != absolute_sample)
  103719. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103720. if(0 != frame_number)
  103721. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103722. if(0 != channel)
  103723. *channel = encoder->private_->verify.error_stats.channel;
  103724. if(0 != sample)
  103725. *sample = encoder->private_->verify.error_stats.sample;
  103726. if(0 != expected)
  103727. *expected = encoder->private_->verify.error_stats.expected;
  103728. if(0 != got)
  103729. *got = encoder->private_->verify.error_stats.got;
  103730. }
  103731. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103732. {
  103733. FLAC__ASSERT(0 != encoder);
  103734. FLAC__ASSERT(0 != encoder->private_);
  103735. FLAC__ASSERT(0 != encoder->protected_);
  103736. return encoder->protected_->verify;
  103737. }
  103738. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103739. {
  103740. FLAC__ASSERT(0 != encoder);
  103741. FLAC__ASSERT(0 != encoder->private_);
  103742. FLAC__ASSERT(0 != encoder->protected_);
  103743. return encoder->protected_->streamable_subset;
  103744. }
  103745. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103746. {
  103747. FLAC__ASSERT(0 != encoder);
  103748. FLAC__ASSERT(0 != encoder->private_);
  103749. FLAC__ASSERT(0 != encoder->protected_);
  103750. return encoder->protected_->do_md5;
  103751. }
  103752. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103753. {
  103754. FLAC__ASSERT(0 != encoder);
  103755. FLAC__ASSERT(0 != encoder->private_);
  103756. FLAC__ASSERT(0 != encoder->protected_);
  103757. return encoder->protected_->channels;
  103758. }
  103759. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103760. {
  103761. FLAC__ASSERT(0 != encoder);
  103762. FLAC__ASSERT(0 != encoder->private_);
  103763. FLAC__ASSERT(0 != encoder->protected_);
  103764. return encoder->protected_->bits_per_sample;
  103765. }
  103766. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103767. {
  103768. FLAC__ASSERT(0 != encoder);
  103769. FLAC__ASSERT(0 != encoder->private_);
  103770. FLAC__ASSERT(0 != encoder->protected_);
  103771. return encoder->protected_->sample_rate;
  103772. }
  103773. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103774. {
  103775. FLAC__ASSERT(0 != encoder);
  103776. FLAC__ASSERT(0 != encoder->private_);
  103777. FLAC__ASSERT(0 != encoder->protected_);
  103778. return encoder->protected_->blocksize;
  103779. }
  103780. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103781. {
  103782. FLAC__ASSERT(0 != encoder);
  103783. FLAC__ASSERT(0 != encoder->private_);
  103784. FLAC__ASSERT(0 != encoder->protected_);
  103785. return encoder->protected_->do_mid_side_stereo;
  103786. }
  103787. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103788. {
  103789. FLAC__ASSERT(0 != encoder);
  103790. FLAC__ASSERT(0 != encoder->private_);
  103791. FLAC__ASSERT(0 != encoder->protected_);
  103792. return encoder->protected_->loose_mid_side_stereo;
  103793. }
  103794. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103795. {
  103796. FLAC__ASSERT(0 != encoder);
  103797. FLAC__ASSERT(0 != encoder->private_);
  103798. FLAC__ASSERT(0 != encoder->protected_);
  103799. return encoder->protected_->max_lpc_order;
  103800. }
  103801. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103802. {
  103803. FLAC__ASSERT(0 != encoder);
  103804. FLAC__ASSERT(0 != encoder->private_);
  103805. FLAC__ASSERT(0 != encoder->protected_);
  103806. return encoder->protected_->qlp_coeff_precision;
  103807. }
  103808. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103809. {
  103810. FLAC__ASSERT(0 != encoder);
  103811. FLAC__ASSERT(0 != encoder->private_);
  103812. FLAC__ASSERT(0 != encoder->protected_);
  103813. return encoder->protected_->do_qlp_coeff_prec_search;
  103814. }
  103815. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103816. {
  103817. FLAC__ASSERT(0 != encoder);
  103818. FLAC__ASSERT(0 != encoder->private_);
  103819. FLAC__ASSERT(0 != encoder->protected_);
  103820. return encoder->protected_->do_escape_coding;
  103821. }
  103822. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103823. {
  103824. FLAC__ASSERT(0 != encoder);
  103825. FLAC__ASSERT(0 != encoder->private_);
  103826. FLAC__ASSERT(0 != encoder->protected_);
  103827. return encoder->protected_->do_exhaustive_model_search;
  103828. }
  103829. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103830. {
  103831. FLAC__ASSERT(0 != encoder);
  103832. FLAC__ASSERT(0 != encoder->private_);
  103833. FLAC__ASSERT(0 != encoder->protected_);
  103834. return encoder->protected_->min_residual_partition_order;
  103835. }
  103836. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103837. {
  103838. FLAC__ASSERT(0 != encoder);
  103839. FLAC__ASSERT(0 != encoder->private_);
  103840. FLAC__ASSERT(0 != encoder->protected_);
  103841. return encoder->protected_->max_residual_partition_order;
  103842. }
  103843. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103844. {
  103845. FLAC__ASSERT(0 != encoder);
  103846. FLAC__ASSERT(0 != encoder->private_);
  103847. FLAC__ASSERT(0 != encoder->protected_);
  103848. return encoder->protected_->rice_parameter_search_dist;
  103849. }
  103850. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103851. {
  103852. FLAC__ASSERT(0 != encoder);
  103853. FLAC__ASSERT(0 != encoder->private_);
  103854. FLAC__ASSERT(0 != encoder->protected_);
  103855. return encoder->protected_->total_samples_estimate;
  103856. }
  103857. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103858. {
  103859. unsigned i, j = 0, channel;
  103860. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103861. FLAC__ASSERT(0 != encoder);
  103862. FLAC__ASSERT(0 != encoder->private_);
  103863. FLAC__ASSERT(0 != encoder->protected_);
  103864. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103865. do {
  103866. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103867. if(encoder->protected_->verify)
  103868. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103869. for(channel = 0; channel < channels; channel++)
  103870. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103871. if(encoder->protected_->do_mid_side_stereo) {
  103872. FLAC__ASSERT(channels == 2);
  103873. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103874. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103875. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103876. 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' ! */
  103877. }
  103878. }
  103879. else
  103880. j += n;
  103881. encoder->private_->current_sample_number += n;
  103882. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103883. if(encoder->private_->current_sample_number > blocksize) {
  103884. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103885. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103886. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103887. return false;
  103888. /* move unprocessed overread samples to beginnings of arrays */
  103889. for(channel = 0; channel < channels; channel++)
  103890. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103891. if(encoder->protected_->do_mid_side_stereo) {
  103892. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103893. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103894. }
  103895. encoder->private_->current_sample_number = 1;
  103896. }
  103897. } while(j < samples);
  103898. return true;
  103899. }
  103900. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103901. {
  103902. unsigned i, j, k, channel;
  103903. FLAC__int32 x, mid, side;
  103904. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103905. FLAC__ASSERT(0 != encoder);
  103906. FLAC__ASSERT(0 != encoder->private_);
  103907. FLAC__ASSERT(0 != encoder->protected_);
  103908. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103909. j = k = 0;
  103910. /*
  103911. * we have several flavors of the same basic loop, optimized for
  103912. * different conditions:
  103913. */
  103914. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103915. /*
  103916. * stereo coding: unroll channel loop
  103917. */
  103918. do {
  103919. if(encoder->protected_->verify)
  103920. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103921. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103922. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103923. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103924. x = buffer[k++];
  103925. encoder->private_->integer_signal[1][i] = x;
  103926. mid += x;
  103927. side -= x;
  103928. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103929. encoder->private_->integer_signal_mid_side[1][i] = side;
  103930. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103931. }
  103932. encoder->private_->current_sample_number = i;
  103933. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103934. if(i > blocksize) {
  103935. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103936. return false;
  103937. /* move unprocessed overread samples to beginnings of arrays */
  103938. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103939. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103940. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103941. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103942. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103943. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103944. encoder->private_->current_sample_number = 1;
  103945. }
  103946. } while(j < samples);
  103947. }
  103948. else {
  103949. /*
  103950. * independent channel coding: buffer each channel in inner loop
  103951. */
  103952. do {
  103953. if(encoder->protected_->verify)
  103954. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103955. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103956. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103957. for(channel = 0; channel < channels; channel++)
  103958. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103959. }
  103960. encoder->private_->current_sample_number = i;
  103961. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103962. if(i > blocksize) {
  103963. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103964. return false;
  103965. /* move unprocessed overread samples to beginnings of arrays */
  103966. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103967. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103968. for(channel = 0; channel < channels; channel++)
  103969. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103970. encoder->private_->current_sample_number = 1;
  103971. }
  103972. } while(j < samples);
  103973. }
  103974. return true;
  103975. }
  103976. /***********************************************************************
  103977. *
  103978. * Private class methods
  103979. *
  103980. ***********************************************************************/
  103981. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103982. {
  103983. FLAC__ASSERT(0 != encoder);
  103984. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103985. encoder->protected_->verify = true;
  103986. #else
  103987. encoder->protected_->verify = false;
  103988. #endif
  103989. encoder->protected_->streamable_subset = true;
  103990. encoder->protected_->do_md5 = true;
  103991. encoder->protected_->do_mid_side_stereo = false;
  103992. encoder->protected_->loose_mid_side_stereo = false;
  103993. encoder->protected_->channels = 2;
  103994. encoder->protected_->bits_per_sample = 16;
  103995. encoder->protected_->sample_rate = 44100;
  103996. encoder->protected_->blocksize = 0;
  103997. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103998. encoder->protected_->num_apodizations = 1;
  103999. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104000. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104001. #endif
  104002. encoder->protected_->max_lpc_order = 0;
  104003. encoder->protected_->qlp_coeff_precision = 0;
  104004. encoder->protected_->do_qlp_coeff_prec_search = false;
  104005. encoder->protected_->do_exhaustive_model_search = false;
  104006. encoder->protected_->do_escape_coding = false;
  104007. encoder->protected_->min_residual_partition_order = 0;
  104008. encoder->protected_->max_residual_partition_order = 0;
  104009. encoder->protected_->rice_parameter_search_dist = 0;
  104010. encoder->protected_->total_samples_estimate = 0;
  104011. encoder->protected_->metadata = 0;
  104012. encoder->protected_->num_metadata_blocks = 0;
  104013. encoder->private_->seek_table = 0;
  104014. encoder->private_->disable_constant_subframes = false;
  104015. encoder->private_->disable_fixed_subframes = false;
  104016. encoder->private_->disable_verbatim_subframes = false;
  104017. #if FLAC__HAS_OGG
  104018. encoder->private_->is_ogg = false;
  104019. #endif
  104020. encoder->private_->read_callback = 0;
  104021. encoder->private_->write_callback = 0;
  104022. encoder->private_->seek_callback = 0;
  104023. encoder->private_->tell_callback = 0;
  104024. encoder->private_->metadata_callback = 0;
  104025. encoder->private_->progress_callback = 0;
  104026. encoder->private_->client_data = 0;
  104027. #if FLAC__HAS_OGG
  104028. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104029. #endif
  104030. }
  104031. void free_(FLAC__StreamEncoder *encoder)
  104032. {
  104033. unsigned i, channel;
  104034. FLAC__ASSERT(0 != encoder);
  104035. if(encoder->protected_->metadata) {
  104036. free(encoder->protected_->metadata);
  104037. encoder->protected_->metadata = 0;
  104038. encoder->protected_->num_metadata_blocks = 0;
  104039. }
  104040. for(i = 0; i < encoder->protected_->channels; i++) {
  104041. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104042. free(encoder->private_->integer_signal_unaligned[i]);
  104043. encoder->private_->integer_signal_unaligned[i] = 0;
  104044. }
  104045. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104046. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104047. free(encoder->private_->real_signal_unaligned[i]);
  104048. encoder->private_->real_signal_unaligned[i] = 0;
  104049. }
  104050. #endif
  104051. }
  104052. for(i = 0; i < 2; i++) {
  104053. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104054. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104055. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104056. }
  104057. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104058. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104059. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104060. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104061. }
  104062. #endif
  104063. }
  104064. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104065. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104066. if(0 != encoder->private_->window_unaligned[i]) {
  104067. free(encoder->private_->window_unaligned[i]);
  104068. encoder->private_->window_unaligned[i] = 0;
  104069. }
  104070. }
  104071. if(0 != encoder->private_->windowed_signal_unaligned) {
  104072. free(encoder->private_->windowed_signal_unaligned);
  104073. encoder->private_->windowed_signal_unaligned = 0;
  104074. }
  104075. #endif
  104076. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104077. for(i = 0; i < 2; i++) {
  104078. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104079. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104080. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104081. }
  104082. }
  104083. }
  104084. for(channel = 0; channel < 2; channel++) {
  104085. for(i = 0; i < 2; i++) {
  104086. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104087. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104088. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104089. }
  104090. }
  104091. }
  104092. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104093. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104094. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104095. }
  104096. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104097. free(encoder->private_->raw_bits_per_partition_unaligned);
  104098. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104099. }
  104100. if(encoder->protected_->verify) {
  104101. for(i = 0; i < encoder->protected_->channels; i++) {
  104102. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104103. free(encoder->private_->verify.input_fifo.data[i]);
  104104. encoder->private_->verify.input_fifo.data[i] = 0;
  104105. }
  104106. }
  104107. }
  104108. FLAC__bitwriter_free(encoder->private_->frame);
  104109. }
  104110. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104111. {
  104112. FLAC__bool ok;
  104113. unsigned i, channel;
  104114. FLAC__ASSERT(new_blocksize > 0);
  104115. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104116. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104117. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104118. if(new_blocksize <= encoder->private_->input_capacity)
  104119. return true;
  104120. ok = true;
  104121. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104122. * requires that the input arrays (in our case the integer signals)
  104123. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104124. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104125. */
  104126. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104127. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104128. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104129. encoder->private_->integer_signal[i] += 4;
  104130. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104131. #if 0 /* @@@ currently unused */
  104132. if(encoder->protected_->max_lpc_order > 0)
  104133. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104134. #endif
  104135. #endif
  104136. }
  104137. for(i = 0; ok && i < 2; i++) {
  104138. 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]);
  104139. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104140. encoder->private_->integer_signal_mid_side[i] += 4;
  104141. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104142. #if 0 /* @@@ currently unused */
  104143. if(encoder->protected_->max_lpc_order > 0)
  104144. 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]);
  104145. #endif
  104146. #endif
  104147. }
  104148. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104149. if(ok && encoder->protected_->max_lpc_order > 0) {
  104150. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104151. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104152. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104153. }
  104154. #endif
  104155. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104156. for(i = 0; ok && i < 2; i++) {
  104157. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104158. }
  104159. }
  104160. for(channel = 0; ok && channel < 2; channel++) {
  104161. for(i = 0; ok && i < 2; i++) {
  104162. 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]);
  104163. }
  104164. }
  104165. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104166. /*@@@ 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) */
  104167. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104168. if(encoder->protected_->do_escape_coding)
  104169. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104170. /* now adjust the windows if the blocksize has changed */
  104171. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104172. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104173. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104174. switch(encoder->protected_->apodizations[i].type) {
  104175. case FLAC__APODIZATION_BARTLETT:
  104176. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104177. break;
  104178. case FLAC__APODIZATION_BARTLETT_HANN:
  104179. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104180. break;
  104181. case FLAC__APODIZATION_BLACKMAN:
  104182. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104183. break;
  104184. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104185. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104186. break;
  104187. case FLAC__APODIZATION_CONNES:
  104188. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104189. break;
  104190. case FLAC__APODIZATION_FLATTOP:
  104191. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104192. break;
  104193. case FLAC__APODIZATION_GAUSS:
  104194. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104195. break;
  104196. case FLAC__APODIZATION_HAMMING:
  104197. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104198. break;
  104199. case FLAC__APODIZATION_HANN:
  104200. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104201. break;
  104202. case FLAC__APODIZATION_KAISER_BESSEL:
  104203. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104204. break;
  104205. case FLAC__APODIZATION_NUTTALL:
  104206. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104207. break;
  104208. case FLAC__APODIZATION_RECTANGLE:
  104209. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104210. break;
  104211. case FLAC__APODIZATION_TRIANGLE:
  104212. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104213. break;
  104214. case FLAC__APODIZATION_TUKEY:
  104215. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104216. break;
  104217. case FLAC__APODIZATION_WELCH:
  104218. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104219. break;
  104220. default:
  104221. FLAC__ASSERT(0);
  104222. /* double protection */
  104223. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104224. break;
  104225. }
  104226. }
  104227. }
  104228. #endif
  104229. if(ok)
  104230. encoder->private_->input_capacity = new_blocksize;
  104231. else
  104232. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104233. return ok;
  104234. }
  104235. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104236. {
  104237. const FLAC__byte *buffer;
  104238. size_t bytes;
  104239. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104240. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104241. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104242. return false;
  104243. }
  104244. if(encoder->protected_->verify) {
  104245. encoder->private_->verify.output.data = buffer;
  104246. encoder->private_->verify.output.bytes = bytes;
  104247. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104248. encoder->private_->verify.needs_magic_hack = true;
  104249. }
  104250. else {
  104251. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104252. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104253. FLAC__bitwriter_clear(encoder->private_->frame);
  104254. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104255. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104256. return false;
  104257. }
  104258. }
  104259. }
  104260. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104261. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104262. FLAC__bitwriter_clear(encoder->private_->frame);
  104263. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104264. return false;
  104265. }
  104266. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104267. FLAC__bitwriter_clear(encoder->private_->frame);
  104268. if(samples > 0) {
  104269. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104270. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104271. }
  104272. return true;
  104273. }
  104274. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104275. {
  104276. FLAC__StreamEncoderWriteStatus status;
  104277. FLAC__uint64 output_position = 0;
  104278. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104279. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104280. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104281. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104282. }
  104283. /*
  104284. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104285. */
  104286. if(samples == 0) {
  104287. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104288. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104289. encoder->protected_->streaminfo_offset = output_position;
  104290. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104291. encoder->protected_->seektable_offset = output_position;
  104292. }
  104293. /*
  104294. * Mark the current seek point if hit (if audio_offset == 0 that
  104295. * means we're still writing metadata and haven't hit the first
  104296. * frame yet)
  104297. */
  104298. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104299. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104300. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104301. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104302. FLAC__uint64 test_sample;
  104303. unsigned i;
  104304. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104305. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104306. if(test_sample > frame_last_sample) {
  104307. break;
  104308. }
  104309. else if(test_sample >= frame_first_sample) {
  104310. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104311. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104312. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104313. encoder->private_->first_seekpoint_to_check++;
  104314. /* DO NOT: "break;" and here's why:
  104315. * The seektable template may contain more than one target
  104316. * sample for any given frame; we will keep looping, generating
  104317. * duplicate seekpoints for them, and we'll clean it up later,
  104318. * just before writing the seektable back to the metadata.
  104319. */
  104320. }
  104321. else {
  104322. encoder->private_->first_seekpoint_to_check++;
  104323. }
  104324. }
  104325. }
  104326. #if FLAC__HAS_OGG
  104327. if(encoder->private_->is_ogg) {
  104328. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104329. &encoder->protected_->ogg_encoder_aspect,
  104330. buffer,
  104331. bytes,
  104332. samples,
  104333. encoder->private_->current_frame_number,
  104334. is_last_block,
  104335. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104336. encoder,
  104337. encoder->private_->client_data
  104338. );
  104339. }
  104340. else
  104341. #endif
  104342. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104343. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104344. encoder->private_->bytes_written += bytes;
  104345. encoder->private_->samples_written += samples;
  104346. /* we keep a high watermark on the number of frames written because
  104347. * when the encoder goes back to write metadata, 'current_frame'
  104348. * will drop back to 0.
  104349. */
  104350. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104351. }
  104352. else
  104353. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104354. return status;
  104355. }
  104356. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104357. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104358. {
  104359. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104360. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104361. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104362. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104363. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104364. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104365. FLAC__StreamEncoderSeekStatus seek_status;
  104366. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104367. /* All this is based on intimate knowledge of the stream header
  104368. * layout, but a change to the header format that would break this
  104369. * would also break all streams encoded in the previous format.
  104370. */
  104371. /*
  104372. * Write MD5 signature
  104373. */
  104374. {
  104375. const unsigned md5_offset =
  104376. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104377. (
  104378. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104379. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104380. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104381. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104382. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104383. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104384. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104385. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104386. ) / 8;
  104387. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104388. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104389. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104390. return;
  104391. }
  104392. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104393. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104394. return;
  104395. }
  104396. }
  104397. /*
  104398. * Write total samples
  104399. */
  104400. {
  104401. const unsigned total_samples_byte_offset =
  104402. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104403. (
  104404. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104405. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104406. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104407. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104408. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104409. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104410. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104411. - 4
  104412. ) / 8;
  104413. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104414. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104415. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104416. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104417. b[4] = (FLAC__byte)(samples & 0xFF);
  104418. 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) {
  104419. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104420. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104421. return;
  104422. }
  104423. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104424. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104425. return;
  104426. }
  104427. }
  104428. /*
  104429. * Write min/max framesize
  104430. */
  104431. {
  104432. const unsigned min_framesize_offset =
  104433. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104434. (
  104435. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104436. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104437. ) / 8;
  104438. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104439. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104440. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104441. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104442. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104443. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104444. 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) {
  104445. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104446. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104447. return;
  104448. }
  104449. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104450. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104451. return;
  104452. }
  104453. }
  104454. /*
  104455. * Write seektable
  104456. */
  104457. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104458. unsigned i;
  104459. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104460. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104461. 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) {
  104462. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104463. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104464. return;
  104465. }
  104466. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104467. FLAC__uint64 xx;
  104468. unsigned x;
  104469. xx = encoder->private_->seek_table->points[i].sample_number;
  104470. b[7] = (FLAC__byte)xx; xx >>= 8;
  104471. b[6] = (FLAC__byte)xx; xx >>= 8;
  104472. b[5] = (FLAC__byte)xx; xx >>= 8;
  104473. b[4] = (FLAC__byte)xx; xx >>= 8;
  104474. b[3] = (FLAC__byte)xx; xx >>= 8;
  104475. b[2] = (FLAC__byte)xx; xx >>= 8;
  104476. b[1] = (FLAC__byte)xx; xx >>= 8;
  104477. b[0] = (FLAC__byte)xx; xx >>= 8;
  104478. xx = encoder->private_->seek_table->points[i].stream_offset;
  104479. b[15] = (FLAC__byte)xx; xx >>= 8;
  104480. b[14] = (FLAC__byte)xx; xx >>= 8;
  104481. b[13] = (FLAC__byte)xx; xx >>= 8;
  104482. b[12] = (FLAC__byte)xx; xx >>= 8;
  104483. b[11] = (FLAC__byte)xx; xx >>= 8;
  104484. b[10] = (FLAC__byte)xx; xx >>= 8;
  104485. b[9] = (FLAC__byte)xx; xx >>= 8;
  104486. b[8] = (FLAC__byte)xx; xx >>= 8;
  104487. x = encoder->private_->seek_table->points[i].frame_samples;
  104488. b[17] = (FLAC__byte)x; x >>= 8;
  104489. b[16] = (FLAC__byte)x; x >>= 8;
  104490. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104491. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104492. return;
  104493. }
  104494. }
  104495. }
  104496. }
  104497. #if FLAC__HAS_OGG
  104498. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104499. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104500. {
  104501. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104502. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104503. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104504. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104505. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104506. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104507. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104508. FLAC__STREAM_SYNC_LENGTH
  104509. ;
  104510. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104511. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104512. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104513. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104514. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104515. ogg_page page;
  104516. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104517. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104518. /* Pre-check that client supports seeking, since we don't want the
  104519. * ogg_helper code to ever have to deal with this condition.
  104520. */
  104521. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104522. return;
  104523. /* All this is based on intimate knowledge of the stream header
  104524. * layout, but a change to the header format that would break this
  104525. * would also break all streams encoded in the previous format.
  104526. */
  104527. /**
  104528. ** Write STREAMINFO stats
  104529. **/
  104530. simple_ogg_page__init(&page);
  104531. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104532. simple_ogg_page__clear(&page);
  104533. return; /* state already set */
  104534. }
  104535. /*
  104536. * Write MD5 signature
  104537. */
  104538. {
  104539. const unsigned md5_offset =
  104540. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104541. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104542. (
  104543. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104544. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104545. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104546. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104547. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104548. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104549. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104550. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104551. ) / 8;
  104552. if(md5_offset + 16 > (unsigned)page.body_len) {
  104553. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104554. simple_ogg_page__clear(&page);
  104555. return;
  104556. }
  104557. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104558. }
  104559. /*
  104560. * Write total samples
  104561. */
  104562. {
  104563. const unsigned total_samples_byte_offset =
  104564. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104565. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104566. (
  104567. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104568. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104569. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104570. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104571. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104572. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104573. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104574. - 4
  104575. ) / 8;
  104576. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104577. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104578. simple_ogg_page__clear(&page);
  104579. return;
  104580. }
  104581. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104582. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104583. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104584. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104585. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104586. b[4] = (FLAC__byte)(samples & 0xFF);
  104587. memcpy(page.body + total_samples_byte_offset, b, 5);
  104588. }
  104589. /*
  104590. * Write min/max framesize
  104591. */
  104592. {
  104593. const unsigned min_framesize_offset =
  104594. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104595. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104596. (
  104597. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104598. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104599. ) / 8;
  104600. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104601. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104602. simple_ogg_page__clear(&page);
  104603. return;
  104604. }
  104605. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104606. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104607. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104608. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104609. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104610. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104611. memcpy(page.body + min_framesize_offset, b, 6);
  104612. }
  104613. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104614. simple_ogg_page__clear(&page);
  104615. return; /* state already set */
  104616. }
  104617. simple_ogg_page__clear(&page);
  104618. /*
  104619. * Write seektable
  104620. */
  104621. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104622. unsigned i;
  104623. FLAC__byte *p;
  104624. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104625. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104626. simple_ogg_page__init(&page);
  104627. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104628. simple_ogg_page__clear(&page);
  104629. return; /* state already set */
  104630. }
  104631. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104632. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104633. simple_ogg_page__clear(&page);
  104634. return;
  104635. }
  104636. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104637. FLAC__uint64 xx;
  104638. unsigned x;
  104639. xx = encoder->private_->seek_table->points[i].sample_number;
  104640. b[7] = (FLAC__byte)xx; xx >>= 8;
  104641. b[6] = (FLAC__byte)xx; xx >>= 8;
  104642. b[5] = (FLAC__byte)xx; xx >>= 8;
  104643. b[4] = (FLAC__byte)xx; xx >>= 8;
  104644. b[3] = (FLAC__byte)xx; xx >>= 8;
  104645. b[2] = (FLAC__byte)xx; xx >>= 8;
  104646. b[1] = (FLAC__byte)xx; xx >>= 8;
  104647. b[0] = (FLAC__byte)xx; xx >>= 8;
  104648. xx = encoder->private_->seek_table->points[i].stream_offset;
  104649. b[15] = (FLAC__byte)xx; xx >>= 8;
  104650. b[14] = (FLAC__byte)xx; xx >>= 8;
  104651. b[13] = (FLAC__byte)xx; xx >>= 8;
  104652. b[12] = (FLAC__byte)xx; xx >>= 8;
  104653. b[11] = (FLAC__byte)xx; xx >>= 8;
  104654. b[10] = (FLAC__byte)xx; xx >>= 8;
  104655. b[9] = (FLAC__byte)xx; xx >>= 8;
  104656. b[8] = (FLAC__byte)xx; xx >>= 8;
  104657. x = encoder->private_->seek_table->points[i].frame_samples;
  104658. b[17] = (FLAC__byte)x; x >>= 8;
  104659. b[16] = (FLAC__byte)x; x >>= 8;
  104660. memcpy(p, b, 18);
  104661. }
  104662. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104663. simple_ogg_page__clear(&page);
  104664. return; /* state already set */
  104665. }
  104666. simple_ogg_page__clear(&page);
  104667. }
  104668. }
  104669. #endif
  104670. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104671. {
  104672. FLAC__uint16 crc;
  104673. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104674. /*
  104675. * Accumulate raw signal to the MD5 signature
  104676. */
  104677. 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)) {
  104678. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104679. return false;
  104680. }
  104681. /*
  104682. * Process the frame header and subframes into the frame bitbuffer
  104683. */
  104684. if(!process_subframes_(encoder, is_fractional_block)) {
  104685. /* the above function sets the state for us in case of an error */
  104686. return false;
  104687. }
  104688. /*
  104689. * Zero-pad the frame to a byte_boundary
  104690. */
  104691. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104692. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104693. return false;
  104694. }
  104695. /*
  104696. * CRC-16 the whole thing
  104697. */
  104698. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104699. if(
  104700. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104701. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104702. ) {
  104703. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104704. return false;
  104705. }
  104706. /*
  104707. * Write it
  104708. */
  104709. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104710. /* the above function sets the state for us in case of an error */
  104711. return false;
  104712. }
  104713. /*
  104714. * Get ready for the next frame
  104715. */
  104716. encoder->private_->current_sample_number = 0;
  104717. encoder->private_->current_frame_number++;
  104718. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104719. return true;
  104720. }
  104721. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104722. {
  104723. FLAC__FrameHeader frame_header;
  104724. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104725. FLAC__bool do_independent, do_mid_side;
  104726. /*
  104727. * Calculate the min,max Rice partition orders
  104728. */
  104729. if(is_fractional_block) {
  104730. max_partition_order = 0;
  104731. }
  104732. else {
  104733. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104734. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104735. }
  104736. min_partition_order = min(min_partition_order, max_partition_order);
  104737. /*
  104738. * Setup the frame
  104739. */
  104740. frame_header.blocksize = encoder->protected_->blocksize;
  104741. frame_header.sample_rate = encoder->protected_->sample_rate;
  104742. frame_header.channels = encoder->protected_->channels;
  104743. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104744. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104745. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104746. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104747. /*
  104748. * Figure out what channel assignments to try
  104749. */
  104750. if(encoder->protected_->do_mid_side_stereo) {
  104751. if(encoder->protected_->loose_mid_side_stereo) {
  104752. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104753. do_independent = true;
  104754. do_mid_side = true;
  104755. }
  104756. else {
  104757. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104758. do_mid_side = !do_independent;
  104759. }
  104760. }
  104761. else {
  104762. do_independent = true;
  104763. do_mid_side = true;
  104764. }
  104765. }
  104766. else {
  104767. do_independent = true;
  104768. do_mid_side = false;
  104769. }
  104770. FLAC__ASSERT(do_independent || do_mid_side);
  104771. /*
  104772. * Check for wasted bits; set effective bps for each subframe
  104773. */
  104774. if(do_independent) {
  104775. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104776. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104777. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104778. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104779. }
  104780. }
  104781. if(do_mid_side) {
  104782. FLAC__ASSERT(encoder->protected_->channels == 2);
  104783. for(channel = 0; channel < 2; channel++) {
  104784. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104785. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104786. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104787. }
  104788. }
  104789. /*
  104790. * First do a normal encoding pass of each independent channel
  104791. */
  104792. if(do_independent) {
  104793. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104794. if(!
  104795. process_subframe_(
  104796. encoder,
  104797. min_partition_order,
  104798. max_partition_order,
  104799. &frame_header,
  104800. encoder->private_->subframe_bps[channel],
  104801. encoder->private_->integer_signal[channel],
  104802. encoder->private_->subframe_workspace_ptr[channel],
  104803. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104804. encoder->private_->residual_workspace[channel],
  104805. encoder->private_->best_subframe+channel,
  104806. encoder->private_->best_subframe_bits+channel
  104807. )
  104808. )
  104809. return false;
  104810. }
  104811. }
  104812. /*
  104813. * Now do mid and side channels if requested
  104814. */
  104815. if(do_mid_side) {
  104816. FLAC__ASSERT(encoder->protected_->channels == 2);
  104817. for(channel = 0; channel < 2; channel++) {
  104818. if(!
  104819. process_subframe_(
  104820. encoder,
  104821. min_partition_order,
  104822. max_partition_order,
  104823. &frame_header,
  104824. encoder->private_->subframe_bps_mid_side[channel],
  104825. encoder->private_->integer_signal_mid_side[channel],
  104826. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104827. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104828. encoder->private_->residual_workspace_mid_side[channel],
  104829. encoder->private_->best_subframe_mid_side+channel,
  104830. encoder->private_->best_subframe_bits_mid_side+channel
  104831. )
  104832. )
  104833. return false;
  104834. }
  104835. }
  104836. /*
  104837. * Compose the frame bitbuffer
  104838. */
  104839. if(do_mid_side) {
  104840. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104841. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104842. FLAC__ChannelAssignment channel_assignment;
  104843. FLAC__ASSERT(encoder->protected_->channels == 2);
  104844. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104845. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104846. }
  104847. else {
  104848. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104849. unsigned min_bits;
  104850. int ca;
  104851. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104852. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104853. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104854. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104855. FLAC__ASSERT(do_independent && do_mid_side);
  104856. /* We have to figure out which channel assignent results in the smallest frame */
  104857. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104858. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104859. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104860. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104861. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104862. min_bits = bits[channel_assignment];
  104863. for(ca = 1; ca <= 3; ca++) {
  104864. if(bits[ca] < min_bits) {
  104865. min_bits = bits[ca];
  104866. channel_assignment = (FLAC__ChannelAssignment)ca;
  104867. }
  104868. }
  104869. }
  104870. frame_header.channel_assignment = channel_assignment;
  104871. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104872. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104873. return false;
  104874. }
  104875. switch(channel_assignment) {
  104876. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104877. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104878. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104879. break;
  104880. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104881. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104882. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104883. break;
  104884. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104885. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104886. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104887. break;
  104888. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104889. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104890. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104891. break;
  104892. default:
  104893. FLAC__ASSERT(0);
  104894. }
  104895. switch(channel_assignment) {
  104896. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104897. left_bps = encoder->private_->subframe_bps [0];
  104898. right_bps = encoder->private_->subframe_bps [1];
  104899. break;
  104900. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104901. left_bps = encoder->private_->subframe_bps [0];
  104902. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104903. break;
  104904. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104905. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104906. right_bps = encoder->private_->subframe_bps [1];
  104907. break;
  104908. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104909. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104910. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104911. break;
  104912. default:
  104913. FLAC__ASSERT(0);
  104914. }
  104915. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104916. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104917. return false;
  104918. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104919. return false;
  104920. }
  104921. else {
  104922. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104923. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104924. return false;
  104925. }
  104926. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104927. 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)) {
  104928. /* the above function sets the state for us in case of an error */
  104929. return false;
  104930. }
  104931. }
  104932. }
  104933. if(encoder->protected_->loose_mid_side_stereo) {
  104934. encoder->private_->loose_mid_side_stereo_frame_count++;
  104935. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104936. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104937. }
  104938. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104939. return true;
  104940. }
  104941. FLAC__bool process_subframe_(
  104942. FLAC__StreamEncoder *encoder,
  104943. unsigned min_partition_order,
  104944. unsigned max_partition_order,
  104945. const FLAC__FrameHeader *frame_header,
  104946. unsigned subframe_bps,
  104947. const FLAC__int32 integer_signal[],
  104948. FLAC__Subframe *subframe[2],
  104949. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104950. FLAC__int32 *residual[2],
  104951. unsigned *best_subframe,
  104952. unsigned *best_bits
  104953. )
  104954. {
  104955. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104956. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104957. #else
  104958. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104959. #endif
  104960. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104961. FLAC__double lpc_residual_bits_per_sample;
  104962. 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 */
  104963. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104964. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104965. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104966. #endif
  104967. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104968. unsigned rice_parameter;
  104969. unsigned _candidate_bits, _best_bits;
  104970. unsigned _best_subframe;
  104971. /* only use RICE2 partitions if stream bps > 16 */
  104972. 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;
  104973. FLAC__ASSERT(frame_header->blocksize > 0);
  104974. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104975. _best_subframe = 0;
  104976. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104977. _best_bits = UINT_MAX;
  104978. else
  104979. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104980. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104981. unsigned signal_is_constant = false;
  104982. 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);
  104983. /* check for constant subframe */
  104984. if(
  104985. !encoder->private_->disable_constant_subframes &&
  104986. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104987. fixed_residual_bits_per_sample[1] == 0.0
  104988. #else
  104989. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104990. #endif
  104991. ) {
  104992. /* the above means it's possible all samples are the same value; now double-check it: */
  104993. unsigned i;
  104994. signal_is_constant = true;
  104995. for(i = 1; i < frame_header->blocksize; i++) {
  104996. if(integer_signal[0] != integer_signal[i]) {
  104997. signal_is_constant = false;
  104998. break;
  104999. }
  105000. }
  105001. }
  105002. if(signal_is_constant) {
  105003. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105004. if(_candidate_bits < _best_bits) {
  105005. _best_subframe = !_best_subframe;
  105006. _best_bits = _candidate_bits;
  105007. }
  105008. }
  105009. else {
  105010. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105011. /* encode fixed */
  105012. if(encoder->protected_->do_exhaustive_model_search) {
  105013. min_fixed_order = 0;
  105014. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105015. }
  105016. else {
  105017. min_fixed_order = max_fixed_order = guess_fixed_order;
  105018. }
  105019. if(max_fixed_order >= frame_header->blocksize)
  105020. max_fixed_order = frame_header->blocksize - 1;
  105021. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105022. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105023. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105024. continue; /* don't even try */
  105025. 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 */
  105026. #else
  105027. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105028. continue; /* don't even try */
  105029. 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 */
  105030. #endif
  105031. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105032. if(rice_parameter >= rice_parameter_limit) {
  105033. #ifdef DEBUG_VERBOSE
  105034. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105035. #endif
  105036. rice_parameter = rice_parameter_limit - 1;
  105037. }
  105038. _candidate_bits =
  105039. evaluate_fixed_subframe_(
  105040. encoder,
  105041. integer_signal,
  105042. residual[!_best_subframe],
  105043. encoder->private_->abs_residual_partition_sums,
  105044. encoder->private_->raw_bits_per_partition,
  105045. frame_header->blocksize,
  105046. subframe_bps,
  105047. fixed_order,
  105048. rice_parameter,
  105049. rice_parameter_limit,
  105050. min_partition_order,
  105051. max_partition_order,
  105052. encoder->protected_->do_escape_coding,
  105053. encoder->protected_->rice_parameter_search_dist,
  105054. subframe[!_best_subframe],
  105055. partitioned_rice_contents[!_best_subframe]
  105056. );
  105057. if(_candidate_bits < _best_bits) {
  105058. _best_subframe = !_best_subframe;
  105059. _best_bits = _candidate_bits;
  105060. }
  105061. }
  105062. }
  105063. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105064. /* encode lpc */
  105065. if(encoder->protected_->max_lpc_order > 0) {
  105066. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105067. max_lpc_order = frame_header->blocksize-1;
  105068. else
  105069. max_lpc_order = encoder->protected_->max_lpc_order;
  105070. if(max_lpc_order > 0) {
  105071. unsigned a;
  105072. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105073. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105074. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105075. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105076. if(autoc[0] != 0.0) {
  105077. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105078. if(encoder->protected_->do_exhaustive_model_search) {
  105079. min_lpc_order = 1;
  105080. }
  105081. else {
  105082. const unsigned guess_lpc_order =
  105083. FLAC__lpc_compute_best_order(
  105084. lpc_error,
  105085. max_lpc_order,
  105086. frame_header->blocksize,
  105087. subframe_bps + (
  105088. encoder->protected_->do_qlp_coeff_prec_search?
  105089. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105090. encoder->protected_->qlp_coeff_precision
  105091. )
  105092. );
  105093. min_lpc_order = max_lpc_order = guess_lpc_order;
  105094. }
  105095. if(max_lpc_order >= frame_header->blocksize)
  105096. max_lpc_order = frame_header->blocksize - 1;
  105097. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105098. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105099. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105100. continue; /* don't even try */
  105101. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105102. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105103. if(rice_parameter >= rice_parameter_limit) {
  105104. #ifdef DEBUG_VERBOSE
  105105. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105106. #endif
  105107. rice_parameter = rice_parameter_limit - 1;
  105108. }
  105109. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105110. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105111. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105112. if(subframe_bps <= 17) {
  105113. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105114. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105115. }
  105116. else
  105117. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105118. }
  105119. else {
  105120. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105121. }
  105122. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105123. _candidate_bits =
  105124. evaluate_lpc_subframe_(
  105125. encoder,
  105126. integer_signal,
  105127. residual[!_best_subframe],
  105128. encoder->private_->abs_residual_partition_sums,
  105129. encoder->private_->raw_bits_per_partition,
  105130. encoder->private_->lp_coeff[lpc_order-1],
  105131. frame_header->blocksize,
  105132. subframe_bps,
  105133. lpc_order,
  105134. qlp_coeff_precision,
  105135. rice_parameter,
  105136. rice_parameter_limit,
  105137. min_partition_order,
  105138. max_partition_order,
  105139. encoder->protected_->do_escape_coding,
  105140. encoder->protected_->rice_parameter_search_dist,
  105141. subframe[!_best_subframe],
  105142. partitioned_rice_contents[!_best_subframe]
  105143. );
  105144. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105145. if(_candidate_bits < _best_bits) {
  105146. _best_subframe = !_best_subframe;
  105147. _best_bits = _candidate_bits;
  105148. }
  105149. }
  105150. }
  105151. }
  105152. }
  105153. }
  105154. }
  105155. }
  105156. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105157. }
  105158. }
  105159. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105160. if(_best_bits == UINT_MAX) {
  105161. FLAC__ASSERT(_best_subframe == 0);
  105162. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105163. }
  105164. *best_subframe = _best_subframe;
  105165. *best_bits = _best_bits;
  105166. return true;
  105167. }
  105168. FLAC__bool add_subframe_(
  105169. FLAC__StreamEncoder *encoder,
  105170. unsigned blocksize,
  105171. unsigned subframe_bps,
  105172. const FLAC__Subframe *subframe,
  105173. FLAC__BitWriter *frame
  105174. )
  105175. {
  105176. switch(subframe->type) {
  105177. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105178. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105179. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105180. return false;
  105181. }
  105182. break;
  105183. case FLAC__SUBFRAME_TYPE_FIXED:
  105184. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105185. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105186. return false;
  105187. }
  105188. break;
  105189. case FLAC__SUBFRAME_TYPE_LPC:
  105190. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105191. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105192. return false;
  105193. }
  105194. break;
  105195. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105196. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105197. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105198. return false;
  105199. }
  105200. break;
  105201. default:
  105202. FLAC__ASSERT(0);
  105203. }
  105204. return true;
  105205. }
  105206. #define SPOTCHECK_ESTIMATE 0
  105207. #if SPOTCHECK_ESTIMATE
  105208. static void spotcheck_subframe_estimate_(
  105209. FLAC__StreamEncoder *encoder,
  105210. unsigned blocksize,
  105211. unsigned subframe_bps,
  105212. const FLAC__Subframe *subframe,
  105213. unsigned estimate
  105214. )
  105215. {
  105216. FLAC__bool ret;
  105217. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105218. if(frame == 0) {
  105219. fprintf(stderr, "EST: can't allocate frame\n");
  105220. return;
  105221. }
  105222. if(!FLAC__bitwriter_init(frame)) {
  105223. fprintf(stderr, "EST: can't init frame\n");
  105224. return;
  105225. }
  105226. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105227. FLAC__ASSERT(ret);
  105228. {
  105229. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105230. if(estimate != actual)
  105231. 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);
  105232. }
  105233. FLAC__bitwriter_delete(frame);
  105234. }
  105235. #endif
  105236. unsigned evaluate_constant_subframe_(
  105237. FLAC__StreamEncoder *encoder,
  105238. const FLAC__int32 signal,
  105239. unsigned blocksize,
  105240. unsigned subframe_bps,
  105241. FLAC__Subframe *subframe
  105242. )
  105243. {
  105244. unsigned estimate;
  105245. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105246. subframe->data.constant.value = signal;
  105247. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105248. #if SPOTCHECK_ESTIMATE
  105249. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105250. #else
  105251. (void)encoder, (void)blocksize;
  105252. #endif
  105253. return estimate;
  105254. }
  105255. unsigned evaluate_fixed_subframe_(
  105256. FLAC__StreamEncoder *encoder,
  105257. const FLAC__int32 signal[],
  105258. FLAC__int32 residual[],
  105259. FLAC__uint64 abs_residual_partition_sums[],
  105260. unsigned raw_bits_per_partition[],
  105261. unsigned blocksize,
  105262. unsigned subframe_bps,
  105263. unsigned order,
  105264. unsigned rice_parameter,
  105265. unsigned rice_parameter_limit,
  105266. unsigned min_partition_order,
  105267. unsigned max_partition_order,
  105268. FLAC__bool do_escape_coding,
  105269. unsigned rice_parameter_search_dist,
  105270. FLAC__Subframe *subframe,
  105271. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105272. )
  105273. {
  105274. unsigned i, residual_bits, estimate;
  105275. const unsigned residual_samples = blocksize - order;
  105276. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105277. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105278. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105279. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105280. subframe->data.fixed.residual = residual;
  105281. residual_bits =
  105282. find_best_partition_order_(
  105283. encoder->private_,
  105284. residual,
  105285. abs_residual_partition_sums,
  105286. raw_bits_per_partition,
  105287. residual_samples,
  105288. order,
  105289. rice_parameter,
  105290. rice_parameter_limit,
  105291. min_partition_order,
  105292. max_partition_order,
  105293. subframe_bps,
  105294. do_escape_coding,
  105295. rice_parameter_search_dist,
  105296. &subframe->data.fixed.entropy_coding_method
  105297. );
  105298. subframe->data.fixed.order = order;
  105299. for(i = 0; i < order; i++)
  105300. subframe->data.fixed.warmup[i] = signal[i];
  105301. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105302. #if SPOTCHECK_ESTIMATE
  105303. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105304. #endif
  105305. return estimate;
  105306. }
  105307. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105308. unsigned evaluate_lpc_subframe_(
  105309. FLAC__StreamEncoder *encoder,
  105310. const FLAC__int32 signal[],
  105311. FLAC__int32 residual[],
  105312. FLAC__uint64 abs_residual_partition_sums[],
  105313. unsigned raw_bits_per_partition[],
  105314. const FLAC__real lp_coeff[],
  105315. unsigned blocksize,
  105316. unsigned subframe_bps,
  105317. unsigned order,
  105318. unsigned qlp_coeff_precision,
  105319. unsigned rice_parameter,
  105320. unsigned rice_parameter_limit,
  105321. unsigned min_partition_order,
  105322. unsigned max_partition_order,
  105323. FLAC__bool do_escape_coding,
  105324. unsigned rice_parameter_search_dist,
  105325. FLAC__Subframe *subframe,
  105326. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105327. )
  105328. {
  105329. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105330. unsigned i, residual_bits, estimate;
  105331. int quantization, ret;
  105332. const unsigned residual_samples = blocksize - order;
  105333. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105334. if(subframe_bps <= 16) {
  105335. FLAC__ASSERT(order > 0);
  105336. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105337. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105338. }
  105339. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105340. if(ret != 0)
  105341. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105342. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105343. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105344. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105345. else
  105346. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105347. else
  105348. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105349. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105350. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105351. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105352. subframe->data.lpc.residual = residual;
  105353. residual_bits =
  105354. find_best_partition_order_(
  105355. encoder->private_,
  105356. residual,
  105357. abs_residual_partition_sums,
  105358. raw_bits_per_partition,
  105359. residual_samples,
  105360. order,
  105361. rice_parameter,
  105362. rice_parameter_limit,
  105363. min_partition_order,
  105364. max_partition_order,
  105365. subframe_bps,
  105366. do_escape_coding,
  105367. rice_parameter_search_dist,
  105368. &subframe->data.lpc.entropy_coding_method
  105369. );
  105370. subframe->data.lpc.order = order;
  105371. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105372. subframe->data.lpc.quantization_level = quantization;
  105373. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105374. for(i = 0; i < order; i++)
  105375. subframe->data.lpc.warmup[i] = signal[i];
  105376. 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;
  105377. #if SPOTCHECK_ESTIMATE
  105378. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105379. #endif
  105380. return estimate;
  105381. }
  105382. #endif
  105383. unsigned evaluate_verbatim_subframe_(
  105384. FLAC__StreamEncoder *encoder,
  105385. const FLAC__int32 signal[],
  105386. unsigned blocksize,
  105387. unsigned subframe_bps,
  105388. FLAC__Subframe *subframe
  105389. )
  105390. {
  105391. unsigned estimate;
  105392. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105393. subframe->data.verbatim.data = signal;
  105394. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105395. #if SPOTCHECK_ESTIMATE
  105396. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105397. #else
  105398. (void)encoder;
  105399. #endif
  105400. return estimate;
  105401. }
  105402. unsigned find_best_partition_order_(
  105403. FLAC__StreamEncoderPrivate *private_,
  105404. const FLAC__int32 residual[],
  105405. FLAC__uint64 abs_residual_partition_sums[],
  105406. unsigned raw_bits_per_partition[],
  105407. unsigned residual_samples,
  105408. unsigned predictor_order,
  105409. unsigned rice_parameter,
  105410. unsigned rice_parameter_limit,
  105411. unsigned min_partition_order,
  105412. unsigned max_partition_order,
  105413. unsigned bps,
  105414. FLAC__bool do_escape_coding,
  105415. unsigned rice_parameter_search_dist,
  105416. FLAC__EntropyCodingMethod *best_ecm
  105417. )
  105418. {
  105419. unsigned residual_bits, best_residual_bits = 0;
  105420. unsigned best_parameters_index = 0;
  105421. unsigned best_partition_order = 0;
  105422. const unsigned blocksize = residual_samples + predictor_order;
  105423. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105424. min_partition_order = min(min_partition_order, max_partition_order);
  105425. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105426. if(do_escape_coding)
  105427. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105428. {
  105429. int partition_order;
  105430. unsigned sum;
  105431. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105432. if(!
  105433. set_partitioned_rice_(
  105434. #ifdef EXACT_RICE_BITS_CALCULATION
  105435. residual,
  105436. #endif
  105437. abs_residual_partition_sums+sum,
  105438. raw_bits_per_partition+sum,
  105439. residual_samples,
  105440. predictor_order,
  105441. rice_parameter,
  105442. rice_parameter_limit,
  105443. rice_parameter_search_dist,
  105444. (unsigned)partition_order,
  105445. do_escape_coding,
  105446. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105447. &residual_bits
  105448. )
  105449. )
  105450. {
  105451. FLAC__ASSERT(best_residual_bits != 0);
  105452. break;
  105453. }
  105454. sum += 1u << partition_order;
  105455. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105456. best_residual_bits = residual_bits;
  105457. best_parameters_index = !best_parameters_index;
  105458. best_partition_order = partition_order;
  105459. }
  105460. }
  105461. }
  105462. best_ecm->data.partitioned_rice.order = best_partition_order;
  105463. {
  105464. /*
  105465. * We are allowed to de-const the pointer based on our special
  105466. * knowledge; it is const to the outside world.
  105467. */
  105468. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105469. unsigned partition;
  105470. /* save best parameters and raw_bits */
  105471. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105472. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105473. if(do_escape_coding)
  105474. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105475. /*
  105476. * Now need to check if the type should be changed to
  105477. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105478. * size of the rice parameters.
  105479. */
  105480. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105481. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105482. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105483. break;
  105484. }
  105485. }
  105486. }
  105487. return best_residual_bits;
  105488. }
  105489. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105490. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105491. const FLAC__int32 residual[],
  105492. FLAC__uint64 abs_residual_partition_sums[],
  105493. unsigned blocksize,
  105494. unsigned predictor_order,
  105495. unsigned min_partition_order,
  105496. unsigned max_partition_order
  105497. );
  105498. #endif
  105499. void precompute_partition_info_sums_(
  105500. const FLAC__int32 residual[],
  105501. FLAC__uint64 abs_residual_partition_sums[],
  105502. unsigned residual_samples,
  105503. unsigned predictor_order,
  105504. unsigned min_partition_order,
  105505. unsigned max_partition_order,
  105506. unsigned bps
  105507. )
  105508. {
  105509. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105510. unsigned partitions = 1u << max_partition_order;
  105511. FLAC__ASSERT(default_partition_samples > predictor_order);
  105512. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105513. /* slightly pessimistic but still catches all common cases */
  105514. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105515. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105516. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105517. return;
  105518. }
  105519. #endif
  105520. /* first do max_partition_order */
  105521. {
  105522. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105523. /* slightly pessimistic but still catches all common cases */
  105524. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105525. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105526. FLAC__uint32 abs_residual_partition_sum;
  105527. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105528. end += default_partition_samples;
  105529. abs_residual_partition_sum = 0;
  105530. for( ; residual_sample < end; residual_sample++)
  105531. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105532. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105533. }
  105534. }
  105535. else { /* have to pessimistically use 64 bits for accumulator */
  105536. FLAC__uint64 abs_residual_partition_sum;
  105537. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105538. end += default_partition_samples;
  105539. abs_residual_partition_sum = 0;
  105540. for( ; residual_sample < end; residual_sample++)
  105541. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105542. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105543. }
  105544. }
  105545. }
  105546. /* now merge partitions for lower orders */
  105547. {
  105548. unsigned from_partition = 0, to_partition = partitions;
  105549. int partition_order;
  105550. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105551. unsigned i;
  105552. partitions >>= 1;
  105553. for(i = 0; i < partitions; i++) {
  105554. abs_residual_partition_sums[to_partition++] =
  105555. abs_residual_partition_sums[from_partition ] +
  105556. abs_residual_partition_sums[from_partition+1];
  105557. from_partition += 2;
  105558. }
  105559. }
  105560. }
  105561. }
  105562. void precompute_partition_info_escapes_(
  105563. const FLAC__int32 residual[],
  105564. unsigned raw_bits_per_partition[],
  105565. unsigned residual_samples,
  105566. unsigned predictor_order,
  105567. unsigned min_partition_order,
  105568. unsigned max_partition_order
  105569. )
  105570. {
  105571. int partition_order;
  105572. unsigned from_partition, to_partition = 0;
  105573. const unsigned blocksize = residual_samples + predictor_order;
  105574. /* first do max_partition_order */
  105575. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105576. FLAC__int32 r;
  105577. FLAC__uint32 rmax;
  105578. unsigned partition, partition_sample, partition_samples, residual_sample;
  105579. const unsigned partitions = 1u << partition_order;
  105580. const unsigned default_partition_samples = blocksize >> partition_order;
  105581. FLAC__ASSERT(default_partition_samples > predictor_order);
  105582. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105583. partition_samples = default_partition_samples;
  105584. if(partition == 0)
  105585. partition_samples -= predictor_order;
  105586. rmax = 0;
  105587. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105588. r = residual[residual_sample++];
  105589. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105590. if(r < 0)
  105591. rmax |= ~r;
  105592. else
  105593. rmax |= r;
  105594. }
  105595. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105596. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105597. }
  105598. to_partition = partitions;
  105599. break; /*@@@ yuck, should remove the 'for' loop instead */
  105600. }
  105601. /* now merge partitions for lower orders */
  105602. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105603. unsigned m;
  105604. unsigned i;
  105605. const unsigned partitions = 1u << partition_order;
  105606. for(i = 0; i < partitions; i++) {
  105607. m = raw_bits_per_partition[from_partition];
  105608. from_partition++;
  105609. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105610. from_partition++;
  105611. to_partition++;
  105612. }
  105613. }
  105614. }
  105615. #ifdef EXACT_RICE_BITS_CALCULATION
  105616. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105617. const unsigned rice_parameter,
  105618. const unsigned partition_samples,
  105619. const FLAC__int32 *residual
  105620. )
  105621. {
  105622. unsigned i, partition_bits =
  105623. 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 */
  105624. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105625. ;
  105626. for(i = 0; i < partition_samples; i++)
  105627. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105628. return partition_bits;
  105629. }
  105630. #else
  105631. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105632. const unsigned rice_parameter,
  105633. const unsigned partition_samples,
  105634. const FLAC__uint64 abs_residual_partition_sum
  105635. )
  105636. {
  105637. return
  105638. 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 */
  105639. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105640. (
  105641. rice_parameter?
  105642. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105643. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105644. )
  105645. - (partition_samples >> 1)
  105646. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105647. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105648. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105649. * So the subtraction term tries to guess how many extra bits were contributed.
  105650. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105651. */
  105652. ;
  105653. }
  105654. #endif
  105655. FLAC__bool set_partitioned_rice_(
  105656. #ifdef EXACT_RICE_BITS_CALCULATION
  105657. const FLAC__int32 residual[],
  105658. #endif
  105659. const FLAC__uint64 abs_residual_partition_sums[],
  105660. const unsigned raw_bits_per_partition[],
  105661. const unsigned residual_samples,
  105662. const unsigned predictor_order,
  105663. const unsigned suggested_rice_parameter,
  105664. const unsigned rice_parameter_limit,
  105665. const unsigned rice_parameter_search_dist,
  105666. const unsigned partition_order,
  105667. const FLAC__bool search_for_escapes,
  105668. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105669. unsigned *bits
  105670. )
  105671. {
  105672. unsigned rice_parameter, partition_bits;
  105673. unsigned best_partition_bits, best_rice_parameter = 0;
  105674. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105675. unsigned *parameters, *raw_bits;
  105676. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105677. unsigned min_rice_parameter, max_rice_parameter;
  105678. #else
  105679. (void)rice_parameter_search_dist;
  105680. #endif
  105681. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105682. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105683. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105684. parameters = partitioned_rice_contents->parameters;
  105685. raw_bits = partitioned_rice_contents->raw_bits;
  105686. if(partition_order == 0) {
  105687. best_partition_bits = (unsigned)(-1);
  105688. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105689. if(rice_parameter_search_dist) {
  105690. if(suggested_rice_parameter < rice_parameter_search_dist)
  105691. min_rice_parameter = 0;
  105692. else
  105693. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105694. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105695. if(max_rice_parameter >= rice_parameter_limit) {
  105696. #ifdef DEBUG_VERBOSE
  105697. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105698. #endif
  105699. max_rice_parameter = rice_parameter_limit - 1;
  105700. }
  105701. }
  105702. else
  105703. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105704. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105705. #else
  105706. rice_parameter = suggested_rice_parameter;
  105707. #endif
  105708. #ifdef EXACT_RICE_BITS_CALCULATION
  105709. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105710. #else
  105711. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105712. #endif
  105713. if(partition_bits < best_partition_bits) {
  105714. best_rice_parameter = rice_parameter;
  105715. best_partition_bits = partition_bits;
  105716. }
  105717. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105718. }
  105719. #endif
  105720. if(search_for_escapes) {
  105721. 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;
  105722. if(partition_bits <= best_partition_bits) {
  105723. raw_bits[0] = raw_bits_per_partition[0];
  105724. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105725. best_partition_bits = partition_bits;
  105726. }
  105727. else
  105728. raw_bits[0] = 0;
  105729. }
  105730. parameters[0] = best_rice_parameter;
  105731. bits_ += best_partition_bits;
  105732. }
  105733. else {
  105734. unsigned partition, residual_sample;
  105735. unsigned partition_samples;
  105736. FLAC__uint64 mean, k;
  105737. const unsigned partitions = 1u << partition_order;
  105738. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105739. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105740. if(partition == 0) {
  105741. if(partition_samples <= predictor_order)
  105742. return false;
  105743. else
  105744. partition_samples -= predictor_order;
  105745. }
  105746. mean = abs_residual_partition_sums[partition];
  105747. /* we are basically calculating the size in bits of the
  105748. * average residual magnitude in the partition:
  105749. * rice_parameter = floor(log2(mean/partition_samples))
  105750. * 'mean' is not a good name for the variable, it is
  105751. * actually the sum of magnitudes of all residual values
  105752. * in the partition, so the actual mean is
  105753. * mean/partition_samples
  105754. */
  105755. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105756. ;
  105757. if(rice_parameter >= rice_parameter_limit) {
  105758. #ifdef DEBUG_VERBOSE
  105759. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105760. #endif
  105761. rice_parameter = rice_parameter_limit - 1;
  105762. }
  105763. best_partition_bits = (unsigned)(-1);
  105764. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105765. if(rice_parameter_search_dist) {
  105766. if(rice_parameter < rice_parameter_search_dist)
  105767. min_rice_parameter = 0;
  105768. else
  105769. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105770. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105771. if(max_rice_parameter >= rice_parameter_limit) {
  105772. #ifdef DEBUG_VERBOSE
  105773. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105774. #endif
  105775. max_rice_parameter = rice_parameter_limit - 1;
  105776. }
  105777. }
  105778. else
  105779. min_rice_parameter = max_rice_parameter = rice_parameter;
  105780. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105781. #endif
  105782. #ifdef EXACT_RICE_BITS_CALCULATION
  105783. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105784. #else
  105785. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105786. #endif
  105787. if(partition_bits < best_partition_bits) {
  105788. best_rice_parameter = rice_parameter;
  105789. best_partition_bits = partition_bits;
  105790. }
  105791. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105792. }
  105793. #endif
  105794. if(search_for_escapes) {
  105795. 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;
  105796. if(partition_bits <= best_partition_bits) {
  105797. raw_bits[partition] = raw_bits_per_partition[partition];
  105798. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105799. best_partition_bits = partition_bits;
  105800. }
  105801. else
  105802. raw_bits[partition] = 0;
  105803. }
  105804. parameters[partition] = best_rice_parameter;
  105805. bits_ += best_partition_bits;
  105806. residual_sample += partition_samples;
  105807. }
  105808. }
  105809. *bits = bits_;
  105810. return true;
  105811. }
  105812. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105813. {
  105814. unsigned i, shift;
  105815. FLAC__int32 x = 0;
  105816. for(i = 0; i < samples && !(x&1); i++)
  105817. x |= signal[i];
  105818. if(x == 0) {
  105819. shift = 0;
  105820. }
  105821. else {
  105822. for(shift = 0; !(x&1); shift++)
  105823. x >>= 1;
  105824. }
  105825. if(shift > 0) {
  105826. for(i = 0; i < samples; i++)
  105827. signal[i] >>= shift;
  105828. }
  105829. return shift;
  105830. }
  105831. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105832. {
  105833. unsigned channel;
  105834. for(channel = 0; channel < channels; channel++)
  105835. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105836. fifo->tail += wide_samples;
  105837. FLAC__ASSERT(fifo->tail <= fifo->size);
  105838. }
  105839. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105840. {
  105841. unsigned channel;
  105842. unsigned sample, wide_sample;
  105843. unsigned tail = fifo->tail;
  105844. sample = input_offset * channels;
  105845. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105846. for(channel = 0; channel < channels; channel++)
  105847. fifo->data[channel][tail] = input[sample++];
  105848. tail++;
  105849. }
  105850. fifo->tail = tail;
  105851. FLAC__ASSERT(fifo->tail <= fifo->size);
  105852. }
  105853. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105854. {
  105855. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105856. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105857. (void)decoder;
  105858. if(encoder->private_->verify.needs_magic_hack) {
  105859. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105860. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105861. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105862. encoder->private_->verify.needs_magic_hack = false;
  105863. }
  105864. else {
  105865. if(encoded_bytes == 0) {
  105866. /*
  105867. * If we get here, a FIFO underflow has occurred,
  105868. * which means there is a bug somewhere.
  105869. */
  105870. FLAC__ASSERT(0);
  105871. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105872. }
  105873. else if(encoded_bytes < *bytes)
  105874. *bytes = encoded_bytes;
  105875. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105876. encoder->private_->verify.output.data += *bytes;
  105877. encoder->private_->verify.output.bytes -= *bytes;
  105878. }
  105879. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105880. }
  105881. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105882. {
  105883. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105884. unsigned channel;
  105885. const unsigned channels = frame->header.channels;
  105886. const unsigned blocksize = frame->header.blocksize;
  105887. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105888. (void)decoder;
  105889. for(channel = 0; channel < channels; channel++) {
  105890. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105891. unsigned i, sample = 0;
  105892. FLAC__int32 expect = 0, got = 0;
  105893. for(i = 0; i < blocksize; i++) {
  105894. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105895. sample = i;
  105896. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105897. got = (FLAC__int32)buffer[channel][i];
  105898. break;
  105899. }
  105900. }
  105901. FLAC__ASSERT(i < blocksize);
  105902. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105903. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105904. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105905. encoder->private_->verify.error_stats.channel = channel;
  105906. encoder->private_->verify.error_stats.sample = sample;
  105907. encoder->private_->verify.error_stats.expected = expect;
  105908. encoder->private_->verify.error_stats.got = got;
  105909. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105910. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105911. }
  105912. }
  105913. /* dequeue the frame from the fifo */
  105914. encoder->private_->verify.input_fifo.tail -= blocksize;
  105915. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105916. for(channel = 0; channel < channels; channel++)
  105917. 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]));
  105918. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105919. }
  105920. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105921. {
  105922. (void)decoder, (void)metadata, (void)client_data;
  105923. }
  105924. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105925. {
  105926. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105927. (void)decoder, (void)status;
  105928. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105929. }
  105930. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105931. {
  105932. (void)client_data;
  105933. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105934. if (*bytes == 0) {
  105935. if (feof(encoder->private_->file))
  105936. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105937. else if (ferror(encoder->private_->file))
  105938. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105939. }
  105940. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105941. }
  105942. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105943. {
  105944. (void)client_data;
  105945. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105946. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105947. else
  105948. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105949. }
  105950. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105951. {
  105952. off_t offset;
  105953. (void)client_data;
  105954. offset = ftello(encoder->private_->file);
  105955. if(offset < 0) {
  105956. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105957. }
  105958. else {
  105959. *absolute_byte_offset = (FLAC__uint64)offset;
  105960. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105961. }
  105962. }
  105963. #ifdef FLAC__VALGRIND_TESTING
  105964. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105965. {
  105966. size_t ret = fwrite(ptr, size, nmemb, stream);
  105967. if(!ferror(stream))
  105968. fflush(stream);
  105969. return ret;
  105970. }
  105971. #else
  105972. #define local__fwrite fwrite
  105973. #endif
  105974. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105975. {
  105976. (void)client_data, (void)current_frame;
  105977. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105978. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105979. #if FLAC__HAS_OGG
  105980. /* We would like to be able to use 'samples > 0' in the
  105981. * clause here but currently because of the nature of our
  105982. * Ogg writing implementation, 'samples' is always 0 (see
  105983. * ogg_encoder_aspect.c). The downside is extra progress
  105984. * callbacks.
  105985. */
  105986. encoder->private_->is_ogg? true :
  105987. #endif
  105988. samples > 0
  105989. );
  105990. if(call_it) {
  105991. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105992. * because at this point in the callback chain, the stats
  105993. * have not been updated. Only after we return and control
  105994. * gets back to write_frame_() are the stats updated
  105995. */
  105996. 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);
  105997. }
  105998. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105999. }
  106000. else
  106001. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106002. }
  106003. /*
  106004. * This will forcibly set stdout to binary mode (for OSes that require it)
  106005. */
  106006. FILE *get_binary_stdout_(void)
  106007. {
  106008. /* if something breaks here it is probably due to the presence or
  106009. * absence of an underscore before the identifiers 'setmode',
  106010. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106011. */
  106012. #if defined _MSC_VER || defined __MINGW32__
  106013. _setmode(_fileno(stdout), _O_BINARY);
  106014. #elif defined __CYGWIN__
  106015. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106016. setmode(_fileno(stdout), _O_BINARY);
  106017. #elif defined __EMX__
  106018. setmode(fileno(stdout), O_BINARY);
  106019. #endif
  106020. return stdout;
  106021. }
  106022. #endif
  106023. /*** End of inlined file: stream_encoder.c ***/
  106024. /*** Start of inlined file: stream_encoder_framing.c ***/
  106025. /*** Start of inlined file: juce_FlacHeader.h ***/
  106026. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106027. // tasks..
  106028. #define VERSION "1.2.1"
  106029. #define FLAC__NO_DLL 1
  106030. #if JUCE_MSVC
  106031. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106032. #endif
  106033. #if JUCE_MAC
  106034. #define FLAC__SYS_DARWIN 1
  106035. #endif
  106036. /*** End of inlined file: juce_FlacHeader.h ***/
  106037. #if JUCE_USE_FLAC
  106038. #if HAVE_CONFIG_H
  106039. # include <config.h>
  106040. #endif
  106041. #include <stdio.h>
  106042. #include <string.h> /* for strlen() */
  106043. #ifdef max
  106044. #undef max
  106045. #endif
  106046. #define max(x,y) ((x)>(y)?(x):(y))
  106047. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106048. 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);
  106049. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106050. {
  106051. unsigned i, j;
  106052. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106053. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106054. return false;
  106055. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106056. return false;
  106057. /*
  106058. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106059. */
  106060. i = metadata->length;
  106061. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106062. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106063. i -= metadata->data.vorbis_comment.vendor_string.length;
  106064. i += vendor_string_length;
  106065. }
  106066. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106067. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106068. return false;
  106069. switch(metadata->type) {
  106070. case FLAC__METADATA_TYPE_STREAMINFO:
  106071. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106072. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106073. return false;
  106074. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106075. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106076. return false;
  106077. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106078. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106079. return false;
  106080. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106081. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106082. return false;
  106083. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106084. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106085. return false;
  106086. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106087. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106088. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106089. return false;
  106090. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106091. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106092. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106093. return false;
  106094. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106095. return false;
  106096. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106097. return false;
  106098. break;
  106099. case FLAC__METADATA_TYPE_PADDING:
  106100. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106101. return false;
  106102. break;
  106103. case FLAC__METADATA_TYPE_APPLICATION:
  106104. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106105. return false;
  106106. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106107. return false;
  106108. break;
  106109. case FLAC__METADATA_TYPE_SEEKTABLE:
  106110. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106111. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106112. return false;
  106113. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106114. return false;
  106115. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106116. return false;
  106117. }
  106118. break;
  106119. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106120. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106121. return false;
  106122. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106123. return false;
  106124. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106125. return false;
  106126. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106127. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106128. return false;
  106129. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106130. return false;
  106131. }
  106132. break;
  106133. case FLAC__METADATA_TYPE_CUESHEET:
  106134. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106135. 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))
  106136. return false;
  106137. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106138. return false;
  106139. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106140. return false;
  106141. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106142. return false;
  106143. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106144. return false;
  106145. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106146. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106147. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106148. return false;
  106149. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106150. return false;
  106151. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106152. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106153. return false;
  106154. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106155. return false;
  106156. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106157. return false;
  106158. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106159. return false;
  106160. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106161. return false;
  106162. for(j = 0; j < track->num_indices; j++) {
  106163. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106164. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106165. return false;
  106166. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106167. return false;
  106168. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106169. return false;
  106170. }
  106171. }
  106172. break;
  106173. case FLAC__METADATA_TYPE_PICTURE:
  106174. {
  106175. size_t len;
  106176. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106177. return false;
  106178. len = strlen(metadata->data.picture.mime_type);
  106179. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106180. return false;
  106181. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106182. return false;
  106183. len = strlen((const char *)metadata->data.picture.description);
  106184. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106185. return false;
  106186. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106187. return false;
  106188. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106189. return false;
  106190. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106191. return false;
  106192. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106193. return false;
  106194. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106195. return false;
  106196. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106197. return false;
  106198. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106199. return false;
  106200. }
  106201. break;
  106202. default:
  106203. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106204. return false;
  106205. break;
  106206. }
  106207. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106208. return true;
  106209. }
  106210. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106211. {
  106212. unsigned u, blocksize_hint, sample_rate_hint;
  106213. FLAC__byte crc;
  106214. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106215. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106216. return false;
  106217. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106218. return false;
  106219. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106220. return false;
  106221. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106222. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106223. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106224. blocksize_hint = 0;
  106225. switch(header->blocksize) {
  106226. case 192: u = 1; break;
  106227. case 576: u = 2; break;
  106228. case 1152: u = 3; break;
  106229. case 2304: u = 4; break;
  106230. case 4608: u = 5; break;
  106231. case 256: u = 8; break;
  106232. case 512: u = 9; break;
  106233. case 1024: u = 10; break;
  106234. case 2048: u = 11; break;
  106235. case 4096: u = 12; break;
  106236. case 8192: u = 13; break;
  106237. case 16384: u = 14; break;
  106238. case 32768: u = 15; break;
  106239. default:
  106240. if(header->blocksize <= 0x100)
  106241. blocksize_hint = u = 6;
  106242. else
  106243. blocksize_hint = u = 7;
  106244. break;
  106245. }
  106246. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106247. return false;
  106248. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106249. sample_rate_hint = 0;
  106250. switch(header->sample_rate) {
  106251. case 88200: u = 1; break;
  106252. case 176400: u = 2; break;
  106253. case 192000: u = 3; break;
  106254. case 8000: u = 4; break;
  106255. case 16000: u = 5; break;
  106256. case 22050: u = 6; break;
  106257. case 24000: u = 7; break;
  106258. case 32000: u = 8; break;
  106259. case 44100: u = 9; break;
  106260. case 48000: u = 10; break;
  106261. case 96000: u = 11; break;
  106262. default:
  106263. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106264. sample_rate_hint = u = 12;
  106265. else if(header->sample_rate % 10 == 0)
  106266. sample_rate_hint = u = 14;
  106267. else if(header->sample_rate <= 0xffff)
  106268. sample_rate_hint = u = 13;
  106269. else
  106270. u = 0;
  106271. break;
  106272. }
  106273. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106274. return false;
  106275. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106276. switch(header->channel_assignment) {
  106277. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106278. u = header->channels - 1;
  106279. break;
  106280. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106281. FLAC__ASSERT(header->channels == 2);
  106282. u = 8;
  106283. break;
  106284. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106285. FLAC__ASSERT(header->channels == 2);
  106286. u = 9;
  106287. break;
  106288. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106289. FLAC__ASSERT(header->channels == 2);
  106290. u = 10;
  106291. break;
  106292. default:
  106293. FLAC__ASSERT(0);
  106294. }
  106295. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106296. return false;
  106297. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106298. switch(header->bits_per_sample) {
  106299. case 8 : u = 1; break;
  106300. case 12: u = 2; break;
  106301. case 16: u = 4; break;
  106302. case 20: u = 5; break;
  106303. case 24: u = 6; break;
  106304. default: u = 0; break;
  106305. }
  106306. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106307. return false;
  106308. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106309. return false;
  106310. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106311. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106312. return false;
  106313. }
  106314. else {
  106315. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106316. return false;
  106317. }
  106318. if(blocksize_hint)
  106319. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106320. return false;
  106321. switch(sample_rate_hint) {
  106322. case 12:
  106323. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106324. return false;
  106325. break;
  106326. case 13:
  106327. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106328. return false;
  106329. break;
  106330. case 14:
  106331. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106332. return false;
  106333. break;
  106334. }
  106335. /* write the CRC */
  106336. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106337. return false;
  106338. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106339. return false;
  106340. return true;
  106341. }
  106342. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106343. {
  106344. FLAC__bool ok;
  106345. ok =
  106346. 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) &&
  106347. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106348. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106349. ;
  106350. return ok;
  106351. }
  106352. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106353. {
  106354. unsigned i;
  106355. 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))
  106356. return false;
  106357. if(wasted_bits)
  106358. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106359. return false;
  106360. for(i = 0; i < subframe->order; i++)
  106361. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106362. return false;
  106363. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106364. return false;
  106365. switch(subframe->entropy_coding_method.type) {
  106366. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106367. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106368. if(!add_residual_partitioned_rice_(
  106369. bw,
  106370. subframe->residual,
  106371. residual_samples,
  106372. subframe->order,
  106373. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106374. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106375. subframe->entropy_coding_method.data.partitioned_rice.order,
  106376. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106377. ))
  106378. return false;
  106379. break;
  106380. default:
  106381. FLAC__ASSERT(0);
  106382. }
  106383. return true;
  106384. }
  106385. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106386. {
  106387. unsigned i;
  106388. 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))
  106389. return false;
  106390. if(wasted_bits)
  106391. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106392. return false;
  106393. for(i = 0; i < subframe->order; i++)
  106394. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106395. return false;
  106396. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106397. return false;
  106398. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106399. return false;
  106400. for(i = 0; i < subframe->order; i++)
  106401. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106402. return false;
  106403. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106404. return false;
  106405. switch(subframe->entropy_coding_method.type) {
  106406. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106407. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106408. if(!add_residual_partitioned_rice_(
  106409. bw,
  106410. subframe->residual,
  106411. residual_samples,
  106412. subframe->order,
  106413. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106414. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106415. subframe->entropy_coding_method.data.partitioned_rice.order,
  106416. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106417. ))
  106418. return false;
  106419. break;
  106420. default:
  106421. FLAC__ASSERT(0);
  106422. }
  106423. return true;
  106424. }
  106425. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106426. {
  106427. unsigned i;
  106428. const FLAC__int32 *signal = subframe->data;
  106429. 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))
  106430. return false;
  106431. if(wasted_bits)
  106432. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106433. return false;
  106434. for(i = 0; i < samples; i++)
  106435. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106436. return false;
  106437. return true;
  106438. }
  106439. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106440. {
  106441. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106442. return false;
  106443. switch(method->type) {
  106444. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106445. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106446. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106447. return false;
  106448. break;
  106449. default:
  106450. FLAC__ASSERT(0);
  106451. }
  106452. return true;
  106453. }
  106454. 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)
  106455. {
  106456. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106457. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106458. if(partition_order == 0) {
  106459. unsigned i;
  106460. if(raw_bits[0] == 0) {
  106461. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106462. return false;
  106463. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106464. return false;
  106465. }
  106466. else {
  106467. FLAC__ASSERT(rice_parameters[0] == 0);
  106468. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106469. return false;
  106470. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106471. return false;
  106472. for(i = 0; i < residual_samples; i++) {
  106473. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106474. return false;
  106475. }
  106476. }
  106477. return true;
  106478. }
  106479. else {
  106480. unsigned i, j, k = 0, k_last = 0;
  106481. unsigned partition_samples;
  106482. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106483. for(i = 0; i < (1u<<partition_order); i++) {
  106484. partition_samples = default_partition_samples;
  106485. if(i == 0)
  106486. partition_samples -= predictor_order;
  106487. k += partition_samples;
  106488. if(raw_bits[i] == 0) {
  106489. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106490. return false;
  106491. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106492. return false;
  106493. }
  106494. else {
  106495. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106496. return false;
  106497. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106498. return false;
  106499. for(j = k_last; j < k; j++) {
  106500. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106501. return false;
  106502. }
  106503. }
  106504. k_last = k;
  106505. }
  106506. return true;
  106507. }
  106508. }
  106509. #endif
  106510. /*** End of inlined file: stream_encoder_framing.c ***/
  106511. /*** Start of inlined file: window_flac.c ***/
  106512. /*** Start of inlined file: juce_FlacHeader.h ***/
  106513. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106514. // tasks..
  106515. #define VERSION "1.2.1"
  106516. #define FLAC__NO_DLL 1
  106517. #if JUCE_MSVC
  106518. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106519. #endif
  106520. #if JUCE_MAC
  106521. #define FLAC__SYS_DARWIN 1
  106522. #endif
  106523. /*** End of inlined file: juce_FlacHeader.h ***/
  106524. #if JUCE_USE_FLAC
  106525. #if HAVE_CONFIG_H
  106526. # include <config.h>
  106527. #endif
  106528. #include <math.h>
  106529. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106530. #ifndef M_PI
  106531. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106532. #define M_PI 3.14159265358979323846
  106533. #endif
  106534. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106535. {
  106536. const FLAC__int32 N = L - 1;
  106537. FLAC__int32 n;
  106538. if (L & 1) {
  106539. for (n = 0; n <= N/2; n++)
  106540. window[n] = 2.0f * n / (float)N;
  106541. for (; n <= N; n++)
  106542. window[n] = 2.0f - 2.0f * n / (float)N;
  106543. }
  106544. else {
  106545. for (n = 0; n <= L/2-1; n++)
  106546. window[n] = 2.0f * n / (float)N;
  106547. for (; n <= N; n++)
  106548. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106549. }
  106550. }
  106551. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106552. {
  106553. const FLAC__int32 N = L - 1;
  106554. FLAC__int32 n;
  106555. for (n = 0; n < L; n++)
  106556. 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)));
  106557. }
  106558. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106559. {
  106560. const FLAC__int32 N = L - 1;
  106561. FLAC__int32 n;
  106562. for (n = 0; n < L; n++)
  106563. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106564. }
  106565. /* 4-term -92dB side-lobe */
  106566. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106567. {
  106568. const FLAC__int32 N = L - 1;
  106569. FLAC__int32 n;
  106570. for (n = 0; n <= N; n++)
  106571. 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));
  106572. }
  106573. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106574. {
  106575. const FLAC__int32 N = L - 1;
  106576. const double N2 = (double)N / 2.;
  106577. FLAC__int32 n;
  106578. for (n = 0; n <= N; n++) {
  106579. double k = ((double)n - N2) / N2;
  106580. k = 1.0f - k * k;
  106581. window[n] = (FLAC__real)(k * k);
  106582. }
  106583. }
  106584. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106585. {
  106586. const FLAC__int32 N = L - 1;
  106587. FLAC__int32 n;
  106588. for (n = 0; n < L; n++)
  106589. 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));
  106590. }
  106591. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106592. {
  106593. const FLAC__int32 N = L - 1;
  106594. const double N2 = (double)N / 2.;
  106595. FLAC__int32 n;
  106596. for (n = 0; n <= N; n++) {
  106597. const double k = ((double)n - N2) / (stddev * N2);
  106598. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106599. }
  106600. }
  106601. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106602. {
  106603. const FLAC__int32 N = L - 1;
  106604. FLAC__int32 n;
  106605. for (n = 0; n < L; n++)
  106606. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106607. }
  106608. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106609. {
  106610. const FLAC__int32 N = L - 1;
  106611. FLAC__int32 n;
  106612. for (n = 0; n < L; n++)
  106613. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106614. }
  106615. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106616. {
  106617. const FLAC__int32 N = L - 1;
  106618. FLAC__int32 n;
  106619. for (n = 0; n < L; n++)
  106620. 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));
  106621. }
  106622. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106623. {
  106624. const FLAC__int32 N = L - 1;
  106625. FLAC__int32 n;
  106626. for (n = 0; n < L; n++)
  106627. 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));
  106628. }
  106629. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106630. {
  106631. FLAC__int32 n;
  106632. for (n = 0; n < L; n++)
  106633. window[n] = 1.0f;
  106634. }
  106635. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106636. {
  106637. FLAC__int32 n;
  106638. if (L & 1) {
  106639. for (n = 1; n <= L+1/2; n++)
  106640. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106641. for (; n <= L; n++)
  106642. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106643. }
  106644. else {
  106645. for (n = 1; n <= L/2; n++)
  106646. window[n-1] = 2.0f * n / (float)L;
  106647. for (; n <= L; n++)
  106648. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106649. }
  106650. }
  106651. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106652. {
  106653. if (p <= 0.0)
  106654. FLAC__window_rectangle(window, L);
  106655. else if (p >= 1.0)
  106656. FLAC__window_hann(window, L);
  106657. else {
  106658. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106659. FLAC__int32 n;
  106660. /* start with rectangle... */
  106661. FLAC__window_rectangle(window, L);
  106662. /* ...replace ends with hann */
  106663. if (Np > 0) {
  106664. for (n = 0; n <= Np; n++) {
  106665. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106666. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106667. }
  106668. }
  106669. }
  106670. }
  106671. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106672. {
  106673. const FLAC__int32 N = L - 1;
  106674. const double N2 = (double)N / 2.;
  106675. FLAC__int32 n;
  106676. for (n = 0; n <= N; n++) {
  106677. const double k = ((double)n - N2) / N2;
  106678. window[n] = (FLAC__real)(1.0f - k * k);
  106679. }
  106680. }
  106681. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106682. #endif
  106683. /*** End of inlined file: window_flac.c ***/
  106684. #else
  106685. #include <FLAC/all.h>
  106686. #endif
  106687. }
  106688. #undef max
  106689. #undef min
  106690. BEGIN_JUCE_NAMESPACE
  106691. static const char* const flacFormatName = "FLAC file";
  106692. static const char* const flacExtensions[] = { ".flac", 0 };
  106693. class FlacReader : public AudioFormatReader
  106694. {
  106695. public:
  106696. FlacReader (InputStream* const in)
  106697. : AudioFormatReader (in, TRANS (flacFormatName)),
  106698. reservoir (2, 0),
  106699. reservoirStart (0),
  106700. samplesInReservoir (0),
  106701. scanningForLength (false)
  106702. {
  106703. using namespace FlacNamespace;
  106704. lengthInSamples = 0;
  106705. decoder = FLAC__stream_decoder_new();
  106706. ok = FLAC__stream_decoder_init_stream (decoder,
  106707. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106708. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106709. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106710. if (ok)
  106711. {
  106712. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106713. if (lengthInSamples == 0 && sampleRate > 0)
  106714. {
  106715. // the length hasn't been stored in the metadata, so we'll need to
  106716. // work it out the length the hard way, by scanning the whole file..
  106717. scanningForLength = true;
  106718. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106719. scanningForLength = false;
  106720. const int64 tempLength = lengthInSamples;
  106721. FLAC__stream_decoder_reset (decoder);
  106722. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106723. lengthInSamples = tempLength;
  106724. }
  106725. }
  106726. }
  106727. ~FlacReader()
  106728. {
  106729. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106730. }
  106731. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106732. {
  106733. sampleRate = info.sample_rate;
  106734. bitsPerSample = info.bits_per_sample;
  106735. lengthInSamples = (unsigned int) info.total_samples;
  106736. numChannels = info.channels;
  106737. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106738. }
  106739. // returns the number of samples read
  106740. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106741. int64 startSampleInFile, int numSamples)
  106742. {
  106743. using namespace FlacNamespace;
  106744. if (! ok)
  106745. return false;
  106746. while (numSamples > 0)
  106747. {
  106748. if (startSampleInFile >= reservoirStart
  106749. && startSampleInFile < reservoirStart + samplesInReservoir)
  106750. {
  106751. const int num = (int) jmin ((int64) numSamples,
  106752. reservoirStart + samplesInReservoir - startSampleInFile);
  106753. jassert (num > 0);
  106754. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106755. if (destSamples[i] != 0)
  106756. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106757. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106758. sizeof (int) * num);
  106759. startOffsetInDestBuffer += num;
  106760. startSampleInFile += num;
  106761. numSamples -= num;
  106762. }
  106763. else
  106764. {
  106765. if (startSampleInFile >= (int) lengthInSamples)
  106766. {
  106767. samplesInReservoir = 0;
  106768. }
  106769. else if (startSampleInFile < reservoirStart
  106770. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106771. {
  106772. // had some problems with flac crashing if the read pos is aligned more
  106773. // accurately than this. Probably fixed in newer versions of the library, though.
  106774. reservoirStart = (int) (startSampleInFile & ~511);
  106775. samplesInReservoir = 0;
  106776. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106777. }
  106778. else
  106779. {
  106780. reservoirStart += samplesInReservoir;
  106781. samplesInReservoir = 0;
  106782. FLAC__stream_decoder_process_single (decoder);
  106783. }
  106784. if (samplesInReservoir == 0)
  106785. break;
  106786. }
  106787. }
  106788. if (numSamples > 0)
  106789. {
  106790. for (int i = numDestChannels; --i >= 0;)
  106791. if (destSamples[i] != 0)
  106792. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106793. sizeof (int) * numSamples);
  106794. }
  106795. return true;
  106796. }
  106797. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106798. {
  106799. if (scanningForLength)
  106800. {
  106801. lengthInSamples += numSamples;
  106802. }
  106803. else
  106804. {
  106805. if (numSamples > reservoir.getNumSamples())
  106806. reservoir.setSize (numChannels, numSamples, false, false, true);
  106807. const int bitsToShift = 32 - bitsPerSample;
  106808. for (int i = 0; i < (int) numChannels; ++i)
  106809. {
  106810. const FlacNamespace::FLAC__int32* src = buffer[i];
  106811. int n = i;
  106812. while (src == 0 && n > 0)
  106813. src = buffer [--n];
  106814. if (src != 0)
  106815. {
  106816. int* dest = (int*) reservoir.getSampleData(i);
  106817. for (int j = 0; j < numSamples; ++j)
  106818. dest[j] = src[j] << bitsToShift;
  106819. }
  106820. }
  106821. samplesInReservoir = numSamples;
  106822. }
  106823. }
  106824. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106825. {
  106826. using namespace FlacNamespace;
  106827. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106828. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106829. }
  106830. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106831. {
  106832. using namespace FlacNamespace;
  106833. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106834. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106835. }
  106836. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106837. {
  106838. using namespace FlacNamespace;
  106839. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106840. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106841. }
  106842. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106843. {
  106844. using namespace FlacNamespace;
  106845. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106846. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106847. }
  106848. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106849. {
  106850. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106851. }
  106852. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106853. const FlacNamespace::FLAC__Frame* frame,
  106854. const FlacNamespace::FLAC__int32* const buffer[],
  106855. void* client_data)
  106856. {
  106857. using namespace FlacNamespace;
  106858. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106859. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106860. }
  106861. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106862. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106863. void* client_data)
  106864. {
  106865. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106866. }
  106867. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106868. {
  106869. }
  106870. juce_UseDebuggingNewOperator
  106871. private:
  106872. FlacNamespace::FLAC__StreamDecoder* decoder;
  106873. AudioSampleBuffer reservoir;
  106874. int reservoirStart, samplesInReservoir;
  106875. bool ok, scanningForLength;
  106876. FlacReader (const FlacReader&);
  106877. FlacReader& operator= (const FlacReader&);
  106878. };
  106879. class FlacWriter : public AudioFormatWriter
  106880. {
  106881. public:
  106882. FlacWriter (OutputStream* const out,
  106883. const double sampleRate_,
  106884. const int numChannels_,
  106885. const int bitsPerSample_)
  106886. : AudioFormatWriter (out, TRANS (flacFormatName),
  106887. sampleRate_,
  106888. numChannels_,
  106889. bitsPerSample_)
  106890. {
  106891. using namespace FlacNamespace;
  106892. encoder = FLAC__stream_encoder_new();
  106893. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106894. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106895. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106896. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106897. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106898. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106899. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106900. ok = FLAC__stream_encoder_init_stream (encoder,
  106901. encodeWriteCallback, encodeSeekCallback,
  106902. encodeTellCallback, encodeMetadataCallback,
  106903. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106904. }
  106905. ~FlacWriter()
  106906. {
  106907. if (ok)
  106908. {
  106909. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106910. output->flush();
  106911. }
  106912. else
  106913. {
  106914. output = 0; // to stop the base class deleting this, as it needs to be returned
  106915. // to the caller of createWriter()
  106916. }
  106917. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106918. }
  106919. bool write (const int** samplesToWrite, int numSamples)
  106920. {
  106921. using namespace FlacNamespace;
  106922. if (! ok)
  106923. return false;
  106924. int* buf[3];
  106925. const int bitsToShift = 32 - bitsPerSample;
  106926. if (bitsToShift > 0)
  106927. {
  106928. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106929. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  106930. buf[0] = (int*) temp.getData();
  106931. buf[1] = buf[0] + numSamples;
  106932. buf[2] = 0;
  106933. for (int i = numChannelsToWrite; --i >= 0;)
  106934. {
  106935. if (samplesToWrite[i] != 0)
  106936. {
  106937. for (int j = 0; j < numSamples; ++j)
  106938. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106939. }
  106940. }
  106941. samplesToWrite = (const int**) buf;
  106942. }
  106943. return FLAC__stream_encoder_process (encoder,
  106944. (const FLAC__int32**) samplesToWrite,
  106945. numSamples) != 0;
  106946. }
  106947. bool writeData (const void* const data, const int size) const
  106948. {
  106949. return output->write (data, size);
  106950. }
  106951. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106952. {
  106953. using namespace FlacNamespace;
  106954. b += bytes;
  106955. for (int i = 0; i < bytes; ++i)
  106956. {
  106957. *(--b) = (FLAC__byte) (val & 0xff);
  106958. val >>= 8;
  106959. }
  106960. }
  106961. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106962. {
  106963. using namespace FlacNamespace;
  106964. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106965. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106966. const unsigned int channelsMinus1 = info.channels - 1;
  106967. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106968. packUint32 (info.min_blocksize, buffer, 2);
  106969. packUint32 (info.max_blocksize, buffer + 2, 2);
  106970. packUint32 (info.min_framesize, buffer + 4, 3);
  106971. packUint32 (info.max_framesize, buffer + 7, 3);
  106972. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106973. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106974. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106975. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106976. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106977. memcpy (buffer + 18, info.md5sum, 16);
  106978. const bool seekOk = output->setPosition (4);
  106979. (void) seekOk;
  106980. // if this fails, you've given it an output stream that can't seek! It needs
  106981. // to be able to seek back to write the header
  106982. jassert (seekOk);
  106983. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106984. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106985. }
  106986. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106987. const FlacNamespace::FLAC__byte buffer[],
  106988. size_t bytes,
  106989. unsigned int /*samples*/,
  106990. unsigned int /*current_frame*/,
  106991. void* client_data)
  106992. {
  106993. using namespace FlacNamespace;
  106994. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106995. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106996. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106997. }
  106998. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106999. {
  107000. using namespace FlacNamespace;
  107001. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107002. }
  107003. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107004. {
  107005. using namespace FlacNamespace;
  107006. if (client_data == 0)
  107007. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107008. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107009. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107010. }
  107011. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107012. {
  107013. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107014. }
  107015. juce_UseDebuggingNewOperator
  107016. bool ok;
  107017. private:
  107018. FlacNamespace::FLAC__StreamEncoder* encoder;
  107019. MemoryBlock temp;
  107020. FlacWriter (const FlacWriter&);
  107021. FlacWriter& operator= (const FlacWriter&);
  107022. };
  107023. FlacAudioFormat::FlacAudioFormat()
  107024. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107025. {
  107026. }
  107027. FlacAudioFormat::~FlacAudioFormat()
  107028. {
  107029. }
  107030. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107031. {
  107032. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107033. return Array <int> (rates);
  107034. }
  107035. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107036. {
  107037. const int depths[] = { 16, 24, 0 };
  107038. return Array <int> (depths);
  107039. }
  107040. bool FlacAudioFormat::canDoStereo()
  107041. {
  107042. return true;
  107043. }
  107044. bool FlacAudioFormat::canDoMono()
  107045. {
  107046. return true;
  107047. }
  107048. bool FlacAudioFormat::isCompressed()
  107049. {
  107050. return true;
  107051. }
  107052. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107053. const bool deleteStreamIfOpeningFails)
  107054. {
  107055. ScopedPointer<FlacReader> r (new FlacReader (in));
  107056. if (r->sampleRate != 0)
  107057. return r.release();
  107058. if (! deleteStreamIfOpeningFails)
  107059. r->input = 0;
  107060. return 0;
  107061. }
  107062. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107063. double sampleRate,
  107064. unsigned int numberOfChannels,
  107065. int bitsPerSample,
  107066. const StringPairArray& /*metadataValues*/,
  107067. int /*qualityOptionIndex*/)
  107068. {
  107069. if (getPossibleBitDepths().contains (bitsPerSample))
  107070. {
  107071. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  107072. if (w->ok)
  107073. return w.release();
  107074. }
  107075. return 0;
  107076. }
  107077. END_JUCE_NAMESPACE
  107078. #endif
  107079. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107080. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107081. #if JUCE_USE_OGGVORBIS
  107082. #if JUCE_MAC
  107083. #define __MACOSX__ 1
  107084. #endif
  107085. namespace OggVorbisNamespace
  107086. {
  107087. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107088. /*** Start of inlined file: vorbisenc.h ***/
  107089. #ifndef _OV_ENC_H_
  107090. #define _OV_ENC_H_
  107091. #ifdef __cplusplus
  107092. extern "C"
  107093. {
  107094. #endif /* __cplusplus */
  107095. /*** Start of inlined file: codec.h ***/
  107096. #ifndef _vorbis_codec_h_
  107097. #define _vorbis_codec_h_
  107098. #ifdef __cplusplus
  107099. extern "C"
  107100. {
  107101. #endif /* __cplusplus */
  107102. /*** Start of inlined file: ogg.h ***/
  107103. #ifndef _OGG_H
  107104. #define _OGG_H
  107105. #ifdef __cplusplus
  107106. extern "C" {
  107107. #endif
  107108. /*** Start of inlined file: os_types.h ***/
  107109. #ifndef _OS_TYPES_H
  107110. #define _OS_TYPES_H
  107111. /* make it easy on the folks that want to compile the libs with a
  107112. different malloc than stdlib */
  107113. #define _ogg_malloc malloc
  107114. #define _ogg_calloc calloc
  107115. #define _ogg_realloc realloc
  107116. #define _ogg_free free
  107117. #if defined(_WIN32)
  107118. # if defined(__CYGWIN__)
  107119. # include <_G_config.h>
  107120. typedef _G_int64_t ogg_int64_t;
  107121. typedef _G_int32_t ogg_int32_t;
  107122. typedef _G_uint32_t ogg_uint32_t;
  107123. typedef _G_int16_t ogg_int16_t;
  107124. typedef _G_uint16_t ogg_uint16_t;
  107125. # elif defined(__MINGW32__)
  107126. typedef short ogg_int16_t;
  107127. typedef unsigned short ogg_uint16_t;
  107128. typedef int ogg_int32_t;
  107129. typedef unsigned int ogg_uint32_t;
  107130. typedef long long ogg_int64_t;
  107131. typedef unsigned long long ogg_uint64_t;
  107132. # elif defined(__MWERKS__)
  107133. typedef long long ogg_int64_t;
  107134. typedef int ogg_int32_t;
  107135. typedef unsigned int ogg_uint32_t;
  107136. typedef short ogg_int16_t;
  107137. typedef unsigned short ogg_uint16_t;
  107138. # else
  107139. /* MSVC/Borland */
  107140. typedef __int64 ogg_int64_t;
  107141. typedef __int32 ogg_int32_t;
  107142. typedef unsigned __int32 ogg_uint32_t;
  107143. typedef __int16 ogg_int16_t;
  107144. typedef unsigned __int16 ogg_uint16_t;
  107145. # endif
  107146. #elif defined(__MACOS__)
  107147. # include <sys/types.h>
  107148. typedef SInt16 ogg_int16_t;
  107149. typedef UInt16 ogg_uint16_t;
  107150. typedef SInt32 ogg_int32_t;
  107151. typedef UInt32 ogg_uint32_t;
  107152. typedef SInt64 ogg_int64_t;
  107153. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107154. # include <sys/types.h>
  107155. typedef int16_t ogg_int16_t;
  107156. typedef u_int16_t ogg_uint16_t;
  107157. typedef int32_t ogg_int32_t;
  107158. typedef u_int32_t ogg_uint32_t;
  107159. typedef int64_t ogg_int64_t;
  107160. #elif defined(__BEOS__)
  107161. /* Be */
  107162. # include <inttypes.h>
  107163. typedef int16_t ogg_int16_t;
  107164. typedef u_int16_t ogg_uint16_t;
  107165. typedef int32_t ogg_int32_t;
  107166. typedef u_int32_t ogg_uint32_t;
  107167. typedef int64_t ogg_int64_t;
  107168. #elif defined (__EMX__)
  107169. /* OS/2 GCC */
  107170. typedef short ogg_int16_t;
  107171. typedef unsigned short ogg_uint16_t;
  107172. typedef int ogg_int32_t;
  107173. typedef unsigned int ogg_uint32_t;
  107174. typedef long long ogg_int64_t;
  107175. #elif defined (DJGPP)
  107176. /* DJGPP */
  107177. typedef short ogg_int16_t;
  107178. typedef int ogg_int32_t;
  107179. typedef unsigned int ogg_uint32_t;
  107180. typedef long long ogg_int64_t;
  107181. #elif defined(R5900)
  107182. /* PS2 EE */
  107183. typedef long ogg_int64_t;
  107184. typedef int ogg_int32_t;
  107185. typedef unsigned ogg_uint32_t;
  107186. typedef short ogg_int16_t;
  107187. #elif defined(__SYMBIAN32__)
  107188. /* Symbian GCC */
  107189. typedef signed short ogg_int16_t;
  107190. typedef unsigned short ogg_uint16_t;
  107191. typedef signed int ogg_int32_t;
  107192. typedef unsigned int ogg_uint32_t;
  107193. typedef long long int ogg_int64_t;
  107194. #else
  107195. # include <sys/types.h>
  107196. /*** Start of inlined file: config_types.h ***/
  107197. #ifndef __CONFIG_TYPES_H__
  107198. #define __CONFIG_TYPES_H__
  107199. typedef int16_t ogg_int16_t;
  107200. typedef unsigned short ogg_uint16_t;
  107201. typedef int32_t ogg_int32_t;
  107202. typedef unsigned int ogg_uint32_t;
  107203. typedef int64_t ogg_int64_t;
  107204. #endif
  107205. /*** End of inlined file: config_types.h ***/
  107206. #endif
  107207. #endif /* _OS_TYPES_H */
  107208. /*** End of inlined file: os_types.h ***/
  107209. typedef struct {
  107210. long endbyte;
  107211. int endbit;
  107212. unsigned char *buffer;
  107213. unsigned char *ptr;
  107214. long storage;
  107215. } oggpack_buffer;
  107216. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107217. typedef struct {
  107218. unsigned char *header;
  107219. long header_len;
  107220. unsigned char *body;
  107221. long body_len;
  107222. } ogg_page;
  107223. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107224. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107225. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107226. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107227. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107228. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107229. }
  107230. /* ogg_stream_state contains the current encode/decode state of a logical
  107231. Ogg bitstream **********************************************************/
  107232. typedef struct {
  107233. unsigned char *body_data; /* bytes from packet bodies */
  107234. long body_storage; /* storage elements allocated */
  107235. long body_fill; /* elements stored; fill mark */
  107236. long body_returned; /* elements of fill returned */
  107237. int *lacing_vals; /* The values that will go to the segment table */
  107238. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107239. this way, but it is simple coupled to the
  107240. lacing fifo */
  107241. long lacing_storage;
  107242. long lacing_fill;
  107243. long lacing_packet;
  107244. long lacing_returned;
  107245. unsigned char header[282]; /* working space for header encode */
  107246. int header_fill;
  107247. int e_o_s; /* set when we have buffered the last packet in the
  107248. logical bitstream */
  107249. int b_o_s; /* set after we've written the initial page
  107250. of a logical bitstream */
  107251. long serialno;
  107252. long pageno;
  107253. ogg_int64_t packetno; /* sequence number for decode; the framing
  107254. knows where there's a hole in the data,
  107255. but we need coupling so that the codec
  107256. (which is in a seperate abstraction
  107257. layer) also knows about the gap */
  107258. ogg_int64_t granulepos;
  107259. } ogg_stream_state;
  107260. /* ogg_packet is used to encapsulate the data and metadata belonging
  107261. to a single raw Ogg/Vorbis packet *************************************/
  107262. typedef struct {
  107263. unsigned char *packet;
  107264. long bytes;
  107265. long b_o_s;
  107266. long e_o_s;
  107267. ogg_int64_t granulepos;
  107268. ogg_int64_t packetno; /* sequence number for decode; the framing
  107269. knows where there's a hole in the data,
  107270. but we need coupling so that the codec
  107271. (which is in a seperate abstraction
  107272. layer) also knows about the gap */
  107273. } ogg_packet;
  107274. typedef struct {
  107275. unsigned char *data;
  107276. int storage;
  107277. int fill;
  107278. int returned;
  107279. int unsynced;
  107280. int headerbytes;
  107281. int bodybytes;
  107282. } ogg_sync_state;
  107283. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107284. extern void oggpack_writeinit(oggpack_buffer *b);
  107285. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107286. extern void oggpack_writealign(oggpack_buffer *b);
  107287. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107288. extern void oggpack_reset(oggpack_buffer *b);
  107289. extern void oggpack_writeclear(oggpack_buffer *b);
  107290. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107291. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107292. extern long oggpack_look(oggpack_buffer *b,int bits);
  107293. extern long oggpack_look1(oggpack_buffer *b);
  107294. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107295. extern void oggpack_adv1(oggpack_buffer *b);
  107296. extern long oggpack_read(oggpack_buffer *b,int bits);
  107297. extern long oggpack_read1(oggpack_buffer *b);
  107298. extern long oggpack_bytes(oggpack_buffer *b);
  107299. extern long oggpack_bits(oggpack_buffer *b);
  107300. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107301. extern void oggpackB_writeinit(oggpack_buffer *b);
  107302. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107303. extern void oggpackB_writealign(oggpack_buffer *b);
  107304. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107305. extern void oggpackB_reset(oggpack_buffer *b);
  107306. extern void oggpackB_writeclear(oggpack_buffer *b);
  107307. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107308. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107309. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107310. extern long oggpackB_look1(oggpack_buffer *b);
  107311. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107312. extern void oggpackB_adv1(oggpack_buffer *b);
  107313. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107314. extern long oggpackB_read1(oggpack_buffer *b);
  107315. extern long oggpackB_bytes(oggpack_buffer *b);
  107316. extern long oggpackB_bits(oggpack_buffer *b);
  107317. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107318. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107319. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107320. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107321. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107322. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107323. extern int ogg_sync_init(ogg_sync_state *oy);
  107324. extern int ogg_sync_clear(ogg_sync_state *oy);
  107325. extern int ogg_sync_reset(ogg_sync_state *oy);
  107326. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107327. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107328. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107329. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107330. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107331. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107332. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107333. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107334. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107335. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107336. extern int ogg_stream_clear(ogg_stream_state *os);
  107337. extern int ogg_stream_reset(ogg_stream_state *os);
  107338. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107339. extern int ogg_stream_destroy(ogg_stream_state *os);
  107340. extern int ogg_stream_eos(ogg_stream_state *os);
  107341. extern void ogg_page_checksum_set(ogg_page *og);
  107342. extern int ogg_page_version(ogg_page *og);
  107343. extern int ogg_page_continued(ogg_page *og);
  107344. extern int ogg_page_bos(ogg_page *og);
  107345. extern int ogg_page_eos(ogg_page *og);
  107346. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107347. extern int ogg_page_serialno(ogg_page *og);
  107348. extern long ogg_page_pageno(ogg_page *og);
  107349. extern int ogg_page_packets(ogg_page *og);
  107350. extern void ogg_packet_clear(ogg_packet *op);
  107351. #ifdef __cplusplus
  107352. }
  107353. #endif
  107354. #endif /* _OGG_H */
  107355. /*** End of inlined file: ogg.h ***/
  107356. typedef struct vorbis_info{
  107357. int version;
  107358. int channels;
  107359. long rate;
  107360. /* The below bitrate declarations are *hints*.
  107361. Combinations of the three values carry the following implications:
  107362. all three set to the same value:
  107363. implies a fixed rate bitstream
  107364. only nominal set:
  107365. implies a VBR stream that averages the nominal bitrate. No hard
  107366. upper/lower limit
  107367. upper and or lower set:
  107368. implies a VBR bitstream that obeys the bitrate limits. nominal
  107369. may also be set to give a nominal rate.
  107370. none set:
  107371. the coder does not care to speculate.
  107372. */
  107373. long bitrate_upper;
  107374. long bitrate_nominal;
  107375. long bitrate_lower;
  107376. long bitrate_window;
  107377. void *codec_setup;
  107378. } vorbis_info;
  107379. /* vorbis_dsp_state buffers the current vorbis audio
  107380. analysis/synthesis state. The DSP state belongs to a specific
  107381. logical bitstream ****************************************************/
  107382. typedef struct vorbis_dsp_state{
  107383. int analysisp;
  107384. vorbis_info *vi;
  107385. float **pcm;
  107386. float **pcmret;
  107387. int pcm_storage;
  107388. int pcm_current;
  107389. int pcm_returned;
  107390. int preextrapolate;
  107391. int eofflag;
  107392. long lW;
  107393. long W;
  107394. long nW;
  107395. long centerW;
  107396. ogg_int64_t granulepos;
  107397. ogg_int64_t sequence;
  107398. ogg_int64_t glue_bits;
  107399. ogg_int64_t time_bits;
  107400. ogg_int64_t floor_bits;
  107401. ogg_int64_t res_bits;
  107402. void *backend_state;
  107403. } vorbis_dsp_state;
  107404. typedef struct vorbis_block{
  107405. /* necessary stream state for linking to the framing abstraction */
  107406. float **pcm; /* this is a pointer into local storage */
  107407. oggpack_buffer opb;
  107408. long lW;
  107409. long W;
  107410. long nW;
  107411. int pcmend;
  107412. int mode;
  107413. int eofflag;
  107414. ogg_int64_t granulepos;
  107415. ogg_int64_t sequence;
  107416. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107417. /* local storage to avoid remallocing; it's up to the mapping to
  107418. structure it */
  107419. void *localstore;
  107420. long localtop;
  107421. long localalloc;
  107422. long totaluse;
  107423. struct alloc_chain *reap;
  107424. /* bitmetrics for the frame */
  107425. long glue_bits;
  107426. long time_bits;
  107427. long floor_bits;
  107428. long res_bits;
  107429. void *internal;
  107430. } vorbis_block;
  107431. /* vorbis_block is a single block of data to be processed as part of
  107432. the analysis/synthesis stream; it belongs to a specific logical
  107433. bitstream, but is independant from other vorbis_blocks belonging to
  107434. that logical bitstream. *************************************************/
  107435. struct alloc_chain{
  107436. void *ptr;
  107437. struct alloc_chain *next;
  107438. };
  107439. /* vorbis_info contains all the setup information specific to the
  107440. specific compression/decompression mode in progress (eg,
  107441. psychoacoustic settings, channel setup, options, codebook
  107442. etc). vorbis_info and substructures are in backends.h.
  107443. *********************************************************************/
  107444. /* the comments are not part of vorbis_info so that vorbis_info can be
  107445. static storage */
  107446. typedef struct vorbis_comment{
  107447. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107448. whatever vendor is set to in encode */
  107449. char **user_comments;
  107450. int *comment_lengths;
  107451. int comments;
  107452. char *vendor;
  107453. } vorbis_comment;
  107454. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107455. and produce a packet (see docs/analysis.txt). The packet is then
  107456. coded into a framed OggSquish bitstream by the second layer (see
  107457. docs/framing.txt). Decode is the reverse process; we sync/frame
  107458. the bitstream and extract individual packets, then decode the
  107459. packet back into PCM audio.
  107460. The extra framing/packetizing is used in streaming formats, such as
  107461. files. Over the net (such as with UDP), the framing and
  107462. packetization aren't necessary as they're provided by the transport
  107463. and the streaming layer is not used */
  107464. /* Vorbis PRIMITIVES: general ***************************************/
  107465. extern void vorbis_info_init(vorbis_info *vi);
  107466. extern void vorbis_info_clear(vorbis_info *vi);
  107467. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107468. extern void vorbis_comment_init(vorbis_comment *vc);
  107469. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107470. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107471. const char *tag, char *contents);
  107472. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107473. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107474. extern void vorbis_comment_clear(vorbis_comment *vc);
  107475. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107476. extern int vorbis_block_clear(vorbis_block *vb);
  107477. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107478. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107479. ogg_int64_t granulepos);
  107480. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107481. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107482. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107483. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107484. vorbis_comment *vc,
  107485. ogg_packet *op,
  107486. ogg_packet *op_comm,
  107487. ogg_packet *op_code);
  107488. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107489. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107490. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107491. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107492. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107493. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107494. ogg_packet *op);
  107495. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107496. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107497. ogg_packet *op);
  107498. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107499. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107500. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107501. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107502. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107503. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107504. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107505. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107506. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107507. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107508. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107509. /* Vorbis ERRORS and return codes ***********************************/
  107510. #define OV_FALSE -1
  107511. #define OV_EOF -2
  107512. #define OV_HOLE -3
  107513. #define OV_EREAD -128
  107514. #define OV_EFAULT -129
  107515. #define OV_EIMPL -130
  107516. #define OV_EINVAL -131
  107517. #define OV_ENOTVORBIS -132
  107518. #define OV_EBADHEADER -133
  107519. #define OV_EVERSION -134
  107520. #define OV_ENOTAUDIO -135
  107521. #define OV_EBADPACKET -136
  107522. #define OV_EBADLINK -137
  107523. #define OV_ENOSEEK -138
  107524. #ifdef __cplusplus
  107525. }
  107526. #endif /* __cplusplus */
  107527. #endif
  107528. /*** End of inlined file: codec.h ***/
  107529. extern int vorbis_encode_init(vorbis_info *vi,
  107530. long channels,
  107531. long rate,
  107532. long max_bitrate,
  107533. long nominal_bitrate,
  107534. long min_bitrate);
  107535. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107536. long channels,
  107537. long rate,
  107538. long max_bitrate,
  107539. long nominal_bitrate,
  107540. long min_bitrate);
  107541. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107542. long channels,
  107543. long rate,
  107544. float quality /* quality level from 0. (lo) to 1. (hi) */
  107545. );
  107546. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107547. long channels,
  107548. long rate,
  107549. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107550. );
  107551. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107552. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107553. /* deprecated rate management supported only for compatability */
  107554. #define OV_ECTL_RATEMANAGE_GET 0x10
  107555. #define OV_ECTL_RATEMANAGE_SET 0x11
  107556. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107557. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107558. struct ovectl_ratemanage_arg {
  107559. int management_active;
  107560. long bitrate_hard_min;
  107561. long bitrate_hard_max;
  107562. double bitrate_hard_window;
  107563. long bitrate_av_lo;
  107564. long bitrate_av_hi;
  107565. double bitrate_av_window;
  107566. double bitrate_av_window_center;
  107567. };
  107568. /* new rate setup */
  107569. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107570. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107571. struct ovectl_ratemanage2_arg {
  107572. int management_active;
  107573. long bitrate_limit_min_kbps;
  107574. long bitrate_limit_max_kbps;
  107575. long bitrate_limit_reservoir_bits;
  107576. double bitrate_limit_reservoir_bias;
  107577. long bitrate_average_kbps;
  107578. double bitrate_average_damping;
  107579. };
  107580. #define OV_ECTL_LOWPASS_GET 0x20
  107581. #define OV_ECTL_LOWPASS_SET 0x21
  107582. #define OV_ECTL_IBLOCK_GET 0x30
  107583. #define OV_ECTL_IBLOCK_SET 0x31
  107584. #ifdef __cplusplus
  107585. }
  107586. #endif /* __cplusplus */
  107587. #endif
  107588. /*** End of inlined file: vorbisenc.h ***/
  107589. /*** Start of inlined file: vorbisfile.h ***/
  107590. #ifndef _OV_FILE_H_
  107591. #define _OV_FILE_H_
  107592. #ifdef __cplusplus
  107593. extern "C"
  107594. {
  107595. #endif /* __cplusplus */
  107596. #include <stdio.h>
  107597. /* The function prototypes for the callbacks are basically the same as for
  107598. * the stdio functions fread, fseek, fclose, ftell.
  107599. * The one difference is that the FILE * arguments have been replaced with
  107600. * a void * - this is to be used as a pointer to whatever internal data these
  107601. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107602. *
  107603. * If you use other functions, check the docs for these functions and return
  107604. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107605. * unseekable
  107606. */
  107607. typedef struct {
  107608. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107609. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107610. int (*close_func) (void *datasource);
  107611. long (*tell_func) (void *datasource);
  107612. } ov_callbacks;
  107613. #define NOTOPEN 0
  107614. #define PARTOPEN 1
  107615. #define OPENED 2
  107616. #define STREAMSET 3
  107617. #define INITSET 4
  107618. typedef struct OggVorbis_File {
  107619. void *datasource; /* Pointer to a FILE *, etc. */
  107620. int seekable;
  107621. ogg_int64_t offset;
  107622. ogg_int64_t end;
  107623. ogg_sync_state oy;
  107624. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107625. stream appears */
  107626. int links;
  107627. ogg_int64_t *offsets;
  107628. ogg_int64_t *dataoffsets;
  107629. long *serialnos;
  107630. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107631. compatability; x2 size, stores both
  107632. beginning and end values */
  107633. vorbis_info *vi;
  107634. vorbis_comment *vc;
  107635. /* Decoding working state local storage */
  107636. ogg_int64_t pcm_offset;
  107637. int ready_state;
  107638. long current_serialno;
  107639. int current_link;
  107640. double bittrack;
  107641. double samptrack;
  107642. ogg_stream_state os; /* take physical pages, weld into a logical
  107643. stream of packets */
  107644. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107645. vorbis_block vb; /* local working space for packet->PCM decode */
  107646. ov_callbacks callbacks;
  107647. } OggVorbis_File;
  107648. extern int ov_clear(OggVorbis_File *vf);
  107649. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107650. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107651. char *initial, long ibytes, ov_callbacks callbacks);
  107652. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107653. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107654. char *initial, long ibytes, ov_callbacks callbacks);
  107655. extern int ov_test_open(OggVorbis_File *vf);
  107656. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107657. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107658. extern long ov_streams(OggVorbis_File *vf);
  107659. extern long ov_seekable(OggVorbis_File *vf);
  107660. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107661. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107662. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107663. extern double ov_time_total(OggVorbis_File *vf,int i);
  107664. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107665. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107666. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107667. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107668. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107669. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107670. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107671. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107672. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107673. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107674. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107675. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107676. extern double ov_time_tell(OggVorbis_File *vf);
  107677. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107678. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107679. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107680. int *bitstream);
  107681. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107682. int bigendianp,int word,int sgned,int *bitstream);
  107683. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107684. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107685. extern int ov_halfrate_p(OggVorbis_File *vf);
  107686. #ifdef __cplusplus
  107687. }
  107688. #endif /* __cplusplus */
  107689. #endif
  107690. /*** End of inlined file: vorbisfile.h ***/
  107691. /*** Start of inlined file: bitwise.c ***/
  107692. /* We're 'LSb' endian; if we write a word but read individual bits,
  107693. then we'll read the lsb first */
  107694. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107695. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107696. // tasks..
  107697. #if JUCE_MSVC
  107698. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107699. #endif
  107700. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107701. #if JUCE_USE_OGGVORBIS
  107702. #include <string.h>
  107703. #include <stdlib.h>
  107704. #define BUFFER_INCREMENT 256
  107705. static const unsigned long mask[]=
  107706. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107707. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107708. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107709. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107710. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107711. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107712. 0x3fffffff,0x7fffffff,0xffffffff };
  107713. static const unsigned int mask8B[]=
  107714. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107715. void oggpack_writeinit(oggpack_buffer *b){
  107716. memset(b,0,sizeof(*b));
  107717. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107718. b->buffer[0]='\0';
  107719. b->storage=BUFFER_INCREMENT;
  107720. }
  107721. void oggpackB_writeinit(oggpack_buffer *b){
  107722. oggpack_writeinit(b);
  107723. }
  107724. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107725. long bytes=bits>>3;
  107726. bits-=bytes*8;
  107727. b->ptr=b->buffer+bytes;
  107728. b->endbit=bits;
  107729. b->endbyte=bytes;
  107730. *b->ptr&=mask[bits];
  107731. }
  107732. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107733. long bytes=bits>>3;
  107734. bits-=bytes*8;
  107735. b->ptr=b->buffer+bytes;
  107736. b->endbit=bits;
  107737. b->endbyte=bytes;
  107738. *b->ptr&=mask8B[bits];
  107739. }
  107740. /* Takes only up to 32 bits. */
  107741. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107742. if(b->endbyte+4>=b->storage){
  107743. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107744. b->storage+=BUFFER_INCREMENT;
  107745. b->ptr=b->buffer+b->endbyte;
  107746. }
  107747. value&=mask[bits];
  107748. bits+=b->endbit;
  107749. b->ptr[0]|=value<<b->endbit;
  107750. if(bits>=8){
  107751. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107752. if(bits>=16){
  107753. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107754. if(bits>=24){
  107755. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107756. if(bits>=32){
  107757. if(b->endbit)
  107758. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107759. else
  107760. b->ptr[4]=0;
  107761. }
  107762. }
  107763. }
  107764. }
  107765. b->endbyte+=bits/8;
  107766. b->ptr+=bits/8;
  107767. b->endbit=bits&7;
  107768. }
  107769. /* Takes only up to 32 bits. */
  107770. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107771. if(b->endbyte+4>=b->storage){
  107772. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107773. b->storage+=BUFFER_INCREMENT;
  107774. b->ptr=b->buffer+b->endbyte;
  107775. }
  107776. value=(value&mask[bits])<<(32-bits);
  107777. bits+=b->endbit;
  107778. b->ptr[0]|=value>>(24+b->endbit);
  107779. if(bits>=8){
  107780. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107781. if(bits>=16){
  107782. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107783. if(bits>=24){
  107784. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107785. if(bits>=32){
  107786. if(b->endbit)
  107787. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107788. else
  107789. b->ptr[4]=0;
  107790. }
  107791. }
  107792. }
  107793. }
  107794. b->endbyte+=bits/8;
  107795. b->ptr+=bits/8;
  107796. b->endbit=bits&7;
  107797. }
  107798. void oggpack_writealign(oggpack_buffer *b){
  107799. int bits=8-b->endbit;
  107800. if(bits<8)
  107801. oggpack_write(b,0,bits);
  107802. }
  107803. void oggpackB_writealign(oggpack_buffer *b){
  107804. int bits=8-b->endbit;
  107805. if(bits<8)
  107806. oggpackB_write(b,0,bits);
  107807. }
  107808. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107809. void *source,
  107810. long bits,
  107811. void (*w)(oggpack_buffer *,
  107812. unsigned long,
  107813. int),
  107814. int msb){
  107815. unsigned char *ptr=(unsigned char *)source;
  107816. long bytes=bits/8;
  107817. bits-=bytes*8;
  107818. if(b->endbit){
  107819. int i;
  107820. /* unaligned copy. Do it the hard way. */
  107821. for(i=0;i<bytes;i++)
  107822. w(b,(unsigned long)(ptr[i]),8);
  107823. }else{
  107824. /* aligned block copy */
  107825. if(b->endbyte+bytes+1>=b->storage){
  107826. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107827. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107828. b->ptr=b->buffer+b->endbyte;
  107829. }
  107830. memmove(b->ptr,source,bytes);
  107831. b->ptr+=bytes;
  107832. b->endbyte+=bytes;
  107833. *b->ptr=0;
  107834. }
  107835. if(bits){
  107836. if(msb)
  107837. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107838. else
  107839. w(b,(unsigned long)(ptr[bytes]),bits);
  107840. }
  107841. }
  107842. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107843. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107844. }
  107845. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107846. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107847. }
  107848. void oggpack_reset(oggpack_buffer *b){
  107849. b->ptr=b->buffer;
  107850. b->buffer[0]=0;
  107851. b->endbit=b->endbyte=0;
  107852. }
  107853. void oggpackB_reset(oggpack_buffer *b){
  107854. oggpack_reset(b);
  107855. }
  107856. void oggpack_writeclear(oggpack_buffer *b){
  107857. _ogg_free(b->buffer);
  107858. memset(b,0,sizeof(*b));
  107859. }
  107860. void oggpackB_writeclear(oggpack_buffer *b){
  107861. oggpack_writeclear(b);
  107862. }
  107863. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107864. memset(b,0,sizeof(*b));
  107865. b->buffer=b->ptr=buf;
  107866. b->storage=bytes;
  107867. }
  107868. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107869. oggpack_readinit(b,buf,bytes);
  107870. }
  107871. /* Read in bits without advancing the bitptr; bits <= 32 */
  107872. long oggpack_look(oggpack_buffer *b,int bits){
  107873. unsigned long ret;
  107874. unsigned long m=mask[bits];
  107875. bits+=b->endbit;
  107876. if(b->endbyte+4>=b->storage){
  107877. /* not the main path */
  107878. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107879. }
  107880. ret=b->ptr[0]>>b->endbit;
  107881. if(bits>8){
  107882. ret|=b->ptr[1]<<(8-b->endbit);
  107883. if(bits>16){
  107884. ret|=b->ptr[2]<<(16-b->endbit);
  107885. if(bits>24){
  107886. ret|=b->ptr[3]<<(24-b->endbit);
  107887. if(bits>32 && b->endbit)
  107888. ret|=b->ptr[4]<<(32-b->endbit);
  107889. }
  107890. }
  107891. }
  107892. return(m&ret);
  107893. }
  107894. /* Read in bits without advancing the bitptr; bits <= 32 */
  107895. long oggpackB_look(oggpack_buffer *b,int bits){
  107896. unsigned long ret;
  107897. int m=32-bits;
  107898. bits+=b->endbit;
  107899. if(b->endbyte+4>=b->storage){
  107900. /* not the main path */
  107901. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107902. }
  107903. ret=b->ptr[0]<<(24+b->endbit);
  107904. if(bits>8){
  107905. ret|=b->ptr[1]<<(16+b->endbit);
  107906. if(bits>16){
  107907. ret|=b->ptr[2]<<(8+b->endbit);
  107908. if(bits>24){
  107909. ret|=b->ptr[3]<<(b->endbit);
  107910. if(bits>32 && b->endbit)
  107911. ret|=b->ptr[4]>>(8-b->endbit);
  107912. }
  107913. }
  107914. }
  107915. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107916. }
  107917. long oggpack_look1(oggpack_buffer *b){
  107918. if(b->endbyte>=b->storage)return(-1);
  107919. return((b->ptr[0]>>b->endbit)&1);
  107920. }
  107921. long oggpackB_look1(oggpack_buffer *b){
  107922. if(b->endbyte>=b->storage)return(-1);
  107923. return((b->ptr[0]>>(7-b->endbit))&1);
  107924. }
  107925. void oggpack_adv(oggpack_buffer *b,int bits){
  107926. bits+=b->endbit;
  107927. b->ptr+=bits/8;
  107928. b->endbyte+=bits/8;
  107929. b->endbit=bits&7;
  107930. }
  107931. void oggpackB_adv(oggpack_buffer *b,int bits){
  107932. oggpack_adv(b,bits);
  107933. }
  107934. void oggpack_adv1(oggpack_buffer *b){
  107935. if(++(b->endbit)>7){
  107936. b->endbit=0;
  107937. b->ptr++;
  107938. b->endbyte++;
  107939. }
  107940. }
  107941. void oggpackB_adv1(oggpack_buffer *b){
  107942. oggpack_adv1(b);
  107943. }
  107944. /* bits <= 32 */
  107945. long oggpack_read(oggpack_buffer *b,int bits){
  107946. long ret;
  107947. unsigned long m=mask[bits];
  107948. bits+=b->endbit;
  107949. if(b->endbyte+4>=b->storage){
  107950. /* not the main path */
  107951. ret=-1L;
  107952. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107953. }
  107954. ret=b->ptr[0]>>b->endbit;
  107955. if(bits>8){
  107956. ret|=b->ptr[1]<<(8-b->endbit);
  107957. if(bits>16){
  107958. ret|=b->ptr[2]<<(16-b->endbit);
  107959. if(bits>24){
  107960. ret|=b->ptr[3]<<(24-b->endbit);
  107961. if(bits>32 && b->endbit){
  107962. ret|=b->ptr[4]<<(32-b->endbit);
  107963. }
  107964. }
  107965. }
  107966. }
  107967. ret&=m;
  107968. overflow:
  107969. b->ptr+=bits/8;
  107970. b->endbyte+=bits/8;
  107971. b->endbit=bits&7;
  107972. return(ret);
  107973. }
  107974. /* bits <= 32 */
  107975. long oggpackB_read(oggpack_buffer *b,int bits){
  107976. long ret;
  107977. long m=32-bits;
  107978. bits+=b->endbit;
  107979. if(b->endbyte+4>=b->storage){
  107980. /* not the main path */
  107981. ret=-1L;
  107982. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107983. }
  107984. ret=b->ptr[0]<<(24+b->endbit);
  107985. if(bits>8){
  107986. ret|=b->ptr[1]<<(16+b->endbit);
  107987. if(bits>16){
  107988. ret|=b->ptr[2]<<(8+b->endbit);
  107989. if(bits>24){
  107990. ret|=b->ptr[3]<<(b->endbit);
  107991. if(bits>32 && b->endbit)
  107992. ret|=b->ptr[4]>>(8-b->endbit);
  107993. }
  107994. }
  107995. }
  107996. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107997. overflow:
  107998. b->ptr+=bits/8;
  107999. b->endbyte+=bits/8;
  108000. b->endbit=bits&7;
  108001. return(ret);
  108002. }
  108003. long oggpack_read1(oggpack_buffer *b){
  108004. long ret;
  108005. if(b->endbyte>=b->storage){
  108006. /* not the main path */
  108007. ret=-1L;
  108008. goto overflow;
  108009. }
  108010. ret=(b->ptr[0]>>b->endbit)&1;
  108011. overflow:
  108012. b->endbit++;
  108013. if(b->endbit>7){
  108014. b->endbit=0;
  108015. b->ptr++;
  108016. b->endbyte++;
  108017. }
  108018. return(ret);
  108019. }
  108020. long oggpackB_read1(oggpack_buffer *b){
  108021. long ret;
  108022. if(b->endbyte>=b->storage){
  108023. /* not the main path */
  108024. ret=-1L;
  108025. goto overflow;
  108026. }
  108027. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108028. overflow:
  108029. b->endbit++;
  108030. if(b->endbit>7){
  108031. b->endbit=0;
  108032. b->ptr++;
  108033. b->endbyte++;
  108034. }
  108035. return(ret);
  108036. }
  108037. long oggpack_bytes(oggpack_buffer *b){
  108038. return(b->endbyte+(b->endbit+7)/8);
  108039. }
  108040. long oggpack_bits(oggpack_buffer *b){
  108041. return(b->endbyte*8+b->endbit);
  108042. }
  108043. long oggpackB_bytes(oggpack_buffer *b){
  108044. return oggpack_bytes(b);
  108045. }
  108046. long oggpackB_bits(oggpack_buffer *b){
  108047. return oggpack_bits(b);
  108048. }
  108049. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108050. return(b->buffer);
  108051. }
  108052. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108053. return oggpack_get_buffer(b);
  108054. }
  108055. /* Self test of the bitwise routines; everything else is based on
  108056. them, so they damned well better be solid. */
  108057. #ifdef _V_SELFTEST
  108058. #include <stdio.h>
  108059. static int ilog(unsigned int v){
  108060. int ret=0;
  108061. while(v){
  108062. ret++;
  108063. v>>=1;
  108064. }
  108065. return(ret);
  108066. }
  108067. oggpack_buffer o;
  108068. oggpack_buffer r;
  108069. void report(char *in){
  108070. fprintf(stderr,"%s",in);
  108071. exit(1);
  108072. }
  108073. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108074. long bytes,i;
  108075. unsigned char *buffer;
  108076. oggpack_reset(&o);
  108077. for(i=0;i<vals;i++)
  108078. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108079. buffer=oggpack_get_buffer(&o);
  108080. bytes=oggpack_bytes(&o);
  108081. if(bytes!=compsize)report("wrong number of bytes!\n");
  108082. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108083. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108084. report("wrote incorrect value!\n");
  108085. }
  108086. oggpack_readinit(&r,buffer,bytes);
  108087. for(i=0;i<vals;i++){
  108088. int tbit=bits?bits:ilog(b[i]);
  108089. if(oggpack_look(&r,tbit)==-1)
  108090. report("out of data!\n");
  108091. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108092. report("looked at incorrect value!\n");
  108093. if(tbit==1)
  108094. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108095. report("looked at single bit incorrect value!\n");
  108096. if(tbit==1){
  108097. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108098. report("read incorrect single bit value!\n");
  108099. }else{
  108100. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108101. report("read incorrect value!\n");
  108102. }
  108103. }
  108104. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108105. }
  108106. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108107. long bytes,i;
  108108. unsigned char *buffer;
  108109. oggpackB_reset(&o);
  108110. for(i=0;i<vals;i++)
  108111. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108112. buffer=oggpackB_get_buffer(&o);
  108113. bytes=oggpackB_bytes(&o);
  108114. if(bytes!=compsize)report("wrong number of bytes!\n");
  108115. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108116. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108117. report("wrote incorrect value!\n");
  108118. }
  108119. oggpackB_readinit(&r,buffer,bytes);
  108120. for(i=0;i<vals;i++){
  108121. int tbit=bits?bits:ilog(b[i]);
  108122. if(oggpackB_look(&r,tbit)==-1)
  108123. report("out of data!\n");
  108124. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108125. report("looked at incorrect value!\n");
  108126. if(tbit==1)
  108127. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108128. report("looked at single bit incorrect value!\n");
  108129. if(tbit==1){
  108130. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108131. report("read incorrect single bit value!\n");
  108132. }else{
  108133. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108134. report("read incorrect value!\n");
  108135. }
  108136. }
  108137. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108138. }
  108139. int main(void){
  108140. unsigned char *buffer;
  108141. long bytes,i;
  108142. static unsigned long testbuffer1[]=
  108143. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108144. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108145. int test1size=43;
  108146. static unsigned long testbuffer2[]=
  108147. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108148. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108149. 85525151,0,12321,1,349528352};
  108150. int test2size=21;
  108151. static unsigned long testbuffer3[]=
  108152. {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,
  108153. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108154. int test3size=56;
  108155. static unsigned long large[]=
  108156. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108157. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108158. 85525151,0,12321,1,2146528352};
  108159. int onesize=33;
  108160. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108161. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108162. 223,4};
  108163. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108164. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108165. 245,251,128};
  108166. int twosize=6;
  108167. static int two[6]={61,255,255,251,231,29};
  108168. static int twoB[6]={247,63,255,253,249,120};
  108169. int threesize=54;
  108170. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108171. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108172. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108173. 100,52,4,14,18,86,77,1};
  108174. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108175. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108176. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108177. 200,20,254,4,58,106,176,144,0};
  108178. int foursize=38;
  108179. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108180. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108181. 28,2,133,0,1};
  108182. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108183. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108184. 129,10,4,32};
  108185. int fivesize=45;
  108186. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108187. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108188. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108189. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108190. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108191. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108192. int sixsize=7;
  108193. static int six[7]={17,177,170,242,169,19,148};
  108194. static int sixB[7]={136,141,85,79,149,200,41};
  108195. /* Test read/write together */
  108196. /* Later we test against pregenerated bitstreams */
  108197. oggpack_writeinit(&o);
  108198. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108199. cliptest(testbuffer1,test1size,0,one,onesize);
  108200. fprintf(stderr,"ok.");
  108201. fprintf(stderr,"\nNull bit call (LSb): ");
  108202. cliptest(testbuffer3,test3size,0,two,twosize);
  108203. fprintf(stderr,"ok.");
  108204. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108205. cliptest(testbuffer2,test2size,0,three,threesize);
  108206. fprintf(stderr,"ok.");
  108207. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108208. oggpack_reset(&o);
  108209. for(i=0;i<test2size;i++)
  108210. oggpack_write(&o,large[i],32);
  108211. buffer=oggpack_get_buffer(&o);
  108212. bytes=oggpack_bytes(&o);
  108213. oggpack_readinit(&r,buffer,bytes);
  108214. for(i=0;i<test2size;i++){
  108215. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108216. if(oggpack_look(&r,32)!=large[i]){
  108217. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108218. oggpack_look(&r,32),large[i]);
  108219. report("read incorrect value!\n");
  108220. }
  108221. oggpack_adv(&r,32);
  108222. }
  108223. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108224. fprintf(stderr,"ok.");
  108225. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108226. cliptest(testbuffer1,test1size,7,four,foursize);
  108227. fprintf(stderr,"ok.");
  108228. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108229. cliptest(testbuffer2,test2size,17,five,fivesize);
  108230. fprintf(stderr,"ok.");
  108231. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108232. cliptest(testbuffer3,test3size,1,six,sixsize);
  108233. fprintf(stderr,"ok.");
  108234. fprintf(stderr,"\nTesting read past end (LSb): ");
  108235. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108236. for(i=0;i<64;i++){
  108237. if(oggpack_read(&r,1)!=0){
  108238. fprintf(stderr,"failed; got -1 prematurely.\n");
  108239. exit(1);
  108240. }
  108241. }
  108242. if(oggpack_look(&r,1)!=-1 ||
  108243. oggpack_read(&r,1)!=-1){
  108244. fprintf(stderr,"failed; read past end without -1.\n");
  108245. exit(1);
  108246. }
  108247. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108248. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108249. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108250. exit(1);
  108251. }
  108252. if(oggpack_look(&r,18)!=0 ||
  108253. oggpack_look(&r,18)!=0){
  108254. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108255. exit(1);
  108256. }
  108257. if(oggpack_look(&r,19)!=-1 ||
  108258. oggpack_look(&r,19)!=-1){
  108259. fprintf(stderr,"failed; read past end without -1.\n");
  108260. exit(1);
  108261. }
  108262. if(oggpack_look(&r,32)!=-1 ||
  108263. oggpack_look(&r,32)!=-1){
  108264. fprintf(stderr,"failed; read past end without -1.\n");
  108265. exit(1);
  108266. }
  108267. oggpack_writeclear(&o);
  108268. fprintf(stderr,"ok.\n");
  108269. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108270. /* Test read/write together */
  108271. /* Later we test against pregenerated bitstreams */
  108272. oggpackB_writeinit(&o);
  108273. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108274. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108275. fprintf(stderr,"ok.");
  108276. fprintf(stderr,"\nNull bit call (MSb): ");
  108277. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108278. fprintf(stderr,"ok.");
  108279. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108280. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108281. fprintf(stderr,"ok.");
  108282. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108283. oggpackB_reset(&o);
  108284. for(i=0;i<test2size;i++)
  108285. oggpackB_write(&o,large[i],32);
  108286. buffer=oggpackB_get_buffer(&o);
  108287. bytes=oggpackB_bytes(&o);
  108288. oggpackB_readinit(&r,buffer,bytes);
  108289. for(i=0;i<test2size;i++){
  108290. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108291. if(oggpackB_look(&r,32)!=large[i]){
  108292. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108293. oggpackB_look(&r,32),large[i]);
  108294. report("read incorrect value!\n");
  108295. }
  108296. oggpackB_adv(&r,32);
  108297. }
  108298. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108299. fprintf(stderr,"ok.");
  108300. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108301. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108302. fprintf(stderr,"ok.");
  108303. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108304. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108305. fprintf(stderr,"ok.");
  108306. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108307. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108308. fprintf(stderr,"ok.");
  108309. fprintf(stderr,"\nTesting read past end (MSb): ");
  108310. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108311. for(i=0;i<64;i++){
  108312. if(oggpackB_read(&r,1)!=0){
  108313. fprintf(stderr,"failed; got -1 prematurely.\n");
  108314. exit(1);
  108315. }
  108316. }
  108317. if(oggpackB_look(&r,1)!=-1 ||
  108318. oggpackB_read(&r,1)!=-1){
  108319. fprintf(stderr,"failed; read past end without -1.\n");
  108320. exit(1);
  108321. }
  108322. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108323. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108324. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108325. exit(1);
  108326. }
  108327. if(oggpackB_look(&r,18)!=0 ||
  108328. oggpackB_look(&r,18)!=0){
  108329. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108330. exit(1);
  108331. }
  108332. if(oggpackB_look(&r,19)!=-1 ||
  108333. oggpackB_look(&r,19)!=-1){
  108334. fprintf(stderr,"failed; read past end without -1.\n");
  108335. exit(1);
  108336. }
  108337. if(oggpackB_look(&r,32)!=-1 ||
  108338. oggpackB_look(&r,32)!=-1){
  108339. fprintf(stderr,"failed; read past end without -1.\n");
  108340. exit(1);
  108341. }
  108342. oggpackB_writeclear(&o);
  108343. fprintf(stderr,"ok.\n\n");
  108344. return(0);
  108345. }
  108346. #endif /* _V_SELFTEST */
  108347. #undef BUFFER_INCREMENT
  108348. #endif
  108349. /*** End of inlined file: bitwise.c ***/
  108350. /*** Start of inlined file: framing.c ***/
  108351. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108352. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108353. // tasks..
  108354. #if JUCE_MSVC
  108355. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108356. #endif
  108357. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108358. #if JUCE_USE_OGGVORBIS
  108359. #include <stdlib.h>
  108360. #include <string.h>
  108361. /* A complete description of Ogg framing exists in docs/framing.html */
  108362. int ogg_page_version(ogg_page *og){
  108363. return((int)(og->header[4]));
  108364. }
  108365. int ogg_page_continued(ogg_page *og){
  108366. return((int)(og->header[5]&0x01));
  108367. }
  108368. int ogg_page_bos(ogg_page *og){
  108369. return((int)(og->header[5]&0x02));
  108370. }
  108371. int ogg_page_eos(ogg_page *og){
  108372. return((int)(og->header[5]&0x04));
  108373. }
  108374. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108375. unsigned char *page=og->header;
  108376. ogg_int64_t granulepos=page[13]&(0xff);
  108377. granulepos= (granulepos<<8)|(page[12]&0xff);
  108378. granulepos= (granulepos<<8)|(page[11]&0xff);
  108379. granulepos= (granulepos<<8)|(page[10]&0xff);
  108380. granulepos= (granulepos<<8)|(page[9]&0xff);
  108381. granulepos= (granulepos<<8)|(page[8]&0xff);
  108382. granulepos= (granulepos<<8)|(page[7]&0xff);
  108383. granulepos= (granulepos<<8)|(page[6]&0xff);
  108384. return(granulepos);
  108385. }
  108386. int ogg_page_serialno(ogg_page *og){
  108387. return(og->header[14] |
  108388. (og->header[15]<<8) |
  108389. (og->header[16]<<16) |
  108390. (og->header[17]<<24));
  108391. }
  108392. long ogg_page_pageno(ogg_page *og){
  108393. return(og->header[18] |
  108394. (og->header[19]<<8) |
  108395. (og->header[20]<<16) |
  108396. (og->header[21]<<24));
  108397. }
  108398. /* returns the number of packets that are completed on this page (if
  108399. the leading packet is begun on a previous page, but ends on this
  108400. page, it's counted */
  108401. /* NOTE:
  108402. If a page consists of a packet begun on a previous page, and a new
  108403. packet begun (but not completed) on this page, the return will be:
  108404. ogg_page_packets(page) ==1,
  108405. ogg_page_continued(page) !=0
  108406. If a page happens to be a single packet that was begun on a
  108407. previous page, and spans to the next page (in the case of a three or
  108408. more page packet), the return will be:
  108409. ogg_page_packets(page) ==0,
  108410. ogg_page_continued(page) !=0
  108411. */
  108412. int ogg_page_packets(ogg_page *og){
  108413. int i,n=og->header[26],count=0;
  108414. for(i=0;i<n;i++)
  108415. if(og->header[27+i]<255)count++;
  108416. return(count);
  108417. }
  108418. #if 0
  108419. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108420. use the static init below) */
  108421. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108422. int i;
  108423. unsigned long r;
  108424. r = index << 24;
  108425. for (i=0; i<8; i++)
  108426. if (r & 0x80000000UL)
  108427. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108428. polynomial, although we use an
  108429. unreflected alg and an init/final
  108430. of 0, not 0xffffffff */
  108431. else
  108432. r<<=1;
  108433. return (r & 0xffffffffUL);
  108434. }
  108435. #endif
  108436. static const ogg_uint32_t crc_lookup[256]={
  108437. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108438. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108439. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108440. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108441. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108442. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108443. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108444. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108445. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108446. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108447. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108448. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108449. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108450. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108451. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108452. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108453. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108454. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108455. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108456. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108457. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108458. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108459. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108460. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108461. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108462. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108463. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108464. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108465. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108466. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108467. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108468. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108469. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108470. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108471. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108472. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108473. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108474. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108475. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108476. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108477. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108478. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108479. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108480. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108481. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108482. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108483. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108484. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108485. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108486. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108487. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108488. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108489. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108490. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108491. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108492. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108493. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108494. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108495. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108496. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108497. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108498. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108499. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108500. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108501. /* init the encode/decode logical stream state */
  108502. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108503. if(os){
  108504. memset(os,0,sizeof(*os));
  108505. os->body_storage=16*1024;
  108506. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108507. os->lacing_storage=1024;
  108508. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108509. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108510. os->serialno=serialno;
  108511. return(0);
  108512. }
  108513. return(-1);
  108514. }
  108515. /* _clear does not free os, only the non-flat storage within */
  108516. int ogg_stream_clear(ogg_stream_state *os){
  108517. if(os){
  108518. if(os->body_data)_ogg_free(os->body_data);
  108519. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108520. if(os->granule_vals)_ogg_free(os->granule_vals);
  108521. memset(os,0,sizeof(*os));
  108522. }
  108523. return(0);
  108524. }
  108525. int ogg_stream_destroy(ogg_stream_state *os){
  108526. if(os){
  108527. ogg_stream_clear(os);
  108528. _ogg_free(os);
  108529. }
  108530. return(0);
  108531. }
  108532. /* Helpers for ogg_stream_encode; this keeps the structure and
  108533. what's happening fairly clear */
  108534. static void _os_body_expand(ogg_stream_state *os,int needed){
  108535. if(os->body_storage<=os->body_fill+needed){
  108536. os->body_storage+=(needed+1024);
  108537. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108538. }
  108539. }
  108540. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108541. if(os->lacing_storage<=os->lacing_fill+needed){
  108542. os->lacing_storage+=(needed+32);
  108543. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108544. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108545. }
  108546. }
  108547. /* checksum the page */
  108548. /* Direct table CRC; note that this will be faster in the future if we
  108549. perform the checksum silmultaneously with other copies */
  108550. void ogg_page_checksum_set(ogg_page *og){
  108551. if(og){
  108552. ogg_uint32_t crc_reg=0;
  108553. int i;
  108554. /* safety; needed for API behavior, but not framing code */
  108555. og->header[22]=0;
  108556. og->header[23]=0;
  108557. og->header[24]=0;
  108558. og->header[25]=0;
  108559. for(i=0;i<og->header_len;i++)
  108560. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108561. for(i=0;i<og->body_len;i++)
  108562. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108563. og->header[22]=(unsigned char)(crc_reg&0xff);
  108564. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108565. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108566. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108567. }
  108568. }
  108569. /* submit data to the internal buffer of the framing engine */
  108570. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108571. int lacing_vals=op->bytes/255+1,i;
  108572. if(os->body_returned){
  108573. /* advance packet data according to the body_returned pointer. We
  108574. had to keep it around to return a pointer into the buffer last
  108575. call */
  108576. os->body_fill-=os->body_returned;
  108577. if(os->body_fill)
  108578. memmove(os->body_data,os->body_data+os->body_returned,
  108579. os->body_fill);
  108580. os->body_returned=0;
  108581. }
  108582. /* make sure we have the buffer storage */
  108583. _os_body_expand(os,op->bytes);
  108584. _os_lacing_expand(os,lacing_vals);
  108585. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108586. the liability of overly clean abstraction for the time being. It
  108587. will actually be fairly easy to eliminate the extra copy in the
  108588. future */
  108589. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108590. os->body_fill+=op->bytes;
  108591. /* Store lacing vals for this packet */
  108592. for(i=0;i<lacing_vals-1;i++){
  108593. os->lacing_vals[os->lacing_fill+i]=255;
  108594. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108595. }
  108596. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108597. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108598. /* flag the first segment as the beginning of the packet */
  108599. os->lacing_vals[os->lacing_fill]|= 0x100;
  108600. os->lacing_fill+=lacing_vals;
  108601. /* for the sake of completeness */
  108602. os->packetno++;
  108603. if(op->e_o_s)os->e_o_s=1;
  108604. return(0);
  108605. }
  108606. /* This will flush remaining packets into a page (returning nonzero),
  108607. even if there is not enough data to trigger a flush normally
  108608. (undersized page). If there are no packets or partial packets to
  108609. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108610. try to flush a normal sized page like ogg_stream_pageout; a call to
  108611. ogg_stream_flush does not guarantee that all packets have flushed.
  108612. Only a return value of 0 from ogg_stream_flush indicates all packet
  108613. data is flushed into pages.
  108614. since ogg_stream_flush will flush the last page in a stream even if
  108615. it's undersized, you almost certainly want to use ogg_stream_pageout
  108616. (and *not* ogg_stream_flush) unless you specifically need to flush
  108617. an page regardless of size in the middle of a stream. */
  108618. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108619. int i;
  108620. int vals=0;
  108621. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108622. int bytes=0;
  108623. long acc=0;
  108624. ogg_int64_t granule_pos=-1;
  108625. if(maxvals==0)return(0);
  108626. /* construct a page */
  108627. /* decide how many segments to include */
  108628. /* If this is the initial header case, the first page must only include
  108629. the initial header packet */
  108630. if(os->b_o_s==0){ /* 'initial header page' case */
  108631. granule_pos=0;
  108632. for(vals=0;vals<maxvals;vals++){
  108633. if((os->lacing_vals[vals]&0x0ff)<255){
  108634. vals++;
  108635. break;
  108636. }
  108637. }
  108638. }else{
  108639. for(vals=0;vals<maxvals;vals++){
  108640. if(acc>4096)break;
  108641. acc+=os->lacing_vals[vals]&0x0ff;
  108642. if((os->lacing_vals[vals]&0xff)<255)
  108643. granule_pos=os->granule_vals[vals];
  108644. }
  108645. }
  108646. /* construct the header in temp storage */
  108647. memcpy(os->header,"OggS",4);
  108648. /* stream structure version */
  108649. os->header[4]=0x00;
  108650. /* continued packet flag? */
  108651. os->header[5]=0x00;
  108652. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108653. /* first page flag? */
  108654. if(os->b_o_s==0)os->header[5]|=0x02;
  108655. /* last page flag? */
  108656. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108657. os->b_o_s=1;
  108658. /* 64 bits of PCM position */
  108659. for(i=6;i<14;i++){
  108660. os->header[i]=(unsigned char)(granule_pos&0xff);
  108661. granule_pos>>=8;
  108662. }
  108663. /* 32 bits of stream serial number */
  108664. {
  108665. long serialno=os->serialno;
  108666. for(i=14;i<18;i++){
  108667. os->header[i]=(unsigned char)(serialno&0xff);
  108668. serialno>>=8;
  108669. }
  108670. }
  108671. /* 32 bits of page counter (we have both counter and page header
  108672. because this val can roll over) */
  108673. if(os->pageno==-1)os->pageno=0; /* because someone called
  108674. stream_reset; this would be a
  108675. strange thing to do in an
  108676. encode stream, but it has
  108677. plausible uses */
  108678. {
  108679. long pageno=os->pageno++;
  108680. for(i=18;i<22;i++){
  108681. os->header[i]=(unsigned char)(pageno&0xff);
  108682. pageno>>=8;
  108683. }
  108684. }
  108685. /* zero for computation; filled in later */
  108686. os->header[22]=0;
  108687. os->header[23]=0;
  108688. os->header[24]=0;
  108689. os->header[25]=0;
  108690. /* segment table */
  108691. os->header[26]=(unsigned char)(vals&0xff);
  108692. for(i=0;i<vals;i++)
  108693. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108694. /* set pointers in the ogg_page struct */
  108695. og->header=os->header;
  108696. og->header_len=os->header_fill=vals+27;
  108697. og->body=os->body_data+os->body_returned;
  108698. og->body_len=bytes;
  108699. /* advance the lacing data and set the body_returned pointer */
  108700. os->lacing_fill-=vals;
  108701. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108702. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108703. os->body_returned+=bytes;
  108704. /* calculate the checksum */
  108705. ogg_page_checksum_set(og);
  108706. /* done */
  108707. return(1);
  108708. }
  108709. /* This constructs pages from buffered packet segments. The pointers
  108710. returned are to static buffers; do not free. The returned buffers are
  108711. good only until the next call (using the same ogg_stream_state) */
  108712. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108713. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108714. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108715. os->lacing_fill>=255 || /* 'segment table full' case */
  108716. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108717. return(ogg_stream_flush(os,og));
  108718. }
  108719. /* not enough data to construct a page and not end of stream */
  108720. return(0);
  108721. }
  108722. int ogg_stream_eos(ogg_stream_state *os){
  108723. return os->e_o_s;
  108724. }
  108725. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108726. /* This has two layers to place more of the multi-serialno and paging
  108727. control in the application's hands. First, we expose a data buffer
  108728. using ogg_sync_buffer(). The app either copies into the
  108729. buffer, or passes it directly to read(), etc. We then call
  108730. ogg_sync_wrote() to tell how many bytes we just added.
  108731. Pages are returned (pointers into the buffer in ogg_sync_state)
  108732. by ogg_sync_pageout(). The page is then submitted to
  108733. ogg_stream_pagein() along with the appropriate
  108734. ogg_stream_state* (ie, matching serialno). We then get raw
  108735. packets out calling ogg_stream_packetout() with a
  108736. ogg_stream_state. */
  108737. /* initialize the struct to a known state */
  108738. int ogg_sync_init(ogg_sync_state *oy){
  108739. if(oy){
  108740. memset(oy,0,sizeof(*oy));
  108741. }
  108742. return(0);
  108743. }
  108744. /* clear non-flat storage within */
  108745. int ogg_sync_clear(ogg_sync_state *oy){
  108746. if(oy){
  108747. if(oy->data)_ogg_free(oy->data);
  108748. ogg_sync_init(oy);
  108749. }
  108750. return(0);
  108751. }
  108752. int ogg_sync_destroy(ogg_sync_state *oy){
  108753. if(oy){
  108754. ogg_sync_clear(oy);
  108755. _ogg_free(oy);
  108756. }
  108757. return(0);
  108758. }
  108759. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108760. /* first, clear out any space that has been previously returned */
  108761. if(oy->returned){
  108762. oy->fill-=oy->returned;
  108763. if(oy->fill>0)
  108764. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108765. oy->returned=0;
  108766. }
  108767. if(size>oy->storage-oy->fill){
  108768. /* We need to extend the internal buffer */
  108769. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108770. if(oy->data)
  108771. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108772. else
  108773. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108774. oy->storage=newsize;
  108775. }
  108776. /* expose a segment at least as large as requested at the fill mark */
  108777. return((char *)oy->data+oy->fill);
  108778. }
  108779. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108780. if(oy->fill+bytes>oy->storage)return(-1);
  108781. oy->fill+=bytes;
  108782. return(0);
  108783. }
  108784. /* sync the stream. This is meant to be useful for finding page
  108785. boundaries.
  108786. return values for this:
  108787. -n) skipped n bytes
  108788. 0) page not ready; more data (no bytes skipped)
  108789. n) page synced at current location; page length n bytes
  108790. */
  108791. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108792. unsigned char *page=oy->data+oy->returned;
  108793. unsigned char *next;
  108794. long bytes=oy->fill-oy->returned;
  108795. if(oy->headerbytes==0){
  108796. int headerbytes,i;
  108797. if(bytes<27)return(0); /* not enough for a header */
  108798. /* verify capture pattern */
  108799. if(memcmp(page,"OggS",4))goto sync_fail;
  108800. headerbytes=page[26]+27;
  108801. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108802. /* count up body length in the segment table */
  108803. for(i=0;i<page[26];i++)
  108804. oy->bodybytes+=page[27+i];
  108805. oy->headerbytes=headerbytes;
  108806. }
  108807. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108808. /* The whole test page is buffered. Verify the checksum */
  108809. {
  108810. /* Grab the checksum bytes, set the header field to zero */
  108811. char chksum[4];
  108812. ogg_page log;
  108813. memcpy(chksum,page+22,4);
  108814. memset(page+22,0,4);
  108815. /* set up a temp page struct and recompute the checksum */
  108816. log.header=page;
  108817. log.header_len=oy->headerbytes;
  108818. log.body=page+oy->headerbytes;
  108819. log.body_len=oy->bodybytes;
  108820. ogg_page_checksum_set(&log);
  108821. /* Compare */
  108822. if(memcmp(chksum,page+22,4)){
  108823. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108824. at all) */
  108825. /* replace the computed checksum with the one actually read in */
  108826. memcpy(page+22,chksum,4);
  108827. /* Bad checksum. Lose sync */
  108828. goto sync_fail;
  108829. }
  108830. }
  108831. /* yes, have a whole page all ready to go */
  108832. {
  108833. unsigned char *page=oy->data+oy->returned;
  108834. long bytes;
  108835. if(og){
  108836. og->header=page;
  108837. og->header_len=oy->headerbytes;
  108838. og->body=page+oy->headerbytes;
  108839. og->body_len=oy->bodybytes;
  108840. }
  108841. oy->unsynced=0;
  108842. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108843. oy->headerbytes=0;
  108844. oy->bodybytes=0;
  108845. return(bytes);
  108846. }
  108847. sync_fail:
  108848. oy->headerbytes=0;
  108849. oy->bodybytes=0;
  108850. /* search for possible capture */
  108851. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108852. if(!next)
  108853. next=oy->data+oy->fill;
  108854. oy->returned=next-oy->data;
  108855. return(-(next-page));
  108856. }
  108857. /* sync the stream and get a page. Keep trying until we find a page.
  108858. Supress 'sync errors' after reporting the first.
  108859. return values:
  108860. -1) recapture (hole in data)
  108861. 0) need more data
  108862. 1) page returned
  108863. Returns pointers into buffered data; invalidated by next call to
  108864. _stream, _clear, _init, or _buffer */
  108865. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108866. /* all we need to do is verify a page at the head of the stream
  108867. buffer. If it doesn't verify, we look for the next potential
  108868. frame */
  108869. for(;;){
  108870. long ret=ogg_sync_pageseek(oy,og);
  108871. if(ret>0){
  108872. /* have a page */
  108873. return(1);
  108874. }
  108875. if(ret==0){
  108876. /* need more data */
  108877. return(0);
  108878. }
  108879. /* head did not start a synced page... skipped some bytes */
  108880. if(!oy->unsynced){
  108881. oy->unsynced=1;
  108882. return(-1);
  108883. }
  108884. /* loop. keep looking */
  108885. }
  108886. }
  108887. /* add the incoming page to the stream state; we decompose the page
  108888. into packet segments here as well. */
  108889. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108890. unsigned char *header=og->header;
  108891. unsigned char *body=og->body;
  108892. long bodysize=og->body_len;
  108893. int segptr=0;
  108894. int version=ogg_page_version(og);
  108895. int continued=ogg_page_continued(og);
  108896. int bos=ogg_page_bos(og);
  108897. int eos=ogg_page_eos(og);
  108898. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108899. int serialno=ogg_page_serialno(og);
  108900. long pageno=ogg_page_pageno(og);
  108901. int segments=header[26];
  108902. /* clean up 'returned data' */
  108903. {
  108904. long lr=os->lacing_returned;
  108905. long br=os->body_returned;
  108906. /* body data */
  108907. if(br){
  108908. os->body_fill-=br;
  108909. if(os->body_fill)
  108910. memmove(os->body_data,os->body_data+br,os->body_fill);
  108911. os->body_returned=0;
  108912. }
  108913. if(lr){
  108914. /* segment table */
  108915. if(os->lacing_fill-lr){
  108916. memmove(os->lacing_vals,os->lacing_vals+lr,
  108917. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108918. memmove(os->granule_vals,os->granule_vals+lr,
  108919. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108920. }
  108921. os->lacing_fill-=lr;
  108922. os->lacing_packet-=lr;
  108923. os->lacing_returned=0;
  108924. }
  108925. }
  108926. /* check the serial number */
  108927. if(serialno!=os->serialno)return(-1);
  108928. if(version>0)return(-1);
  108929. _os_lacing_expand(os,segments+1);
  108930. /* are we in sequence? */
  108931. if(pageno!=os->pageno){
  108932. int i;
  108933. /* unroll previous partial packet (if any) */
  108934. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108935. os->body_fill-=os->lacing_vals[i]&0xff;
  108936. os->lacing_fill=os->lacing_packet;
  108937. /* make a note of dropped data in segment table */
  108938. if(os->pageno!=-1){
  108939. os->lacing_vals[os->lacing_fill++]=0x400;
  108940. os->lacing_packet++;
  108941. }
  108942. }
  108943. /* are we a 'continued packet' page? If so, we may need to skip
  108944. some segments */
  108945. if(continued){
  108946. if(os->lacing_fill<1 ||
  108947. os->lacing_vals[os->lacing_fill-1]==0x400){
  108948. bos=0;
  108949. for(;segptr<segments;segptr++){
  108950. int val=header[27+segptr];
  108951. body+=val;
  108952. bodysize-=val;
  108953. if(val<255){
  108954. segptr++;
  108955. break;
  108956. }
  108957. }
  108958. }
  108959. }
  108960. if(bodysize){
  108961. _os_body_expand(os,bodysize);
  108962. memcpy(os->body_data+os->body_fill,body,bodysize);
  108963. os->body_fill+=bodysize;
  108964. }
  108965. {
  108966. int saved=-1;
  108967. while(segptr<segments){
  108968. int val=header[27+segptr];
  108969. os->lacing_vals[os->lacing_fill]=val;
  108970. os->granule_vals[os->lacing_fill]=-1;
  108971. if(bos){
  108972. os->lacing_vals[os->lacing_fill]|=0x100;
  108973. bos=0;
  108974. }
  108975. if(val<255)saved=os->lacing_fill;
  108976. os->lacing_fill++;
  108977. segptr++;
  108978. if(val<255)os->lacing_packet=os->lacing_fill;
  108979. }
  108980. /* set the granulepos on the last granuleval of the last full packet */
  108981. if(saved!=-1){
  108982. os->granule_vals[saved]=granulepos;
  108983. }
  108984. }
  108985. if(eos){
  108986. os->e_o_s=1;
  108987. if(os->lacing_fill>0)
  108988. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108989. }
  108990. os->pageno=pageno+1;
  108991. return(0);
  108992. }
  108993. /* clear things to an initial state. Good to call, eg, before seeking */
  108994. int ogg_sync_reset(ogg_sync_state *oy){
  108995. oy->fill=0;
  108996. oy->returned=0;
  108997. oy->unsynced=0;
  108998. oy->headerbytes=0;
  108999. oy->bodybytes=0;
  109000. return(0);
  109001. }
  109002. int ogg_stream_reset(ogg_stream_state *os){
  109003. os->body_fill=0;
  109004. os->body_returned=0;
  109005. os->lacing_fill=0;
  109006. os->lacing_packet=0;
  109007. os->lacing_returned=0;
  109008. os->header_fill=0;
  109009. os->e_o_s=0;
  109010. os->b_o_s=0;
  109011. os->pageno=-1;
  109012. os->packetno=0;
  109013. os->granulepos=0;
  109014. return(0);
  109015. }
  109016. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109017. ogg_stream_reset(os);
  109018. os->serialno=serialno;
  109019. return(0);
  109020. }
  109021. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109022. /* The last part of decode. We have the stream broken into packet
  109023. segments. Now we need to group them into packets (or return the
  109024. out of sync markers) */
  109025. int ptr=os->lacing_returned;
  109026. if(os->lacing_packet<=ptr)return(0);
  109027. if(os->lacing_vals[ptr]&0x400){
  109028. /* we need to tell the codec there's a gap; it might need to
  109029. handle previous packet dependencies. */
  109030. os->lacing_returned++;
  109031. os->packetno++;
  109032. return(-1);
  109033. }
  109034. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109035. to ask if there's a whole packet
  109036. waiting */
  109037. /* Gather the whole packet. We'll have no holes or a partial packet */
  109038. {
  109039. int size=os->lacing_vals[ptr]&0xff;
  109040. int bytes=size;
  109041. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109042. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109043. while(size==255){
  109044. int val=os->lacing_vals[++ptr];
  109045. size=val&0xff;
  109046. if(val&0x200)eos=0x200;
  109047. bytes+=size;
  109048. }
  109049. if(op){
  109050. op->e_o_s=eos;
  109051. op->b_o_s=bos;
  109052. op->packet=os->body_data+os->body_returned;
  109053. op->packetno=os->packetno;
  109054. op->granulepos=os->granule_vals[ptr];
  109055. op->bytes=bytes;
  109056. }
  109057. if(adv){
  109058. os->body_returned+=bytes;
  109059. os->lacing_returned=ptr+1;
  109060. os->packetno++;
  109061. }
  109062. }
  109063. return(1);
  109064. }
  109065. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109066. return _packetout(os,op,1);
  109067. }
  109068. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109069. return _packetout(os,op,0);
  109070. }
  109071. void ogg_packet_clear(ogg_packet *op) {
  109072. _ogg_free(op->packet);
  109073. memset(op, 0, sizeof(*op));
  109074. }
  109075. #ifdef _V_SELFTEST
  109076. #include <stdio.h>
  109077. ogg_stream_state os_en, os_de;
  109078. ogg_sync_state oy;
  109079. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109080. long j;
  109081. static int sequence=0;
  109082. static int lastno=0;
  109083. if(op->bytes!=len){
  109084. fprintf(stderr,"incorrect packet length!\n");
  109085. exit(1);
  109086. }
  109087. if(op->granulepos!=pos){
  109088. fprintf(stderr,"incorrect packet position!\n");
  109089. exit(1);
  109090. }
  109091. /* packet number just follows sequence/gap; adjust the input number
  109092. for that */
  109093. if(no==0){
  109094. sequence=0;
  109095. }else{
  109096. sequence++;
  109097. if(no>lastno+1)
  109098. sequence++;
  109099. }
  109100. lastno=no;
  109101. if(op->packetno!=sequence){
  109102. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109103. (long)(op->packetno),sequence);
  109104. exit(1);
  109105. }
  109106. /* Test data */
  109107. for(j=0;j<op->bytes;j++)
  109108. if(op->packet[j]!=((j+no)&0xff)){
  109109. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109110. j,op->packet[j],(j+no)&0xff);
  109111. exit(1);
  109112. }
  109113. }
  109114. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109115. long j;
  109116. /* Test data */
  109117. for(j=0;j<og->body_len;j++)
  109118. if(og->body[j]!=data[j]){
  109119. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109120. j,data[j],og->body[j]);
  109121. exit(1);
  109122. }
  109123. /* Test header */
  109124. for(j=0;j<og->header_len;j++){
  109125. if(og->header[j]!=header[j]){
  109126. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109127. for(j=0;j<header[26]+27;j++)
  109128. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109129. fprintf(stderr,"\n");
  109130. exit(1);
  109131. }
  109132. }
  109133. if(og->header_len!=header[26]+27){
  109134. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109135. og->header_len,header[26]+27);
  109136. exit(1);
  109137. }
  109138. }
  109139. void print_header(ogg_page *og){
  109140. int j;
  109141. fprintf(stderr,"\nHEADER:\n");
  109142. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109143. og->header[0],og->header[1],og->header[2],og->header[3],
  109144. (int)og->header[4],(int)og->header[5]);
  109145. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109146. (og->header[9]<<24)|(og->header[8]<<16)|
  109147. (og->header[7]<<8)|og->header[6],
  109148. (og->header[17]<<24)|(og->header[16]<<16)|
  109149. (og->header[15]<<8)|og->header[14],
  109150. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109151. (og->header[19]<<8)|og->header[18]);
  109152. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109153. (int)og->header[22],(int)og->header[23],
  109154. (int)og->header[24],(int)og->header[25],
  109155. (int)og->header[26]);
  109156. for(j=27;j<og->header_len;j++)
  109157. fprintf(stderr,"%d ",(int)og->header[j]);
  109158. fprintf(stderr,")\n\n");
  109159. }
  109160. void copy_page(ogg_page *og){
  109161. unsigned char *temp=_ogg_malloc(og->header_len);
  109162. memcpy(temp,og->header,og->header_len);
  109163. og->header=temp;
  109164. temp=_ogg_malloc(og->body_len);
  109165. memcpy(temp,og->body,og->body_len);
  109166. og->body=temp;
  109167. }
  109168. void free_page(ogg_page *og){
  109169. _ogg_free (og->header);
  109170. _ogg_free (og->body);
  109171. }
  109172. void error(void){
  109173. fprintf(stderr,"error!\n");
  109174. exit(1);
  109175. }
  109176. /* 17 only */
  109177. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109178. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109179. 0x01,0x02,0x03,0x04,0,0,0,0,
  109180. 0x15,0xed,0xec,0x91,
  109181. 1,
  109182. 17};
  109183. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109184. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109185. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109186. 0x01,0x02,0x03,0x04,0,0,0,0,
  109187. 0x59,0x10,0x6c,0x2c,
  109188. 1,
  109189. 17};
  109190. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109191. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109192. 0x01,0x02,0x03,0x04,1,0,0,0,
  109193. 0x89,0x33,0x85,0xce,
  109194. 13,
  109195. 254,255,0,255,1,255,245,255,255,0,
  109196. 255,255,90};
  109197. /* nil packets; beginning,middle,end */
  109198. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109199. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109200. 0x01,0x02,0x03,0x04,0,0,0,0,
  109201. 0xff,0x7b,0x23,0x17,
  109202. 1,
  109203. 0};
  109204. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109205. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109206. 0x01,0x02,0x03,0x04,1,0,0,0,
  109207. 0x5c,0x3f,0x66,0xcb,
  109208. 17,
  109209. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109210. 255,255,90,0};
  109211. /* large initial packet */
  109212. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109213. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109214. 0x01,0x02,0x03,0x04,0,0,0,0,
  109215. 0x01,0x27,0x31,0xaa,
  109216. 18,
  109217. 255,255,255,255,255,255,255,255,
  109218. 255,255,255,255,255,255,255,255,255,10};
  109219. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109220. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109221. 0x01,0x02,0x03,0x04,1,0,0,0,
  109222. 0x7f,0x4e,0x8a,0xd2,
  109223. 4,
  109224. 255,4,255,0};
  109225. /* continuing packet test */
  109226. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109227. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109228. 0x01,0x02,0x03,0x04,0,0,0,0,
  109229. 0xff,0x7b,0x23,0x17,
  109230. 1,
  109231. 0};
  109232. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109233. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109234. 0x01,0x02,0x03,0x04,1,0,0,0,
  109235. 0x54,0x05,0x51,0xc8,
  109236. 17,
  109237. 255,255,255,255,255,255,255,255,
  109238. 255,255,255,255,255,255,255,255,255};
  109239. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109240. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109241. 0x01,0x02,0x03,0x04,2,0,0,0,
  109242. 0xc8,0xc3,0xcb,0xed,
  109243. 5,
  109244. 10,255,4,255,0};
  109245. /* page with the 255 segment limit */
  109246. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109247. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109248. 0x01,0x02,0x03,0x04,0,0,0,0,
  109249. 0xff,0x7b,0x23,0x17,
  109250. 1,
  109251. 0};
  109252. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109253. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109254. 0x01,0x02,0x03,0x04,1,0,0,0,
  109255. 0xed,0x2a,0x2e,0xa7,
  109256. 255,
  109257. 10,10,10,10,10,10,10,10,
  109258. 10,10,10,10,10,10,10,10,
  109259. 10,10,10,10,10,10,10,10,
  109260. 10,10,10,10,10,10,10,10,
  109261. 10,10,10,10,10,10,10,10,
  109262. 10,10,10,10,10,10,10,10,
  109263. 10,10,10,10,10,10,10,10,
  109264. 10,10,10,10,10,10,10,10,
  109265. 10,10,10,10,10,10,10,10,
  109266. 10,10,10,10,10,10,10,10,
  109267. 10,10,10,10,10,10,10,10,
  109268. 10,10,10,10,10,10,10,10,
  109269. 10,10,10,10,10,10,10,10,
  109270. 10,10,10,10,10,10,10,10,
  109271. 10,10,10,10,10,10,10,10,
  109272. 10,10,10,10,10,10,10,10,
  109273. 10,10,10,10,10,10,10,10,
  109274. 10,10,10,10,10,10,10,10,
  109275. 10,10,10,10,10,10,10,10,
  109276. 10,10,10,10,10,10,10,10,
  109277. 10,10,10,10,10,10,10,10,
  109278. 10,10,10,10,10,10,10,10,
  109279. 10,10,10,10,10,10,10,10,
  109280. 10,10,10,10,10,10,10,10,
  109281. 10,10,10,10,10,10,10,10,
  109282. 10,10,10,10,10,10,10,10,
  109283. 10,10,10,10,10,10,10,10,
  109284. 10,10,10,10,10,10,10,10,
  109285. 10,10,10,10,10,10,10,10,
  109286. 10,10,10,10,10,10,10,10,
  109287. 10,10,10,10,10,10,10,10,
  109288. 10,10,10,10,10,10,10};
  109289. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109290. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109291. 0x01,0x02,0x03,0x04,2,0,0,0,
  109292. 0x6c,0x3b,0x82,0x3d,
  109293. 1,
  109294. 50};
  109295. /* packet that overspans over an entire page */
  109296. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109297. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109298. 0x01,0x02,0x03,0x04,0,0,0,0,
  109299. 0xff,0x7b,0x23,0x17,
  109300. 1,
  109301. 0};
  109302. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109303. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109304. 0x01,0x02,0x03,0x04,1,0,0,0,
  109305. 0x3c,0xd9,0x4d,0x3f,
  109306. 17,
  109307. 100,255,255,255,255,255,255,255,255,
  109308. 255,255,255,255,255,255,255,255};
  109309. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109310. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109311. 0x01,0x02,0x03,0x04,2,0,0,0,
  109312. 0x01,0xd2,0xe5,0xe5,
  109313. 17,
  109314. 255,255,255,255,255,255,255,255,
  109315. 255,255,255,255,255,255,255,255,255};
  109316. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109317. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109318. 0x01,0x02,0x03,0x04,3,0,0,0,
  109319. 0xef,0xdd,0x88,0xde,
  109320. 7,
  109321. 255,255,75,255,4,255,0};
  109322. /* packet that overspans over an entire page */
  109323. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109324. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109325. 0x01,0x02,0x03,0x04,0,0,0,0,
  109326. 0xff,0x7b,0x23,0x17,
  109327. 1,
  109328. 0};
  109329. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109330. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109331. 0x01,0x02,0x03,0x04,1,0,0,0,
  109332. 0x3c,0xd9,0x4d,0x3f,
  109333. 17,
  109334. 100,255,255,255,255,255,255,255,255,
  109335. 255,255,255,255,255,255,255,255};
  109336. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109337. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109338. 0x01,0x02,0x03,0x04,2,0,0,0,
  109339. 0xd4,0xe0,0x60,0xe5,
  109340. 1,0};
  109341. void test_pack(const int *pl, const int **headers, int byteskip,
  109342. int pageskip, int packetskip){
  109343. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109344. long inptr=0;
  109345. long outptr=0;
  109346. long deptr=0;
  109347. long depacket=0;
  109348. long granule_pos=7,pageno=0;
  109349. int i,j,packets,pageout=pageskip;
  109350. int eosflag=0;
  109351. int bosflag=0;
  109352. int byteskipcount=0;
  109353. ogg_stream_reset(&os_en);
  109354. ogg_stream_reset(&os_de);
  109355. ogg_sync_reset(&oy);
  109356. for(packets=0;packets<packetskip;packets++)
  109357. depacket+=pl[packets];
  109358. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109359. for(i=0;i<packets;i++){
  109360. /* construct a test packet */
  109361. ogg_packet op;
  109362. int len=pl[i];
  109363. op.packet=data+inptr;
  109364. op.bytes=len;
  109365. op.e_o_s=(pl[i+1]<0?1:0);
  109366. op.granulepos=granule_pos;
  109367. granule_pos+=1024;
  109368. for(j=0;j<len;j++)data[inptr++]=i+j;
  109369. /* submit the test packet */
  109370. ogg_stream_packetin(&os_en,&op);
  109371. /* retrieve any finished pages */
  109372. {
  109373. ogg_page og;
  109374. while(ogg_stream_pageout(&os_en,&og)){
  109375. /* We have a page. Check it carefully */
  109376. fprintf(stderr,"%ld, ",pageno);
  109377. if(headers[pageno]==NULL){
  109378. fprintf(stderr,"coded too many pages!\n");
  109379. exit(1);
  109380. }
  109381. check_page(data+outptr,headers[pageno],&og);
  109382. outptr+=og.body_len;
  109383. pageno++;
  109384. if(pageskip){
  109385. bosflag=1;
  109386. pageskip--;
  109387. deptr+=og.body_len;
  109388. }
  109389. /* have a complete page; submit it to sync/decode */
  109390. {
  109391. ogg_page og_de;
  109392. ogg_packet op_de,op_de2;
  109393. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109394. char *next=buf;
  109395. byteskipcount+=og.header_len;
  109396. if(byteskipcount>byteskip){
  109397. memcpy(next,og.header,byteskipcount-byteskip);
  109398. next+=byteskipcount-byteskip;
  109399. byteskipcount=byteskip;
  109400. }
  109401. byteskipcount+=og.body_len;
  109402. if(byteskipcount>byteskip){
  109403. memcpy(next,og.body,byteskipcount-byteskip);
  109404. next+=byteskipcount-byteskip;
  109405. byteskipcount=byteskip;
  109406. }
  109407. ogg_sync_wrote(&oy,next-buf);
  109408. while(1){
  109409. int ret=ogg_sync_pageout(&oy,&og_de);
  109410. if(ret==0)break;
  109411. if(ret<0)continue;
  109412. /* got a page. Happy happy. Verify that it's good. */
  109413. fprintf(stderr,"(%ld), ",pageout);
  109414. check_page(data+deptr,headers[pageout],&og_de);
  109415. deptr+=og_de.body_len;
  109416. pageout++;
  109417. /* submit it to deconstitution */
  109418. ogg_stream_pagein(&os_de,&og_de);
  109419. /* packets out? */
  109420. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109421. ogg_stream_packetpeek(&os_de,NULL);
  109422. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109423. /* verify peek and out match */
  109424. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109425. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109426. depacket);
  109427. exit(1);
  109428. }
  109429. /* verify the packet! */
  109430. /* check data */
  109431. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109432. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109433. depacket);
  109434. exit(1);
  109435. }
  109436. /* check bos flag */
  109437. if(bosflag==0 && op_de.b_o_s==0){
  109438. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109439. exit(1);
  109440. }
  109441. if(bosflag && op_de.b_o_s){
  109442. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109443. exit(1);
  109444. }
  109445. bosflag=1;
  109446. depacket+=op_de.bytes;
  109447. /* check eos flag */
  109448. if(eosflag){
  109449. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109450. exit(1);
  109451. }
  109452. if(op_de.e_o_s)eosflag=1;
  109453. /* check granulepos flag */
  109454. if(op_de.granulepos!=-1){
  109455. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109456. }
  109457. }
  109458. }
  109459. }
  109460. }
  109461. }
  109462. }
  109463. _ogg_free(data);
  109464. if(headers[pageno]!=NULL){
  109465. fprintf(stderr,"did not write last page!\n");
  109466. exit(1);
  109467. }
  109468. if(headers[pageout]!=NULL){
  109469. fprintf(stderr,"did not decode last page!\n");
  109470. exit(1);
  109471. }
  109472. if(inptr!=outptr){
  109473. fprintf(stderr,"encoded page data incomplete!\n");
  109474. exit(1);
  109475. }
  109476. if(inptr!=deptr){
  109477. fprintf(stderr,"decoded page data incomplete!\n");
  109478. exit(1);
  109479. }
  109480. if(inptr!=depacket){
  109481. fprintf(stderr,"decoded packet data incomplete!\n");
  109482. exit(1);
  109483. }
  109484. if(!eosflag){
  109485. fprintf(stderr,"Never got a packet with EOS set!\n");
  109486. exit(1);
  109487. }
  109488. fprintf(stderr,"ok.\n");
  109489. }
  109490. int main(void){
  109491. ogg_stream_init(&os_en,0x04030201);
  109492. ogg_stream_init(&os_de,0x04030201);
  109493. ogg_sync_init(&oy);
  109494. /* Exercise each code path in the framing code. Also verify that
  109495. the checksums are working. */
  109496. {
  109497. /* 17 only */
  109498. const int packets[]={17, -1};
  109499. const int *headret[]={head1_0,NULL};
  109500. fprintf(stderr,"testing single page encoding... ");
  109501. test_pack(packets,headret,0,0,0);
  109502. }
  109503. {
  109504. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109505. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109506. const int *headret[]={head1_1,head2_1,NULL};
  109507. fprintf(stderr,"testing basic page encoding... ");
  109508. test_pack(packets,headret,0,0,0);
  109509. }
  109510. {
  109511. /* nil packets; beginning,middle,end */
  109512. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109513. const int *headret[]={head1_2,head2_2,NULL};
  109514. fprintf(stderr,"testing basic nil packets... ");
  109515. test_pack(packets,headret,0,0,0);
  109516. }
  109517. {
  109518. /* large initial packet */
  109519. const int packets[]={4345,259,255,-1};
  109520. const int *headret[]={head1_3,head2_3,NULL};
  109521. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109522. test_pack(packets,headret,0,0,0);
  109523. }
  109524. {
  109525. /* continuing packet test */
  109526. const int packets[]={0,4345,259,255,-1};
  109527. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109528. fprintf(stderr,"testing single packet page span... ");
  109529. test_pack(packets,headret,0,0,0);
  109530. }
  109531. /* page with the 255 segment limit */
  109532. {
  109533. const int packets[]={0,10,10,10,10,10,10,10,10,
  109534. 10,10,10,10,10,10,10,10,
  109535. 10,10,10,10,10,10,10,10,
  109536. 10,10,10,10,10,10,10,10,
  109537. 10,10,10,10,10,10,10,10,
  109538. 10,10,10,10,10,10,10,10,
  109539. 10,10,10,10,10,10,10,10,
  109540. 10,10,10,10,10,10,10,10,
  109541. 10,10,10,10,10,10,10,10,
  109542. 10,10,10,10,10,10,10,10,
  109543. 10,10,10,10,10,10,10,10,
  109544. 10,10,10,10,10,10,10,10,
  109545. 10,10,10,10,10,10,10,10,
  109546. 10,10,10,10,10,10,10,10,
  109547. 10,10,10,10,10,10,10,10,
  109548. 10,10,10,10,10,10,10,10,
  109549. 10,10,10,10,10,10,10,10,
  109550. 10,10,10,10,10,10,10,10,
  109551. 10,10,10,10,10,10,10,10,
  109552. 10,10,10,10,10,10,10,10,
  109553. 10,10,10,10,10,10,10,10,
  109554. 10,10,10,10,10,10,10,10,
  109555. 10,10,10,10,10,10,10,10,
  109556. 10,10,10,10,10,10,10,10,
  109557. 10,10,10,10,10,10,10,10,
  109558. 10,10,10,10,10,10,10,10,
  109559. 10,10,10,10,10,10,10,10,
  109560. 10,10,10,10,10,10,10,10,
  109561. 10,10,10,10,10,10,10,10,
  109562. 10,10,10,10,10,10,10,10,
  109563. 10,10,10,10,10,10,10,10,
  109564. 10,10,10,10,10,10,10,50,-1};
  109565. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109566. fprintf(stderr,"testing max packet segments... ");
  109567. test_pack(packets,headret,0,0,0);
  109568. }
  109569. {
  109570. /* packet that overspans over an entire page */
  109571. const int packets[]={0,100,9000,259,255,-1};
  109572. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109573. fprintf(stderr,"testing very large packets... ");
  109574. test_pack(packets,headret,0,0,0);
  109575. }
  109576. {
  109577. /* test for the libogg 1.1.1 resync in large continuation bug
  109578. found by Josh Coalson) */
  109579. const int packets[]={0,100,9000,259,255,-1};
  109580. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109581. fprintf(stderr,"testing continuation resync in very large packets... ");
  109582. test_pack(packets,headret,100,2,3);
  109583. }
  109584. {
  109585. /* term only page. why not? */
  109586. const int packets[]={0,100,4080,-1};
  109587. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109588. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109589. test_pack(packets,headret,0,0,0);
  109590. }
  109591. {
  109592. /* build a bunch of pages for testing */
  109593. unsigned char *data=_ogg_malloc(1024*1024);
  109594. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109595. int inptr=0,i,j;
  109596. ogg_page og[5];
  109597. ogg_stream_reset(&os_en);
  109598. for(i=0;pl[i]!=-1;i++){
  109599. ogg_packet op;
  109600. int len=pl[i];
  109601. op.packet=data+inptr;
  109602. op.bytes=len;
  109603. op.e_o_s=(pl[i+1]<0?1:0);
  109604. op.granulepos=(i+1)*1000;
  109605. for(j=0;j<len;j++)data[inptr++]=i+j;
  109606. ogg_stream_packetin(&os_en,&op);
  109607. }
  109608. _ogg_free(data);
  109609. /* retrieve finished pages */
  109610. for(i=0;i<5;i++){
  109611. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109612. fprintf(stderr,"Too few pages output building sync tests!\n");
  109613. exit(1);
  109614. }
  109615. copy_page(&og[i]);
  109616. }
  109617. /* Test lost pages on pagein/packetout: no rollback */
  109618. {
  109619. ogg_page temp;
  109620. ogg_packet test;
  109621. fprintf(stderr,"Testing loss of pages... ");
  109622. ogg_sync_reset(&oy);
  109623. ogg_stream_reset(&os_de);
  109624. for(i=0;i<5;i++){
  109625. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109626. og[i].header_len);
  109627. ogg_sync_wrote(&oy,og[i].header_len);
  109628. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109629. ogg_sync_wrote(&oy,og[i].body_len);
  109630. }
  109631. ogg_sync_pageout(&oy,&temp);
  109632. ogg_stream_pagein(&os_de,&temp);
  109633. ogg_sync_pageout(&oy,&temp);
  109634. ogg_stream_pagein(&os_de,&temp);
  109635. ogg_sync_pageout(&oy,&temp);
  109636. /* skip */
  109637. ogg_sync_pageout(&oy,&temp);
  109638. ogg_stream_pagein(&os_de,&temp);
  109639. /* do we get the expected results/packets? */
  109640. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109641. checkpacket(&test,0,0,0);
  109642. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109643. checkpacket(&test,100,1,-1);
  109644. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109645. checkpacket(&test,4079,2,3000);
  109646. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109647. fprintf(stderr,"Error: loss of page did not return error\n");
  109648. exit(1);
  109649. }
  109650. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109651. checkpacket(&test,76,5,-1);
  109652. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109653. checkpacket(&test,34,6,-1);
  109654. fprintf(stderr,"ok.\n");
  109655. }
  109656. /* Test lost pages on pagein/packetout: rollback with continuation */
  109657. {
  109658. ogg_page temp;
  109659. ogg_packet test;
  109660. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109661. ogg_sync_reset(&oy);
  109662. ogg_stream_reset(&os_de);
  109663. for(i=0;i<5;i++){
  109664. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109665. og[i].header_len);
  109666. ogg_sync_wrote(&oy,og[i].header_len);
  109667. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109668. ogg_sync_wrote(&oy,og[i].body_len);
  109669. }
  109670. ogg_sync_pageout(&oy,&temp);
  109671. ogg_stream_pagein(&os_de,&temp);
  109672. ogg_sync_pageout(&oy,&temp);
  109673. ogg_stream_pagein(&os_de,&temp);
  109674. ogg_sync_pageout(&oy,&temp);
  109675. ogg_stream_pagein(&os_de,&temp);
  109676. ogg_sync_pageout(&oy,&temp);
  109677. /* skip */
  109678. ogg_sync_pageout(&oy,&temp);
  109679. ogg_stream_pagein(&os_de,&temp);
  109680. /* do we get the expected results/packets? */
  109681. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109682. checkpacket(&test,0,0,0);
  109683. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109684. checkpacket(&test,100,1,-1);
  109685. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109686. checkpacket(&test,4079,2,3000);
  109687. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109688. checkpacket(&test,2956,3,4000);
  109689. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109690. fprintf(stderr,"Error: loss of page did not return error\n");
  109691. exit(1);
  109692. }
  109693. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109694. checkpacket(&test,300,13,14000);
  109695. fprintf(stderr,"ok.\n");
  109696. }
  109697. /* the rest only test sync */
  109698. {
  109699. ogg_page og_de;
  109700. /* Test fractional page inputs: incomplete capture */
  109701. fprintf(stderr,"Testing sync on partial inputs... ");
  109702. ogg_sync_reset(&oy);
  109703. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109704. 3);
  109705. ogg_sync_wrote(&oy,3);
  109706. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109707. /* Test fractional page inputs: incomplete fixed header */
  109708. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109709. 20);
  109710. ogg_sync_wrote(&oy,20);
  109711. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109712. /* Test fractional page inputs: incomplete header */
  109713. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109714. 5);
  109715. ogg_sync_wrote(&oy,5);
  109716. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109717. /* Test fractional page inputs: incomplete body */
  109718. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109719. og[1].header_len-28);
  109720. ogg_sync_wrote(&oy,og[1].header_len-28);
  109721. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109722. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109723. ogg_sync_wrote(&oy,1000);
  109724. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109725. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109726. og[1].body_len-1000);
  109727. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109728. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109729. fprintf(stderr,"ok.\n");
  109730. }
  109731. /* Test fractional page inputs: page + incomplete capture */
  109732. {
  109733. ogg_page og_de;
  109734. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109735. ogg_sync_reset(&oy);
  109736. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109737. og[1].header_len);
  109738. ogg_sync_wrote(&oy,og[1].header_len);
  109739. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109740. og[1].body_len);
  109741. ogg_sync_wrote(&oy,og[1].body_len);
  109742. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109743. 20);
  109744. ogg_sync_wrote(&oy,20);
  109745. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109746. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109747. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109748. og[1].header_len-20);
  109749. ogg_sync_wrote(&oy,og[1].header_len-20);
  109750. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109751. og[1].body_len);
  109752. ogg_sync_wrote(&oy,og[1].body_len);
  109753. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109754. fprintf(stderr,"ok.\n");
  109755. }
  109756. /* Test recapture: garbage + page */
  109757. {
  109758. ogg_page og_de;
  109759. fprintf(stderr,"Testing search for capture... ");
  109760. ogg_sync_reset(&oy);
  109761. /* 'garbage' */
  109762. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109763. og[1].body_len);
  109764. ogg_sync_wrote(&oy,og[1].body_len);
  109765. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109766. og[1].header_len);
  109767. ogg_sync_wrote(&oy,og[1].header_len);
  109768. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109769. og[1].body_len);
  109770. ogg_sync_wrote(&oy,og[1].body_len);
  109771. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109772. 20);
  109773. ogg_sync_wrote(&oy,20);
  109774. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109775. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109776. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109777. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109778. og[2].header_len-20);
  109779. ogg_sync_wrote(&oy,og[2].header_len-20);
  109780. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109781. og[2].body_len);
  109782. ogg_sync_wrote(&oy,og[2].body_len);
  109783. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109784. fprintf(stderr,"ok.\n");
  109785. }
  109786. /* Test recapture: page + garbage + page */
  109787. {
  109788. ogg_page og_de;
  109789. fprintf(stderr,"Testing recapture... ");
  109790. ogg_sync_reset(&oy);
  109791. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109792. og[1].header_len);
  109793. ogg_sync_wrote(&oy,og[1].header_len);
  109794. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109795. og[1].body_len);
  109796. ogg_sync_wrote(&oy,og[1].body_len);
  109797. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109798. og[2].header_len);
  109799. ogg_sync_wrote(&oy,og[2].header_len);
  109800. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109801. og[2].header_len);
  109802. ogg_sync_wrote(&oy,og[2].header_len);
  109803. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109804. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109805. og[2].body_len-5);
  109806. ogg_sync_wrote(&oy,og[2].body_len-5);
  109807. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109808. og[3].header_len);
  109809. ogg_sync_wrote(&oy,og[3].header_len);
  109810. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109811. og[3].body_len);
  109812. ogg_sync_wrote(&oy,og[3].body_len);
  109813. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109814. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109815. fprintf(stderr,"ok.\n");
  109816. }
  109817. /* Free page data that was previously copied */
  109818. {
  109819. for(i=0;i<5;i++){
  109820. free_page(&og[i]);
  109821. }
  109822. }
  109823. }
  109824. return(0);
  109825. }
  109826. #endif
  109827. #endif
  109828. /*** End of inlined file: framing.c ***/
  109829. /*** Start of inlined file: analysis.c ***/
  109830. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109831. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109832. // tasks..
  109833. #if JUCE_MSVC
  109834. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109835. #endif
  109836. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109837. #if JUCE_USE_OGGVORBIS
  109838. #include <stdio.h>
  109839. #include <string.h>
  109840. #include <math.h>
  109841. /*** Start of inlined file: codec_internal.h ***/
  109842. #ifndef _V_CODECI_H_
  109843. #define _V_CODECI_H_
  109844. /*** Start of inlined file: envelope.h ***/
  109845. #ifndef _V_ENVELOPE_
  109846. #define _V_ENVELOPE_
  109847. /*** Start of inlined file: mdct.h ***/
  109848. #ifndef _OGG_mdct_H_
  109849. #define _OGG_mdct_H_
  109850. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109851. #ifdef MDCT_INTEGERIZED
  109852. #define DATA_TYPE int
  109853. #define REG_TYPE register int
  109854. #define TRIGBITS 14
  109855. #define cPI3_8 6270
  109856. #define cPI2_8 11585
  109857. #define cPI1_8 15137
  109858. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109859. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109860. #define HALVE(x) ((x)>>1)
  109861. #else
  109862. #define DATA_TYPE float
  109863. #define REG_TYPE float
  109864. #define cPI3_8 .38268343236508977175F
  109865. #define cPI2_8 .70710678118654752441F
  109866. #define cPI1_8 .92387953251128675613F
  109867. #define FLOAT_CONV(x) (x)
  109868. #define MULT_NORM(x) (x)
  109869. #define HALVE(x) ((x)*.5f)
  109870. #endif
  109871. typedef struct {
  109872. int n;
  109873. int log2n;
  109874. DATA_TYPE *trig;
  109875. int *bitrev;
  109876. DATA_TYPE scale;
  109877. } mdct_lookup;
  109878. extern void mdct_init(mdct_lookup *lookup,int n);
  109879. extern void mdct_clear(mdct_lookup *l);
  109880. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109881. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109882. #endif
  109883. /*** End of inlined file: mdct.h ***/
  109884. #define VE_PRE 16
  109885. #define VE_WIN 4
  109886. #define VE_POST 2
  109887. #define VE_AMP (VE_PRE+VE_POST-1)
  109888. #define VE_BANDS 7
  109889. #define VE_NEARDC 15
  109890. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109891. #define VE_MAXSTRETCH 12 /* one-third full block */
  109892. typedef struct {
  109893. float ampbuf[VE_AMP];
  109894. int ampptr;
  109895. float nearDC[VE_NEARDC];
  109896. float nearDC_acc;
  109897. float nearDC_partialacc;
  109898. int nearptr;
  109899. } envelope_filter_state;
  109900. typedef struct {
  109901. int begin;
  109902. int end;
  109903. float *window;
  109904. float total;
  109905. } envelope_band;
  109906. typedef struct {
  109907. int ch;
  109908. int winlength;
  109909. int searchstep;
  109910. float minenergy;
  109911. mdct_lookup mdct;
  109912. float *mdct_win;
  109913. envelope_band band[VE_BANDS];
  109914. envelope_filter_state *filter;
  109915. int stretch;
  109916. int *mark;
  109917. long storage;
  109918. long current;
  109919. long curmark;
  109920. long cursor;
  109921. } envelope_lookup;
  109922. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109923. extern void _ve_envelope_clear(envelope_lookup *e);
  109924. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109925. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109926. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109927. #endif
  109928. /*** End of inlined file: envelope.h ***/
  109929. /*** Start of inlined file: codebook.h ***/
  109930. #ifndef _V_CODEBOOK_H_
  109931. #define _V_CODEBOOK_H_
  109932. /* This structure encapsulates huffman and VQ style encoding books; it
  109933. doesn't do anything specific to either.
  109934. valuelist/quantlist are nonNULL (and q_* significant) only if
  109935. there's entry->value mapping to be done.
  109936. If encode-side mapping must be done (and thus the entry needs to be
  109937. hunted), the auxiliary encode pointer will point to a decision
  109938. tree. This is true of both VQ and huffman, but is mostly useful
  109939. with VQ.
  109940. */
  109941. typedef struct static_codebook{
  109942. long dim; /* codebook dimensions (elements per vector) */
  109943. long entries; /* codebook entries */
  109944. long *lengthlist; /* codeword lengths in bits */
  109945. /* mapping ***************************************************************/
  109946. int maptype; /* 0=none
  109947. 1=implicitly populated values from map column
  109948. 2=listed arbitrary values */
  109949. /* The below does a linear, single monotonic sequence mapping. */
  109950. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109951. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109952. int q_quant; /* bits: 0 < quant <= 16 */
  109953. int q_sequencep; /* bitflag */
  109954. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109955. map == 2: list of dim*entries quantized entry vals
  109956. */
  109957. /* encode helpers ********************************************************/
  109958. struct encode_aux_nearestmatch *nearest_tree;
  109959. struct encode_aux_threshmatch *thresh_tree;
  109960. struct encode_aux_pigeonhole *pigeon_tree;
  109961. int allocedp;
  109962. } static_codebook;
  109963. /* this structures an arbitrary trained book to quickly find the
  109964. nearest cell match */
  109965. typedef struct encode_aux_nearestmatch{
  109966. /* pre-calculated partitioning tree */
  109967. long *ptr0;
  109968. long *ptr1;
  109969. long *p; /* decision points (each is an entry) */
  109970. long *q; /* decision points (each is an entry) */
  109971. long aux; /* number of tree entries */
  109972. long alloc;
  109973. } encode_aux_nearestmatch;
  109974. /* assumes a maptype of 1; encode side only, so that's OK */
  109975. typedef struct encode_aux_threshmatch{
  109976. float *quantthresh;
  109977. long *quantmap;
  109978. int quantvals;
  109979. int threshvals;
  109980. } encode_aux_threshmatch;
  109981. typedef struct encode_aux_pigeonhole{
  109982. float min;
  109983. float del;
  109984. int mapentries;
  109985. int quantvals;
  109986. long *pigeonmap;
  109987. long fittotal;
  109988. long *fitlist;
  109989. long *fitmap;
  109990. long *fitlength;
  109991. } encode_aux_pigeonhole;
  109992. typedef struct codebook{
  109993. long dim; /* codebook dimensions (elements per vector) */
  109994. long entries; /* codebook entries */
  109995. long used_entries; /* populated codebook entries */
  109996. const static_codebook *c;
  109997. /* for encode, the below are entry-ordered, fully populated */
  109998. /* for decode, the below are ordered by bitreversed codeword and only
  109999. used entries are populated */
  110000. float *valuelist; /* list of dim*entries actual entry values */
  110001. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110002. int *dec_index; /* only used if sparseness collapsed */
  110003. char *dec_codelengths;
  110004. ogg_uint32_t *dec_firsttable;
  110005. int dec_firsttablen;
  110006. int dec_maxlength;
  110007. } codebook;
  110008. extern void vorbis_staticbook_clear(static_codebook *b);
  110009. extern void vorbis_staticbook_destroy(static_codebook *b);
  110010. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110011. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110012. extern void vorbis_book_clear(codebook *b);
  110013. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110014. extern float *_book_logdist(const static_codebook *b,float *vals);
  110015. extern float _float32_unpack(long val);
  110016. extern long _float32_pack(float val);
  110017. extern int _best(codebook *book, float *a, int step);
  110018. extern int _ilog(unsigned int v);
  110019. extern long _book_maptype1_quantvals(const static_codebook *b);
  110020. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110021. extern long vorbis_book_codeword(codebook *book,int entry);
  110022. extern long vorbis_book_codelen(codebook *book,int entry);
  110023. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110024. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110025. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110026. extern int vorbis_book_errorv(codebook *book, float *a);
  110027. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110028. oggpack_buffer *b);
  110029. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110030. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110031. oggpack_buffer *b,int n);
  110032. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110033. oggpack_buffer *b,int n);
  110034. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110035. oggpack_buffer *b,int n);
  110036. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110037. long off,int ch,
  110038. oggpack_buffer *b,int n);
  110039. #endif
  110040. /*** End of inlined file: codebook.h ***/
  110041. #define BLOCKTYPE_IMPULSE 0
  110042. #define BLOCKTYPE_PADDING 1
  110043. #define BLOCKTYPE_TRANSITION 0
  110044. #define BLOCKTYPE_LONG 1
  110045. #define PACKETBLOBS 15
  110046. typedef struct vorbis_block_internal{
  110047. float **pcmdelay; /* this is a pointer into local storage */
  110048. float ampmax;
  110049. int blocktype;
  110050. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110051. blob [PACKETBLOBS/2] points to
  110052. the oggpack_buffer in the
  110053. main vorbis_block */
  110054. } vorbis_block_internal;
  110055. typedef void vorbis_look_floor;
  110056. typedef void vorbis_look_residue;
  110057. typedef void vorbis_look_transform;
  110058. /* mode ************************************************************/
  110059. typedef struct {
  110060. int blockflag;
  110061. int windowtype;
  110062. int transformtype;
  110063. int mapping;
  110064. } vorbis_info_mode;
  110065. typedef void vorbis_info_floor;
  110066. typedef void vorbis_info_residue;
  110067. typedef void vorbis_info_mapping;
  110068. /*** Start of inlined file: psy.h ***/
  110069. #ifndef _V_PSY_H_
  110070. #define _V_PSY_H_
  110071. /*** Start of inlined file: smallft.h ***/
  110072. #ifndef _V_SMFT_H_
  110073. #define _V_SMFT_H_
  110074. typedef struct {
  110075. int n;
  110076. float *trigcache;
  110077. int *splitcache;
  110078. } drft_lookup;
  110079. extern void drft_forward(drft_lookup *l,float *data);
  110080. extern void drft_backward(drft_lookup *l,float *data);
  110081. extern void drft_init(drft_lookup *l,int n);
  110082. extern void drft_clear(drft_lookup *l);
  110083. #endif
  110084. /*** End of inlined file: smallft.h ***/
  110085. /*** Start of inlined file: backends.h ***/
  110086. /* this is exposed up here because we need it for static modes.
  110087. Lookups for each backend aren't exposed because there's no reason
  110088. to do so */
  110089. #ifndef _vorbis_backend_h_
  110090. #define _vorbis_backend_h_
  110091. /* this would all be simpler/shorter with templates, but.... */
  110092. /* Floor backend generic *****************************************/
  110093. typedef struct{
  110094. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110095. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110096. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110097. void (*free_info) (vorbis_info_floor *);
  110098. void (*free_look) (vorbis_look_floor *);
  110099. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110100. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110101. void *buffer,float *);
  110102. } vorbis_func_floor;
  110103. typedef struct{
  110104. int order;
  110105. long rate;
  110106. long barkmap;
  110107. int ampbits;
  110108. int ampdB;
  110109. int numbooks; /* <= 16 */
  110110. int books[16];
  110111. float lessthan; /* encode-only config setting hacks for libvorbis */
  110112. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110113. } vorbis_info_floor0;
  110114. #define VIF_POSIT 63
  110115. #define VIF_CLASS 16
  110116. #define VIF_PARTS 31
  110117. typedef struct{
  110118. int partitions; /* 0 to 31 */
  110119. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110120. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110121. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110122. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110123. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110124. int mult; /* 1 2 3 or 4 */
  110125. int postlist[VIF_POSIT+2]; /* first two implicit */
  110126. /* encode side analysis parameters */
  110127. float maxover;
  110128. float maxunder;
  110129. float maxerr;
  110130. float twofitweight;
  110131. float twofitatten;
  110132. int n;
  110133. } vorbis_info_floor1;
  110134. /* Residue backend generic *****************************************/
  110135. typedef struct{
  110136. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110137. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110138. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110139. vorbis_info_residue *);
  110140. void (*free_info) (vorbis_info_residue *);
  110141. void (*free_look) (vorbis_look_residue *);
  110142. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110143. float **,int *,int);
  110144. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110145. vorbis_look_residue *,
  110146. float **,float **,int *,int,long **);
  110147. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110148. float **,int *,int);
  110149. } vorbis_func_residue;
  110150. typedef struct vorbis_info_residue0{
  110151. /* block-partitioned VQ coded straight residue */
  110152. long begin;
  110153. long end;
  110154. /* first stage (lossless partitioning) */
  110155. int grouping; /* group n vectors per partition */
  110156. int partitions; /* possible codebooks for a partition */
  110157. int groupbook; /* huffbook for partitioning */
  110158. int secondstages[64]; /* expanded out to pointers in lookup */
  110159. int booklist[256]; /* list of second stage books */
  110160. float classmetric1[64];
  110161. float classmetric2[64];
  110162. } vorbis_info_residue0;
  110163. /* Mapping backend generic *****************************************/
  110164. typedef struct{
  110165. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110166. oggpack_buffer *);
  110167. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110168. void (*free_info) (vorbis_info_mapping *);
  110169. int (*forward) (struct vorbis_block *vb);
  110170. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110171. } vorbis_func_mapping;
  110172. typedef struct vorbis_info_mapping0{
  110173. int submaps; /* <= 16 */
  110174. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110175. int floorsubmap[16]; /* [mux] submap to floors */
  110176. int residuesubmap[16]; /* [mux] submap to residue */
  110177. int coupling_steps;
  110178. int coupling_mag[256];
  110179. int coupling_ang[256];
  110180. } vorbis_info_mapping0;
  110181. #endif
  110182. /*** End of inlined file: backends.h ***/
  110183. #ifndef EHMER_MAX
  110184. #define EHMER_MAX 56
  110185. #endif
  110186. /* psychoacoustic setup ********************************************/
  110187. #define P_BANDS 17 /* 62Hz to 16kHz */
  110188. #define P_LEVELS 8 /* 30dB to 100dB */
  110189. #define P_LEVEL_0 30. /* 30 dB */
  110190. #define P_NOISECURVES 3
  110191. #define NOISE_COMPAND_LEVELS 40
  110192. typedef struct vorbis_info_psy{
  110193. int blockflag;
  110194. float ath_adjatt;
  110195. float ath_maxatt;
  110196. float tone_masteratt[P_NOISECURVES];
  110197. float tone_centerboost;
  110198. float tone_decay;
  110199. float tone_abs_limit;
  110200. float toneatt[P_BANDS];
  110201. int noisemaskp;
  110202. float noisemaxsupp;
  110203. float noisewindowlo;
  110204. float noisewindowhi;
  110205. int noisewindowlomin;
  110206. int noisewindowhimin;
  110207. int noisewindowfixed;
  110208. float noiseoff[P_NOISECURVES][P_BANDS];
  110209. float noisecompand[NOISE_COMPAND_LEVELS];
  110210. float max_curve_dB;
  110211. int normal_channel_p;
  110212. int normal_point_p;
  110213. int normal_start;
  110214. int normal_partition;
  110215. double normal_thresh;
  110216. } vorbis_info_psy;
  110217. typedef struct{
  110218. int eighth_octave_lines;
  110219. /* for block long/short tuning; encode only */
  110220. float preecho_thresh[VE_BANDS];
  110221. float postecho_thresh[VE_BANDS];
  110222. float stretch_penalty;
  110223. float preecho_minenergy;
  110224. float ampmax_att_per_sec;
  110225. /* channel coupling config */
  110226. int coupling_pkHz[PACKETBLOBS];
  110227. int coupling_pointlimit[2][PACKETBLOBS];
  110228. int coupling_prepointamp[PACKETBLOBS];
  110229. int coupling_postpointamp[PACKETBLOBS];
  110230. int sliding_lowpass[2][PACKETBLOBS];
  110231. } vorbis_info_psy_global;
  110232. typedef struct {
  110233. float ampmax;
  110234. int channels;
  110235. vorbis_info_psy_global *gi;
  110236. int coupling_pointlimit[2][P_NOISECURVES];
  110237. } vorbis_look_psy_global;
  110238. typedef struct {
  110239. int n;
  110240. struct vorbis_info_psy *vi;
  110241. float ***tonecurves;
  110242. float **noiseoffset;
  110243. float *ath;
  110244. long *octave; /* in n.ocshift format */
  110245. long *bark;
  110246. long firstoc;
  110247. long shiftoc;
  110248. int eighth_octave_lines; /* power of two, please */
  110249. int total_octave_lines;
  110250. long rate; /* cache it */
  110251. float m_val; /* Masking compensation value */
  110252. } vorbis_look_psy;
  110253. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110254. vorbis_info_psy_global *gi,int n,long rate);
  110255. extern void _vp_psy_clear(vorbis_look_psy *p);
  110256. extern void *_vi_psy_dup(void *source);
  110257. extern void _vi_psy_free(vorbis_info_psy *i);
  110258. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110259. extern void _vp_remove_floor(vorbis_look_psy *p,
  110260. float *mdct,
  110261. int *icodedflr,
  110262. float *residue,
  110263. int sliding_lowpass);
  110264. extern void _vp_noisemask(vorbis_look_psy *p,
  110265. float *logmdct,
  110266. float *logmask);
  110267. extern void _vp_tonemask(vorbis_look_psy *p,
  110268. float *logfft,
  110269. float *logmask,
  110270. float global_specmax,
  110271. float local_specmax);
  110272. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110273. float *noise,
  110274. float *tone,
  110275. int offset_select,
  110276. float *logmask,
  110277. float *mdct,
  110278. float *logmdct);
  110279. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110280. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110281. vorbis_info_psy_global *g,
  110282. vorbis_look_psy *p,
  110283. vorbis_info_mapping0 *vi,
  110284. float **mdct);
  110285. extern void _vp_couple(int blobno,
  110286. vorbis_info_psy_global *g,
  110287. vorbis_look_psy *p,
  110288. vorbis_info_mapping0 *vi,
  110289. float **res,
  110290. float **mag_memo,
  110291. int **mag_sort,
  110292. int **ifloor,
  110293. int *nonzero,
  110294. int sliding_lowpass);
  110295. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110296. float *in,float *out,int *sortedindex);
  110297. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110298. float *magnitudes,int *sortedindex);
  110299. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110300. vorbis_look_psy *p,
  110301. vorbis_info_mapping0 *vi,
  110302. float **mags);
  110303. extern void hf_reduction(vorbis_info_psy_global *g,
  110304. vorbis_look_psy *p,
  110305. vorbis_info_mapping0 *vi,
  110306. float **mdct);
  110307. #endif
  110308. /*** End of inlined file: psy.h ***/
  110309. /*** Start of inlined file: bitrate.h ***/
  110310. #ifndef _V_BITRATE_H_
  110311. #define _V_BITRATE_H_
  110312. /*** Start of inlined file: os.h ***/
  110313. #ifndef _OS_H
  110314. #define _OS_H
  110315. /********************************************************************
  110316. * *
  110317. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110318. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110319. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110320. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110321. * *
  110322. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110323. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110324. * *
  110325. ********************************************************************
  110326. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110327. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110328. ********************************************************************/
  110329. #ifdef HAVE_CONFIG_H
  110330. #include "config.h"
  110331. #endif
  110332. #include <math.h>
  110333. /*** Start of inlined file: misc.h ***/
  110334. #ifndef _V_RANDOM_H_
  110335. #define _V_RANDOM_H_
  110336. extern int analysis_noisy;
  110337. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110338. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110339. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110340. ogg_int64_t off);
  110341. #ifdef DEBUG_MALLOC
  110342. #define _VDBG_GRAPHFILE "malloc.m"
  110343. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110344. extern void _VDBG_free(void *ptr,char *file,long line);
  110345. #ifndef MISC_C
  110346. #undef _ogg_malloc
  110347. #undef _ogg_calloc
  110348. #undef _ogg_realloc
  110349. #undef _ogg_free
  110350. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110351. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110352. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110353. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110354. #endif
  110355. #endif
  110356. #endif
  110357. /*** End of inlined file: misc.h ***/
  110358. #ifndef _V_IFDEFJAIL_H_
  110359. # define _V_IFDEFJAIL_H_
  110360. # ifdef __GNUC__
  110361. # define STIN static __inline__
  110362. # elif _WIN32
  110363. # define STIN static __inline
  110364. # else
  110365. # define STIN static
  110366. # endif
  110367. #ifdef DJGPP
  110368. # define rint(x) (floor((x)+0.5f))
  110369. #endif
  110370. #ifndef M_PI
  110371. # define M_PI (3.1415926536f)
  110372. #endif
  110373. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110374. # include <malloc.h>
  110375. # define rint(x) (floor((x)+0.5f))
  110376. # define NO_FLOAT_MATH_LIB
  110377. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110378. #endif
  110379. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110380. void *_alloca(size_t size);
  110381. # define alloca _alloca
  110382. #endif
  110383. #ifndef FAST_HYPOT
  110384. # define FAST_HYPOT hypot
  110385. #endif
  110386. #endif
  110387. #ifdef HAVE_ALLOCA_H
  110388. # include <alloca.h>
  110389. #endif
  110390. #ifdef USE_MEMORY_H
  110391. # include <memory.h>
  110392. #endif
  110393. #ifndef min
  110394. # define min(x,y) ((x)>(y)?(y):(x))
  110395. #endif
  110396. #ifndef max
  110397. # define max(x,y) ((x)<(y)?(y):(x))
  110398. #endif
  110399. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110400. # define VORBIS_FPU_CONTROL
  110401. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110402. Because of encapsulation constraints (GCC can't see inside the asm
  110403. block and so we end up doing stupid things like a store/load that
  110404. is collectively a noop), we do it this way */
  110405. /* we must set up the fpu before this works!! */
  110406. typedef ogg_int16_t vorbis_fpu_control;
  110407. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110408. ogg_int16_t ret;
  110409. ogg_int16_t temp;
  110410. __asm__ __volatile__("fnstcw %0\n\t"
  110411. "movw %0,%%dx\n\t"
  110412. "orw $62463,%%dx\n\t"
  110413. "movw %%dx,%1\n\t"
  110414. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110415. *fpu=ret;
  110416. }
  110417. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110418. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110419. }
  110420. /* assumes the FPU is in round mode! */
  110421. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110422. we get extra fst/fld to
  110423. truncate precision */
  110424. int i;
  110425. __asm__("fistl %0": "=m"(i) : "t"(f));
  110426. return(i);
  110427. }
  110428. #endif
  110429. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110430. # define VORBIS_FPU_CONTROL
  110431. typedef ogg_int16_t vorbis_fpu_control;
  110432. static __inline int vorbis_ftoi(double f){
  110433. int i;
  110434. __asm{
  110435. fld f
  110436. fistp i
  110437. }
  110438. return i;
  110439. }
  110440. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110441. }
  110442. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110443. }
  110444. #endif
  110445. #ifndef VORBIS_FPU_CONTROL
  110446. typedef int vorbis_fpu_control;
  110447. static int vorbis_ftoi(double f){
  110448. return (int)(f+.5);
  110449. }
  110450. /* We don't have special code for this compiler/arch, so do it the slow way */
  110451. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110452. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110453. #endif
  110454. #endif /* _OS_H */
  110455. /*** End of inlined file: os.h ***/
  110456. /* encode side bitrate tracking */
  110457. typedef struct bitrate_manager_state {
  110458. int managed;
  110459. long avg_reservoir;
  110460. long minmax_reservoir;
  110461. long avg_bitsper;
  110462. long min_bitsper;
  110463. long max_bitsper;
  110464. long short_per_long;
  110465. double avgfloat;
  110466. vorbis_block *vb;
  110467. int choice;
  110468. } bitrate_manager_state;
  110469. typedef struct bitrate_manager_info{
  110470. long avg_rate;
  110471. long min_rate;
  110472. long max_rate;
  110473. long reservoir_bits;
  110474. double reservoir_bias;
  110475. double slew_damp;
  110476. } bitrate_manager_info;
  110477. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110478. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110479. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110480. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110481. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110482. #endif
  110483. /*** End of inlined file: bitrate.h ***/
  110484. static int ilog(unsigned int v){
  110485. int ret=0;
  110486. while(v){
  110487. ret++;
  110488. v>>=1;
  110489. }
  110490. return(ret);
  110491. }
  110492. static int ilog2(unsigned int v){
  110493. int ret=0;
  110494. if(v)--v;
  110495. while(v){
  110496. ret++;
  110497. v>>=1;
  110498. }
  110499. return(ret);
  110500. }
  110501. typedef struct private_state {
  110502. /* local lookup storage */
  110503. envelope_lookup *ve; /* envelope lookup */
  110504. int window[2];
  110505. vorbis_look_transform **transform[2]; /* block, type */
  110506. drft_lookup fft_look[2];
  110507. int modebits;
  110508. vorbis_look_floor **flr;
  110509. vorbis_look_residue **residue;
  110510. vorbis_look_psy *psy;
  110511. vorbis_look_psy_global *psy_g_look;
  110512. /* local storage, only used on the encoding side. This way the
  110513. application does not need to worry about freeing some packets'
  110514. memory and not others'; packet storage is always tracked.
  110515. Cleared next call to a _dsp_ function */
  110516. unsigned char *header;
  110517. unsigned char *header1;
  110518. unsigned char *header2;
  110519. bitrate_manager_state bms;
  110520. ogg_int64_t sample_count;
  110521. } private_state;
  110522. /* codec_setup_info contains all the setup information specific to the
  110523. specific compression/decompression mode in progress (eg,
  110524. psychoacoustic settings, channel setup, options, codebook
  110525. etc).
  110526. *********************************************************************/
  110527. /*** Start of inlined file: highlevel.h ***/
  110528. typedef struct highlevel_byblocktype {
  110529. double tone_mask_setting;
  110530. double tone_peaklimit_setting;
  110531. double noise_bias_setting;
  110532. double noise_compand_setting;
  110533. } highlevel_byblocktype;
  110534. typedef struct highlevel_encode_setup {
  110535. void *setup;
  110536. int set_in_stone;
  110537. double base_setting;
  110538. double long_setting;
  110539. double short_setting;
  110540. double impulse_noisetune;
  110541. int managed;
  110542. long bitrate_min;
  110543. long bitrate_av;
  110544. double bitrate_av_damp;
  110545. long bitrate_max;
  110546. long bitrate_reservoir;
  110547. double bitrate_reservoir_bias;
  110548. int impulse_block_p;
  110549. int noise_normalize_p;
  110550. double stereo_point_setting;
  110551. double lowpass_kHz;
  110552. double ath_floating_dB;
  110553. double ath_absolute_dB;
  110554. double amplitude_track_dBpersec;
  110555. double trigger_setting;
  110556. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110557. } highlevel_encode_setup;
  110558. /*** End of inlined file: highlevel.h ***/
  110559. typedef struct codec_setup_info {
  110560. /* Vorbis supports only short and long blocks, but allows the
  110561. encoder to choose the sizes */
  110562. long blocksizes[2];
  110563. /* modes are the primary means of supporting on-the-fly different
  110564. blocksizes, different channel mappings (LR or M/A),
  110565. different residue backends, etc. Each mode consists of a
  110566. blocksize flag and a mapping (along with the mapping setup */
  110567. int modes;
  110568. int maps;
  110569. int floors;
  110570. int residues;
  110571. int books;
  110572. int psys; /* encode only */
  110573. vorbis_info_mode *mode_param[64];
  110574. int map_type[64];
  110575. vorbis_info_mapping *map_param[64];
  110576. int floor_type[64];
  110577. vorbis_info_floor *floor_param[64];
  110578. int residue_type[64];
  110579. vorbis_info_residue *residue_param[64];
  110580. static_codebook *book_param[256];
  110581. codebook *fullbooks;
  110582. vorbis_info_psy *psy_param[4]; /* encode only */
  110583. vorbis_info_psy_global psy_g_param;
  110584. bitrate_manager_info bi;
  110585. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110586. highly redundant structure, but
  110587. improves clarity of program flow. */
  110588. int halfrate_flag; /* painless downsample for decode */
  110589. } codec_setup_info;
  110590. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110591. extern void _vp_global_free(vorbis_look_psy_global *look);
  110592. #endif
  110593. /*** End of inlined file: codec_internal.h ***/
  110594. /*** Start of inlined file: registry.h ***/
  110595. #ifndef _V_REG_H_
  110596. #define _V_REG_H_
  110597. #define VI_TRANSFORMB 1
  110598. #define VI_WINDOWB 1
  110599. #define VI_TIMEB 1
  110600. #define VI_FLOORB 2
  110601. #define VI_RESB 3
  110602. #define VI_MAPB 1
  110603. extern vorbis_func_floor *_floor_P[];
  110604. extern vorbis_func_residue *_residue_P[];
  110605. extern vorbis_func_mapping *_mapping_P[];
  110606. #endif
  110607. /*** End of inlined file: registry.h ***/
  110608. /*** Start of inlined file: scales.h ***/
  110609. #ifndef _V_SCALES_H_
  110610. #define _V_SCALES_H_
  110611. #include <math.h>
  110612. /* 20log10(x) */
  110613. #define VORBIS_IEEE_FLOAT32 1
  110614. #ifdef VORBIS_IEEE_FLOAT32
  110615. static float unitnorm(float x){
  110616. union {
  110617. ogg_uint32_t i;
  110618. float f;
  110619. } ix;
  110620. ix.f = x;
  110621. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110622. return ix.f;
  110623. }
  110624. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110625. static float todB(const float *x){
  110626. union {
  110627. ogg_uint32_t i;
  110628. float f;
  110629. } ix;
  110630. ix.f = *x;
  110631. ix.i = ix.i&0x7fffffff;
  110632. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110633. }
  110634. #define todB_nn(x) todB(x)
  110635. #else
  110636. static float unitnorm(float x){
  110637. if(x<0)return(-1.f);
  110638. return(1.f);
  110639. }
  110640. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110641. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110642. #endif
  110643. #define fromdB(x) (exp((x)*.11512925f))
  110644. /* The bark scale equations are approximations, since the original
  110645. table was somewhat hand rolled. The below are chosen to have the
  110646. best possible fit to the rolled tables, thus their somewhat odd
  110647. appearance (these are more accurate and over a longer range than
  110648. the oft-quoted bark equations found in the texts I have). The
  110649. approximations are valid from 0 - 30kHz (nyquist) or so.
  110650. all f in Hz, z in Bark */
  110651. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110652. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110653. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110654. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110655. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110656. 0.0 */
  110657. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110658. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110659. #endif
  110660. /*** End of inlined file: scales.h ***/
  110661. int analysis_noisy=1;
  110662. /* decides between modes, dispatches to the appropriate mapping. */
  110663. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110664. int ret,i;
  110665. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110666. vb->glue_bits=0;
  110667. vb->time_bits=0;
  110668. vb->floor_bits=0;
  110669. vb->res_bits=0;
  110670. /* first things first. Make sure encode is ready */
  110671. for(i=0;i<PACKETBLOBS;i++)
  110672. oggpack_reset(vbi->packetblob[i]);
  110673. /* we only have one mapping type (0), and we let the mapping code
  110674. itself figure out what soft mode to use. This allows easier
  110675. bitrate management */
  110676. if((ret=_mapping_P[0]->forward(vb)))
  110677. return(ret);
  110678. if(op){
  110679. if(vorbis_bitrate_managed(vb))
  110680. /* The app is using a bitmanaged mode... but not using the
  110681. bitrate management interface. */
  110682. return(OV_EINVAL);
  110683. op->packet=oggpack_get_buffer(&vb->opb);
  110684. op->bytes=oggpack_bytes(&vb->opb);
  110685. op->b_o_s=0;
  110686. op->e_o_s=vb->eofflag;
  110687. op->granulepos=vb->granulepos;
  110688. op->packetno=vb->sequence; /* for sake of completeness */
  110689. }
  110690. return(0);
  110691. }
  110692. /* there was no great place to put this.... */
  110693. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110694. int j;
  110695. FILE *of;
  110696. char buffer[80];
  110697. /* if(i==5870){*/
  110698. sprintf(buffer,"%s_%d.m",base,i);
  110699. of=fopen(buffer,"w");
  110700. if(!of)perror("failed to open data dump file");
  110701. for(j=0;j<n;j++){
  110702. if(bark){
  110703. float b=toBARK((4000.f*j/n)+.25);
  110704. fprintf(of,"%f ",b);
  110705. }else
  110706. if(off!=0)
  110707. fprintf(of,"%f ",(double)(j+off)/8000.);
  110708. else
  110709. fprintf(of,"%f ",(double)j);
  110710. if(dB){
  110711. float val;
  110712. if(v[j]==0.)
  110713. val=-140.;
  110714. else
  110715. val=todB(v+j);
  110716. fprintf(of,"%f\n",val);
  110717. }else{
  110718. fprintf(of,"%f\n",v[j]);
  110719. }
  110720. }
  110721. fclose(of);
  110722. /* } */
  110723. }
  110724. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110725. ogg_int64_t off){
  110726. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110727. }
  110728. #endif
  110729. /*** End of inlined file: analysis.c ***/
  110730. /*** Start of inlined file: bitrate.c ***/
  110731. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110732. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110733. // tasks..
  110734. #if JUCE_MSVC
  110735. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110736. #endif
  110737. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110738. #if JUCE_USE_OGGVORBIS
  110739. #include <stdlib.h>
  110740. #include <string.h>
  110741. #include <math.h>
  110742. /* compute bitrate tracking setup */
  110743. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110744. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110745. bitrate_manager_info *bi=&ci->bi;
  110746. memset(bm,0,sizeof(*bm));
  110747. if(bi && (bi->reservoir_bits>0)){
  110748. long ratesamples=vi->rate;
  110749. int halfsamples=ci->blocksizes[0]>>1;
  110750. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110751. bm->managed=1;
  110752. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110753. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110754. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110755. bm->avgfloat=PACKETBLOBS/2;
  110756. /* not a necessary fix, but one that leads to a more balanced
  110757. typical initialization */
  110758. {
  110759. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110760. bm->minmax_reservoir=desired_fill;
  110761. bm->avg_reservoir=desired_fill;
  110762. }
  110763. }
  110764. }
  110765. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110766. memset(bm,0,sizeof(*bm));
  110767. return;
  110768. }
  110769. int vorbis_bitrate_managed(vorbis_block *vb){
  110770. vorbis_dsp_state *vd=vb->vd;
  110771. private_state *b=(private_state*)vd->backend_state;
  110772. bitrate_manager_state *bm=&b->bms;
  110773. if(bm && bm->managed)return(1);
  110774. return(0);
  110775. }
  110776. /* finish taking in the block we just processed */
  110777. int vorbis_bitrate_addblock(vorbis_block *vb){
  110778. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110779. vorbis_dsp_state *vd=vb->vd;
  110780. private_state *b=(private_state*)vd->backend_state;
  110781. bitrate_manager_state *bm=&b->bms;
  110782. vorbis_info *vi=vd->vi;
  110783. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110784. bitrate_manager_info *bi=&ci->bi;
  110785. int choice=rint(bm->avgfloat);
  110786. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110787. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110788. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110789. int samples=ci->blocksizes[vb->W]>>1;
  110790. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110791. if(!bm->managed){
  110792. /* not a bitrate managed stream, but for API simplicity, we'll
  110793. buffer the packet to keep the code path clean */
  110794. if(bm->vb)return(-1); /* one has been submitted without
  110795. being claimed */
  110796. bm->vb=vb;
  110797. return(0);
  110798. }
  110799. bm->vb=vb;
  110800. /* look ahead for avg floater */
  110801. if(bm->avg_bitsper>0){
  110802. double slew=0.;
  110803. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110804. double slewlimit= 15./bi->slew_damp;
  110805. /* choosing a new floater:
  110806. if we're over target, we slew down
  110807. if we're under target, we slew up
  110808. choose slew as follows: look through packetblobs of this frame
  110809. and set slew as the first in the appropriate direction that
  110810. gives us the slew we want. This may mean no slew if delta is
  110811. already favorable.
  110812. Then limit slew to slew max */
  110813. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110814. while(choice>0 && this_bits>avg_target_bits &&
  110815. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110816. choice--;
  110817. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110818. }
  110819. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110820. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110821. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110822. choice++;
  110823. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110824. }
  110825. }
  110826. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110827. if(slew<-slewlimit)slew=-slewlimit;
  110828. if(slew>slewlimit)slew=slewlimit;
  110829. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110830. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110831. }
  110832. /* enforce min(if used) on the current floater (if used) */
  110833. if(bm->min_bitsper>0){
  110834. /* do we need to force the bitrate up? */
  110835. if(this_bits<min_target_bits){
  110836. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110837. choice++;
  110838. if(choice>=PACKETBLOBS)break;
  110839. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110840. }
  110841. }
  110842. }
  110843. /* enforce max (if used) on the current floater (if used) */
  110844. if(bm->max_bitsper>0){
  110845. /* do we need to force the bitrate down? */
  110846. if(this_bits>max_target_bits){
  110847. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110848. choice--;
  110849. if(choice<0)break;
  110850. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110851. }
  110852. }
  110853. }
  110854. /* Choice of packetblobs now made based on floater, and min/max
  110855. requirements. Now boundary check extreme choices */
  110856. if(choice<0){
  110857. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110858. frame will need to be truncated */
  110859. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110860. bm->choice=choice=0;
  110861. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110862. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110863. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110864. }
  110865. }else{
  110866. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110867. if(choice>=PACKETBLOBS)
  110868. choice=PACKETBLOBS-1;
  110869. bm->choice=choice;
  110870. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110871. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110872. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110873. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110874. }
  110875. /* now we have the final packet and the final packet size. Update statistics */
  110876. /* min and max reservoir */
  110877. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110878. if(max_target_bits>0 && this_bits>max_target_bits){
  110879. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110880. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110881. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110882. }else{
  110883. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110884. if(bm->minmax_reservoir>desired_fill){
  110885. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110886. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110887. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110888. }else{
  110889. bm->minmax_reservoir=desired_fill;
  110890. }
  110891. }else{
  110892. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110893. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110894. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110895. }else{
  110896. bm->minmax_reservoir=desired_fill;
  110897. }
  110898. }
  110899. }
  110900. }
  110901. /* avg reservoir */
  110902. if(bm->avg_bitsper>0){
  110903. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110904. bm->avg_reservoir+=this_bits-avg_target_bits;
  110905. }
  110906. return(0);
  110907. }
  110908. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110909. private_state *b=(private_state*)vd->backend_state;
  110910. bitrate_manager_state *bm=&b->bms;
  110911. vorbis_block *vb=bm->vb;
  110912. int choice=PACKETBLOBS/2;
  110913. if(!vb)return 0;
  110914. if(op){
  110915. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110916. if(vorbis_bitrate_managed(vb))
  110917. choice=bm->choice;
  110918. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110919. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110920. op->b_o_s=0;
  110921. op->e_o_s=vb->eofflag;
  110922. op->granulepos=vb->granulepos;
  110923. op->packetno=vb->sequence; /* for sake of completeness */
  110924. }
  110925. bm->vb=0;
  110926. return(1);
  110927. }
  110928. #endif
  110929. /*** End of inlined file: bitrate.c ***/
  110930. /*** Start of inlined file: block.c ***/
  110931. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110932. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110933. // tasks..
  110934. #if JUCE_MSVC
  110935. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110936. #endif
  110937. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110938. #if JUCE_USE_OGGVORBIS
  110939. #include <stdio.h>
  110940. #include <stdlib.h>
  110941. #include <string.h>
  110942. /*** Start of inlined file: window.h ***/
  110943. #ifndef _V_WINDOW_
  110944. #define _V_WINDOW_
  110945. extern float *_vorbis_window_get(int n);
  110946. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110947. int lW,int W,int nW);
  110948. #endif
  110949. /*** End of inlined file: window.h ***/
  110950. /*** Start of inlined file: lpc.h ***/
  110951. #ifndef _V_LPC_H_
  110952. #define _V_LPC_H_
  110953. /* simple linear scale LPC code */
  110954. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110955. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110956. float *data,long n);
  110957. #endif
  110958. /*** End of inlined file: lpc.h ***/
  110959. /* pcm accumulator examples (not exhaustive):
  110960. <-------------- lW ---------------->
  110961. <--------------- W ---------------->
  110962. : .....|..... _______________ |
  110963. : .''' | '''_--- | |\ |
  110964. :.....''' |_____--- '''......| | \_______|
  110965. :.................|__________________|_______|__|______|
  110966. |<------ Sl ------>| > Sr < |endW
  110967. |beginSl |endSl | |endSr
  110968. |beginW |endlW |beginSr
  110969. |< lW >|
  110970. <--------------- W ---------------->
  110971. | | .. ______________ |
  110972. | | ' `/ | ---_ |
  110973. |___.'___/`. | ---_____|
  110974. |_______|__|_______|_________________|
  110975. | >|Sl|< |<------ Sr ----->|endW
  110976. | | |endSl |beginSr |endSr
  110977. |beginW | |endlW
  110978. mult[0] |beginSl mult[n]
  110979. <-------------- lW ----------------->
  110980. |<--W-->|
  110981. : .............. ___ | |
  110982. : .''' |`/ \ | |
  110983. :.....''' |/`....\|...|
  110984. :.........................|___|___|___|
  110985. |Sl |Sr |endW
  110986. | | |endSr
  110987. | |beginSr
  110988. | |endSl
  110989. |beginSl
  110990. |beginW
  110991. */
  110992. /* block abstraction setup *********************************************/
  110993. #ifndef WORD_ALIGN
  110994. #define WORD_ALIGN 8
  110995. #endif
  110996. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110997. int i;
  110998. memset(vb,0,sizeof(*vb));
  110999. vb->vd=v;
  111000. vb->localalloc=0;
  111001. vb->localstore=NULL;
  111002. if(v->analysisp){
  111003. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111004. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111005. vbi->ampmax=-9999;
  111006. for(i=0;i<PACKETBLOBS;i++){
  111007. if(i==PACKETBLOBS/2){
  111008. vbi->packetblob[i]=&vb->opb;
  111009. }else{
  111010. vbi->packetblob[i]=
  111011. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111012. }
  111013. oggpack_writeinit(vbi->packetblob[i]);
  111014. }
  111015. }
  111016. return(0);
  111017. }
  111018. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111019. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111020. if(bytes+vb->localtop>vb->localalloc){
  111021. /* can't just _ogg_realloc... there are outstanding pointers */
  111022. if(vb->localstore){
  111023. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111024. vb->totaluse+=vb->localtop;
  111025. link->next=vb->reap;
  111026. link->ptr=vb->localstore;
  111027. vb->reap=link;
  111028. }
  111029. /* highly conservative */
  111030. vb->localalloc=bytes;
  111031. vb->localstore=_ogg_malloc(vb->localalloc);
  111032. vb->localtop=0;
  111033. }
  111034. {
  111035. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111036. vb->localtop+=bytes;
  111037. return ret;
  111038. }
  111039. }
  111040. /* reap the chain, pull the ripcord */
  111041. void _vorbis_block_ripcord(vorbis_block *vb){
  111042. /* reap the chain */
  111043. struct alloc_chain *reap=vb->reap;
  111044. while(reap){
  111045. struct alloc_chain *next=reap->next;
  111046. _ogg_free(reap->ptr);
  111047. memset(reap,0,sizeof(*reap));
  111048. _ogg_free(reap);
  111049. reap=next;
  111050. }
  111051. /* consolidate storage */
  111052. if(vb->totaluse){
  111053. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111054. vb->localalloc+=vb->totaluse;
  111055. vb->totaluse=0;
  111056. }
  111057. /* pull the ripcord */
  111058. vb->localtop=0;
  111059. vb->reap=NULL;
  111060. }
  111061. int vorbis_block_clear(vorbis_block *vb){
  111062. int i;
  111063. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111064. _vorbis_block_ripcord(vb);
  111065. if(vb->localstore)_ogg_free(vb->localstore);
  111066. if(vbi){
  111067. for(i=0;i<PACKETBLOBS;i++){
  111068. oggpack_writeclear(vbi->packetblob[i]);
  111069. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111070. }
  111071. _ogg_free(vbi);
  111072. }
  111073. memset(vb,0,sizeof(*vb));
  111074. return(0);
  111075. }
  111076. /* Analysis side code, but directly related to blocking. Thus it's
  111077. here and not in analysis.c (which is for analysis transforms only).
  111078. The init is here because some of it is shared */
  111079. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111080. int i;
  111081. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111082. private_state *b=NULL;
  111083. int hs;
  111084. if(ci==NULL) return 1;
  111085. hs=ci->halfrate_flag;
  111086. memset(v,0,sizeof(*v));
  111087. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111088. v->vi=vi;
  111089. b->modebits=ilog2(ci->modes);
  111090. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111091. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111092. /* MDCT is tranform 0 */
  111093. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111094. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111095. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111096. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111097. /* Vorbis I uses only window type 0 */
  111098. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111099. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111100. if(encp){ /* encode/decode differ here */
  111101. /* analysis always needs an fft */
  111102. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111103. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111104. /* finish the codebooks */
  111105. if(!ci->fullbooks){
  111106. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111107. for(i=0;i<ci->books;i++)
  111108. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111109. }
  111110. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111111. for(i=0;i<ci->psys;i++){
  111112. _vp_psy_init(b->psy+i,
  111113. ci->psy_param[i],
  111114. &ci->psy_g_param,
  111115. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111116. vi->rate);
  111117. }
  111118. v->analysisp=1;
  111119. }else{
  111120. /* finish the codebooks */
  111121. if(!ci->fullbooks){
  111122. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111123. for(i=0;i<ci->books;i++){
  111124. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111125. /* decode codebooks are now standalone after init */
  111126. vorbis_staticbook_destroy(ci->book_param[i]);
  111127. ci->book_param[i]=NULL;
  111128. }
  111129. }
  111130. }
  111131. /* initialize the storage vectors. blocksize[1] is small for encode,
  111132. but the correct size for decode */
  111133. v->pcm_storage=ci->blocksizes[1];
  111134. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111135. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111136. {
  111137. int i;
  111138. for(i=0;i<vi->channels;i++)
  111139. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111140. }
  111141. /* all 1 (large block) or 0 (small block) */
  111142. /* explicitly set for the sake of clarity */
  111143. v->lW=0; /* previous window size */
  111144. v->W=0; /* current window size */
  111145. /* all vector indexes */
  111146. v->centerW=ci->blocksizes[1]/2;
  111147. v->pcm_current=v->centerW;
  111148. /* initialize all the backend lookups */
  111149. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111150. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111151. for(i=0;i<ci->floors;i++)
  111152. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111153. look(v,ci->floor_param[i]);
  111154. for(i=0;i<ci->residues;i++)
  111155. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111156. look(v,ci->residue_param[i]);
  111157. return 0;
  111158. }
  111159. /* arbitrary settings and spec-mandated numbers get filled in here */
  111160. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111161. private_state *b=NULL;
  111162. if(_vds_shared_init(v,vi,1))return 1;
  111163. b=(private_state*)v->backend_state;
  111164. b->psy_g_look=_vp_global_look(vi);
  111165. /* Initialize the envelope state storage */
  111166. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111167. _ve_envelope_init(b->ve,vi);
  111168. vorbis_bitrate_init(vi,&b->bms);
  111169. /* compressed audio packets start after the headers
  111170. with sequence number 3 */
  111171. v->sequence=3;
  111172. return(0);
  111173. }
  111174. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111175. int i;
  111176. if(v){
  111177. vorbis_info *vi=v->vi;
  111178. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111179. private_state *b=(private_state*)v->backend_state;
  111180. if(b){
  111181. if(b->ve){
  111182. _ve_envelope_clear(b->ve);
  111183. _ogg_free(b->ve);
  111184. }
  111185. if(b->transform[0]){
  111186. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111187. _ogg_free(b->transform[0][0]);
  111188. _ogg_free(b->transform[0]);
  111189. }
  111190. if(b->transform[1]){
  111191. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111192. _ogg_free(b->transform[1][0]);
  111193. _ogg_free(b->transform[1]);
  111194. }
  111195. if(b->flr){
  111196. for(i=0;i<ci->floors;i++)
  111197. _floor_P[ci->floor_type[i]]->
  111198. free_look(b->flr[i]);
  111199. _ogg_free(b->flr);
  111200. }
  111201. if(b->residue){
  111202. for(i=0;i<ci->residues;i++)
  111203. _residue_P[ci->residue_type[i]]->
  111204. free_look(b->residue[i]);
  111205. _ogg_free(b->residue);
  111206. }
  111207. if(b->psy){
  111208. for(i=0;i<ci->psys;i++)
  111209. _vp_psy_clear(b->psy+i);
  111210. _ogg_free(b->psy);
  111211. }
  111212. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111213. vorbis_bitrate_clear(&b->bms);
  111214. drft_clear(&b->fft_look[0]);
  111215. drft_clear(&b->fft_look[1]);
  111216. }
  111217. if(v->pcm){
  111218. for(i=0;i<vi->channels;i++)
  111219. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111220. _ogg_free(v->pcm);
  111221. if(v->pcmret)_ogg_free(v->pcmret);
  111222. }
  111223. if(b){
  111224. /* free header, header1, header2 */
  111225. if(b->header)_ogg_free(b->header);
  111226. if(b->header1)_ogg_free(b->header1);
  111227. if(b->header2)_ogg_free(b->header2);
  111228. _ogg_free(b);
  111229. }
  111230. memset(v,0,sizeof(*v));
  111231. }
  111232. }
  111233. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111234. int i;
  111235. vorbis_info *vi=v->vi;
  111236. private_state *b=(private_state*)v->backend_state;
  111237. /* free header, header1, header2 */
  111238. if(b->header)_ogg_free(b->header);b->header=NULL;
  111239. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111240. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111241. /* Do we have enough storage space for the requested buffer? If not,
  111242. expand the PCM (and envelope) storage */
  111243. if(v->pcm_current+vals>=v->pcm_storage){
  111244. v->pcm_storage=v->pcm_current+vals*2;
  111245. for(i=0;i<vi->channels;i++){
  111246. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111247. }
  111248. }
  111249. for(i=0;i<vi->channels;i++)
  111250. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111251. return(v->pcmret);
  111252. }
  111253. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111254. int i;
  111255. int order=32;
  111256. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111257. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111258. long j;
  111259. v->preextrapolate=1;
  111260. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111261. for(i=0;i<v->vi->channels;i++){
  111262. /* need to run the extrapolation in reverse! */
  111263. for(j=0;j<v->pcm_current;j++)
  111264. work[j]=v->pcm[i][v->pcm_current-j-1];
  111265. /* prime as above */
  111266. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111267. /* run the predictor filter */
  111268. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111269. order,
  111270. work+v->pcm_current-v->centerW,
  111271. v->centerW);
  111272. for(j=0;j<v->pcm_current;j++)
  111273. v->pcm[i][v->pcm_current-j-1]=work[j];
  111274. }
  111275. }
  111276. }
  111277. /* call with val<=0 to set eof */
  111278. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111279. vorbis_info *vi=v->vi;
  111280. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111281. if(vals<=0){
  111282. int order=32;
  111283. int i;
  111284. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111285. /* if it wasn't done earlier (very short sample) */
  111286. if(!v->preextrapolate)
  111287. _preextrapolate_helper(v);
  111288. /* We're encoding the end of the stream. Just make sure we have
  111289. [at least] a few full blocks of zeroes at the end. */
  111290. /* actually, we don't want zeroes; that could drop a large
  111291. amplitude off a cliff, creating spread spectrum noise that will
  111292. suck to encode. Extrapolate for the sake of cleanliness. */
  111293. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111294. v->eofflag=v->pcm_current;
  111295. v->pcm_current+=ci->blocksizes[1]*3;
  111296. for(i=0;i<vi->channels;i++){
  111297. if(v->eofflag>order*2){
  111298. /* extrapolate with LPC to fill in */
  111299. long n;
  111300. /* make a predictor filter */
  111301. n=v->eofflag;
  111302. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111303. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111304. /* run the predictor filter */
  111305. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111306. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111307. }else{
  111308. /* not enough data to extrapolate (unlikely to happen due to
  111309. guarding the overlap, but bulletproof in case that
  111310. assumtion goes away). zeroes will do. */
  111311. memset(v->pcm[i]+v->eofflag,0,
  111312. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111313. }
  111314. }
  111315. }else{
  111316. if(v->pcm_current+vals>v->pcm_storage)
  111317. return(OV_EINVAL);
  111318. v->pcm_current+=vals;
  111319. /* we may want to reverse extrapolate the beginning of a stream
  111320. too... in case we're beginning on a cliff! */
  111321. /* clumsy, but simple. It only runs once, so simple is good. */
  111322. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111323. _preextrapolate_helper(v);
  111324. }
  111325. return(0);
  111326. }
  111327. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111328. the next block on which to continue analysis */
  111329. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111330. int i;
  111331. vorbis_info *vi=v->vi;
  111332. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111333. private_state *b=(private_state*)v->backend_state;
  111334. vorbis_look_psy_global *g=b->psy_g_look;
  111335. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111336. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111337. /* check to see if we're started... */
  111338. if(!v->preextrapolate)return(0);
  111339. /* check to see if we're done... */
  111340. if(v->eofflag==-1)return(0);
  111341. /* By our invariant, we have lW, W and centerW set. Search for
  111342. the next boundary so we can determine nW (the next window size)
  111343. which lets us compute the shape of the current block's window */
  111344. /* we do an envelope search even on a single blocksize; we may still
  111345. be throwing more bits at impulses, and envelope search handles
  111346. marking impulses too. */
  111347. {
  111348. long bp=_ve_envelope_search(v);
  111349. if(bp==-1){
  111350. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111351. full long block */
  111352. v->nW=0;
  111353. }else{
  111354. if(ci->blocksizes[0]==ci->blocksizes[1])
  111355. v->nW=0;
  111356. else
  111357. v->nW=bp;
  111358. }
  111359. }
  111360. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111361. {
  111362. /* center of next block + next block maximum right side. */
  111363. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111364. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111365. although this check is
  111366. less strict that the
  111367. _ve_envelope_search,
  111368. the search is not run
  111369. if we only use one
  111370. block size */
  111371. }
  111372. /* fill in the block. Note that for a short window, lW and nW are *short*
  111373. regardless of actual settings in the stream */
  111374. _vorbis_block_ripcord(vb);
  111375. vb->lW=v->lW;
  111376. vb->W=v->W;
  111377. vb->nW=v->nW;
  111378. if(v->W){
  111379. if(!v->lW || !v->nW){
  111380. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111381. /*fprintf(stderr,"-");*/
  111382. }else{
  111383. vbi->blocktype=BLOCKTYPE_LONG;
  111384. /*fprintf(stderr,"_");*/
  111385. }
  111386. }else{
  111387. if(_ve_envelope_mark(v)){
  111388. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111389. /*fprintf(stderr,"|");*/
  111390. }else{
  111391. vbi->blocktype=BLOCKTYPE_PADDING;
  111392. /*fprintf(stderr,".");*/
  111393. }
  111394. }
  111395. vb->vd=v;
  111396. vb->sequence=v->sequence++;
  111397. vb->granulepos=v->granulepos;
  111398. vb->pcmend=ci->blocksizes[v->W];
  111399. /* copy the vectors; this uses the local storage in vb */
  111400. /* this tracks 'strongest peak' for later psychoacoustics */
  111401. /* moved to the global psy state; clean this mess up */
  111402. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111403. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111404. vbi->ampmax=g->ampmax;
  111405. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111406. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111407. for(i=0;i<vi->channels;i++){
  111408. vbi->pcmdelay[i]=
  111409. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111410. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111411. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111412. /* before we added the delay
  111413. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111414. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111415. */
  111416. }
  111417. /* handle eof detection: eof==0 means that we've not yet received EOF
  111418. eof>0 marks the last 'real' sample in pcm[]
  111419. eof<0 'no more to do'; doesn't get here */
  111420. if(v->eofflag){
  111421. if(v->centerW>=v->eofflag){
  111422. v->eofflag=-1;
  111423. vb->eofflag=1;
  111424. return(1);
  111425. }
  111426. }
  111427. /* advance storage vectors and clean up */
  111428. {
  111429. int new_centerNext=ci->blocksizes[1]/2;
  111430. int movementW=centerNext-new_centerNext;
  111431. if(movementW>0){
  111432. _ve_envelope_shift(b->ve,movementW);
  111433. v->pcm_current-=movementW;
  111434. for(i=0;i<vi->channels;i++)
  111435. memmove(v->pcm[i],v->pcm[i]+movementW,
  111436. v->pcm_current*sizeof(*v->pcm[i]));
  111437. v->lW=v->W;
  111438. v->W=v->nW;
  111439. v->centerW=new_centerNext;
  111440. if(v->eofflag){
  111441. v->eofflag-=movementW;
  111442. if(v->eofflag<=0)v->eofflag=-1;
  111443. /* do not add padding to end of stream! */
  111444. if(v->centerW>=v->eofflag){
  111445. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111446. }else{
  111447. v->granulepos+=movementW;
  111448. }
  111449. }else{
  111450. v->granulepos+=movementW;
  111451. }
  111452. }
  111453. }
  111454. /* done */
  111455. return(1);
  111456. }
  111457. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111458. vorbis_info *vi=v->vi;
  111459. codec_setup_info *ci;
  111460. int hs;
  111461. if(!v->backend_state)return -1;
  111462. if(!vi)return -1;
  111463. ci=(codec_setup_info*) vi->codec_setup;
  111464. if(!ci)return -1;
  111465. hs=ci->halfrate_flag;
  111466. v->centerW=ci->blocksizes[1]>>(hs+1);
  111467. v->pcm_current=v->centerW>>hs;
  111468. v->pcm_returned=-1;
  111469. v->granulepos=-1;
  111470. v->sequence=-1;
  111471. v->eofflag=0;
  111472. ((private_state *)(v->backend_state))->sample_count=-1;
  111473. return(0);
  111474. }
  111475. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111476. if(_vds_shared_init(v,vi,0)) return 1;
  111477. vorbis_synthesis_restart(v);
  111478. return 0;
  111479. }
  111480. /* Unlike in analysis, the window is only partially applied for each
  111481. block. The time domain envelope is not yet handled at the point of
  111482. calling (as it relies on the previous block). */
  111483. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111484. vorbis_info *vi=v->vi;
  111485. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111486. private_state *b=(private_state*)v->backend_state;
  111487. int hs=ci->halfrate_flag;
  111488. int i,j;
  111489. if(!vb)return(OV_EINVAL);
  111490. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111491. v->lW=v->W;
  111492. v->W=vb->W;
  111493. v->nW=-1;
  111494. if((v->sequence==-1)||
  111495. (v->sequence+1 != vb->sequence)){
  111496. v->granulepos=-1; /* out of sequence; lose count */
  111497. b->sample_count=-1;
  111498. }
  111499. v->sequence=vb->sequence;
  111500. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111501. was called on block */
  111502. int n=ci->blocksizes[v->W]>>(hs+1);
  111503. int n0=ci->blocksizes[0]>>(hs+1);
  111504. int n1=ci->blocksizes[1]>>(hs+1);
  111505. int thisCenter;
  111506. int prevCenter;
  111507. v->glue_bits+=vb->glue_bits;
  111508. v->time_bits+=vb->time_bits;
  111509. v->floor_bits+=vb->floor_bits;
  111510. v->res_bits+=vb->res_bits;
  111511. if(v->centerW){
  111512. thisCenter=n1;
  111513. prevCenter=0;
  111514. }else{
  111515. thisCenter=0;
  111516. prevCenter=n1;
  111517. }
  111518. /* v->pcm is now used like a two-stage double buffer. We don't want
  111519. to have to constantly shift *or* adjust memory usage. Don't
  111520. accept a new block until the old is shifted out */
  111521. for(j=0;j<vi->channels;j++){
  111522. /* the overlap/add section */
  111523. if(v->lW){
  111524. if(v->W){
  111525. /* large/large */
  111526. float *w=_vorbis_window_get(b->window[1]-hs);
  111527. float *pcm=v->pcm[j]+prevCenter;
  111528. float *p=vb->pcm[j];
  111529. for(i=0;i<n1;i++)
  111530. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111531. }else{
  111532. /* large/small */
  111533. float *w=_vorbis_window_get(b->window[0]-hs);
  111534. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111535. float *p=vb->pcm[j];
  111536. for(i=0;i<n0;i++)
  111537. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111538. }
  111539. }else{
  111540. if(v->W){
  111541. /* small/large */
  111542. float *w=_vorbis_window_get(b->window[0]-hs);
  111543. float *pcm=v->pcm[j]+prevCenter;
  111544. float *p=vb->pcm[j]+n1/2-n0/2;
  111545. for(i=0;i<n0;i++)
  111546. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111547. for(;i<n1/2+n0/2;i++)
  111548. pcm[i]=p[i];
  111549. }else{
  111550. /* small/small */
  111551. float *w=_vorbis_window_get(b->window[0]-hs);
  111552. float *pcm=v->pcm[j]+prevCenter;
  111553. float *p=vb->pcm[j];
  111554. for(i=0;i<n0;i++)
  111555. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111556. }
  111557. }
  111558. /* the copy section */
  111559. {
  111560. float *pcm=v->pcm[j]+thisCenter;
  111561. float *p=vb->pcm[j]+n;
  111562. for(i=0;i<n;i++)
  111563. pcm[i]=p[i];
  111564. }
  111565. }
  111566. if(v->centerW)
  111567. v->centerW=0;
  111568. else
  111569. v->centerW=n1;
  111570. /* deal with initial packet state; we do this using the explicit
  111571. pcm_returned==-1 flag otherwise we're sensitive to first block
  111572. being short or long */
  111573. if(v->pcm_returned==-1){
  111574. v->pcm_returned=thisCenter;
  111575. v->pcm_current=thisCenter;
  111576. }else{
  111577. v->pcm_returned=prevCenter;
  111578. v->pcm_current=prevCenter+
  111579. ((ci->blocksizes[v->lW]/4+
  111580. ci->blocksizes[v->W]/4)>>hs);
  111581. }
  111582. }
  111583. /* track the frame number... This is for convenience, but also
  111584. making sure our last packet doesn't end with added padding. If
  111585. the last packet is partial, the number of samples we'll have to
  111586. return will be past the vb->granulepos.
  111587. This is not foolproof! It will be confused if we begin
  111588. decoding at the last page after a seek or hole. In that case,
  111589. we don't have a starting point to judge where the last frame
  111590. is. For this reason, vorbisfile will always try to make sure
  111591. it reads the last two marked pages in proper sequence */
  111592. if(b->sample_count==-1){
  111593. b->sample_count=0;
  111594. }else{
  111595. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111596. }
  111597. if(v->granulepos==-1){
  111598. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111599. v->granulepos=vb->granulepos;
  111600. /* is this a short page? */
  111601. if(b->sample_count>v->granulepos){
  111602. /* corner case; if this is both the first and last audio page,
  111603. then spec says the end is cut, not beginning */
  111604. if(vb->eofflag){
  111605. /* trim the end */
  111606. /* no preceeding granulepos; assume we started at zero (we'd
  111607. have to in a short single-page stream) */
  111608. /* granulepos could be -1 due to a seek, but that would result
  111609. in a long count, not short count */
  111610. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111611. }else{
  111612. /* trim the beginning */
  111613. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111614. if(v->pcm_returned>v->pcm_current)
  111615. v->pcm_returned=v->pcm_current;
  111616. }
  111617. }
  111618. }
  111619. }else{
  111620. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111621. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111622. if(v->granulepos>vb->granulepos){
  111623. long extra=v->granulepos-vb->granulepos;
  111624. if(extra)
  111625. if(vb->eofflag){
  111626. /* partial last frame. Strip the extra samples off */
  111627. v->pcm_current-=extra>>hs;
  111628. } /* else {Shouldn't happen *unless* the bitstream is out of
  111629. spec. Either way, believe the bitstream } */
  111630. } /* else {Shouldn't happen *unless* the bitstream is out of
  111631. spec. Either way, believe the bitstream } */
  111632. v->granulepos=vb->granulepos;
  111633. }
  111634. }
  111635. /* Update, cleanup */
  111636. if(vb->eofflag)v->eofflag=1;
  111637. return(0);
  111638. }
  111639. /* pcm==NULL indicates we just want the pending samples, no more */
  111640. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111641. vorbis_info *vi=v->vi;
  111642. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111643. if(pcm){
  111644. int i;
  111645. for(i=0;i<vi->channels;i++)
  111646. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111647. *pcm=v->pcmret;
  111648. }
  111649. return(v->pcm_current-v->pcm_returned);
  111650. }
  111651. return(0);
  111652. }
  111653. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111654. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111655. v->pcm_returned+=n;
  111656. return(0);
  111657. }
  111658. /* intended for use with a specific vorbisfile feature; we want access
  111659. to the [usually synthetic/postextrapolated] buffer and lapping at
  111660. the end of a decode cycle, specifically, a half-short-block worth.
  111661. This funtion works like pcmout above, except it will also expose
  111662. this implicit buffer data not normally decoded. */
  111663. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111664. vorbis_info *vi=v->vi;
  111665. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111666. int hs=ci->halfrate_flag;
  111667. int n=ci->blocksizes[v->W]>>(hs+1);
  111668. int n0=ci->blocksizes[0]>>(hs+1);
  111669. int n1=ci->blocksizes[1]>>(hs+1);
  111670. int i,j;
  111671. if(v->pcm_returned<0)return 0;
  111672. /* our returned data ends at pcm_returned; because the synthesis pcm
  111673. buffer is a two-fragment ring, that means our data block may be
  111674. fragmented by buffering, wrapping or a short block not filling
  111675. out a buffer. To simplify things, we unfragment if it's at all
  111676. possibly needed. Otherwise, we'd need to call lapout more than
  111677. once as well as hold additional dsp state. Opt for
  111678. simplicity. */
  111679. /* centerW was advanced by blockin; it would be the center of the
  111680. *next* block */
  111681. if(v->centerW==n1){
  111682. /* the data buffer wraps; swap the halves */
  111683. /* slow, sure, small */
  111684. for(j=0;j<vi->channels;j++){
  111685. float *p=v->pcm[j];
  111686. for(i=0;i<n1;i++){
  111687. float temp=p[i];
  111688. p[i]=p[i+n1];
  111689. p[i+n1]=temp;
  111690. }
  111691. }
  111692. v->pcm_current-=n1;
  111693. v->pcm_returned-=n1;
  111694. v->centerW=0;
  111695. }
  111696. /* solidify buffer into contiguous space */
  111697. if((v->lW^v->W)==1){
  111698. /* long/short or short/long */
  111699. for(j=0;j<vi->channels;j++){
  111700. float *s=v->pcm[j];
  111701. float *d=v->pcm[j]+(n1-n0)/2;
  111702. for(i=(n1+n0)/2-1;i>=0;--i)
  111703. d[i]=s[i];
  111704. }
  111705. v->pcm_returned+=(n1-n0)/2;
  111706. v->pcm_current+=(n1-n0)/2;
  111707. }else{
  111708. if(v->lW==0){
  111709. /* short/short */
  111710. for(j=0;j<vi->channels;j++){
  111711. float *s=v->pcm[j];
  111712. float *d=v->pcm[j]+n1-n0;
  111713. for(i=n0-1;i>=0;--i)
  111714. d[i]=s[i];
  111715. }
  111716. v->pcm_returned+=n1-n0;
  111717. v->pcm_current+=n1-n0;
  111718. }
  111719. }
  111720. if(pcm){
  111721. int i;
  111722. for(i=0;i<vi->channels;i++)
  111723. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111724. *pcm=v->pcmret;
  111725. }
  111726. return(n1+n-v->pcm_returned);
  111727. }
  111728. float *vorbis_window(vorbis_dsp_state *v,int W){
  111729. vorbis_info *vi=v->vi;
  111730. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111731. int hs=ci->halfrate_flag;
  111732. private_state *b=(private_state*)v->backend_state;
  111733. if(b->window[W]-1<0)return NULL;
  111734. return _vorbis_window_get(b->window[W]-hs);
  111735. }
  111736. #endif
  111737. /*** End of inlined file: block.c ***/
  111738. /*** Start of inlined file: codebook.c ***/
  111739. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111740. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111741. // tasks..
  111742. #if JUCE_MSVC
  111743. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111744. #endif
  111745. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111746. #if JUCE_USE_OGGVORBIS
  111747. #include <stdlib.h>
  111748. #include <string.h>
  111749. #include <math.h>
  111750. /* packs the given codebook into the bitstream **************************/
  111751. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111752. long i,j;
  111753. int ordered=0;
  111754. /* first the basic parameters */
  111755. oggpack_write(opb,0x564342,24);
  111756. oggpack_write(opb,c->dim,16);
  111757. oggpack_write(opb,c->entries,24);
  111758. /* pack the codewords. There are two packings; length ordered and
  111759. length random. Decide between the two now. */
  111760. for(i=1;i<c->entries;i++)
  111761. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111762. if(i==c->entries)ordered=1;
  111763. if(ordered){
  111764. /* length ordered. We only need to say how many codewords of
  111765. each length. The actual codewords are generated
  111766. deterministically */
  111767. long count=0;
  111768. oggpack_write(opb,1,1); /* ordered */
  111769. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111770. for(i=1;i<c->entries;i++){
  111771. long thisx=c->lengthlist[i];
  111772. long last=c->lengthlist[i-1];
  111773. if(thisx>last){
  111774. for(j=last;j<thisx;j++){
  111775. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111776. count=i;
  111777. }
  111778. }
  111779. }
  111780. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111781. }else{
  111782. /* length random. Again, we don't code the codeword itself, just
  111783. the length. This time, though, we have to encode each length */
  111784. oggpack_write(opb,0,1); /* unordered */
  111785. /* algortihmic mapping has use for 'unused entries', which we tag
  111786. here. The algorithmic mapping happens as usual, but the unused
  111787. entry has no codeword. */
  111788. for(i=0;i<c->entries;i++)
  111789. if(c->lengthlist[i]==0)break;
  111790. if(i==c->entries){
  111791. oggpack_write(opb,0,1); /* no unused entries */
  111792. for(i=0;i<c->entries;i++)
  111793. oggpack_write(opb,c->lengthlist[i]-1,5);
  111794. }else{
  111795. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111796. for(i=0;i<c->entries;i++){
  111797. if(c->lengthlist[i]==0){
  111798. oggpack_write(opb,0,1);
  111799. }else{
  111800. oggpack_write(opb,1,1);
  111801. oggpack_write(opb,c->lengthlist[i]-1,5);
  111802. }
  111803. }
  111804. }
  111805. }
  111806. /* is the entry number the desired return value, or do we have a
  111807. mapping? If we have a mapping, what type? */
  111808. oggpack_write(opb,c->maptype,4);
  111809. switch(c->maptype){
  111810. case 0:
  111811. /* no mapping */
  111812. break;
  111813. case 1:case 2:
  111814. /* implicitly populated value mapping */
  111815. /* explicitly populated value mapping */
  111816. if(!c->quantlist){
  111817. /* no quantlist? error */
  111818. return(-1);
  111819. }
  111820. /* values that define the dequantization */
  111821. oggpack_write(opb,c->q_min,32);
  111822. oggpack_write(opb,c->q_delta,32);
  111823. oggpack_write(opb,c->q_quant-1,4);
  111824. oggpack_write(opb,c->q_sequencep,1);
  111825. {
  111826. int quantvals;
  111827. switch(c->maptype){
  111828. case 1:
  111829. /* a single column of (c->entries/c->dim) quantized values for
  111830. building a full value list algorithmically (square lattice) */
  111831. quantvals=_book_maptype1_quantvals(c);
  111832. break;
  111833. case 2:
  111834. /* every value (c->entries*c->dim total) specified explicitly */
  111835. quantvals=c->entries*c->dim;
  111836. break;
  111837. default: /* NOT_REACHABLE */
  111838. quantvals=-1;
  111839. }
  111840. /* quantized values */
  111841. for(i=0;i<quantvals;i++)
  111842. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111843. }
  111844. break;
  111845. default:
  111846. /* error case; we don't have any other map types now */
  111847. return(-1);
  111848. }
  111849. return(0);
  111850. }
  111851. /* unpacks a codebook from the packet buffer into the codebook struct,
  111852. readies the codebook auxiliary structures for decode *************/
  111853. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111854. long i,j;
  111855. memset(s,0,sizeof(*s));
  111856. s->allocedp=1;
  111857. /* make sure alignment is correct */
  111858. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111859. /* first the basic parameters */
  111860. s->dim=oggpack_read(opb,16);
  111861. s->entries=oggpack_read(opb,24);
  111862. if(s->entries==-1)goto _eofout;
  111863. /* codeword ordering.... length ordered or unordered? */
  111864. switch((int)oggpack_read(opb,1)){
  111865. case 0:
  111866. /* unordered */
  111867. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111868. /* allocated but unused entries? */
  111869. if(oggpack_read(opb,1)){
  111870. /* yes, unused entries */
  111871. for(i=0;i<s->entries;i++){
  111872. if(oggpack_read(opb,1)){
  111873. long num=oggpack_read(opb,5);
  111874. if(num==-1)goto _eofout;
  111875. s->lengthlist[i]=num+1;
  111876. }else
  111877. s->lengthlist[i]=0;
  111878. }
  111879. }else{
  111880. /* all entries used; no tagging */
  111881. for(i=0;i<s->entries;i++){
  111882. long num=oggpack_read(opb,5);
  111883. if(num==-1)goto _eofout;
  111884. s->lengthlist[i]=num+1;
  111885. }
  111886. }
  111887. break;
  111888. case 1:
  111889. /* ordered */
  111890. {
  111891. long length=oggpack_read(opb,5)+1;
  111892. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111893. for(i=0;i<s->entries;){
  111894. long num=oggpack_read(opb,_ilog(s->entries-i));
  111895. if(num==-1)goto _eofout;
  111896. for(j=0;j<num && i<s->entries;j++,i++)
  111897. s->lengthlist[i]=length;
  111898. length++;
  111899. }
  111900. }
  111901. break;
  111902. default:
  111903. /* EOF */
  111904. return(-1);
  111905. }
  111906. /* Do we have a mapping to unpack? */
  111907. switch((s->maptype=oggpack_read(opb,4))){
  111908. case 0:
  111909. /* no mapping */
  111910. break;
  111911. case 1: case 2:
  111912. /* implicitly populated value mapping */
  111913. /* explicitly populated value mapping */
  111914. s->q_min=oggpack_read(opb,32);
  111915. s->q_delta=oggpack_read(opb,32);
  111916. s->q_quant=oggpack_read(opb,4)+1;
  111917. s->q_sequencep=oggpack_read(opb,1);
  111918. {
  111919. int quantvals=0;
  111920. switch(s->maptype){
  111921. case 1:
  111922. quantvals=_book_maptype1_quantvals(s);
  111923. break;
  111924. case 2:
  111925. quantvals=s->entries*s->dim;
  111926. break;
  111927. }
  111928. /* quantized values */
  111929. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111930. for(i=0;i<quantvals;i++)
  111931. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111932. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111933. }
  111934. break;
  111935. default:
  111936. goto _errout;
  111937. }
  111938. /* all set */
  111939. return(0);
  111940. _errout:
  111941. _eofout:
  111942. vorbis_staticbook_clear(s);
  111943. return(-1);
  111944. }
  111945. /* returns the number of bits ************************************************/
  111946. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111947. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111948. return(book->c->lengthlist[a]);
  111949. }
  111950. /* One the encode side, our vector writers are each designed for a
  111951. specific purpose, and the encoder is not flexible without modification:
  111952. The LSP vector coder uses a single stage nearest-match with no
  111953. interleave, so no step and no error return. This is specced by floor0
  111954. and doesn't change.
  111955. Residue0 encoding interleaves, uses multiple stages, and each stage
  111956. peels of a specific amount of resolution from a lattice (thus we want
  111957. to match by threshold, not nearest match). Residue doesn't *have* to
  111958. be encoded that way, but to change it, one will need to add more
  111959. infrastructure on the encode side (decode side is specced and simpler) */
  111960. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111961. /* returns entry number and *modifies a* to the quantization value *****/
  111962. int vorbis_book_errorv(codebook *book,float *a){
  111963. int dim=book->dim,k;
  111964. int best=_best(book,a,1);
  111965. for(k=0;k<dim;k++)
  111966. a[k]=(book->valuelist+best*dim)[k];
  111967. return(best);
  111968. }
  111969. /* returns the number of bits and *modifies a* to the quantization value *****/
  111970. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111971. int k,dim=book->dim;
  111972. for(k=0;k<dim;k++)
  111973. a[k]=(book->valuelist+best*dim)[k];
  111974. return(vorbis_book_encode(book,best,b));
  111975. }
  111976. /* the 'eliminate the decode tree' optimization actually requires the
  111977. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111978. (and one of the first places where carefully thought out design
  111979. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111980. to an MSb bitpacker), but not actually the huge hit it appears to
  111981. be. The first-stage decode table catches most words so that
  111982. bitreverse is not in the main execution path. */
  111983. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111984. int read=book->dec_maxlength;
  111985. long lo,hi;
  111986. long lok = oggpack_look(b,book->dec_firsttablen);
  111987. if (lok >= 0) {
  111988. long entry = book->dec_firsttable[lok];
  111989. if(entry&0x80000000UL){
  111990. lo=(entry>>15)&0x7fff;
  111991. hi=book->used_entries-(entry&0x7fff);
  111992. }else{
  111993. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111994. return(entry-1);
  111995. }
  111996. }else{
  111997. lo=0;
  111998. hi=book->used_entries;
  111999. }
  112000. lok = oggpack_look(b, read);
  112001. while(lok<0 && read>1)
  112002. lok = oggpack_look(b, --read);
  112003. if(lok<0)return -1;
  112004. /* bisect search for the codeword in the ordered list */
  112005. {
  112006. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112007. while(hi-lo>1){
  112008. long p=(hi-lo)>>1;
  112009. long test=book->codelist[lo+p]>testword;
  112010. lo+=p&(test-1);
  112011. hi-=p&(-test);
  112012. }
  112013. if(book->dec_codelengths[lo]<=read){
  112014. oggpack_adv(b, book->dec_codelengths[lo]);
  112015. return(lo);
  112016. }
  112017. }
  112018. oggpack_adv(b, read);
  112019. return(-1);
  112020. }
  112021. /* Decode side is specced and easier, because we don't need to find
  112022. matches using different criteria; we simply read and map. There are
  112023. two things we need to do 'depending':
  112024. We may need to support interleave. We don't really, but it's
  112025. convenient to do it here rather than rebuild the vector later.
  112026. Cascades may be additive or multiplicitive; this is not inherent in
  112027. the codebook, but set in the code using the codebook. Like
  112028. interleaving, it's easiest to do it here.
  112029. addmul==0 -> declarative (set the value)
  112030. addmul==1 -> additive
  112031. addmul==2 -> multiplicitive */
  112032. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112033. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112034. long packed_entry=decode_packed_entry_number(book,b);
  112035. if(packed_entry>=0)
  112036. return(book->dec_index[packed_entry]);
  112037. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112038. return(packed_entry);
  112039. }
  112040. /* returns 0 on OK or -1 on eof *************************************/
  112041. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112042. int step=n/book->dim;
  112043. long *entry = (long*)alloca(sizeof(*entry)*step);
  112044. float **t = (float**)alloca(sizeof(*t)*step);
  112045. int i,j,o;
  112046. for (i = 0; i < step; i++) {
  112047. entry[i]=decode_packed_entry_number(book,b);
  112048. if(entry[i]==-1)return(-1);
  112049. t[i] = book->valuelist+entry[i]*book->dim;
  112050. }
  112051. for(i=0,o=0;i<book->dim;i++,o+=step)
  112052. for (j=0;j<step;j++)
  112053. a[o+j]+=t[j][i];
  112054. return(0);
  112055. }
  112056. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112057. int i,j,entry;
  112058. float *t;
  112059. if(book->dim>8){
  112060. for(i=0;i<n;){
  112061. entry = decode_packed_entry_number(book,b);
  112062. if(entry==-1)return(-1);
  112063. t = book->valuelist+entry*book->dim;
  112064. for (j=0;j<book->dim;)
  112065. a[i++]+=t[j++];
  112066. }
  112067. }else{
  112068. for(i=0;i<n;){
  112069. entry = decode_packed_entry_number(book,b);
  112070. if(entry==-1)return(-1);
  112071. t = book->valuelist+entry*book->dim;
  112072. j=0;
  112073. switch((int)book->dim){
  112074. case 8:
  112075. a[i++]+=t[j++];
  112076. case 7:
  112077. a[i++]+=t[j++];
  112078. case 6:
  112079. a[i++]+=t[j++];
  112080. case 5:
  112081. a[i++]+=t[j++];
  112082. case 4:
  112083. a[i++]+=t[j++];
  112084. case 3:
  112085. a[i++]+=t[j++];
  112086. case 2:
  112087. a[i++]+=t[j++];
  112088. case 1:
  112089. a[i++]+=t[j++];
  112090. case 0:
  112091. break;
  112092. }
  112093. }
  112094. }
  112095. return(0);
  112096. }
  112097. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112098. int i,j,entry;
  112099. float *t;
  112100. for(i=0;i<n;){
  112101. entry = decode_packed_entry_number(book,b);
  112102. if(entry==-1)return(-1);
  112103. t = book->valuelist+entry*book->dim;
  112104. for (j=0;j<book->dim;)
  112105. a[i++]=t[j++];
  112106. }
  112107. return(0);
  112108. }
  112109. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112110. oggpack_buffer *b,int n){
  112111. long i,j,entry;
  112112. int chptr=0;
  112113. for(i=offset/ch;i<(offset+n)/ch;){
  112114. entry = decode_packed_entry_number(book,b);
  112115. if(entry==-1)return(-1);
  112116. {
  112117. const float *t = book->valuelist+entry*book->dim;
  112118. for (j=0;j<book->dim;j++){
  112119. a[chptr++][i]+=t[j];
  112120. if(chptr==ch){
  112121. chptr=0;
  112122. i++;
  112123. }
  112124. }
  112125. }
  112126. }
  112127. return(0);
  112128. }
  112129. #ifdef _V_SELFTEST
  112130. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112131. number of vectors through (keeping track of the quantized values),
  112132. and decode using the unpacked book. quantized version of in should
  112133. exactly equal out */
  112134. #include <stdio.h>
  112135. #include "vorbis/book/lsp20_0.vqh"
  112136. #include "vorbis/book/res0a_13.vqh"
  112137. #define TESTSIZE 40
  112138. float test1[TESTSIZE]={
  112139. 0.105939f,
  112140. 0.215373f,
  112141. 0.429117f,
  112142. 0.587974f,
  112143. 0.181173f,
  112144. 0.296583f,
  112145. 0.515707f,
  112146. 0.715261f,
  112147. 0.162327f,
  112148. 0.263834f,
  112149. 0.342876f,
  112150. 0.406025f,
  112151. 0.103571f,
  112152. 0.223561f,
  112153. 0.368513f,
  112154. 0.540313f,
  112155. 0.136672f,
  112156. 0.395882f,
  112157. 0.587183f,
  112158. 0.652476f,
  112159. 0.114338f,
  112160. 0.417300f,
  112161. 0.525486f,
  112162. 0.698679f,
  112163. 0.147492f,
  112164. 0.324481f,
  112165. 0.643089f,
  112166. 0.757582f,
  112167. 0.139556f,
  112168. 0.215795f,
  112169. 0.324559f,
  112170. 0.399387f,
  112171. 0.120236f,
  112172. 0.267420f,
  112173. 0.446940f,
  112174. 0.608760f,
  112175. 0.115587f,
  112176. 0.287234f,
  112177. 0.571081f,
  112178. 0.708603f,
  112179. };
  112180. float test3[TESTSIZE]={
  112181. 0,1,-2,3,4,-5,6,7,8,9,
  112182. 8,-2,7,-1,4,6,8,3,1,-9,
  112183. 10,11,12,13,14,15,26,17,18,19,
  112184. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112185. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112186. &_vq_book_res0a_13,NULL};
  112187. float *testvec[]={test1,test3};
  112188. int main(){
  112189. oggpack_buffer write;
  112190. oggpack_buffer read;
  112191. long ptr=0,i;
  112192. oggpack_writeinit(&write);
  112193. fprintf(stderr,"Testing codebook abstraction...:\n");
  112194. while(testlist[ptr]){
  112195. codebook c;
  112196. static_codebook s;
  112197. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112198. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112199. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112200. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112201. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112202. /* pack the codebook, write the testvector */
  112203. oggpack_reset(&write);
  112204. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112205. we can write */
  112206. vorbis_staticbook_pack(testlist[ptr],&write);
  112207. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112208. for(i=0;i<TESTSIZE;i+=c.dim){
  112209. int best=_best(&c,qv+i,1);
  112210. vorbis_book_encodev(&c,best,qv+i,&write);
  112211. }
  112212. vorbis_book_clear(&c);
  112213. fprintf(stderr,"OK.\n");
  112214. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112215. /* transfer the write data to a read buffer and unpack/read */
  112216. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112217. if(vorbis_staticbook_unpack(&read,&s)){
  112218. fprintf(stderr,"Error unpacking codebook.\n");
  112219. exit(1);
  112220. }
  112221. if(vorbis_book_init_decode(&c,&s)){
  112222. fprintf(stderr,"Error initializing codebook.\n");
  112223. exit(1);
  112224. }
  112225. for(i=0;i<TESTSIZE;i+=c.dim)
  112226. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112227. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112228. exit(1);
  112229. }
  112230. for(i=0;i<TESTSIZE;i++)
  112231. if(fabs(qv[i]-iv[i])>.000001){
  112232. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112233. iv[i],qv[i],i);
  112234. exit(1);
  112235. }
  112236. fprintf(stderr,"OK\n");
  112237. ptr++;
  112238. }
  112239. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112240. exit(0);
  112241. }
  112242. #endif
  112243. #endif
  112244. /*** End of inlined file: codebook.c ***/
  112245. /*** Start of inlined file: envelope.c ***/
  112246. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112247. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112248. // tasks..
  112249. #if JUCE_MSVC
  112250. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112251. #endif
  112252. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112253. #if JUCE_USE_OGGVORBIS
  112254. #include <stdlib.h>
  112255. #include <string.h>
  112256. #include <stdio.h>
  112257. #include <math.h>
  112258. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112259. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112260. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112261. int ch=vi->channels;
  112262. int i,j;
  112263. int n=e->winlength=128;
  112264. e->searchstep=64; /* not random */
  112265. e->minenergy=gi->preecho_minenergy;
  112266. e->ch=ch;
  112267. e->storage=128;
  112268. e->cursor=ci->blocksizes[1]/2;
  112269. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112270. mdct_init(&e->mdct,n);
  112271. for(i=0;i<n;i++){
  112272. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112273. e->mdct_win[i]*=e->mdct_win[i];
  112274. }
  112275. /* magic follows */
  112276. e->band[0].begin=2; e->band[0].end=4;
  112277. e->band[1].begin=4; e->band[1].end=5;
  112278. e->band[2].begin=6; e->band[2].end=6;
  112279. e->band[3].begin=9; e->band[3].end=8;
  112280. e->band[4].begin=13; e->band[4].end=8;
  112281. e->band[5].begin=17; e->band[5].end=8;
  112282. e->band[6].begin=22; e->band[6].end=8;
  112283. for(j=0;j<VE_BANDS;j++){
  112284. n=e->band[j].end;
  112285. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112286. for(i=0;i<n;i++){
  112287. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112288. e->band[j].total+=e->band[j].window[i];
  112289. }
  112290. e->band[j].total=1./e->band[j].total;
  112291. }
  112292. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112293. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112294. }
  112295. void _ve_envelope_clear(envelope_lookup *e){
  112296. int i;
  112297. mdct_clear(&e->mdct);
  112298. for(i=0;i<VE_BANDS;i++)
  112299. _ogg_free(e->band[i].window);
  112300. _ogg_free(e->mdct_win);
  112301. _ogg_free(e->filter);
  112302. _ogg_free(e->mark);
  112303. memset(e,0,sizeof(*e));
  112304. }
  112305. /* fairly straight threshhold-by-band based until we find something
  112306. that works better and isn't patented. */
  112307. static int _ve_amp(envelope_lookup *ve,
  112308. vorbis_info_psy_global *gi,
  112309. float *data,
  112310. envelope_band *bands,
  112311. envelope_filter_state *filters,
  112312. long pos){
  112313. long n=ve->winlength;
  112314. int ret=0;
  112315. long i,j;
  112316. float decay;
  112317. /* we want to have a 'minimum bar' for energy, else we're just
  112318. basing blocks on quantization noise that outweighs the signal
  112319. itself (for low power signals) */
  112320. float minV=ve->minenergy;
  112321. float *vec=(float*) alloca(n*sizeof(*vec));
  112322. /* stretch is used to gradually lengthen the number of windows
  112323. considered prevoius-to-potential-trigger */
  112324. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112325. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112326. if(penalty<0.f)penalty=0.f;
  112327. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112328. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112329. totalshift+pos*ve->searchstep);*/
  112330. /* window and transform */
  112331. for(i=0;i<n;i++)
  112332. vec[i]=data[i]*ve->mdct_win[i];
  112333. mdct_forward(&ve->mdct,vec,vec);
  112334. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112335. /* near-DC spreading function; this has nothing to do with
  112336. psychoacoustics, just sidelobe leakage and window size */
  112337. {
  112338. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112339. int ptr=filters->nearptr;
  112340. /* the accumulation is regularly refreshed from scratch to avoid
  112341. floating point creep */
  112342. if(ptr==0){
  112343. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112344. filters->nearDC_partialacc=temp;
  112345. }else{
  112346. decay=filters->nearDC_acc+=temp;
  112347. filters->nearDC_partialacc+=temp;
  112348. }
  112349. filters->nearDC_acc-=filters->nearDC[ptr];
  112350. filters->nearDC[ptr]=temp;
  112351. decay*=(1./(VE_NEARDC+1));
  112352. filters->nearptr++;
  112353. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112354. decay=todB(&decay)*.5-15.f;
  112355. }
  112356. /* perform spreading and limiting, also smooth the spectrum. yes,
  112357. the MDCT results in all real coefficients, but it still *behaves*
  112358. like real/imaginary pairs */
  112359. for(i=0;i<n/2;i+=2){
  112360. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112361. val=todB(&val)*.5f;
  112362. if(val<decay)val=decay;
  112363. if(val<minV)val=minV;
  112364. vec[i>>1]=val;
  112365. decay-=8.;
  112366. }
  112367. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112368. /* perform preecho/postecho triggering by band */
  112369. for(j=0;j<VE_BANDS;j++){
  112370. float acc=0.;
  112371. float valmax,valmin;
  112372. /* accumulate amplitude */
  112373. for(i=0;i<bands[j].end;i++)
  112374. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112375. acc*=bands[j].total;
  112376. /* convert amplitude to delta */
  112377. {
  112378. int p,thisx=filters[j].ampptr;
  112379. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112380. p=thisx;
  112381. p--;
  112382. if(p<0)p+=VE_AMP;
  112383. postmax=max(acc,filters[j].ampbuf[p]);
  112384. postmin=min(acc,filters[j].ampbuf[p]);
  112385. for(i=0;i<stretch;i++){
  112386. p--;
  112387. if(p<0)p+=VE_AMP;
  112388. premax=max(premax,filters[j].ampbuf[p]);
  112389. premin=min(premin,filters[j].ampbuf[p]);
  112390. }
  112391. valmin=postmin-premin;
  112392. valmax=postmax-premax;
  112393. /*filters[j].markers[pos]=valmax;*/
  112394. filters[j].ampbuf[thisx]=acc;
  112395. filters[j].ampptr++;
  112396. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112397. }
  112398. /* look at min/max, decide trigger */
  112399. if(valmax>gi->preecho_thresh[j]+penalty){
  112400. ret|=1;
  112401. ret|=4;
  112402. }
  112403. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112404. }
  112405. return(ret);
  112406. }
  112407. #if 0
  112408. static int seq=0;
  112409. static ogg_int64_t totalshift=-1024;
  112410. #endif
  112411. long _ve_envelope_search(vorbis_dsp_state *v){
  112412. vorbis_info *vi=v->vi;
  112413. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112414. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112415. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112416. long i,j;
  112417. int first=ve->current/ve->searchstep;
  112418. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112419. if(first<0)first=0;
  112420. /* make sure we have enough storage to match the PCM */
  112421. if(last+VE_WIN+VE_POST>ve->storage){
  112422. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112423. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112424. }
  112425. for(j=first;j<last;j++){
  112426. int ret=0;
  112427. ve->stretch++;
  112428. if(ve->stretch>VE_MAXSTRETCH*2)
  112429. ve->stretch=VE_MAXSTRETCH*2;
  112430. for(i=0;i<ve->ch;i++){
  112431. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112432. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112433. }
  112434. ve->mark[j+VE_POST]=0;
  112435. if(ret&1){
  112436. ve->mark[j]=1;
  112437. ve->mark[j+1]=1;
  112438. }
  112439. if(ret&2){
  112440. ve->mark[j]=1;
  112441. if(j>0)ve->mark[j-1]=1;
  112442. }
  112443. if(ret&4)ve->stretch=-1;
  112444. }
  112445. ve->current=last*ve->searchstep;
  112446. {
  112447. long centerW=v->centerW;
  112448. long testW=
  112449. centerW+
  112450. ci->blocksizes[v->W]/4+
  112451. ci->blocksizes[1]/2+
  112452. ci->blocksizes[0]/4;
  112453. j=ve->cursor;
  112454. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112455. working back one window */
  112456. if(j>=testW)return(1);
  112457. ve->cursor=j;
  112458. if(ve->mark[j/ve->searchstep]){
  112459. if(j>centerW){
  112460. #if 0
  112461. if(j>ve->curmark){
  112462. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112463. int l,m;
  112464. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112465. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112466. seq,
  112467. (totalshift+ve->cursor)/44100.,
  112468. (totalshift+j)/44100.);
  112469. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112470. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112471. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112472. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112473. for(m=0;m<VE_BANDS;m++){
  112474. char buf[80];
  112475. sprintf(buf,"delL%d",m);
  112476. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112477. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112478. }
  112479. for(m=0;m<VE_BANDS;m++){
  112480. char buf[80];
  112481. sprintf(buf,"delR%d",m);
  112482. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112483. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112484. }
  112485. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112486. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112487. seq++;
  112488. }
  112489. #endif
  112490. ve->curmark=j;
  112491. if(j>=testW)return(1);
  112492. return(0);
  112493. }
  112494. }
  112495. j+=ve->searchstep;
  112496. }
  112497. }
  112498. return(-1);
  112499. }
  112500. int _ve_envelope_mark(vorbis_dsp_state *v){
  112501. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112502. vorbis_info *vi=v->vi;
  112503. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112504. long centerW=v->centerW;
  112505. long beginW=centerW-ci->blocksizes[v->W]/4;
  112506. long endW=centerW+ci->blocksizes[v->W]/4;
  112507. if(v->W){
  112508. beginW-=ci->blocksizes[v->lW]/4;
  112509. endW+=ci->blocksizes[v->nW]/4;
  112510. }else{
  112511. beginW-=ci->blocksizes[0]/4;
  112512. endW+=ci->blocksizes[0]/4;
  112513. }
  112514. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112515. {
  112516. long first=beginW/ve->searchstep;
  112517. long last=endW/ve->searchstep;
  112518. long i;
  112519. for(i=first;i<last;i++)
  112520. if(ve->mark[i])return(1);
  112521. }
  112522. return(0);
  112523. }
  112524. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112525. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112526. ahead of ve->current */
  112527. int smallshift=shift/e->searchstep;
  112528. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112529. #if 0
  112530. for(i=0;i<VE_BANDS*e->ch;i++)
  112531. memmove(e->filter[i].markers,
  112532. e->filter[i].markers+smallshift,
  112533. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112534. totalshift+=shift;
  112535. #endif
  112536. e->current-=shift;
  112537. if(e->curmark>=0)
  112538. e->curmark-=shift;
  112539. e->cursor-=shift;
  112540. }
  112541. #endif
  112542. /*** End of inlined file: envelope.c ***/
  112543. /*** Start of inlined file: floor0.c ***/
  112544. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112545. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112546. // tasks..
  112547. #if JUCE_MSVC
  112548. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112549. #endif
  112550. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112551. #if JUCE_USE_OGGVORBIS
  112552. #include <stdlib.h>
  112553. #include <string.h>
  112554. #include <math.h>
  112555. /*** Start of inlined file: lsp.h ***/
  112556. #ifndef _V_LSP_H_
  112557. #define _V_LSP_H_
  112558. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112559. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112560. float *lsp,int m,
  112561. float amp,float ampoffset);
  112562. #endif
  112563. /*** End of inlined file: lsp.h ***/
  112564. #include <stdio.h>
  112565. typedef struct {
  112566. int ln;
  112567. int m;
  112568. int **linearmap;
  112569. int n[2];
  112570. vorbis_info_floor0 *vi;
  112571. long bits;
  112572. long frames;
  112573. } vorbis_look_floor0;
  112574. /***********************************************/
  112575. static void floor0_free_info(vorbis_info_floor *i){
  112576. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112577. if(info){
  112578. memset(info,0,sizeof(*info));
  112579. _ogg_free(info);
  112580. }
  112581. }
  112582. static void floor0_free_look(vorbis_look_floor *i){
  112583. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112584. if(look){
  112585. if(look->linearmap){
  112586. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112587. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112588. _ogg_free(look->linearmap);
  112589. }
  112590. memset(look,0,sizeof(*look));
  112591. _ogg_free(look);
  112592. }
  112593. }
  112594. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112595. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112596. int j;
  112597. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112598. info->order=oggpack_read(opb,8);
  112599. info->rate=oggpack_read(opb,16);
  112600. info->barkmap=oggpack_read(opb,16);
  112601. info->ampbits=oggpack_read(opb,6);
  112602. info->ampdB=oggpack_read(opb,8);
  112603. info->numbooks=oggpack_read(opb,4)+1;
  112604. if(info->order<1)goto err_out;
  112605. if(info->rate<1)goto err_out;
  112606. if(info->barkmap<1)goto err_out;
  112607. if(info->numbooks<1)goto err_out;
  112608. for(j=0;j<info->numbooks;j++){
  112609. info->books[j]=oggpack_read(opb,8);
  112610. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112611. }
  112612. return(info);
  112613. err_out:
  112614. floor0_free_info(info);
  112615. return(NULL);
  112616. }
  112617. /* initialize Bark scale and normalization lookups. We could do this
  112618. with static tables, but Vorbis allows a number of possible
  112619. combinations, so it's best to do it computationally.
  112620. The below is authoritative in terms of defining scale mapping.
  112621. Note that the scale depends on the sampling rate as well as the
  112622. linear block and mapping sizes */
  112623. static void floor0_map_lazy_init(vorbis_block *vb,
  112624. vorbis_info_floor *infoX,
  112625. vorbis_look_floor0 *look){
  112626. if(!look->linearmap[vb->W]){
  112627. vorbis_dsp_state *vd=vb->vd;
  112628. vorbis_info *vi=vd->vi;
  112629. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112630. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112631. int W=vb->W;
  112632. int n=ci->blocksizes[W]/2,j;
  112633. /* we choose a scaling constant so that:
  112634. floor(bark(rate/2-1)*C)=mapped-1
  112635. floor(bark(rate/2)*C)=mapped */
  112636. float scale=look->ln/toBARK(info->rate/2.f);
  112637. /* the mapping from a linear scale to a smaller bark scale is
  112638. straightforward. We do *not* make sure that the linear mapping
  112639. does not skip bark-scale bins; the decoder simply skips them and
  112640. the encoder may do what it wishes in filling them. They're
  112641. necessary in some mapping combinations to keep the scale spacing
  112642. accurate */
  112643. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112644. for(j=0;j<n;j++){
  112645. int val=floor( toBARK((info->rate/2.f)/n*j)
  112646. *scale); /* bark numbers represent band edges */
  112647. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112648. look->linearmap[W][j]=val;
  112649. }
  112650. look->linearmap[W][j]=-1;
  112651. look->n[W]=n;
  112652. }
  112653. }
  112654. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112655. vorbis_info_floor *i){
  112656. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112657. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112658. look->m=info->order;
  112659. look->ln=info->barkmap;
  112660. look->vi=info;
  112661. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112662. return look;
  112663. }
  112664. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112665. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112666. vorbis_info_floor0 *info=look->vi;
  112667. int j,k;
  112668. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112669. if(ampraw>0){ /* also handles the -1 out of data case */
  112670. long maxval=(1<<info->ampbits)-1;
  112671. float amp=(float)ampraw/maxval*info->ampdB;
  112672. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112673. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112674. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112675. codebook *b=ci->fullbooks+info->books[booknum];
  112676. float last=0.f;
  112677. /* the additional b->dim is a guard against any possible stack
  112678. smash; b->dim is provably more than we can overflow the
  112679. vector */
  112680. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112681. for(j=0;j<look->m;j+=b->dim)
  112682. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112683. for(j=0;j<look->m;){
  112684. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112685. last=lsp[j-1];
  112686. }
  112687. lsp[look->m]=amp;
  112688. return(lsp);
  112689. }
  112690. }
  112691. eop:
  112692. return(NULL);
  112693. }
  112694. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112695. void *memo,float *out){
  112696. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112697. vorbis_info_floor0 *info=look->vi;
  112698. floor0_map_lazy_init(vb,info,look);
  112699. if(memo){
  112700. float *lsp=(float *)memo;
  112701. float amp=lsp[look->m];
  112702. /* take the coefficients back to a spectral envelope curve */
  112703. vorbis_lsp_to_curve(out,
  112704. look->linearmap[vb->W],
  112705. look->n[vb->W],
  112706. look->ln,
  112707. lsp,look->m,amp,(float)info->ampdB);
  112708. return(1);
  112709. }
  112710. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112711. return(0);
  112712. }
  112713. /* export hooks */
  112714. vorbis_func_floor floor0_exportbundle={
  112715. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112716. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112717. };
  112718. #endif
  112719. /*** End of inlined file: floor0.c ***/
  112720. /*** Start of inlined file: floor1.c ***/
  112721. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112722. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112723. // tasks..
  112724. #if JUCE_MSVC
  112725. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112726. #endif
  112727. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112728. #if JUCE_USE_OGGVORBIS
  112729. #include <stdlib.h>
  112730. #include <string.h>
  112731. #include <math.h>
  112732. #include <stdio.h>
  112733. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112734. typedef struct {
  112735. int sorted_index[VIF_POSIT+2];
  112736. int forward_index[VIF_POSIT+2];
  112737. int reverse_index[VIF_POSIT+2];
  112738. int hineighbor[VIF_POSIT];
  112739. int loneighbor[VIF_POSIT];
  112740. int posts;
  112741. int n;
  112742. int quant_q;
  112743. vorbis_info_floor1 *vi;
  112744. long phrasebits;
  112745. long postbits;
  112746. long frames;
  112747. } vorbis_look_floor1;
  112748. typedef struct lsfit_acc{
  112749. long x0;
  112750. long x1;
  112751. long xa;
  112752. long ya;
  112753. long x2a;
  112754. long y2a;
  112755. long xya;
  112756. long an;
  112757. } lsfit_acc;
  112758. /***********************************************/
  112759. static void floor1_free_info(vorbis_info_floor *i){
  112760. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112761. if(info){
  112762. memset(info,0,sizeof(*info));
  112763. _ogg_free(info);
  112764. }
  112765. }
  112766. static void floor1_free_look(vorbis_look_floor *i){
  112767. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112768. if(look){
  112769. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112770. (float)look->phrasebits/look->frames,
  112771. (float)look->postbits/look->frames,
  112772. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112773. memset(look,0,sizeof(*look));
  112774. _ogg_free(look);
  112775. }
  112776. }
  112777. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112778. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112779. int j,k;
  112780. int count=0;
  112781. int rangebits;
  112782. int maxposit=info->postlist[1];
  112783. int maxclass=-1;
  112784. /* save out partitions */
  112785. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112786. for(j=0;j<info->partitions;j++){
  112787. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112788. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112789. }
  112790. /* save out partition classes */
  112791. for(j=0;j<maxclass+1;j++){
  112792. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112793. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112794. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112795. for(k=0;k<(1<<info->class_subs[j]);k++)
  112796. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112797. }
  112798. /* save out the post list */
  112799. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112800. oggpack_write(opb,ilog2(maxposit),4);
  112801. rangebits=ilog2(maxposit);
  112802. for(j=0,k=0;j<info->partitions;j++){
  112803. count+=info->class_dim[info->partitionclass[j]];
  112804. for(;k<count;k++)
  112805. oggpack_write(opb,info->postlist[k+2],rangebits);
  112806. }
  112807. }
  112808. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112809. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112810. int j,k,count=0,maxclass=-1,rangebits;
  112811. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112812. /* read partitions */
  112813. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112814. for(j=0;j<info->partitions;j++){
  112815. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112816. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112817. }
  112818. /* read partition classes */
  112819. for(j=0;j<maxclass+1;j++){
  112820. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112821. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112822. if(info->class_subs[j]<0)
  112823. goto err_out;
  112824. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112825. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112826. goto err_out;
  112827. for(k=0;k<(1<<info->class_subs[j]);k++){
  112828. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112829. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112830. goto err_out;
  112831. }
  112832. }
  112833. /* read the post list */
  112834. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112835. rangebits=oggpack_read(opb,4);
  112836. for(j=0,k=0;j<info->partitions;j++){
  112837. count+=info->class_dim[info->partitionclass[j]];
  112838. for(;k<count;k++){
  112839. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112840. if(t<0 || t>=(1<<rangebits))
  112841. goto err_out;
  112842. }
  112843. }
  112844. info->postlist[0]=0;
  112845. info->postlist[1]=1<<rangebits;
  112846. return(info);
  112847. err_out:
  112848. floor1_free_info(info);
  112849. return(NULL);
  112850. }
  112851. static int icomp(const void *a,const void *b){
  112852. return(**(int **)a-**(int **)b);
  112853. }
  112854. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112855. vorbis_info_floor *in){
  112856. int *sortpointer[VIF_POSIT+2];
  112857. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112858. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112859. int i,j,n=0;
  112860. look->vi=info;
  112861. look->n=info->postlist[1];
  112862. /* we drop each position value in-between already decoded values,
  112863. and use linear interpolation to predict each new value past the
  112864. edges. The positions are read in the order of the position
  112865. list... we precompute the bounding positions in the lookup. Of
  112866. course, the neighbors can change (if a position is declined), but
  112867. this is an initial mapping */
  112868. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112869. n+=2;
  112870. look->posts=n;
  112871. /* also store a sorted position index */
  112872. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112873. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112874. /* points from sort order back to range number */
  112875. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112876. /* points from range order to sorted position */
  112877. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112878. /* we actually need the post values too */
  112879. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112880. /* quantize values to multiplier spec */
  112881. switch(info->mult){
  112882. case 1: /* 1024 -> 256 */
  112883. look->quant_q=256;
  112884. break;
  112885. case 2: /* 1024 -> 128 */
  112886. look->quant_q=128;
  112887. break;
  112888. case 3: /* 1024 -> 86 */
  112889. look->quant_q=86;
  112890. break;
  112891. case 4: /* 1024 -> 64 */
  112892. look->quant_q=64;
  112893. break;
  112894. }
  112895. /* discover our neighbors for decode where we don't use fit flags
  112896. (that would push the neighbors outward) */
  112897. for(i=0;i<n-2;i++){
  112898. int lo=0;
  112899. int hi=1;
  112900. int lx=0;
  112901. int hx=look->n;
  112902. int currentx=info->postlist[i+2];
  112903. for(j=0;j<i+2;j++){
  112904. int x=info->postlist[j];
  112905. if(x>lx && x<currentx){
  112906. lo=j;
  112907. lx=x;
  112908. }
  112909. if(x<hx && x>currentx){
  112910. hi=j;
  112911. hx=x;
  112912. }
  112913. }
  112914. look->loneighbor[i]=lo;
  112915. look->hineighbor[i]=hi;
  112916. }
  112917. return(look);
  112918. }
  112919. static int render_point(int x0,int x1,int y0,int y1,int x){
  112920. y0&=0x7fff; /* mask off flag */
  112921. y1&=0x7fff;
  112922. {
  112923. int dy=y1-y0;
  112924. int adx=x1-x0;
  112925. int ady=abs(dy);
  112926. int err=ady*(x-x0);
  112927. int off=err/adx;
  112928. if(dy<0)return(y0-off);
  112929. return(y0+off);
  112930. }
  112931. }
  112932. static int vorbis_dBquant(const float *x){
  112933. int i= *x*7.3142857f+1023.5f;
  112934. if(i>1023)return(1023);
  112935. if(i<0)return(0);
  112936. return i;
  112937. }
  112938. static float FLOOR1_fromdB_LOOKUP[256]={
  112939. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112940. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112941. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112942. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112943. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112944. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112945. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112946. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112947. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112948. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112949. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112950. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112951. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112952. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112953. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112954. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112955. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112956. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112957. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112958. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112959. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112960. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112961. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112962. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112963. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112964. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112965. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112966. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112967. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112968. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112969. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112970. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112971. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112972. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112973. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112974. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112975. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112976. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112977. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112978. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112979. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112980. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112981. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112982. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112983. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112984. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112985. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112986. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112987. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112988. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112989. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112990. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112991. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112992. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112993. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112994. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112995. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112996. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112997. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112998. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112999. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113000. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113001. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113002. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113003. };
  113004. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113005. int dy=y1-y0;
  113006. int adx=x1-x0;
  113007. int ady=abs(dy);
  113008. int base=dy/adx;
  113009. int sy=(dy<0?base-1:base+1);
  113010. int x=x0;
  113011. int y=y0;
  113012. int err=0;
  113013. ady-=abs(base*adx);
  113014. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113015. while(++x<x1){
  113016. err=err+ady;
  113017. if(err>=adx){
  113018. err-=adx;
  113019. y+=sy;
  113020. }else{
  113021. y+=base;
  113022. }
  113023. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113024. }
  113025. }
  113026. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113027. int dy=y1-y0;
  113028. int adx=x1-x0;
  113029. int ady=abs(dy);
  113030. int base=dy/adx;
  113031. int sy=(dy<0?base-1:base+1);
  113032. int x=x0;
  113033. int y=y0;
  113034. int err=0;
  113035. ady-=abs(base*adx);
  113036. d[x]=y;
  113037. while(++x<x1){
  113038. err=err+ady;
  113039. if(err>=adx){
  113040. err-=adx;
  113041. y+=sy;
  113042. }else{
  113043. y+=base;
  113044. }
  113045. d[x]=y;
  113046. }
  113047. }
  113048. /* the floor has already been filtered to only include relevant sections */
  113049. static int accumulate_fit(const float *flr,const float *mdct,
  113050. int x0, int x1,lsfit_acc *a,
  113051. int n,vorbis_info_floor1 *info){
  113052. long i;
  113053. 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;
  113054. memset(a,0,sizeof(*a));
  113055. a->x0=x0;
  113056. a->x1=x1;
  113057. if(x1>=n)x1=n-1;
  113058. for(i=x0;i<=x1;i++){
  113059. int quantized=vorbis_dBquant(flr+i);
  113060. if(quantized){
  113061. if(mdct[i]+info->twofitatten>=flr[i]){
  113062. xa += i;
  113063. ya += quantized;
  113064. x2a += i*i;
  113065. y2a += quantized*quantized;
  113066. xya += i*quantized;
  113067. na++;
  113068. }else{
  113069. xb += i;
  113070. yb += quantized;
  113071. x2b += i*i;
  113072. y2b += quantized*quantized;
  113073. xyb += i*quantized;
  113074. nb++;
  113075. }
  113076. }
  113077. }
  113078. xb+=xa;
  113079. yb+=ya;
  113080. x2b+=x2a;
  113081. y2b+=y2a;
  113082. xyb+=xya;
  113083. nb+=na;
  113084. /* weight toward the actually used frequencies if we meet the threshhold */
  113085. {
  113086. int weight=nb*info->twofitweight/(na+1);
  113087. a->xa=xa*weight+xb;
  113088. a->ya=ya*weight+yb;
  113089. a->x2a=x2a*weight+x2b;
  113090. a->y2a=y2a*weight+y2b;
  113091. a->xya=xya*weight+xyb;
  113092. a->an=na*weight+nb;
  113093. }
  113094. return(na);
  113095. }
  113096. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113097. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113098. long x0=a[0].x0;
  113099. long x1=a[fits-1].x1;
  113100. for(i=0;i<fits;i++){
  113101. x+=a[i].xa;
  113102. y+=a[i].ya;
  113103. x2+=a[i].x2a;
  113104. y2+=a[i].y2a;
  113105. xy+=a[i].xya;
  113106. an+=a[i].an;
  113107. }
  113108. if(*y0>=0){
  113109. x+= x0;
  113110. y+= *y0;
  113111. x2+= x0 * x0;
  113112. y2+= *y0 * *y0;
  113113. xy+= *y0 * x0;
  113114. an++;
  113115. }
  113116. if(*y1>=0){
  113117. x+= x1;
  113118. y+= *y1;
  113119. x2+= x1 * x1;
  113120. y2+= *y1 * *y1;
  113121. xy+= *y1 * x1;
  113122. an++;
  113123. }
  113124. if(an){
  113125. /* need 64 bit multiplies, which C doesn't give portably as int */
  113126. double fx=x;
  113127. double fy=y;
  113128. double fx2=x2;
  113129. double fxy=xy;
  113130. double denom=1./(an*fx2-fx*fx);
  113131. double a=(fy*fx2-fxy*fx)*denom;
  113132. double b=(an*fxy-fx*fy)*denom;
  113133. *y0=rint(a+b*x0);
  113134. *y1=rint(a+b*x1);
  113135. /* limit to our range! */
  113136. if(*y0>1023)*y0=1023;
  113137. if(*y1>1023)*y1=1023;
  113138. if(*y0<0)*y0=0;
  113139. if(*y1<0)*y1=0;
  113140. }else{
  113141. *y0=0;
  113142. *y1=0;
  113143. }
  113144. }
  113145. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113146. long y=0;
  113147. int i;
  113148. for(i=0;i<fits && y==0;i++)
  113149. y+=a[i].ya;
  113150. *y0=*y1=y;
  113151. }*/
  113152. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113153. const float *mdct,
  113154. vorbis_info_floor1 *info){
  113155. int dy=y1-y0;
  113156. int adx=x1-x0;
  113157. int ady=abs(dy);
  113158. int base=dy/adx;
  113159. int sy=(dy<0?base-1:base+1);
  113160. int x=x0;
  113161. int y=y0;
  113162. int err=0;
  113163. int val=vorbis_dBquant(mask+x);
  113164. int mse=0;
  113165. int n=0;
  113166. ady-=abs(base*adx);
  113167. mse=(y-val);
  113168. mse*=mse;
  113169. n++;
  113170. if(mdct[x]+info->twofitatten>=mask[x]){
  113171. if(y+info->maxover<val)return(1);
  113172. if(y-info->maxunder>val)return(1);
  113173. }
  113174. while(++x<x1){
  113175. err=err+ady;
  113176. if(err>=adx){
  113177. err-=adx;
  113178. y+=sy;
  113179. }else{
  113180. y+=base;
  113181. }
  113182. val=vorbis_dBquant(mask+x);
  113183. mse+=((y-val)*(y-val));
  113184. n++;
  113185. if(mdct[x]+info->twofitatten>=mask[x]){
  113186. if(val){
  113187. if(y+info->maxover<val)return(1);
  113188. if(y-info->maxunder>val)return(1);
  113189. }
  113190. }
  113191. }
  113192. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113193. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113194. if(mse/n>info->maxerr)return(1);
  113195. return(0);
  113196. }
  113197. static int post_Y(int *A,int *B,int pos){
  113198. if(A[pos]<0)
  113199. return B[pos];
  113200. if(B[pos]<0)
  113201. return A[pos];
  113202. return (A[pos]+B[pos])>>1;
  113203. }
  113204. int *floor1_fit(vorbis_block *vb,void *look_,
  113205. const float *logmdct, /* in */
  113206. const float *logmask){
  113207. long i,j;
  113208. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113209. vorbis_info_floor1 *info=look->vi;
  113210. long n=look->n;
  113211. long posts=look->posts;
  113212. long nonzero=0;
  113213. lsfit_acc fits[VIF_POSIT+1];
  113214. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113215. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113216. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113217. int hineighbor[VIF_POSIT+2];
  113218. int *output=NULL;
  113219. int memo[VIF_POSIT+2];
  113220. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113221. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113222. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113223. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113224. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113225. /* quantize the relevant floor points and collect them into line fit
  113226. structures (one per minimal division) at the same time */
  113227. if(posts==0){
  113228. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113229. }else{
  113230. for(i=0;i<posts-1;i++)
  113231. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113232. look->sorted_index[i+1],fits+i,
  113233. n,info);
  113234. }
  113235. if(nonzero){
  113236. /* start by fitting the implicit base case.... */
  113237. int y0=-200;
  113238. int y1=-200;
  113239. fit_line(fits,posts-1,&y0,&y1);
  113240. fit_valueA[0]=y0;
  113241. fit_valueB[0]=y0;
  113242. fit_valueB[1]=y1;
  113243. fit_valueA[1]=y1;
  113244. /* Non degenerate case */
  113245. /* start progressive splitting. This is a greedy, non-optimal
  113246. algorithm, but simple and close enough to the best
  113247. answer. */
  113248. for(i=2;i<posts;i++){
  113249. int sortpos=look->reverse_index[i];
  113250. int ln=loneighbor[sortpos];
  113251. int hn=hineighbor[sortpos];
  113252. /* eliminate repeat searches of a particular range with a memo */
  113253. if(memo[ln]!=hn){
  113254. /* haven't performed this error search yet */
  113255. int lsortpos=look->reverse_index[ln];
  113256. int hsortpos=look->reverse_index[hn];
  113257. memo[ln]=hn;
  113258. {
  113259. /* A note: we want to bound/minimize *local*, not global, error */
  113260. int lx=info->postlist[ln];
  113261. int hx=info->postlist[hn];
  113262. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113263. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113264. if(ly==-1 || hy==-1){
  113265. exit(1);
  113266. }
  113267. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113268. /* outside error bounds/begin search area. Split it. */
  113269. int ly0=-200;
  113270. int ly1=-200;
  113271. int hy0=-200;
  113272. int hy1=-200;
  113273. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113274. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113275. /* store new edge values */
  113276. fit_valueB[ln]=ly0;
  113277. if(ln==0)fit_valueA[ln]=ly0;
  113278. fit_valueA[i]=ly1;
  113279. fit_valueB[i]=hy0;
  113280. fit_valueA[hn]=hy1;
  113281. if(hn==1)fit_valueB[hn]=hy1;
  113282. if(ly1>=0 || hy0>=0){
  113283. /* store new neighbor values */
  113284. for(j=sortpos-1;j>=0;j--)
  113285. if(hineighbor[j]==hn)
  113286. hineighbor[j]=i;
  113287. else
  113288. break;
  113289. for(j=sortpos+1;j<posts;j++)
  113290. if(loneighbor[j]==ln)
  113291. loneighbor[j]=i;
  113292. else
  113293. break;
  113294. }
  113295. }else{
  113296. fit_valueA[i]=-200;
  113297. fit_valueB[i]=-200;
  113298. }
  113299. }
  113300. }
  113301. }
  113302. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113303. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113304. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113305. /* fill in posts marked as not using a fit; we will zero
  113306. back out to 'unused' when encoding them so long as curve
  113307. interpolation doesn't force them into use */
  113308. for(i=2;i<posts;i++){
  113309. int ln=look->loneighbor[i-2];
  113310. int hn=look->hineighbor[i-2];
  113311. int x0=info->postlist[ln];
  113312. int x1=info->postlist[hn];
  113313. int y0=output[ln];
  113314. int y1=output[hn];
  113315. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113316. int vx=post_Y(fit_valueA,fit_valueB,i);
  113317. if(vx>=0 && predicted!=vx){
  113318. output[i]=vx;
  113319. }else{
  113320. output[i]= predicted|0x8000;
  113321. }
  113322. }
  113323. }
  113324. return(output);
  113325. }
  113326. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113327. int *A,int *B,
  113328. int del){
  113329. long i;
  113330. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113331. long posts=look->posts;
  113332. int *output=NULL;
  113333. if(A && B){
  113334. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113335. for(i=0;i<posts;i++){
  113336. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113337. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113338. }
  113339. }
  113340. return(output);
  113341. }
  113342. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113343. void*look_,
  113344. int *post,int *ilogmask){
  113345. long i,j;
  113346. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113347. vorbis_info_floor1 *info=look->vi;
  113348. long posts=look->posts;
  113349. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113350. int out[VIF_POSIT+2];
  113351. static_codebook **sbooks=ci->book_param;
  113352. codebook *books=ci->fullbooks;
  113353. static long seq=0;
  113354. /* quantize values to multiplier spec */
  113355. if(post){
  113356. for(i=0;i<posts;i++){
  113357. int val=post[i]&0x7fff;
  113358. switch(info->mult){
  113359. case 1: /* 1024 -> 256 */
  113360. val>>=2;
  113361. break;
  113362. case 2: /* 1024 -> 128 */
  113363. val>>=3;
  113364. break;
  113365. case 3: /* 1024 -> 86 */
  113366. val/=12;
  113367. break;
  113368. case 4: /* 1024 -> 64 */
  113369. val>>=4;
  113370. break;
  113371. }
  113372. post[i]=val | (post[i]&0x8000);
  113373. }
  113374. out[0]=post[0];
  113375. out[1]=post[1];
  113376. /* find prediction values for each post and subtract them */
  113377. for(i=2;i<posts;i++){
  113378. int ln=look->loneighbor[i-2];
  113379. int hn=look->hineighbor[i-2];
  113380. int x0=info->postlist[ln];
  113381. int x1=info->postlist[hn];
  113382. int y0=post[ln];
  113383. int y1=post[hn];
  113384. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113385. if((post[i]&0x8000) || (predicted==post[i])){
  113386. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113387. in interpolation */
  113388. out[i]=0;
  113389. }else{
  113390. int headroom=(look->quant_q-predicted<predicted?
  113391. look->quant_q-predicted:predicted);
  113392. int val=post[i]-predicted;
  113393. /* at this point the 'deviation' value is in the range +/- max
  113394. range, but the real, unique range can always be mapped to
  113395. only [0-maxrange). So we want to wrap the deviation into
  113396. this limited range, but do it in the way that least screws
  113397. an essentially gaussian probability distribution. */
  113398. if(val<0)
  113399. if(val<-headroom)
  113400. val=headroom-val-1;
  113401. else
  113402. val=-1-(val<<1);
  113403. else
  113404. if(val>=headroom)
  113405. val= val+headroom;
  113406. else
  113407. val<<=1;
  113408. out[i]=val;
  113409. post[ln]&=0x7fff;
  113410. post[hn]&=0x7fff;
  113411. }
  113412. }
  113413. /* we have everything we need. pack it out */
  113414. /* mark nontrivial floor */
  113415. oggpack_write(opb,1,1);
  113416. /* beginning/end post */
  113417. look->frames++;
  113418. look->postbits+=ilog(look->quant_q-1)*2;
  113419. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113420. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113421. /* partition by partition */
  113422. for(i=0,j=2;i<info->partitions;i++){
  113423. int classx=info->partitionclass[i];
  113424. int cdim=info->class_dim[classx];
  113425. int csubbits=info->class_subs[classx];
  113426. int csub=1<<csubbits;
  113427. int bookas[8]={0,0,0,0,0,0,0,0};
  113428. int cval=0;
  113429. int cshift=0;
  113430. int k,l;
  113431. /* generate the partition's first stage cascade value */
  113432. if(csubbits){
  113433. int maxval[8];
  113434. for(k=0;k<csub;k++){
  113435. int booknum=info->class_subbook[classx][k];
  113436. if(booknum<0){
  113437. maxval[k]=1;
  113438. }else{
  113439. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113440. }
  113441. }
  113442. for(k=0;k<cdim;k++){
  113443. for(l=0;l<csub;l++){
  113444. int val=out[j+k];
  113445. if(val<maxval[l]){
  113446. bookas[k]=l;
  113447. break;
  113448. }
  113449. }
  113450. cval|= bookas[k]<<cshift;
  113451. cshift+=csubbits;
  113452. }
  113453. /* write it */
  113454. look->phrasebits+=
  113455. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113456. #ifdef TRAIN_FLOOR1
  113457. {
  113458. FILE *of;
  113459. char buffer[80];
  113460. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113461. vb->pcmend/2,posts-2,class);
  113462. of=fopen(buffer,"a");
  113463. fprintf(of,"%d\n",cval);
  113464. fclose(of);
  113465. }
  113466. #endif
  113467. }
  113468. /* write post values */
  113469. for(k=0;k<cdim;k++){
  113470. int book=info->class_subbook[classx][bookas[k]];
  113471. if(book>=0){
  113472. /* hack to allow training with 'bad' books */
  113473. if(out[j+k]<(books+book)->entries)
  113474. look->postbits+=vorbis_book_encode(books+book,
  113475. out[j+k],opb);
  113476. /*else
  113477. fprintf(stderr,"+!");*/
  113478. #ifdef TRAIN_FLOOR1
  113479. {
  113480. FILE *of;
  113481. char buffer[80];
  113482. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113483. vb->pcmend/2,posts-2,class,bookas[k]);
  113484. of=fopen(buffer,"a");
  113485. fprintf(of,"%d\n",out[j+k]);
  113486. fclose(of);
  113487. }
  113488. #endif
  113489. }
  113490. }
  113491. j+=cdim;
  113492. }
  113493. {
  113494. /* generate quantized floor equivalent to what we'd unpack in decode */
  113495. /* render the lines */
  113496. int hx=0;
  113497. int lx=0;
  113498. int ly=post[0]*info->mult;
  113499. for(j=1;j<look->posts;j++){
  113500. int current=look->forward_index[j];
  113501. int hy=post[current]&0x7fff;
  113502. if(hy==post[current]){
  113503. hy*=info->mult;
  113504. hx=info->postlist[current];
  113505. render_line0(lx,hx,ly,hy,ilogmask);
  113506. lx=hx;
  113507. ly=hy;
  113508. }
  113509. }
  113510. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113511. seq++;
  113512. return(1);
  113513. }
  113514. }else{
  113515. oggpack_write(opb,0,1);
  113516. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113517. seq++;
  113518. return(0);
  113519. }
  113520. }
  113521. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113522. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113523. vorbis_info_floor1 *info=look->vi;
  113524. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113525. int i,j,k;
  113526. codebook *books=ci->fullbooks;
  113527. /* unpack wrapped/predicted values from stream */
  113528. if(oggpack_read(&vb->opb,1)==1){
  113529. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113530. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113531. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113532. /* partition by partition */
  113533. for(i=0,j=2;i<info->partitions;i++){
  113534. int classx=info->partitionclass[i];
  113535. int cdim=info->class_dim[classx];
  113536. int csubbits=info->class_subs[classx];
  113537. int csub=1<<csubbits;
  113538. int cval=0;
  113539. /* decode the partition's first stage cascade value */
  113540. if(csubbits){
  113541. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113542. if(cval==-1)goto eop;
  113543. }
  113544. for(k=0;k<cdim;k++){
  113545. int book=info->class_subbook[classx][cval&(csub-1)];
  113546. cval>>=csubbits;
  113547. if(book>=0){
  113548. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113549. goto eop;
  113550. }else{
  113551. fit_value[j+k]=0;
  113552. }
  113553. }
  113554. j+=cdim;
  113555. }
  113556. /* unwrap positive values and reconsitute via linear interpolation */
  113557. for(i=2;i<look->posts;i++){
  113558. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113559. info->postlist[look->hineighbor[i-2]],
  113560. fit_value[look->loneighbor[i-2]],
  113561. fit_value[look->hineighbor[i-2]],
  113562. info->postlist[i]);
  113563. int hiroom=look->quant_q-predicted;
  113564. int loroom=predicted;
  113565. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113566. int val=fit_value[i];
  113567. if(val){
  113568. if(val>=room){
  113569. if(hiroom>loroom){
  113570. val = val-loroom;
  113571. }else{
  113572. val = -1-(val-hiroom);
  113573. }
  113574. }else{
  113575. if(val&1){
  113576. val= -((val+1)>>1);
  113577. }else{
  113578. val>>=1;
  113579. }
  113580. }
  113581. fit_value[i]=val+predicted;
  113582. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113583. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113584. }else{
  113585. fit_value[i]=predicted|0x8000;
  113586. }
  113587. }
  113588. return(fit_value);
  113589. }
  113590. eop:
  113591. return(NULL);
  113592. }
  113593. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113594. float *out){
  113595. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113596. vorbis_info_floor1 *info=look->vi;
  113597. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113598. int n=ci->blocksizes[vb->W]/2;
  113599. int j;
  113600. if(memo){
  113601. /* render the lines */
  113602. int *fit_value=(int *)memo;
  113603. int hx=0;
  113604. int lx=0;
  113605. int ly=fit_value[0]*info->mult;
  113606. for(j=1;j<look->posts;j++){
  113607. int current=look->forward_index[j];
  113608. int hy=fit_value[current]&0x7fff;
  113609. if(hy==fit_value[current]){
  113610. hy*=info->mult;
  113611. hx=info->postlist[current];
  113612. render_line(lx,hx,ly,hy,out);
  113613. lx=hx;
  113614. ly=hy;
  113615. }
  113616. }
  113617. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113618. return(1);
  113619. }
  113620. memset(out,0,sizeof(*out)*n);
  113621. return(0);
  113622. }
  113623. /* export hooks */
  113624. vorbis_func_floor floor1_exportbundle={
  113625. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113626. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113627. };
  113628. #endif
  113629. /*** End of inlined file: floor1.c ***/
  113630. /*** Start of inlined file: info.c ***/
  113631. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113632. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113633. // tasks..
  113634. #if JUCE_MSVC
  113635. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113636. #endif
  113637. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113638. #if JUCE_USE_OGGVORBIS
  113639. /* general handling of the header and the vorbis_info structure (and
  113640. substructures) */
  113641. #include <stdlib.h>
  113642. #include <string.h>
  113643. #include <ctype.h>
  113644. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113645. while(bytes--){
  113646. oggpack_write(o,*s++,8);
  113647. }
  113648. }
  113649. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113650. while(bytes--){
  113651. *buf++=oggpack_read(o,8);
  113652. }
  113653. }
  113654. void vorbis_comment_init(vorbis_comment *vc){
  113655. memset(vc,0,sizeof(*vc));
  113656. }
  113657. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113658. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113659. (vc->comments+2)*sizeof(*vc->user_comments));
  113660. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113661. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113662. vc->comment_lengths[vc->comments]=strlen(comment);
  113663. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113664. strcpy(vc->user_comments[vc->comments], comment);
  113665. vc->comments++;
  113666. vc->user_comments[vc->comments]=NULL;
  113667. }
  113668. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113669. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113670. strcpy(comment, tag);
  113671. strcat(comment, "=");
  113672. strcat(comment, contents);
  113673. vorbis_comment_add(vc, comment);
  113674. }
  113675. /* This is more or less the same as strncasecmp - but that doesn't exist
  113676. * everywhere, and this is a fairly trivial function, so we include it */
  113677. static int tagcompare(const char *s1, const char *s2, int n){
  113678. int c=0;
  113679. while(c < n){
  113680. if(toupper(s1[c]) != toupper(s2[c]))
  113681. return !0;
  113682. c++;
  113683. }
  113684. return 0;
  113685. }
  113686. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113687. long i;
  113688. int found = 0;
  113689. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113690. char *fulltag = (char*)alloca(taglen+ 1);
  113691. strcpy(fulltag, tag);
  113692. strcat(fulltag, "=");
  113693. for(i=0;i<vc->comments;i++){
  113694. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113695. if(count == found)
  113696. /* We return a pointer to the data, not a copy */
  113697. return vc->user_comments[i] + taglen;
  113698. else
  113699. found++;
  113700. }
  113701. }
  113702. return NULL; /* didn't find anything */
  113703. }
  113704. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113705. int i,count=0;
  113706. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113707. char *fulltag = (char*)alloca(taglen+1);
  113708. strcpy(fulltag,tag);
  113709. strcat(fulltag, "=");
  113710. for(i=0;i<vc->comments;i++){
  113711. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113712. count++;
  113713. }
  113714. return count;
  113715. }
  113716. void vorbis_comment_clear(vorbis_comment *vc){
  113717. if(vc){
  113718. long i;
  113719. for(i=0;i<vc->comments;i++)
  113720. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113721. if(vc->user_comments)_ogg_free(vc->user_comments);
  113722. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113723. if(vc->vendor)_ogg_free(vc->vendor);
  113724. }
  113725. memset(vc,0,sizeof(*vc));
  113726. }
  113727. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113728. They may be equal, but short will never ge greater than long */
  113729. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113730. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113731. return ci ? ci->blocksizes[zo] : -1;
  113732. }
  113733. /* used by synthesis, which has a full, alloced vi */
  113734. void vorbis_info_init(vorbis_info *vi){
  113735. memset(vi,0,sizeof(*vi));
  113736. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113737. }
  113738. void vorbis_info_clear(vorbis_info *vi){
  113739. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113740. int i;
  113741. if(ci){
  113742. for(i=0;i<ci->modes;i++)
  113743. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113744. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113745. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113746. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113747. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113748. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113749. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113750. for(i=0;i<ci->books;i++){
  113751. if(ci->book_param[i]){
  113752. /* knows if the book was not alloced */
  113753. vorbis_staticbook_destroy(ci->book_param[i]);
  113754. }
  113755. if(ci->fullbooks)
  113756. vorbis_book_clear(ci->fullbooks+i);
  113757. }
  113758. if(ci->fullbooks)
  113759. _ogg_free(ci->fullbooks);
  113760. for(i=0;i<ci->psys;i++)
  113761. _vi_psy_free(ci->psy_param[i]);
  113762. _ogg_free(ci);
  113763. }
  113764. memset(vi,0,sizeof(*vi));
  113765. }
  113766. /* Header packing/unpacking ********************************************/
  113767. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113768. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113769. if(!ci)return(OV_EFAULT);
  113770. vi->version=oggpack_read(opb,32);
  113771. if(vi->version!=0)return(OV_EVERSION);
  113772. vi->channels=oggpack_read(opb,8);
  113773. vi->rate=oggpack_read(opb,32);
  113774. vi->bitrate_upper=oggpack_read(opb,32);
  113775. vi->bitrate_nominal=oggpack_read(opb,32);
  113776. vi->bitrate_lower=oggpack_read(opb,32);
  113777. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113778. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113779. if(vi->rate<1)goto err_out;
  113780. if(vi->channels<1)goto err_out;
  113781. if(ci->blocksizes[0]<8)goto err_out;
  113782. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113783. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113784. return(0);
  113785. err_out:
  113786. vorbis_info_clear(vi);
  113787. return(OV_EBADHEADER);
  113788. }
  113789. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113790. int i;
  113791. int vendorlen=oggpack_read(opb,32);
  113792. if(vendorlen<0)goto err_out;
  113793. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113794. _v_readstring(opb,vc->vendor,vendorlen);
  113795. vc->comments=oggpack_read(opb,32);
  113796. if(vc->comments<0)goto err_out;
  113797. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113798. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113799. for(i=0;i<vc->comments;i++){
  113800. int len=oggpack_read(opb,32);
  113801. if(len<0)goto err_out;
  113802. vc->comment_lengths[i]=len;
  113803. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113804. _v_readstring(opb,vc->user_comments[i],len);
  113805. }
  113806. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113807. return(0);
  113808. err_out:
  113809. vorbis_comment_clear(vc);
  113810. return(OV_EBADHEADER);
  113811. }
  113812. /* all of the real encoding details are here. The modes, books,
  113813. everything */
  113814. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113815. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113816. int i;
  113817. if(!ci)return(OV_EFAULT);
  113818. /* codebooks */
  113819. ci->books=oggpack_read(opb,8)+1;
  113820. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113821. for(i=0;i<ci->books;i++){
  113822. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113823. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113824. }
  113825. /* time backend settings; hooks are unused */
  113826. {
  113827. int times=oggpack_read(opb,6)+1;
  113828. for(i=0;i<times;i++){
  113829. int test=oggpack_read(opb,16);
  113830. if(test<0 || test>=VI_TIMEB)goto err_out;
  113831. }
  113832. }
  113833. /* floor backend settings */
  113834. ci->floors=oggpack_read(opb,6)+1;
  113835. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113836. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113837. for(i=0;i<ci->floors;i++){
  113838. ci->floor_type[i]=oggpack_read(opb,16);
  113839. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113840. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113841. if(!ci->floor_param[i])goto err_out;
  113842. }
  113843. /* residue backend settings */
  113844. ci->residues=oggpack_read(opb,6)+1;
  113845. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113846. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113847. for(i=0;i<ci->residues;i++){
  113848. ci->residue_type[i]=oggpack_read(opb,16);
  113849. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113850. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113851. if(!ci->residue_param[i])goto err_out;
  113852. }
  113853. /* map backend settings */
  113854. ci->maps=oggpack_read(opb,6)+1;
  113855. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113856. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113857. for(i=0;i<ci->maps;i++){
  113858. ci->map_type[i]=oggpack_read(opb,16);
  113859. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113860. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113861. if(!ci->map_param[i])goto err_out;
  113862. }
  113863. /* mode settings */
  113864. ci->modes=oggpack_read(opb,6)+1;
  113865. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113866. for(i=0;i<ci->modes;i++){
  113867. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113868. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113869. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113870. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113871. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113872. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113873. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113874. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113875. }
  113876. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113877. return(0);
  113878. err_out:
  113879. vorbis_info_clear(vi);
  113880. return(OV_EBADHEADER);
  113881. }
  113882. /* The Vorbis header is in three packets; the initial small packet in
  113883. the first page that identifies basic parameters, a second packet
  113884. with bitstream comments and a third packet that holds the
  113885. codebook. */
  113886. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113887. oggpack_buffer opb;
  113888. if(op){
  113889. oggpack_readinit(&opb,op->packet,op->bytes);
  113890. /* Which of the three types of header is this? */
  113891. /* Also verify header-ness, vorbis */
  113892. {
  113893. char buffer[6];
  113894. int packtype=oggpack_read(&opb,8);
  113895. memset(buffer,0,6);
  113896. _v_readstring(&opb,buffer,6);
  113897. if(memcmp(buffer,"vorbis",6)){
  113898. /* not a vorbis header */
  113899. return(OV_ENOTVORBIS);
  113900. }
  113901. switch(packtype){
  113902. case 0x01: /* least significant *bit* is read first */
  113903. if(!op->b_o_s){
  113904. /* Not the initial packet */
  113905. return(OV_EBADHEADER);
  113906. }
  113907. if(vi->rate!=0){
  113908. /* previously initialized info header */
  113909. return(OV_EBADHEADER);
  113910. }
  113911. return(_vorbis_unpack_info(vi,&opb));
  113912. case 0x03: /* least significant *bit* is read first */
  113913. if(vi->rate==0){
  113914. /* um... we didn't get the initial header */
  113915. return(OV_EBADHEADER);
  113916. }
  113917. return(_vorbis_unpack_comment(vc,&opb));
  113918. case 0x05: /* least significant *bit* is read first */
  113919. if(vi->rate==0 || vc->vendor==NULL){
  113920. /* um... we didn;t get the initial header or comments yet */
  113921. return(OV_EBADHEADER);
  113922. }
  113923. return(_vorbis_unpack_books(vi,&opb));
  113924. default:
  113925. /* Not a valid vorbis header type */
  113926. return(OV_EBADHEADER);
  113927. break;
  113928. }
  113929. }
  113930. }
  113931. return(OV_EBADHEADER);
  113932. }
  113933. /* pack side **********************************************************/
  113934. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113935. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113936. if(!ci)return(OV_EFAULT);
  113937. /* preamble */
  113938. oggpack_write(opb,0x01,8);
  113939. _v_writestring(opb,"vorbis", 6);
  113940. /* basic information about the stream */
  113941. oggpack_write(opb,0x00,32);
  113942. oggpack_write(opb,vi->channels,8);
  113943. oggpack_write(opb,vi->rate,32);
  113944. oggpack_write(opb,vi->bitrate_upper,32);
  113945. oggpack_write(opb,vi->bitrate_nominal,32);
  113946. oggpack_write(opb,vi->bitrate_lower,32);
  113947. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113948. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113949. oggpack_write(opb,1,1);
  113950. return(0);
  113951. }
  113952. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113953. char temp[]="Xiph.Org libVorbis I 20050304";
  113954. int bytes = strlen(temp);
  113955. /* preamble */
  113956. oggpack_write(opb,0x03,8);
  113957. _v_writestring(opb,"vorbis", 6);
  113958. /* vendor */
  113959. oggpack_write(opb,bytes,32);
  113960. _v_writestring(opb,temp, bytes);
  113961. /* comments */
  113962. oggpack_write(opb,vc->comments,32);
  113963. if(vc->comments){
  113964. int i;
  113965. for(i=0;i<vc->comments;i++){
  113966. if(vc->user_comments[i]){
  113967. oggpack_write(opb,vc->comment_lengths[i],32);
  113968. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113969. }else{
  113970. oggpack_write(opb,0,32);
  113971. }
  113972. }
  113973. }
  113974. oggpack_write(opb,1,1);
  113975. return(0);
  113976. }
  113977. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113978. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113979. int i;
  113980. if(!ci)return(OV_EFAULT);
  113981. oggpack_write(opb,0x05,8);
  113982. _v_writestring(opb,"vorbis", 6);
  113983. /* books */
  113984. oggpack_write(opb,ci->books-1,8);
  113985. for(i=0;i<ci->books;i++)
  113986. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113987. /* times; hook placeholders */
  113988. oggpack_write(opb,0,6);
  113989. oggpack_write(opb,0,16);
  113990. /* floors */
  113991. oggpack_write(opb,ci->floors-1,6);
  113992. for(i=0;i<ci->floors;i++){
  113993. oggpack_write(opb,ci->floor_type[i],16);
  113994. if(_floor_P[ci->floor_type[i]]->pack)
  113995. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113996. else
  113997. goto err_out;
  113998. }
  113999. /* residues */
  114000. oggpack_write(opb,ci->residues-1,6);
  114001. for(i=0;i<ci->residues;i++){
  114002. oggpack_write(opb,ci->residue_type[i],16);
  114003. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114004. }
  114005. /* maps */
  114006. oggpack_write(opb,ci->maps-1,6);
  114007. for(i=0;i<ci->maps;i++){
  114008. oggpack_write(opb,ci->map_type[i],16);
  114009. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114010. }
  114011. /* modes */
  114012. oggpack_write(opb,ci->modes-1,6);
  114013. for(i=0;i<ci->modes;i++){
  114014. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114015. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114016. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114017. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114018. }
  114019. oggpack_write(opb,1,1);
  114020. return(0);
  114021. err_out:
  114022. return(-1);
  114023. }
  114024. int vorbis_commentheader_out(vorbis_comment *vc,
  114025. ogg_packet *op){
  114026. oggpack_buffer opb;
  114027. oggpack_writeinit(&opb);
  114028. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114029. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114030. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114031. op->bytes=oggpack_bytes(&opb);
  114032. op->b_o_s=0;
  114033. op->e_o_s=0;
  114034. op->granulepos=0;
  114035. op->packetno=1;
  114036. return 0;
  114037. }
  114038. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114039. vorbis_comment *vc,
  114040. ogg_packet *op,
  114041. ogg_packet *op_comm,
  114042. ogg_packet *op_code){
  114043. int ret=OV_EIMPL;
  114044. vorbis_info *vi=v->vi;
  114045. oggpack_buffer opb;
  114046. private_state *b=(private_state*)v->backend_state;
  114047. if(!b){
  114048. ret=OV_EFAULT;
  114049. goto err_out;
  114050. }
  114051. /* first header packet **********************************************/
  114052. oggpack_writeinit(&opb);
  114053. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114054. /* build the packet */
  114055. if(b->header)_ogg_free(b->header);
  114056. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114057. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114058. op->packet=b->header;
  114059. op->bytes=oggpack_bytes(&opb);
  114060. op->b_o_s=1;
  114061. op->e_o_s=0;
  114062. op->granulepos=0;
  114063. op->packetno=0;
  114064. /* second header packet (comments) **********************************/
  114065. oggpack_reset(&opb);
  114066. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114067. if(b->header1)_ogg_free(b->header1);
  114068. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114069. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114070. op_comm->packet=b->header1;
  114071. op_comm->bytes=oggpack_bytes(&opb);
  114072. op_comm->b_o_s=0;
  114073. op_comm->e_o_s=0;
  114074. op_comm->granulepos=0;
  114075. op_comm->packetno=1;
  114076. /* third header packet (modes/codebooks) ****************************/
  114077. oggpack_reset(&opb);
  114078. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114079. if(b->header2)_ogg_free(b->header2);
  114080. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114081. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114082. op_code->packet=b->header2;
  114083. op_code->bytes=oggpack_bytes(&opb);
  114084. op_code->b_o_s=0;
  114085. op_code->e_o_s=0;
  114086. op_code->granulepos=0;
  114087. op_code->packetno=2;
  114088. oggpack_writeclear(&opb);
  114089. return(0);
  114090. err_out:
  114091. oggpack_writeclear(&opb);
  114092. memset(op,0,sizeof(*op));
  114093. memset(op_comm,0,sizeof(*op_comm));
  114094. memset(op_code,0,sizeof(*op_code));
  114095. if(b->header)_ogg_free(b->header);
  114096. if(b->header1)_ogg_free(b->header1);
  114097. if(b->header2)_ogg_free(b->header2);
  114098. b->header=NULL;
  114099. b->header1=NULL;
  114100. b->header2=NULL;
  114101. return(ret);
  114102. }
  114103. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114104. if(granulepos>=0)
  114105. return((double)granulepos/v->vi->rate);
  114106. return(-1);
  114107. }
  114108. #endif
  114109. /*** End of inlined file: info.c ***/
  114110. /*** Start of inlined file: lpc.c ***/
  114111. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114112. are derived from code written by Jutta Degener and Carsten Bormann;
  114113. thus we include their copyright below. The entirety of this file
  114114. is freely redistributable on the condition that both of these
  114115. copyright notices are preserved without modification. */
  114116. /* Preserved Copyright: *********************************************/
  114117. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114118. Technische Universita"t Berlin
  114119. Any use of this software is permitted provided that this notice is not
  114120. removed and that neither the authors nor the Technische Universita"t
  114121. Berlin are deemed to have made any representations as to the
  114122. suitability of this software for any purpose nor are held responsible
  114123. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114124. THIS SOFTWARE.
  114125. As a matter of courtesy, the authors request to be informed about uses
  114126. this software has found, about bugs in this software, and about any
  114127. improvements that may be of general interest.
  114128. Berlin, 28.11.1994
  114129. Jutta Degener
  114130. Carsten Bormann
  114131. *********************************************************************/
  114132. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114133. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114134. // tasks..
  114135. #if JUCE_MSVC
  114136. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114137. #endif
  114138. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114139. #if JUCE_USE_OGGVORBIS
  114140. #include <stdlib.h>
  114141. #include <string.h>
  114142. #include <math.h>
  114143. /* Autocorrelation LPC coeff generation algorithm invented by
  114144. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114145. /* Input : n elements of time doamin data
  114146. Output: m lpc coefficients, excitation energy */
  114147. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114148. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114149. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114150. double error;
  114151. int i,j;
  114152. /* autocorrelation, p+1 lag coefficients */
  114153. j=m+1;
  114154. while(j--){
  114155. double d=0; /* double needed for accumulator depth */
  114156. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114157. aut[j]=d;
  114158. }
  114159. /* Generate lpc coefficients from autocorr values */
  114160. error=aut[0];
  114161. for(i=0;i<m;i++){
  114162. double r= -aut[i+1];
  114163. if(error==0){
  114164. memset(lpci,0,m*sizeof(*lpci));
  114165. return 0;
  114166. }
  114167. /* Sum up this iteration's reflection coefficient; note that in
  114168. Vorbis we don't save it. If anyone wants to recycle this code
  114169. and needs reflection coefficients, save the results of 'r' from
  114170. each iteration. */
  114171. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114172. r/=error;
  114173. /* Update LPC coefficients and total error */
  114174. lpc[i]=r;
  114175. for(j=0;j<i/2;j++){
  114176. double tmp=lpc[j];
  114177. lpc[j]+=r*lpc[i-1-j];
  114178. lpc[i-1-j]+=r*tmp;
  114179. }
  114180. if(i%2)lpc[j]+=lpc[j]*r;
  114181. error*=1.f-r*r;
  114182. }
  114183. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114184. /* we need the error value to know how big an impulse to hit the
  114185. filter with later */
  114186. return error;
  114187. }
  114188. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114189. float *data,long n){
  114190. /* in: coeff[0...m-1] LPC coefficients
  114191. prime[0...m-1] initial values (allocated size of n+m-1)
  114192. out: data[0...n-1] data samples */
  114193. long i,j,o,p;
  114194. float y;
  114195. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114196. if(!prime)
  114197. for(i=0;i<m;i++)
  114198. work[i]=0.f;
  114199. else
  114200. for(i=0;i<m;i++)
  114201. work[i]=prime[i];
  114202. for(i=0;i<n;i++){
  114203. y=0;
  114204. o=i;
  114205. p=m;
  114206. for(j=0;j<m;j++)
  114207. y-=work[o++]*coeff[--p];
  114208. data[i]=work[o]=y;
  114209. }
  114210. }
  114211. #endif
  114212. /*** End of inlined file: lpc.c ***/
  114213. /*** Start of inlined file: lsp.c ***/
  114214. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114215. an iterative root polisher (CACM algorithm 283). It *is* possible
  114216. to confuse this algorithm into not converging; that should only
  114217. happen with absurdly closely spaced roots (very sharp peaks in the
  114218. LPC f response) which in turn should be impossible in our use of
  114219. the code. If this *does* happen anyway, it's a bug in the floor
  114220. finder; find the cause of the confusion (probably a single bin
  114221. spike or accidental near-float-limit resolution problems) and
  114222. correct it. */
  114223. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114224. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114225. // tasks..
  114226. #if JUCE_MSVC
  114227. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114228. #endif
  114229. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114230. #if JUCE_USE_OGGVORBIS
  114231. #include <math.h>
  114232. #include <string.h>
  114233. #include <stdlib.h>
  114234. /*** Start of inlined file: lookup.h ***/
  114235. #ifndef _V_LOOKUP_H_
  114236. #ifdef FLOAT_LOOKUP
  114237. extern float vorbis_coslook(float a);
  114238. extern float vorbis_invsqlook(float a);
  114239. extern float vorbis_invsq2explook(int a);
  114240. extern float vorbis_fromdBlook(float a);
  114241. #endif
  114242. #ifdef INT_LOOKUP
  114243. extern long vorbis_invsqlook_i(long a,long e);
  114244. extern long vorbis_coslook_i(long a);
  114245. extern float vorbis_fromdBlook_i(long a);
  114246. #endif
  114247. #endif
  114248. /*** End of inlined file: lookup.h ***/
  114249. /* three possible LSP to f curve functions; the exact computation
  114250. (float), a lookup based float implementation, and an integer
  114251. implementation. The float lookup is likely the optimal choice on
  114252. any machine with an FPU. The integer implementation is *not* fixed
  114253. point (due to the need for a large dynamic range and thus a
  114254. seperately tracked exponent) and thus much more complex than the
  114255. relatively simple float implementations. It's mostly for future
  114256. work on a fully fixed point implementation for processors like the
  114257. ARM family. */
  114258. /* undefine both for the 'old' but more precise implementation */
  114259. #define FLOAT_LOOKUP
  114260. #undef INT_LOOKUP
  114261. #ifdef FLOAT_LOOKUP
  114262. /*** Start of inlined file: lookup.c ***/
  114263. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114264. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114265. // tasks..
  114266. #if JUCE_MSVC
  114267. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114268. #endif
  114269. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114270. #if JUCE_USE_OGGVORBIS
  114271. #include <math.h>
  114272. /*** Start of inlined file: lookup.h ***/
  114273. #ifndef _V_LOOKUP_H_
  114274. #ifdef FLOAT_LOOKUP
  114275. extern float vorbis_coslook(float a);
  114276. extern float vorbis_invsqlook(float a);
  114277. extern float vorbis_invsq2explook(int a);
  114278. extern float vorbis_fromdBlook(float a);
  114279. #endif
  114280. #ifdef INT_LOOKUP
  114281. extern long vorbis_invsqlook_i(long a,long e);
  114282. extern long vorbis_coslook_i(long a);
  114283. extern float vorbis_fromdBlook_i(long a);
  114284. #endif
  114285. #endif
  114286. /*** End of inlined file: lookup.h ***/
  114287. /*** Start of inlined file: lookup_data.h ***/
  114288. #ifndef _V_LOOKUP_DATA_H_
  114289. #ifdef FLOAT_LOOKUP
  114290. #define COS_LOOKUP_SZ 128
  114291. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114292. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114293. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114294. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114295. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114296. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114297. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114298. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114299. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114300. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114301. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114302. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114303. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114304. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114305. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114306. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114307. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114308. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114309. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114310. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114311. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114312. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114313. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114314. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114315. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114316. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114317. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114318. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114319. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114320. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114321. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114322. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114323. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114324. -1.0000000000000f,
  114325. };
  114326. #define INVSQ_LOOKUP_SZ 32
  114327. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114328. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114329. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114330. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114331. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114332. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114333. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114334. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114335. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114336. 1.000000000000f,
  114337. };
  114338. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114339. #define INVSQ2EXP_LOOKUP_MAX 32
  114340. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114341. INVSQ2EXP_LOOKUP_MIN+1]={
  114342. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114343. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114344. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114345. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114346. 256.f, 181.019336f, 128.f, 90.50966799f,
  114347. 64.f, 45.254834f, 32.f, 22.627417f,
  114348. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114349. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114350. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114351. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114352. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114353. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114354. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114355. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114356. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114357. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114358. 1.525878906e-05f,
  114359. };
  114360. #endif
  114361. #define FROMdB_LOOKUP_SZ 35
  114362. #define FROMdB2_LOOKUP_SZ 32
  114363. #define FROMdB_SHIFT 5
  114364. #define FROMdB2_SHIFT 3
  114365. #define FROMdB2_MASK 31
  114366. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114367. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114368. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114369. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114370. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114371. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114372. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114373. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114374. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114375. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114376. };
  114377. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114378. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114379. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114380. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114381. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114382. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114383. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114384. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114385. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114386. };
  114387. #ifdef INT_LOOKUP
  114388. #define INVSQ_LOOKUP_I_SHIFT 10
  114389. #define INVSQ_LOOKUP_I_MASK 1023
  114390. static long INVSQ_LOOKUP_I[64+1]={
  114391. 92682l, 91966l, 91267l, 90583l,
  114392. 89915l, 89261l, 88621l, 87995l,
  114393. 87381l, 86781l, 86192l, 85616l,
  114394. 85051l, 84497l, 83953l, 83420l,
  114395. 82897l, 82384l, 81880l, 81385l,
  114396. 80899l, 80422l, 79953l, 79492l,
  114397. 79039l, 78594l, 78156l, 77726l,
  114398. 77302l, 76885l, 76475l, 76072l,
  114399. 75674l, 75283l, 74898l, 74519l,
  114400. 74146l, 73778l, 73415l, 73058l,
  114401. 72706l, 72359l, 72016l, 71679l,
  114402. 71347l, 71019l, 70695l, 70376l,
  114403. 70061l, 69750l, 69444l, 69141l,
  114404. 68842l, 68548l, 68256l, 67969l,
  114405. 67685l, 67405l, 67128l, 66855l,
  114406. 66585l, 66318l, 66054l, 65794l,
  114407. 65536l,
  114408. };
  114409. #define COS_LOOKUP_I_SHIFT 9
  114410. #define COS_LOOKUP_I_MASK 511
  114411. #define COS_LOOKUP_I_SZ 128
  114412. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114413. 16384l, 16379l, 16364l, 16340l,
  114414. 16305l, 16261l, 16207l, 16143l,
  114415. 16069l, 15986l, 15893l, 15791l,
  114416. 15679l, 15557l, 15426l, 15286l,
  114417. 15137l, 14978l, 14811l, 14635l,
  114418. 14449l, 14256l, 14053l, 13842l,
  114419. 13623l, 13395l, 13160l, 12916l,
  114420. 12665l, 12406l, 12140l, 11866l,
  114421. 11585l, 11297l, 11003l, 10702l,
  114422. 10394l, 10080l, 9760l, 9434l,
  114423. 9102l, 8765l, 8423l, 8076l,
  114424. 7723l, 7366l, 7005l, 6639l,
  114425. 6270l, 5897l, 5520l, 5139l,
  114426. 4756l, 4370l, 3981l, 3590l,
  114427. 3196l, 2801l, 2404l, 2006l,
  114428. 1606l, 1205l, 804l, 402l,
  114429. 0l, -401l, -803l, -1204l,
  114430. -1605l, -2005l, -2403l, -2800l,
  114431. -3195l, -3589l, -3980l, -4369l,
  114432. -4755l, -5138l, -5519l, -5896l,
  114433. -6269l, -6638l, -7004l, -7365l,
  114434. -7722l, -8075l, -8422l, -8764l,
  114435. -9101l, -9433l, -9759l, -10079l,
  114436. -10393l, -10701l, -11002l, -11296l,
  114437. -11584l, -11865l, -12139l, -12405l,
  114438. -12664l, -12915l, -13159l, -13394l,
  114439. -13622l, -13841l, -14052l, -14255l,
  114440. -14448l, -14634l, -14810l, -14977l,
  114441. -15136l, -15285l, -15425l, -15556l,
  114442. -15678l, -15790l, -15892l, -15985l,
  114443. -16068l, -16142l, -16206l, -16260l,
  114444. -16304l, -16339l, -16363l, -16378l,
  114445. -16383l,
  114446. };
  114447. #endif
  114448. #endif
  114449. /*** End of inlined file: lookup_data.h ***/
  114450. #ifdef FLOAT_LOOKUP
  114451. /* interpolated lookup based cos function, domain 0 to PI only */
  114452. float vorbis_coslook(float a){
  114453. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114454. int i=vorbis_ftoi(d-.5);
  114455. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114456. }
  114457. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114458. float vorbis_invsqlook(float a){
  114459. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114460. int i=vorbis_ftoi(d-.5f);
  114461. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114462. }
  114463. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114464. float vorbis_invsq2explook(int a){
  114465. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114466. }
  114467. #include <stdio.h>
  114468. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114469. float vorbis_fromdBlook(float a){
  114470. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114471. return (i<0)?1.f:
  114472. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114473. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114474. }
  114475. #endif
  114476. #ifdef INT_LOOKUP
  114477. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114478. 16.16 format
  114479. returns in m.8 format */
  114480. long vorbis_invsqlook_i(long a,long e){
  114481. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114482. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114483. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114484. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114485. d)>>16); /* result 1.16 */
  114486. e+=32;
  114487. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114488. e=(e>>1)-8;
  114489. return(val>>e);
  114490. }
  114491. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114492. /* a is in n.12 format */
  114493. float vorbis_fromdBlook_i(long a){
  114494. int i=(-a)>>(12-FROMdB2_SHIFT);
  114495. return (i<0)?1.f:
  114496. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114497. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114498. }
  114499. /* interpolated lookup based cos function, domain 0 to PI only */
  114500. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114501. long vorbis_coslook_i(long a){
  114502. int i=a>>COS_LOOKUP_I_SHIFT;
  114503. int d=a&COS_LOOKUP_I_MASK;
  114504. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114505. COS_LOOKUP_I_SHIFT);
  114506. }
  114507. #endif
  114508. #endif
  114509. /*** End of inlined file: lookup.c ***/
  114510. /* catch this in the build system; we #include for
  114511. compilers (like gcc) that can't inline across
  114512. modules */
  114513. /* side effect: changes *lsp to cosines of lsp */
  114514. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114515. float amp,float ampoffset){
  114516. int i;
  114517. float wdel=M_PI/ln;
  114518. vorbis_fpu_control fpu;
  114519. (void) fpu; // to avoid an unused variable warning
  114520. vorbis_fpu_setround(&fpu);
  114521. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114522. i=0;
  114523. while(i<n){
  114524. int k=map[i];
  114525. int qexp;
  114526. float p=.7071067812f;
  114527. float q=.7071067812f;
  114528. float w=vorbis_coslook(wdel*k);
  114529. float *ftmp=lsp;
  114530. int c=m>>1;
  114531. do{
  114532. q*=ftmp[0]-w;
  114533. p*=ftmp[1]-w;
  114534. ftmp+=2;
  114535. }while(--c);
  114536. if(m&1){
  114537. /* odd order filter; slightly assymetric */
  114538. /* the last coefficient */
  114539. q*=ftmp[0]-w;
  114540. q*=q;
  114541. p*=p*(1.f-w*w);
  114542. }else{
  114543. /* even order filter; still symmetric */
  114544. q*=q*(1.f+w);
  114545. p*=p*(1.f-w);
  114546. }
  114547. q=frexp(p+q,&qexp);
  114548. q=vorbis_fromdBlook(amp*
  114549. vorbis_invsqlook(q)*
  114550. vorbis_invsq2explook(qexp+m)-
  114551. ampoffset);
  114552. do{
  114553. curve[i++]*=q;
  114554. }while(map[i]==k);
  114555. }
  114556. vorbis_fpu_restore(fpu);
  114557. }
  114558. #else
  114559. #ifdef INT_LOOKUP
  114560. /*** Start of inlined file: lookup.c ***/
  114561. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114562. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114563. // tasks..
  114564. #if JUCE_MSVC
  114565. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114566. #endif
  114567. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114568. #if JUCE_USE_OGGVORBIS
  114569. #include <math.h>
  114570. /*** Start of inlined file: lookup.h ***/
  114571. #ifndef _V_LOOKUP_H_
  114572. #ifdef FLOAT_LOOKUP
  114573. extern float vorbis_coslook(float a);
  114574. extern float vorbis_invsqlook(float a);
  114575. extern float vorbis_invsq2explook(int a);
  114576. extern float vorbis_fromdBlook(float a);
  114577. #endif
  114578. #ifdef INT_LOOKUP
  114579. extern long vorbis_invsqlook_i(long a,long e);
  114580. extern long vorbis_coslook_i(long a);
  114581. extern float vorbis_fromdBlook_i(long a);
  114582. #endif
  114583. #endif
  114584. /*** End of inlined file: lookup.h ***/
  114585. /*** Start of inlined file: lookup_data.h ***/
  114586. #ifndef _V_LOOKUP_DATA_H_
  114587. #ifdef FLOAT_LOOKUP
  114588. #define COS_LOOKUP_SZ 128
  114589. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114590. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114591. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114592. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114593. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114594. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114595. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114596. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114597. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114598. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114599. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114600. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114601. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114602. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114603. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114604. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114605. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114606. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114607. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114608. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114609. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114610. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114611. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114612. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114613. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114614. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114615. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114616. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114617. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114618. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114619. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114620. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114621. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114622. -1.0000000000000f,
  114623. };
  114624. #define INVSQ_LOOKUP_SZ 32
  114625. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114626. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114627. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114628. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114629. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114630. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114631. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114632. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114633. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114634. 1.000000000000f,
  114635. };
  114636. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114637. #define INVSQ2EXP_LOOKUP_MAX 32
  114638. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114639. INVSQ2EXP_LOOKUP_MIN+1]={
  114640. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114641. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114642. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114643. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114644. 256.f, 181.019336f, 128.f, 90.50966799f,
  114645. 64.f, 45.254834f, 32.f, 22.627417f,
  114646. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114647. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114648. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114649. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114650. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114651. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114652. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114653. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114654. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114655. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114656. 1.525878906e-05f,
  114657. };
  114658. #endif
  114659. #define FROMdB_LOOKUP_SZ 35
  114660. #define FROMdB2_LOOKUP_SZ 32
  114661. #define FROMdB_SHIFT 5
  114662. #define FROMdB2_SHIFT 3
  114663. #define FROMdB2_MASK 31
  114664. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114665. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114666. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114667. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114668. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114669. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114670. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114671. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114672. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114673. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114674. };
  114675. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114676. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114677. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114678. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114679. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114680. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114681. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114682. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114683. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114684. };
  114685. #ifdef INT_LOOKUP
  114686. #define INVSQ_LOOKUP_I_SHIFT 10
  114687. #define INVSQ_LOOKUP_I_MASK 1023
  114688. static long INVSQ_LOOKUP_I[64+1]={
  114689. 92682l, 91966l, 91267l, 90583l,
  114690. 89915l, 89261l, 88621l, 87995l,
  114691. 87381l, 86781l, 86192l, 85616l,
  114692. 85051l, 84497l, 83953l, 83420l,
  114693. 82897l, 82384l, 81880l, 81385l,
  114694. 80899l, 80422l, 79953l, 79492l,
  114695. 79039l, 78594l, 78156l, 77726l,
  114696. 77302l, 76885l, 76475l, 76072l,
  114697. 75674l, 75283l, 74898l, 74519l,
  114698. 74146l, 73778l, 73415l, 73058l,
  114699. 72706l, 72359l, 72016l, 71679l,
  114700. 71347l, 71019l, 70695l, 70376l,
  114701. 70061l, 69750l, 69444l, 69141l,
  114702. 68842l, 68548l, 68256l, 67969l,
  114703. 67685l, 67405l, 67128l, 66855l,
  114704. 66585l, 66318l, 66054l, 65794l,
  114705. 65536l,
  114706. };
  114707. #define COS_LOOKUP_I_SHIFT 9
  114708. #define COS_LOOKUP_I_MASK 511
  114709. #define COS_LOOKUP_I_SZ 128
  114710. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114711. 16384l, 16379l, 16364l, 16340l,
  114712. 16305l, 16261l, 16207l, 16143l,
  114713. 16069l, 15986l, 15893l, 15791l,
  114714. 15679l, 15557l, 15426l, 15286l,
  114715. 15137l, 14978l, 14811l, 14635l,
  114716. 14449l, 14256l, 14053l, 13842l,
  114717. 13623l, 13395l, 13160l, 12916l,
  114718. 12665l, 12406l, 12140l, 11866l,
  114719. 11585l, 11297l, 11003l, 10702l,
  114720. 10394l, 10080l, 9760l, 9434l,
  114721. 9102l, 8765l, 8423l, 8076l,
  114722. 7723l, 7366l, 7005l, 6639l,
  114723. 6270l, 5897l, 5520l, 5139l,
  114724. 4756l, 4370l, 3981l, 3590l,
  114725. 3196l, 2801l, 2404l, 2006l,
  114726. 1606l, 1205l, 804l, 402l,
  114727. 0l, -401l, -803l, -1204l,
  114728. -1605l, -2005l, -2403l, -2800l,
  114729. -3195l, -3589l, -3980l, -4369l,
  114730. -4755l, -5138l, -5519l, -5896l,
  114731. -6269l, -6638l, -7004l, -7365l,
  114732. -7722l, -8075l, -8422l, -8764l,
  114733. -9101l, -9433l, -9759l, -10079l,
  114734. -10393l, -10701l, -11002l, -11296l,
  114735. -11584l, -11865l, -12139l, -12405l,
  114736. -12664l, -12915l, -13159l, -13394l,
  114737. -13622l, -13841l, -14052l, -14255l,
  114738. -14448l, -14634l, -14810l, -14977l,
  114739. -15136l, -15285l, -15425l, -15556l,
  114740. -15678l, -15790l, -15892l, -15985l,
  114741. -16068l, -16142l, -16206l, -16260l,
  114742. -16304l, -16339l, -16363l, -16378l,
  114743. -16383l,
  114744. };
  114745. #endif
  114746. #endif
  114747. /*** End of inlined file: lookup_data.h ***/
  114748. #ifdef FLOAT_LOOKUP
  114749. /* interpolated lookup based cos function, domain 0 to PI only */
  114750. float vorbis_coslook(float a){
  114751. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114752. int i=vorbis_ftoi(d-.5);
  114753. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114754. }
  114755. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114756. float vorbis_invsqlook(float a){
  114757. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114758. int i=vorbis_ftoi(d-.5f);
  114759. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114760. }
  114761. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114762. float vorbis_invsq2explook(int a){
  114763. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114764. }
  114765. #include <stdio.h>
  114766. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114767. float vorbis_fromdBlook(float a){
  114768. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114769. return (i<0)?1.f:
  114770. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114771. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114772. }
  114773. #endif
  114774. #ifdef INT_LOOKUP
  114775. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114776. 16.16 format
  114777. returns in m.8 format */
  114778. long vorbis_invsqlook_i(long a,long e){
  114779. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114780. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114781. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114782. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114783. d)>>16); /* result 1.16 */
  114784. e+=32;
  114785. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114786. e=(e>>1)-8;
  114787. return(val>>e);
  114788. }
  114789. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114790. /* a is in n.12 format */
  114791. float vorbis_fromdBlook_i(long a){
  114792. int i=(-a)>>(12-FROMdB2_SHIFT);
  114793. return (i<0)?1.f:
  114794. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114795. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114796. }
  114797. /* interpolated lookup based cos function, domain 0 to PI only */
  114798. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114799. long vorbis_coslook_i(long a){
  114800. int i=a>>COS_LOOKUP_I_SHIFT;
  114801. int d=a&COS_LOOKUP_I_MASK;
  114802. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114803. COS_LOOKUP_I_SHIFT);
  114804. }
  114805. #endif
  114806. #endif
  114807. /*** End of inlined file: lookup.c ***/
  114808. /* catch this in the build system; we #include for
  114809. compilers (like gcc) that can't inline across
  114810. modules */
  114811. static int MLOOP_1[64]={
  114812. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114813. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114814. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114815. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114816. };
  114817. static int MLOOP_2[64]={
  114818. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114819. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114820. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114821. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114822. };
  114823. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114824. /* side effect: changes *lsp to cosines of lsp */
  114825. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114826. float amp,float ampoffset){
  114827. /* 0 <= m < 256 */
  114828. /* set up for using all int later */
  114829. int i;
  114830. int ampoffseti=rint(ampoffset*4096.f);
  114831. int ampi=rint(amp*16.f);
  114832. long *ilsp=alloca(m*sizeof(*ilsp));
  114833. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114834. i=0;
  114835. while(i<n){
  114836. int j,k=map[i];
  114837. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114838. unsigned long qi=46341;
  114839. int qexp=0,shift;
  114840. long wi=vorbis_coslook_i(k*65536/ln);
  114841. qi*=labs(ilsp[0]-wi);
  114842. pi*=labs(ilsp[1]-wi);
  114843. for(j=3;j<m;j+=2){
  114844. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114845. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114846. shift=MLOOP_3[(pi|qi)>>16];
  114847. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114848. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114849. qexp+=shift;
  114850. }
  114851. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114852. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114853. shift=MLOOP_3[(pi|qi)>>16];
  114854. /* pi,qi normalized collectively, both tracked using qexp */
  114855. if(m&1){
  114856. /* odd order filter; slightly assymetric */
  114857. /* the last coefficient */
  114858. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114859. pi=(pi>>shift)<<14;
  114860. qexp+=shift;
  114861. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114862. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114863. shift=MLOOP_3[(pi|qi)>>16];
  114864. pi>>=shift;
  114865. qi>>=shift;
  114866. qexp+=shift-14*((m+1)>>1);
  114867. pi=((pi*pi)>>16);
  114868. qi=((qi*qi)>>16);
  114869. qexp=qexp*2+m;
  114870. pi*=(1<<14)-((wi*wi)>>14);
  114871. qi+=pi>>14;
  114872. }else{
  114873. /* even order filter; still symmetric */
  114874. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114875. worth tracking step by step */
  114876. pi>>=shift;
  114877. qi>>=shift;
  114878. qexp+=shift-7*m;
  114879. pi=((pi*pi)>>16);
  114880. qi=((qi*qi)>>16);
  114881. qexp=qexp*2+m;
  114882. pi*=(1<<14)-wi;
  114883. qi*=(1<<14)+wi;
  114884. qi=(qi+pi)>>14;
  114885. }
  114886. /* we've let the normalization drift because it wasn't important;
  114887. however, for the lookup, things must be normalized again. We
  114888. need at most one right shift or a number of left shifts */
  114889. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114890. qi>>=1; qexp++;
  114891. }else
  114892. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114893. qi<<=1; qexp--;
  114894. }
  114895. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114896. vorbis_invsqlook_i(qi,qexp)-
  114897. /* m.8, m+n<=8 */
  114898. ampoffseti); /* 8.12[0] */
  114899. curve[i]*=amp;
  114900. while(map[++i]==k)curve[i]*=amp;
  114901. }
  114902. }
  114903. #else
  114904. /* old, nonoptimized but simple version for any poor sap who needs to
  114905. figure out what the hell this code does, or wants the other
  114906. fraction of a dB precision */
  114907. /* side effect: changes *lsp to cosines of lsp */
  114908. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114909. float amp,float ampoffset){
  114910. int i;
  114911. float wdel=M_PI/ln;
  114912. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114913. i=0;
  114914. while(i<n){
  114915. int j,k=map[i];
  114916. float p=.5f;
  114917. float q=.5f;
  114918. float w=2.f*cos(wdel*k);
  114919. for(j=1;j<m;j+=2){
  114920. q *= w-lsp[j-1];
  114921. p *= w-lsp[j];
  114922. }
  114923. if(j==m){
  114924. /* odd order filter; slightly assymetric */
  114925. /* the last coefficient */
  114926. q*=w-lsp[j-1];
  114927. p*=p*(4.f-w*w);
  114928. q*=q;
  114929. }else{
  114930. /* even order filter; still symmetric */
  114931. p*=p*(2.f-w);
  114932. q*=q*(2.f+w);
  114933. }
  114934. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114935. curve[i]*=q;
  114936. while(map[++i]==k)curve[i]*=q;
  114937. }
  114938. }
  114939. #endif
  114940. #endif
  114941. static void cheby(float *g, int ord) {
  114942. int i, j;
  114943. g[0] *= .5f;
  114944. for(i=2; i<= ord; i++) {
  114945. for(j=ord; j >= i; j--) {
  114946. g[j-2] -= g[j];
  114947. g[j] += g[j];
  114948. }
  114949. }
  114950. }
  114951. static int comp(const void *a,const void *b){
  114952. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114953. }
  114954. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114955. but there are root sets for which it gets into limit cycles
  114956. (exacerbated by zero suppression) and fails. We can't afford to
  114957. fail, even if the failure is 1 in 100,000,000, so we now use
  114958. Laguerre and later polish with Newton-Raphson (which can then
  114959. afford to fail) */
  114960. #define EPSILON 10e-7
  114961. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114962. int i,m;
  114963. double lastdelta=0.f;
  114964. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114965. for(i=0;i<=ord;i++)defl[i]=a[i];
  114966. for(m=ord;m>0;m--){
  114967. double newx=0.f,delta;
  114968. /* iterate a root */
  114969. while(1){
  114970. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114971. /* eval the polynomial and its first two derivatives */
  114972. for(i=m;i>0;i--){
  114973. ppp = newx*ppp + pp;
  114974. pp = newx*pp + p;
  114975. p = newx*p + defl[i-1];
  114976. }
  114977. /* Laguerre's method */
  114978. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114979. if(denom<0)
  114980. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114981. if(pp>0){
  114982. denom = pp + sqrt(denom);
  114983. if(denom<EPSILON)denom=EPSILON;
  114984. }else{
  114985. denom = pp - sqrt(denom);
  114986. if(denom>-(EPSILON))denom=-(EPSILON);
  114987. }
  114988. delta = m*p/denom;
  114989. newx -= delta;
  114990. if(delta<0.f)delta*=-1;
  114991. if(fabs(delta/newx)<10e-12)break;
  114992. lastdelta=delta;
  114993. }
  114994. r[m-1]=newx;
  114995. /* forward deflation */
  114996. for(i=m;i>0;i--)
  114997. defl[i-1]+=newx*defl[i];
  114998. defl++;
  114999. }
  115000. return(0);
  115001. }
  115002. /* for spit-and-polish only */
  115003. static int Newton_Raphson(float *a,int ord,float *r){
  115004. int i, k, count=0;
  115005. double error=1.f;
  115006. double *root=(double*)alloca(ord*sizeof(*root));
  115007. for(i=0; i<ord;i++) root[i] = r[i];
  115008. while(error>1e-20){
  115009. error=0;
  115010. for(i=0; i<ord; i++) { /* Update each point. */
  115011. double pp=0.,delta;
  115012. double rooti=root[i];
  115013. double p=a[ord];
  115014. for(k=ord-1; k>= 0; k--) {
  115015. pp= pp* rooti + p;
  115016. p = p * rooti + a[k];
  115017. }
  115018. delta = p/pp;
  115019. root[i] -= delta;
  115020. error+= delta*delta;
  115021. }
  115022. if(count>40)return(-1);
  115023. count++;
  115024. }
  115025. /* Replaced the original bubble sort with a real sort. With your
  115026. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115027. for(i=0; i<ord;i++) r[i] = root[i];
  115028. return(0);
  115029. }
  115030. /* Convert lpc coefficients to lsp coefficients */
  115031. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115032. int order2=(m+1)>>1;
  115033. int g1_order,g2_order;
  115034. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115035. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115036. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115037. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115038. int i;
  115039. /* even and odd are slightly different base cases */
  115040. g1_order=(m+1)>>1;
  115041. g2_order=(m) >>1;
  115042. /* Compute the lengths of the x polynomials. */
  115043. /* Compute the first half of K & R F1 & F2 polynomials. */
  115044. /* Compute half of the symmetric and antisymmetric polynomials. */
  115045. /* Remove the roots at +1 and -1. */
  115046. g1[g1_order] = 1.f;
  115047. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115048. g2[g2_order] = 1.f;
  115049. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115050. if(g1_order>g2_order){
  115051. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115052. }else{
  115053. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115054. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115055. }
  115056. /* Convert into polynomials in cos(alpha) */
  115057. cheby(g1,g1_order);
  115058. cheby(g2,g2_order);
  115059. /* Find the roots of the 2 even polynomials.*/
  115060. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115061. Laguerre_With_Deflation(g2,g2_order,g2r))
  115062. return(-1);
  115063. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115064. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115065. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115066. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115067. for(i=0;i<g1_order;i++)
  115068. lsp[i*2] = acos(g1r[i]);
  115069. for(i=0;i<g2_order;i++)
  115070. lsp[i*2+1] = acos(g2r[i]);
  115071. return(0);
  115072. }
  115073. #endif
  115074. /*** End of inlined file: lsp.c ***/
  115075. /*** Start of inlined file: mapping0.c ***/
  115076. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115077. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115078. // tasks..
  115079. #if JUCE_MSVC
  115080. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115081. #endif
  115082. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115083. #if JUCE_USE_OGGVORBIS
  115084. #include <stdlib.h>
  115085. #include <stdio.h>
  115086. #include <string.h>
  115087. #include <math.h>
  115088. /* simplistic, wasteful way of doing this (unique lookup for each
  115089. mode/submapping); there should be a central repository for
  115090. identical lookups. That will require minor work, so I'm putting it
  115091. off as low priority.
  115092. Why a lookup for each backend in a given mode? Because the
  115093. blocksize is set by the mode, and low backend lookups may require
  115094. parameters from other areas of the mode/mapping */
  115095. static void mapping0_free_info(vorbis_info_mapping *i){
  115096. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115097. if(info){
  115098. memset(info,0,sizeof(*info));
  115099. _ogg_free(info);
  115100. }
  115101. }
  115102. static int ilog3(unsigned int v){
  115103. int ret=0;
  115104. if(v)--v;
  115105. while(v){
  115106. ret++;
  115107. v>>=1;
  115108. }
  115109. return(ret);
  115110. }
  115111. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115112. oggpack_buffer *opb){
  115113. int i;
  115114. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115115. /* another 'we meant to do it this way' hack... up to beta 4, we
  115116. packed 4 binary zeros here to signify one submapping in use. We
  115117. now redefine that to mean four bitflags that indicate use of
  115118. deeper features; bit0:submappings, bit1:coupling,
  115119. bit2,3:reserved. This is backward compatable with all actual uses
  115120. of the beta code. */
  115121. if(info->submaps>1){
  115122. oggpack_write(opb,1,1);
  115123. oggpack_write(opb,info->submaps-1,4);
  115124. }else
  115125. oggpack_write(opb,0,1);
  115126. if(info->coupling_steps>0){
  115127. oggpack_write(opb,1,1);
  115128. oggpack_write(opb,info->coupling_steps-1,8);
  115129. for(i=0;i<info->coupling_steps;i++){
  115130. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115131. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115132. }
  115133. }else
  115134. oggpack_write(opb,0,1);
  115135. oggpack_write(opb,0,2); /* 2,3:reserved */
  115136. /* we don't write the channel submappings if we only have one... */
  115137. if(info->submaps>1){
  115138. for(i=0;i<vi->channels;i++)
  115139. oggpack_write(opb,info->chmuxlist[i],4);
  115140. }
  115141. for(i=0;i<info->submaps;i++){
  115142. oggpack_write(opb,0,8); /* time submap unused */
  115143. oggpack_write(opb,info->floorsubmap[i],8);
  115144. oggpack_write(opb,info->residuesubmap[i],8);
  115145. }
  115146. }
  115147. /* also responsible for range checking */
  115148. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115149. int i;
  115150. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115151. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115152. memset(info,0,sizeof(*info));
  115153. if(oggpack_read(opb,1))
  115154. info->submaps=oggpack_read(opb,4)+1;
  115155. else
  115156. info->submaps=1;
  115157. if(oggpack_read(opb,1)){
  115158. info->coupling_steps=oggpack_read(opb,8)+1;
  115159. for(i=0;i<info->coupling_steps;i++){
  115160. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115161. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115162. if(testM<0 ||
  115163. testA<0 ||
  115164. testM==testA ||
  115165. testM>=vi->channels ||
  115166. testA>=vi->channels) goto err_out;
  115167. }
  115168. }
  115169. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115170. if(info->submaps>1){
  115171. for(i=0;i<vi->channels;i++){
  115172. info->chmuxlist[i]=oggpack_read(opb,4);
  115173. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115174. }
  115175. }
  115176. for(i=0;i<info->submaps;i++){
  115177. oggpack_read(opb,8); /* time submap unused */
  115178. info->floorsubmap[i]=oggpack_read(opb,8);
  115179. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115180. info->residuesubmap[i]=oggpack_read(opb,8);
  115181. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115182. }
  115183. return info;
  115184. err_out:
  115185. mapping0_free_info(info);
  115186. return(NULL);
  115187. }
  115188. #if 0
  115189. static long seq=0;
  115190. static ogg_int64_t total=0;
  115191. static float FLOOR1_fromdB_LOOKUP[256]={
  115192. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115193. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115194. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115195. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115196. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115197. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115198. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115199. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115200. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115201. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115202. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115203. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115204. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115205. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115206. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115207. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115208. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115209. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115210. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115211. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115212. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115213. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115214. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115215. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115216. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115217. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115218. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115219. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115220. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115221. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115222. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115223. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115224. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115225. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115226. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115227. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115228. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115229. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115230. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115231. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115232. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115233. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115234. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115235. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115236. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115237. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115238. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115239. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115240. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115241. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115242. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115243. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115244. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115245. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115246. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115247. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115248. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115249. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115250. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115251. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115252. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115253. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115254. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115255. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115256. };
  115257. #endif
  115258. extern int *floor1_fit(vorbis_block *vb,void *look,
  115259. const float *logmdct, /* in */
  115260. const float *logmask);
  115261. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115262. int *A,int *B,
  115263. int del);
  115264. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115265. void*look,
  115266. int *post,int *ilogmask);
  115267. static int mapping0_forward(vorbis_block *vb){
  115268. vorbis_dsp_state *vd=vb->vd;
  115269. vorbis_info *vi=vd->vi;
  115270. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115271. private_state *b=(private_state*)vb->vd->backend_state;
  115272. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115273. int n=vb->pcmend;
  115274. int i,j,k;
  115275. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115276. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115277. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115278. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115279. float global_ampmax=vbi->ampmax;
  115280. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115281. int blocktype=vbi->blocktype;
  115282. int modenumber=vb->W;
  115283. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115284. vorbis_look_psy *psy_look=
  115285. b->psy+blocktype+(vb->W?2:0);
  115286. vb->mode=modenumber;
  115287. for(i=0;i<vi->channels;i++){
  115288. float scale=4.f/n;
  115289. float scale_dB;
  115290. float *pcm =vb->pcm[i];
  115291. float *logfft =pcm;
  115292. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115293. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115294. todB estimation used on IEEE 754
  115295. compliant machines had a bug that
  115296. returned dB values about a third
  115297. of a decibel too high. The bug
  115298. was harmless because tunings
  115299. implicitly took that into
  115300. account. However, fixing the bug
  115301. in the estimator requires
  115302. changing all the tunings as well.
  115303. For now, it's easier to sync
  115304. things back up here, and
  115305. recalibrate the tunings in the
  115306. next major model upgrade. */
  115307. #if 0
  115308. if(vi->channels==2)
  115309. if(i==0)
  115310. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115311. else
  115312. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115313. #endif
  115314. /* window the PCM data */
  115315. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115316. #if 0
  115317. if(vi->channels==2)
  115318. if(i==0)
  115319. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115320. else
  115321. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115322. #endif
  115323. /* transform the PCM data */
  115324. /* only MDCT right now.... */
  115325. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115326. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115327. drft_forward(&b->fft_look[vb->W],pcm);
  115328. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115329. original todB estimation used on
  115330. IEEE 754 compliant machines had a
  115331. bug that returned dB values about
  115332. a third of a decibel too high.
  115333. The bug was harmless because
  115334. tunings implicitly took that into
  115335. account. However, fixing the bug
  115336. in the estimator requires
  115337. changing all the tunings as well.
  115338. For now, it's easier to sync
  115339. things back up here, and
  115340. recalibrate the tunings in the
  115341. next major model upgrade. */
  115342. local_ampmax[i]=logfft[0];
  115343. for(j=1;j<n-1;j+=2){
  115344. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115345. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115346. .345 is a hack; the original todB
  115347. estimation used on IEEE 754
  115348. compliant machines had a bug that
  115349. returned dB values about a third
  115350. of a decibel too high. The bug
  115351. was harmless because tunings
  115352. implicitly took that into
  115353. account. However, fixing the bug
  115354. in the estimator requires
  115355. changing all the tunings as well.
  115356. For now, it's easier to sync
  115357. things back up here, and
  115358. recalibrate the tunings in the
  115359. next major model upgrade. */
  115360. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115361. }
  115362. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115363. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115364. #if 0
  115365. if(vi->channels==2){
  115366. if(i==0){
  115367. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115368. }else{
  115369. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115370. }
  115371. }
  115372. #endif
  115373. }
  115374. {
  115375. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115376. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115377. for(i=0;i<vi->channels;i++){
  115378. /* the encoder setup assumes that all the modes used by any
  115379. specific bitrate tweaking use the same floor */
  115380. int submap=info->chmuxlist[i];
  115381. /* the following makes things clearer to *me* anyway */
  115382. float *mdct =gmdct[i];
  115383. float *logfft =vb->pcm[i];
  115384. float *logmdct =logfft+n/2;
  115385. float *logmask =logfft;
  115386. vb->mode=modenumber;
  115387. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115388. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115389. for(j=0;j<n/2;j++)
  115390. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115391. todB estimation used on IEEE 754
  115392. compliant machines had a bug that
  115393. returned dB values about a third
  115394. of a decibel too high. The bug
  115395. was harmless because tunings
  115396. implicitly took that into
  115397. account. However, fixing the bug
  115398. in the estimator requires
  115399. changing all the tunings as well.
  115400. For now, it's easier to sync
  115401. things back up here, and
  115402. recalibrate the tunings in the
  115403. next major model upgrade. */
  115404. #if 0
  115405. if(vi->channels==2){
  115406. if(i==0)
  115407. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115408. else
  115409. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115410. }else{
  115411. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115412. }
  115413. #endif
  115414. /* first step; noise masking. Not only does 'noise masking'
  115415. give us curves from which we can decide how much resolution
  115416. to give noise parts of the spectrum, it also implicitly hands
  115417. us a tonality estimate (the larger the value in the
  115418. 'noise_depth' vector, the more tonal that area is) */
  115419. _vp_noisemask(psy_look,
  115420. logmdct,
  115421. noise); /* noise does not have by-frequency offset
  115422. bias applied yet */
  115423. #if 0
  115424. if(vi->channels==2){
  115425. if(i==0)
  115426. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115427. else
  115428. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115429. }
  115430. #endif
  115431. /* second step: 'all the other crap'; all the stuff that isn't
  115432. computed/fit for bitrate management goes in the second psy
  115433. vector. This includes tone masking, peak limiting and ATH */
  115434. _vp_tonemask(psy_look,
  115435. logfft,
  115436. tone,
  115437. global_ampmax,
  115438. local_ampmax[i]);
  115439. #if 0
  115440. if(vi->channels==2){
  115441. if(i==0)
  115442. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115443. else
  115444. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115445. }
  115446. #endif
  115447. /* third step; we offset the noise vectors, overlay tone
  115448. masking. We then do a floor1-specific line fit. If we're
  115449. performing bitrate management, the line fit is performed
  115450. multiple times for up/down tweakage on demand. */
  115451. #if 0
  115452. {
  115453. float aotuv[psy_look->n];
  115454. #endif
  115455. _vp_offset_and_mix(psy_look,
  115456. noise,
  115457. tone,
  115458. 1,
  115459. logmask,
  115460. mdct,
  115461. logmdct);
  115462. #if 0
  115463. if(vi->channels==2){
  115464. if(i==0)
  115465. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115466. else
  115467. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115468. }
  115469. }
  115470. #endif
  115471. #if 0
  115472. if(vi->channels==2){
  115473. if(i==0)
  115474. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115475. else
  115476. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115477. }
  115478. #endif
  115479. /* this algorithm is hardwired to floor 1 for now; abort out if
  115480. we're *not* floor1. This won't happen unless someone has
  115481. broken the encode setup lib. Guard it anyway. */
  115482. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115483. floor_posts[i][PACKETBLOBS/2]=
  115484. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115485. logmdct,
  115486. logmask);
  115487. /* are we managing bitrate? If so, perform two more fits for
  115488. later rate tweaking (fits represent hi/lo) */
  115489. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115490. /* higher rate by way of lower noise curve */
  115491. _vp_offset_and_mix(psy_look,
  115492. noise,
  115493. tone,
  115494. 2,
  115495. logmask,
  115496. mdct,
  115497. logmdct);
  115498. #if 0
  115499. if(vi->channels==2){
  115500. if(i==0)
  115501. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115502. else
  115503. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115504. }
  115505. #endif
  115506. floor_posts[i][PACKETBLOBS-1]=
  115507. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115508. logmdct,
  115509. logmask);
  115510. /* lower rate by way of higher noise curve */
  115511. _vp_offset_and_mix(psy_look,
  115512. noise,
  115513. tone,
  115514. 0,
  115515. logmask,
  115516. mdct,
  115517. logmdct);
  115518. #if 0
  115519. if(vi->channels==2)
  115520. if(i==0)
  115521. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115522. else
  115523. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115524. #endif
  115525. floor_posts[i][0]=
  115526. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115527. logmdct,
  115528. logmask);
  115529. /* we also interpolate a range of intermediate curves for
  115530. intermediate rates */
  115531. for(k=1;k<PACKETBLOBS/2;k++)
  115532. floor_posts[i][k]=
  115533. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115534. floor_posts[i][0],
  115535. floor_posts[i][PACKETBLOBS/2],
  115536. k*65536/(PACKETBLOBS/2));
  115537. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115538. floor_posts[i][k]=
  115539. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115540. floor_posts[i][PACKETBLOBS/2],
  115541. floor_posts[i][PACKETBLOBS-1],
  115542. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115543. }
  115544. }
  115545. }
  115546. vbi->ampmax=global_ampmax;
  115547. /*
  115548. the next phases are performed once for vbr-only and PACKETBLOB
  115549. times for bitrate managed modes.
  115550. 1) encode actual mode being used
  115551. 2) encode the floor for each channel, compute coded mask curve/res
  115552. 3) normalize and couple.
  115553. 4) encode residue
  115554. 5) save packet bytes to the packetblob vector
  115555. */
  115556. /* iterate over the many masking curve fits we've created */
  115557. {
  115558. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115559. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115560. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115561. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115562. float **mag_memo;
  115563. int **mag_sort;
  115564. if(info->coupling_steps){
  115565. mag_memo=_vp_quantize_couple_memo(vb,
  115566. &ci->psy_g_param,
  115567. psy_look,
  115568. info,
  115569. gmdct);
  115570. mag_sort=_vp_quantize_couple_sort(vb,
  115571. psy_look,
  115572. info,
  115573. mag_memo);
  115574. hf_reduction(&ci->psy_g_param,
  115575. psy_look,
  115576. info,
  115577. mag_memo);
  115578. }
  115579. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115580. if(psy_look->vi->normal_channel_p){
  115581. for(i=0;i<vi->channels;i++){
  115582. float *mdct =gmdct[i];
  115583. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115584. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115585. }
  115586. }
  115587. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115588. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115589. k++){
  115590. oggpack_buffer *opb=vbi->packetblob[k];
  115591. /* start out our new packet blob with packet type and mode */
  115592. /* Encode the packet type */
  115593. oggpack_write(opb,0,1);
  115594. /* Encode the modenumber */
  115595. /* Encode frame mode, pre,post windowsize, then dispatch */
  115596. oggpack_write(opb,modenumber,b->modebits);
  115597. if(vb->W){
  115598. oggpack_write(opb,vb->lW,1);
  115599. oggpack_write(opb,vb->nW,1);
  115600. }
  115601. /* encode floor, compute masking curve, sep out residue */
  115602. for(i=0;i<vi->channels;i++){
  115603. int submap=info->chmuxlist[i];
  115604. float *mdct =gmdct[i];
  115605. float *res =vb->pcm[i];
  115606. int *ilogmask=ilogmaskch[i]=
  115607. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115608. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115609. floor_posts[i][k],
  115610. ilogmask);
  115611. #if 0
  115612. {
  115613. char buf[80];
  115614. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115615. float work[n/2];
  115616. for(j=0;j<n/2;j++)
  115617. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115618. _analysis_output(buf,seq,work,n/2,1,1,0);
  115619. }
  115620. #endif
  115621. _vp_remove_floor(psy_look,
  115622. mdct,
  115623. ilogmask,
  115624. res,
  115625. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115626. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115627. #if 0
  115628. {
  115629. char buf[80];
  115630. float work[n/2];
  115631. for(j=0;j<n/2;j++)
  115632. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115633. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115634. _analysis_output(buf,seq,work,n/2,1,1,0);
  115635. }
  115636. #endif
  115637. }
  115638. /* our iteration is now based on masking curve, not prequant and
  115639. coupling. Only one prequant/coupling step */
  115640. /* quantize/couple */
  115641. /* incomplete implementation that assumes the tree is all depth
  115642. one, or no tree at all */
  115643. if(info->coupling_steps){
  115644. _vp_couple(k,
  115645. &ci->psy_g_param,
  115646. psy_look,
  115647. info,
  115648. vb->pcm,
  115649. mag_memo,
  115650. mag_sort,
  115651. ilogmaskch,
  115652. nonzero,
  115653. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115654. }
  115655. /* classify and encode by submap */
  115656. for(i=0;i<info->submaps;i++){
  115657. int ch_in_bundle=0;
  115658. long **classifications;
  115659. int resnum=info->residuesubmap[i];
  115660. for(j=0;j<vi->channels;j++){
  115661. if(info->chmuxlist[j]==i){
  115662. zerobundle[ch_in_bundle]=0;
  115663. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115664. res_bundle[ch_in_bundle]=vb->pcm[j];
  115665. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115666. }
  115667. }
  115668. classifications=_residue_P[ci->residue_type[resnum]]->
  115669. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115670. _residue_P[ci->residue_type[resnum]]->
  115671. forward(opb,vb,b->residue[resnum],
  115672. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115673. }
  115674. /* ok, done encoding. Next protopacket. */
  115675. }
  115676. }
  115677. #if 0
  115678. seq++;
  115679. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115680. #endif
  115681. return(0);
  115682. }
  115683. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115684. vorbis_dsp_state *vd=vb->vd;
  115685. vorbis_info *vi=vd->vi;
  115686. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115687. private_state *b=(private_state*)vd->backend_state;
  115688. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115689. int i,j;
  115690. long n=vb->pcmend=ci->blocksizes[vb->W];
  115691. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115692. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115693. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115694. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115695. /* recover the spectral envelope; store it in the PCM vector for now */
  115696. for(i=0;i<vi->channels;i++){
  115697. int submap=info->chmuxlist[i];
  115698. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115699. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115700. if(floormemo[i])
  115701. nonzero[i]=1;
  115702. else
  115703. nonzero[i]=0;
  115704. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115705. }
  115706. /* channel coupling can 'dirty' the nonzero listing */
  115707. for(i=0;i<info->coupling_steps;i++){
  115708. if(nonzero[info->coupling_mag[i]] ||
  115709. nonzero[info->coupling_ang[i]]){
  115710. nonzero[info->coupling_mag[i]]=1;
  115711. nonzero[info->coupling_ang[i]]=1;
  115712. }
  115713. }
  115714. /* recover the residue into our working vectors */
  115715. for(i=0;i<info->submaps;i++){
  115716. int ch_in_bundle=0;
  115717. for(j=0;j<vi->channels;j++){
  115718. if(info->chmuxlist[j]==i){
  115719. if(nonzero[j])
  115720. zerobundle[ch_in_bundle]=1;
  115721. else
  115722. zerobundle[ch_in_bundle]=0;
  115723. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115724. }
  115725. }
  115726. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115727. inverse(vb,b->residue[info->residuesubmap[i]],
  115728. pcmbundle,zerobundle,ch_in_bundle);
  115729. }
  115730. /* channel coupling */
  115731. for(i=info->coupling_steps-1;i>=0;i--){
  115732. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115733. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115734. for(j=0;j<n/2;j++){
  115735. float mag=pcmM[j];
  115736. float ang=pcmA[j];
  115737. if(mag>0)
  115738. if(ang>0){
  115739. pcmM[j]=mag;
  115740. pcmA[j]=mag-ang;
  115741. }else{
  115742. pcmA[j]=mag;
  115743. pcmM[j]=mag+ang;
  115744. }
  115745. else
  115746. if(ang>0){
  115747. pcmM[j]=mag;
  115748. pcmA[j]=mag+ang;
  115749. }else{
  115750. pcmA[j]=mag;
  115751. pcmM[j]=mag-ang;
  115752. }
  115753. }
  115754. }
  115755. /* compute and apply spectral envelope */
  115756. for(i=0;i<vi->channels;i++){
  115757. float *pcm=vb->pcm[i];
  115758. int submap=info->chmuxlist[i];
  115759. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115760. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115761. floormemo[i],pcm);
  115762. }
  115763. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115764. /* only MDCT right now.... */
  115765. for(i=0;i<vi->channels;i++){
  115766. float *pcm=vb->pcm[i];
  115767. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115768. }
  115769. /* all done! */
  115770. return(0);
  115771. }
  115772. /* export hooks */
  115773. vorbis_func_mapping mapping0_exportbundle={
  115774. &mapping0_pack,
  115775. &mapping0_unpack,
  115776. &mapping0_free_info,
  115777. &mapping0_forward,
  115778. &mapping0_inverse
  115779. };
  115780. #endif
  115781. /*** End of inlined file: mapping0.c ***/
  115782. /*** Start of inlined file: mdct.c ***/
  115783. /* this can also be run as an integer transform by uncommenting a
  115784. define in mdct.h; the integerization is a first pass and although
  115785. it's likely stable for Vorbis, the dynamic range is constrained and
  115786. roundoff isn't done (so it's noisy). Consider it functional, but
  115787. only a starting point. There's no point on a machine with an FPU */
  115788. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115789. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115790. // tasks..
  115791. #if JUCE_MSVC
  115792. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115793. #endif
  115794. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115795. #if JUCE_USE_OGGVORBIS
  115796. #include <stdio.h>
  115797. #include <stdlib.h>
  115798. #include <string.h>
  115799. #include <math.h>
  115800. /* build lookups for trig functions; also pre-figure scaling and
  115801. some window function algebra. */
  115802. void mdct_init(mdct_lookup *lookup,int n){
  115803. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115804. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115805. int i;
  115806. int n2=n>>1;
  115807. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115808. lookup->n=n;
  115809. lookup->trig=T;
  115810. lookup->bitrev=bitrev;
  115811. /* trig lookups... */
  115812. for(i=0;i<n/4;i++){
  115813. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115814. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115815. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115816. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115817. }
  115818. for(i=0;i<n/8;i++){
  115819. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115820. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115821. }
  115822. /* bitreverse lookup... */
  115823. {
  115824. int mask=(1<<(log2n-1))-1,i,j;
  115825. int msb=1<<(log2n-2);
  115826. for(i=0;i<n/8;i++){
  115827. int acc=0;
  115828. for(j=0;msb>>j;j++)
  115829. if((msb>>j)&i)acc|=1<<j;
  115830. bitrev[i*2]=((~acc)&mask)-1;
  115831. bitrev[i*2+1]=acc;
  115832. }
  115833. }
  115834. lookup->scale=FLOAT_CONV(4.f/n);
  115835. }
  115836. /* 8 point butterfly (in place, 4 register) */
  115837. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115838. REG_TYPE r0 = x[6] + x[2];
  115839. REG_TYPE r1 = x[6] - x[2];
  115840. REG_TYPE r2 = x[4] + x[0];
  115841. REG_TYPE r3 = x[4] - x[0];
  115842. x[6] = r0 + r2;
  115843. x[4] = r0 - r2;
  115844. r0 = x[5] - x[1];
  115845. r2 = x[7] - x[3];
  115846. x[0] = r1 + r0;
  115847. x[2] = r1 - r0;
  115848. r0 = x[5] + x[1];
  115849. r1 = x[7] + x[3];
  115850. x[3] = r2 + r3;
  115851. x[1] = r2 - r3;
  115852. x[7] = r1 + r0;
  115853. x[5] = r1 - r0;
  115854. }
  115855. /* 16 point butterfly (in place, 4 register) */
  115856. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115857. REG_TYPE r0 = x[1] - x[9];
  115858. REG_TYPE r1 = x[0] - x[8];
  115859. x[8] += x[0];
  115860. x[9] += x[1];
  115861. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115862. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115863. r0 = x[3] - x[11];
  115864. r1 = x[10] - x[2];
  115865. x[10] += x[2];
  115866. x[11] += x[3];
  115867. x[2] = r0;
  115868. x[3] = r1;
  115869. r0 = x[12] - x[4];
  115870. r1 = x[13] - x[5];
  115871. x[12] += x[4];
  115872. x[13] += x[5];
  115873. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115874. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115875. r0 = x[14] - x[6];
  115876. r1 = x[15] - x[7];
  115877. x[14] += x[6];
  115878. x[15] += x[7];
  115879. x[6] = r0;
  115880. x[7] = r1;
  115881. mdct_butterfly_8(x);
  115882. mdct_butterfly_8(x+8);
  115883. }
  115884. /* 32 point butterfly (in place, 4 register) */
  115885. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115886. REG_TYPE r0 = x[30] - x[14];
  115887. REG_TYPE r1 = x[31] - x[15];
  115888. x[30] += x[14];
  115889. x[31] += x[15];
  115890. x[14] = r0;
  115891. x[15] = r1;
  115892. r0 = x[28] - x[12];
  115893. r1 = x[29] - x[13];
  115894. x[28] += x[12];
  115895. x[29] += x[13];
  115896. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115897. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115898. r0 = x[26] - x[10];
  115899. r1 = x[27] - x[11];
  115900. x[26] += x[10];
  115901. x[27] += x[11];
  115902. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115903. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115904. r0 = x[24] - x[8];
  115905. r1 = x[25] - x[9];
  115906. x[24] += x[8];
  115907. x[25] += x[9];
  115908. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115909. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115910. r0 = x[22] - x[6];
  115911. r1 = x[7] - x[23];
  115912. x[22] += x[6];
  115913. x[23] += x[7];
  115914. x[6] = r1;
  115915. x[7] = r0;
  115916. r0 = x[4] - x[20];
  115917. r1 = x[5] - x[21];
  115918. x[20] += x[4];
  115919. x[21] += x[5];
  115920. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115921. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115922. r0 = x[2] - x[18];
  115923. r1 = x[3] - x[19];
  115924. x[18] += x[2];
  115925. x[19] += x[3];
  115926. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115927. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115928. r0 = x[0] - x[16];
  115929. r1 = x[1] - x[17];
  115930. x[16] += x[0];
  115931. x[17] += x[1];
  115932. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115933. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115934. mdct_butterfly_16(x);
  115935. mdct_butterfly_16(x+16);
  115936. }
  115937. /* N point first stage butterfly (in place, 2 register) */
  115938. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115939. DATA_TYPE *x,
  115940. int points){
  115941. DATA_TYPE *x1 = x + points - 8;
  115942. DATA_TYPE *x2 = x + (points>>1) - 8;
  115943. REG_TYPE r0;
  115944. REG_TYPE r1;
  115945. do{
  115946. r0 = x1[6] - x2[6];
  115947. r1 = x1[7] - x2[7];
  115948. x1[6] += x2[6];
  115949. x1[7] += x2[7];
  115950. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115951. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115952. r0 = x1[4] - x2[4];
  115953. r1 = x1[5] - x2[5];
  115954. x1[4] += x2[4];
  115955. x1[5] += x2[5];
  115956. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115957. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115958. r0 = x1[2] - x2[2];
  115959. r1 = x1[3] - x2[3];
  115960. x1[2] += x2[2];
  115961. x1[3] += x2[3];
  115962. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115963. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115964. r0 = x1[0] - x2[0];
  115965. r1 = x1[1] - x2[1];
  115966. x1[0] += x2[0];
  115967. x1[1] += x2[1];
  115968. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115969. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115970. x1-=8;
  115971. x2-=8;
  115972. T+=16;
  115973. }while(x2>=x);
  115974. }
  115975. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115976. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115977. DATA_TYPE *x,
  115978. int points,
  115979. int trigint){
  115980. DATA_TYPE *x1 = x + points - 8;
  115981. DATA_TYPE *x2 = x + (points>>1) - 8;
  115982. REG_TYPE r0;
  115983. REG_TYPE r1;
  115984. do{
  115985. r0 = x1[6] - x2[6];
  115986. r1 = x1[7] - x2[7];
  115987. x1[6] += x2[6];
  115988. x1[7] += x2[7];
  115989. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115990. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115991. T+=trigint;
  115992. r0 = x1[4] - x2[4];
  115993. r1 = x1[5] - x2[5];
  115994. x1[4] += x2[4];
  115995. x1[5] += x2[5];
  115996. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115997. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115998. T+=trigint;
  115999. r0 = x1[2] - x2[2];
  116000. r1 = x1[3] - x2[3];
  116001. x1[2] += x2[2];
  116002. x1[3] += x2[3];
  116003. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116004. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116005. T+=trigint;
  116006. r0 = x1[0] - x2[0];
  116007. r1 = x1[1] - x2[1];
  116008. x1[0] += x2[0];
  116009. x1[1] += x2[1];
  116010. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116011. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116012. T+=trigint;
  116013. x1-=8;
  116014. x2-=8;
  116015. }while(x2>=x);
  116016. }
  116017. STIN void mdct_butterflies(mdct_lookup *init,
  116018. DATA_TYPE *x,
  116019. int points){
  116020. DATA_TYPE *T=init->trig;
  116021. int stages=init->log2n-5;
  116022. int i,j;
  116023. if(--stages>0){
  116024. mdct_butterfly_first(T,x,points);
  116025. }
  116026. for(i=1;--stages>0;i++){
  116027. for(j=0;j<(1<<i);j++)
  116028. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116029. }
  116030. for(j=0;j<points;j+=32)
  116031. mdct_butterfly_32(x+j);
  116032. }
  116033. void mdct_clear(mdct_lookup *l){
  116034. if(l){
  116035. if(l->trig)_ogg_free(l->trig);
  116036. if(l->bitrev)_ogg_free(l->bitrev);
  116037. memset(l,0,sizeof(*l));
  116038. }
  116039. }
  116040. STIN void mdct_bitreverse(mdct_lookup *init,
  116041. DATA_TYPE *x){
  116042. int n = init->n;
  116043. int *bit = init->bitrev;
  116044. DATA_TYPE *w0 = x;
  116045. DATA_TYPE *w1 = x = w0+(n>>1);
  116046. DATA_TYPE *T = init->trig+n;
  116047. do{
  116048. DATA_TYPE *x0 = x+bit[0];
  116049. DATA_TYPE *x1 = x+bit[1];
  116050. REG_TYPE r0 = x0[1] - x1[1];
  116051. REG_TYPE r1 = x0[0] + x1[0];
  116052. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116053. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116054. w1 -= 4;
  116055. r0 = HALVE(x0[1] + x1[1]);
  116056. r1 = HALVE(x0[0] - x1[0]);
  116057. w0[0] = r0 + r2;
  116058. w1[2] = r0 - r2;
  116059. w0[1] = r1 + r3;
  116060. w1[3] = r3 - r1;
  116061. x0 = x+bit[2];
  116062. x1 = x+bit[3];
  116063. r0 = x0[1] - x1[1];
  116064. r1 = x0[0] + x1[0];
  116065. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116066. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116067. r0 = HALVE(x0[1] + x1[1]);
  116068. r1 = HALVE(x0[0] - x1[0]);
  116069. w0[2] = r0 + r2;
  116070. w1[0] = r0 - r2;
  116071. w0[3] = r1 + r3;
  116072. w1[1] = r3 - r1;
  116073. T += 4;
  116074. bit += 4;
  116075. w0 += 4;
  116076. }while(w0<w1);
  116077. }
  116078. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116079. int n=init->n;
  116080. int n2=n>>1;
  116081. int n4=n>>2;
  116082. /* rotate */
  116083. DATA_TYPE *iX = in+n2-7;
  116084. DATA_TYPE *oX = out+n2+n4;
  116085. DATA_TYPE *T = init->trig+n4;
  116086. do{
  116087. oX -= 4;
  116088. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116089. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116090. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116091. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116092. iX -= 8;
  116093. T += 4;
  116094. }while(iX>=in);
  116095. iX = in+n2-8;
  116096. oX = out+n2+n4;
  116097. T = init->trig+n4;
  116098. do{
  116099. T -= 4;
  116100. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116101. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116102. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116103. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116104. iX -= 8;
  116105. oX += 4;
  116106. }while(iX>=in);
  116107. mdct_butterflies(init,out+n2,n2);
  116108. mdct_bitreverse(init,out);
  116109. /* roatate + window */
  116110. {
  116111. DATA_TYPE *oX1=out+n2+n4;
  116112. DATA_TYPE *oX2=out+n2+n4;
  116113. DATA_TYPE *iX =out;
  116114. T =init->trig+n2;
  116115. do{
  116116. oX1-=4;
  116117. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116118. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116119. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116120. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116121. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116122. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116123. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116124. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116125. oX2+=4;
  116126. iX += 8;
  116127. T += 8;
  116128. }while(iX<oX1);
  116129. iX=out+n2+n4;
  116130. oX1=out+n4;
  116131. oX2=oX1;
  116132. do{
  116133. oX1-=4;
  116134. iX-=4;
  116135. oX2[0] = -(oX1[3] = iX[3]);
  116136. oX2[1] = -(oX1[2] = iX[2]);
  116137. oX2[2] = -(oX1[1] = iX[1]);
  116138. oX2[3] = -(oX1[0] = iX[0]);
  116139. oX2+=4;
  116140. }while(oX2<iX);
  116141. iX=out+n2+n4;
  116142. oX1=out+n2+n4;
  116143. oX2=out+n2;
  116144. do{
  116145. oX1-=4;
  116146. oX1[0]= iX[3];
  116147. oX1[1]= iX[2];
  116148. oX1[2]= iX[1];
  116149. oX1[3]= iX[0];
  116150. iX+=4;
  116151. }while(oX1>oX2);
  116152. }
  116153. }
  116154. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116155. int n=init->n;
  116156. int n2=n>>1;
  116157. int n4=n>>2;
  116158. int n8=n>>3;
  116159. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116160. DATA_TYPE *w2=w+n2;
  116161. /* rotate */
  116162. /* window + rotate + step 1 */
  116163. REG_TYPE r0;
  116164. REG_TYPE r1;
  116165. DATA_TYPE *x0=in+n2+n4;
  116166. DATA_TYPE *x1=x0+1;
  116167. DATA_TYPE *T=init->trig+n2;
  116168. int i=0;
  116169. for(i=0;i<n8;i+=2){
  116170. x0 -=4;
  116171. T-=2;
  116172. r0= x0[2] + x1[0];
  116173. r1= x0[0] + x1[2];
  116174. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116175. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116176. x1 +=4;
  116177. }
  116178. x1=in+1;
  116179. for(;i<n2-n8;i+=2){
  116180. T-=2;
  116181. x0 -=4;
  116182. r0= x0[2] - x1[0];
  116183. r1= x0[0] - x1[2];
  116184. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116185. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116186. x1 +=4;
  116187. }
  116188. x0=in+n;
  116189. for(;i<n2;i+=2){
  116190. T-=2;
  116191. x0 -=4;
  116192. r0= -x0[2] - x1[0];
  116193. r1= -x0[0] - x1[2];
  116194. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116195. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116196. x1 +=4;
  116197. }
  116198. mdct_butterflies(init,w+n2,n2);
  116199. mdct_bitreverse(init,w);
  116200. /* roatate + window */
  116201. T=init->trig+n2;
  116202. x0=out+n2;
  116203. for(i=0;i<n4;i++){
  116204. x0--;
  116205. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116206. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116207. w+=2;
  116208. T+=2;
  116209. }
  116210. }
  116211. #endif
  116212. /*** End of inlined file: mdct.c ***/
  116213. /*** Start of inlined file: psy.c ***/
  116214. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116215. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116216. // tasks..
  116217. #if JUCE_MSVC
  116218. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116219. #endif
  116220. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116221. #if JUCE_USE_OGGVORBIS
  116222. #include <stdlib.h>
  116223. #include <math.h>
  116224. #include <string.h>
  116225. /*** Start of inlined file: masking.h ***/
  116226. #ifndef _V_MASKING_H_
  116227. #define _V_MASKING_H_
  116228. /* more detailed ATH; the bass if flat to save stressing the floor
  116229. overly for only a bin or two of savings. */
  116230. #define MAX_ATH 88
  116231. static float ATH[]={
  116232. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116233. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116234. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116235. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116236. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116237. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116238. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116239. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116240. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116241. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116242. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116243. };
  116244. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116245. replaced by an empirically collected data set. The previously
  116246. published values were, far too often, simply on crack. */
  116247. #define EHMER_OFFSET 16
  116248. #define EHMER_MAX 56
  116249. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116250. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116251. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116252. for collection of these curves) */
  116253. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116254. /* 62.5 Hz */
  116255. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116256. -60, -60, -60, -60, -62, -62, -65, -73,
  116257. -69, -68, -68, -67, -70, -70, -72, -74,
  116258. -75, -79, -79, -80, -83, -88, -93, -100,
  116259. -110, -999, -999, -999, -999, -999, -999, -999,
  116260. -999, -999, -999, -999, -999, -999, -999, -999,
  116261. -999, -999, -999, -999, -999, -999, -999, -999},
  116262. { -48, -48, -48, -48, -48, -48, -48, -48,
  116263. -48, -48, -48, -48, -48, -53, -61, -66,
  116264. -66, -68, -67, -70, -76, -76, -72, -73,
  116265. -75, -76, -78, -79, -83, -88, -93, -100,
  116266. -110, -999, -999, -999, -999, -999, -999, -999,
  116267. -999, -999, -999, -999, -999, -999, -999, -999,
  116268. -999, -999, -999, -999, -999, -999, -999, -999},
  116269. { -37, -37, -37, -37, -37, -37, -37, -37,
  116270. -38, -40, -42, -46, -48, -53, -55, -62,
  116271. -65, -58, -56, -56, -61, -60, -65, -67,
  116272. -69, -71, -77, -77, -78, -80, -82, -84,
  116273. -88, -93, -98, -106, -112, -999, -999, -999,
  116274. -999, -999, -999, -999, -999, -999, -999, -999,
  116275. -999, -999, -999, -999, -999, -999, -999, -999},
  116276. { -25, -25, -25, -25, -25, -25, -25, -25,
  116277. -25, -26, -27, -29, -32, -38, -48, -52,
  116278. -52, -50, -48, -48, -51, -52, -54, -60,
  116279. -67, -67, -66, -68, -69, -73, -73, -76,
  116280. -80, -81, -81, -85, -85, -86, -88, -93,
  116281. -100, -110, -999, -999, -999, -999, -999, -999,
  116282. -999, -999, -999, -999, -999, -999, -999, -999},
  116283. { -16, -16, -16, -16, -16, -16, -16, -16,
  116284. -17, -19, -20, -22, -26, -28, -31, -40,
  116285. -47, -39, -39, -40, -42, -43, -47, -51,
  116286. -57, -52, -55, -55, -60, -58, -62, -63,
  116287. -70, -67, -69, -72, -73, -77, -80, -82,
  116288. -83, -87, -90, -94, -98, -104, -115, -999,
  116289. -999, -999, -999, -999, -999, -999, -999, -999},
  116290. { -8, -8, -8, -8, -8, -8, -8, -8,
  116291. -8, -8, -10, -11, -15, -19, -25, -30,
  116292. -34, -31, -30, -31, -29, -32, -35, -42,
  116293. -48, -42, -44, -46, -50, -50, -51, -52,
  116294. -59, -54, -55, -55, -58, -62, -63, -66,
  116295. -72, -73, -76, -75, -78, -80, -80, -81,
  116296. -84, -88, -90, -94, -98, -101, -106, -110}},
  116297. /* 88Hz */
  116298. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116299. -66, -66, -66, -66, -66, -67, -67, -67,
  116300. -76, -72, -71, -74, -76, -76, -75, -78,
  116301. -79, -79, -81, -83, -86, -89, -93, -97,
  116302. -100, -105, -110, -999, -999, -999, -999, -999,
  116303. -999, -999, -999, -999, -999, -999, -999, -999,
  116304. -999, -999, -999, -999, -999, -999, -999, -999},
  116305. { -47, -47, -47, -47, -47, -47, -47, -47,
  116306. -47, -47, -47, -48, -51, -55, -59, -66,
  116307. -66, -66, -67, -66, -68, -69, -70, -74,
  116308. -79, -77, -77, -78, -80, -81, -82, -84,
  116309. -86, -88, -91, -95, -100, -108, -116, -999,
  116310. -999, -999, -999, -999, -999, -999, -999, -999,
  116311. -999, -999, -999, -999, -999, -999, -999, -999},
  116312. { -36, -36, -36, -36, -36, -36, -36, -36,
  116313. -36, -37, -37, -41, -44, -48, -51, -58,
  116314. -62, -60, -57, -59, -59, -60, -63, -65,
  116315. -72, -71, -70, -72, -74, -77, -76, -78,
  116316. -81, -81, -80, -83, -86, -91, -96, -100,
  116317. -105, -110, -999, -999, -999, -999, -999, -999,
  116318. -999, -999, -999, -999, -999, -999, -999, -999},
  116319. { -28, -28, -28, -28, -28, -28, -28, -28,
  116320. -28, -30, -32, -32, -33, -35, -41, -49,
  116321. -50, -49, -47, -48, -48, -52, -51, -57,
  116322. -65, -61, -59, -61, -64, -69, -70, -74,
  116323. -77, -77, -78, -81, -84, -85, -87, -90,
  116324. -92, -96, -100, -107, -112, -999, -999, -999,
  116325. -999, -999, -999, -999, -999, -999, -999, -999},
  116326. { -19, -19, -19, -19, -19, -19, -19, -19,
  116327. -20, -21, -23, -27, -30, -35, -36, -41,
  116328. -46, -44, -42, -40, -41, -41, -43, -48,
  116329. -55, -53, -52, -53, -56, -59, -58, -60,
  116330. -67, -66, -69, -71, -72, -75, -79, -81,
  116331. -84, -87, -90, -93, -97, -101, -107, -114,
  116332. -999, -999, -999, -999, -999, -999, -999, -999},
  116333. { -9, -9, -9, -9, -9, -9, -9, -9,
  116334. -11, -12, -12, -15, -16, -20, -23, -30,
  116335. -37, -34, -33, -34, -31, -32, -32, -38,
  116336. -47, -44, -41, -40, -47, -49, -46, -46,
  116337. -58, -50, -50, -54, -58, -62, -64, -67,
  116338. -67, -70, -72, -76, -79, -83, -87, -91,
  116339. -96, -100, -104, -110, -999, -999, -999, -999}},
  116340. /* 125 Hz */
  116341. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116342. -62, -62, -63, -64, -66, -67, -66, -68,
  116343. -75, -72, -76, -75, -76, -78, -79, -82,
  116344. -84, -85, -90, -94, -101, -110, -999, -999,
  116345. -999, -999, -999, -999, -999, -999, -999, -999,
  116346. -999, -999, -999, -999, -999, -999, -999, -999,
  116347. -999, -999, -999, -999, -999, -999, -999, -999},
  116348. { -59, -59, -59, -59, -59, -59, -59, -59,
  116349. -59, -59, -59, -60, -60, -61, -63, -66,
  116350. -71, -68, -70, -70, -71, -72, -72, -75,
  116351. -81, -78, -79, -82, -83, -86, -90, -97,
  116352. -103, -113, -999, -999, -999, -999, -999, -999,
  116353. -999, -999, -999, -999, -999, -999, -999, -999,
  116354. -999, -999, -999, -999, -999, -999, -999, -999},
  116355. { -53, -53, -53, -53, -53, -53, -53, -53,
  116356. -53, -54, -55, -57, -56, -57, -55, -61,
  116357. -65, -60, -60, -62, -63, -63, -66, -68,
  116358. -74, -73, -75, -75, -78, -80, -80, -82,
  116359. -85, -90, -96, -101, -108, -999, -999, -999,
  116360. -999, -999, -999, -999, -999, -999, -999, -999,
  116361. -999, -999, -999, -999, -999, -999, -999, -999},
  116362. { -46, -46, -46, -46, -46, -46, -46, -46,
  116363. -46, -46, -47, -47, -47, -47, -48, -51,
  116364. -57, -51, -49, -50, -51, -53, -54, -59,
  116365. -66, -60, -62, -67, -67, -70, -72, -75,
  116366. -76, -78, -81, -85, -88, -94, -97, -104,
  116367. -112, -999, -999, -999, -999, -999, -999, -999,
  116368. -999, -999, -999, -999, -999, -999, -999, -999},
  116369. { -36, -36, -36, -36, -36, -36, -36, -36,
  116370. -39, -41, -42, -42, -39, -38, -41, -43,
  116371. -52, -44, -40, -39, -37, -37, -40, -47,
  116372. -54, -50, -48, -50, -55, -61, -59, -62,
  116373. -66, -66, -66, -69, -69, -73, -74, -74,
  116374. -75, -77, -79, -82, -87, -91, -95, -100,
  116375. -108, -115, -999, -999, -999, -999, -999, -999},
  116376. { -28, -26, -24, -22, -20, -20, -23, -29,
  116377. -30, -31, -28, -27, -28, -28, -28, -35,
  116378. -40, -33, -32, -29, -30, -30, -30, -37,
  116379. -45, -41, -37, -38, -45, -47, -47, -48,
  116380. -53, -49, -48, -50, -49, -49, -51, -52,
  116381. -58, -56, -57, -56, -60, -61, -62, -70,
  116382. -72, -74, -78, -83, -88, -93, -100, -106}},
  116383. /* 177 Hz */
  116384. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116385. -999, -110, -105, -100, -95, -91, -87, -83,
  116386. -80, -78, -76, -78, -78, -81, -83, -85,
  116387. -86, -85, -86, -87, -90, -97, -107, -999,
  116388. -999, -999, -999, -999, -999, -999, -999, -999,
  116389. -999, -999, -999, -999, -999, -999, -999, -999,
  116390. -999, -999, -999, -999, -999, -999, -999, -999},
  116391. {-999, -999, -999, -110, -105, -100, -95, -90,
  116392. -85, -81, -77, -73, -70, -67, -67, -68,
  116393. -75, -73, -70, -69, -70, -72, -75, -79,
  116394. -84, -83, -84, -86, -88, -89, -89, -93,
  116395. -98, -105, -112, -999, -999, -999, -999, -999,
  116396. -999, -999, -999, -999, -999, -999, -999, -999,
  116397. -999, -999, -999, -999, -999, -999, -999, -999},
  116398. {-105, -100, -95, -90, -85, -80, -76, -71,
  116399. -68, -68, -65, -63, -63, -62, -62, -64,
  116400. -65, -64, -61, -62, -63, -64, -66, -68,
  116401. -73, -73, -74, -75, -76, -81, -83, -85,
  116402. -88, -89, -92, -95, -100, -108, -999, -999,
  116403. -999, -999, -999, -999, -999, -999, -999, -999,
  116404. -999, -999, -999, -999, -999, -999, -999, -999},
  116405. { -80, -75, -71, -68, -65, -63, -62, -61,
  116406. -61, -61, -61, -59, -56, -57, -53, -50,
  116407. -58, -52, -50, -50, -52, -53, -54, -58,
  116408. -67, -63, -67, -68, -72, -75, -78, -80,
  116409. -81, -81, -82, -85, -89, -90, -93, -97,
  116410. -101, -107, -114, -999, -999, -999, -999, -999,
  116411. -999, -999, -999, -999, -999, -999, -999, -999},
  116412. { -65, -61, -59, -57, -56, -55, -55, -56,
  116413. -56, -57, -55, -53, -52, -47, -44, -44,
  116414. -50, -44, -41, -39, -39, -42, -40, -46,
  116415. -51, -49, -50, -53, -54, -63, -60, -61,
  116416. -62, -66, -66, -66, -70, -73, -74, -75,
  116417. -76, -75, -79, -85, -89, -91, -96, -102,
  116418. -110, -999, -999, -999, -999, -999, -999, -999},
  116419. { -52, -50, -49, -49, -48, -48, -48, -49,
  116420. -50, -50, -49, -46, -43, -39, -35, -33,
  116421. -38, -36, -32, -29, -32, -32, -32, -35,
  116422. -44, -39, -38, -38, -46, -50, -45, -46,
  116423. -53, -50, -50, -50, -54, -54, -53, -53,
  116424. -56, -57, -59, -66, -70, -72, -74, -79,
  116425. -83, -85, -90, -97, -114, -999, -999, -999}},
  116426. /* 250 Hz */
  116427. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116428. -100, -95, -90, -86, -80, -75, -75, -79,
  116429. -80, -79, -80, -81, -82, -88, -95, -103,
  116430. -110, -999, -999, -999, -999, -999, -999, -999,
  116431. -999, -999, -999, -999, -999, -999, -999, -999,
  116432. -999, -999, -999, -999, -999, -999, -999, -999,
  116433. -999, -999, -999, -999, -999, -999, -999, -999},
  116434. {-999, -999, -999, -999, -108, -103, -98, -93,
  116435. -88, -83, -79, -78, -75, -71, -67, -68,
  116436. -73, -73, -72, -73, -75, -77, -80, -82,
  116437. -88, -93, -100, -107, -114, -999, -999, -999,
  116438. -999, -999, -999, -999, -999, -999, -999, -999,
  116439. -999, -999, -999, -999, -999, -999, -999, -999,
  116440. -999, -999, -999, -999, -999, -999, -999, -999},
  116441. {-999, -999, -999, -110, -105, -101, -96, -90,
  116442. -86, -81, -77, -73, -69, -66, -61, -62,
  116443. -66, -64, -62, -65, -66, -70, -72, -76,
  116444. -81, -80, -84, -90, -95, -102, -110, -999,
  116445. -999, -999, -999, -999, -999, -999, -999, -999,
  116446. -999, -999, -999, -999, -999, -999, -999, -999,
  116447. -999, -999, -999, -999, -999, -999, -999, -999},
  116448. {-999, -999, -999, -107, -103, -97, -92, -88,
  116449. -83, -79, -74, -70, -66, -59, -53, -58,
  116450. -62, -55, -54, -54, -54, -58, -61, -62,
  116451. -72, -70, -72, -75, -78, -80, -81, -80,
  116452. -83, -83, -88, -93, -100, -107, -115, -999,
  116453. -999, -999, -999, -999, -999, -999, -999, -999,
  116454. -999, -999, -999, -999, -999, -999, -999, -999},
  116455. {-999, -999, -999, -105, -100, -95, -90, -85,
  116456. -80, -75, -70, -66, -62, -56, -48, -44,
  116457. -48, -46, -46, -43, -46, -48, -48, -51,
  116458. -58, -58, -59, -60, -62, -62, -61, -61,
  116459. -65, -64, -65, -68, -70, -74, -75, -78,
  116460. -81, -86, -95, -110, -999, -999, -999, -999,
  116461. -999, -999, -999, -999, -999, -999, -999, -999},
  116462. {-999, -999, -105, -100, -95, -90, -85, -80,
  116463. -75, -70, -65, -61, -55, -49, -39, -33,
  116464. -40, -35, -32, -38, -40, -33, -35, -37,
  116465. -46, -41, -45, -44, -46, -42, -45, -46,
  116466. -52, -50, -50, -50, -54, -54, -55, -57,
  116467. -62, -64, -66, -68, -70, -76, -81, -90,
  116468. -100, -110, -999, -999, -999, -999, -999, -999}},
  116469. /* 354 hz */
  116470. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116471. -105, -98, -90, -85, -82, -83, -80, -78,
  116472. -84, -79, -80, -83, -87, -89, -91, -93,
  116473. -99, -106, -117, -999, -999, -999, -999, -999,
  116474. -999, -999, -999, -999, -999, -999, -999, -999,
  116475. -999, -999, -999, -999, -999, -999, -999, -999,
  116476. -999, -999, -999, -999, -999, -999, -999, -999},
  116477. {-999, -999, -999, -999, -999, -999, -999, -999,
  116478. -105, -98, -90, -85, -80, -75, -70, -68,
  116479. -74, -72, -74, -77, -80, -82, -85, -87,
  116480. -92, -89, -91, -95, -100, -106, -112, -999,
  116481. -999, -999, -999, -999, -999, -999, -999, -999,
  116482. -999, -999, -999, -999, -999, -999, -999, -999,
  116483. -999, -999, -999, -999, -999, -999, -999, -999},
  116484. {-999, -999, -999, -999, -999, -999, -999, -999,
  116485. -105, -98, -90, -83, -75, -71, -63, -64,
  116486. -67, -62, -64, -67, -70, -73, -77, -81,
  116487. -84, -83, -85, -89, -90, -93, -98, -104,
  116488. -109, -114, -999, -999, -999, -999, -999, -999,
  116489. -999, -999, -999, -999, -999, -999, -999, -999,
  116490. -999, -999, -999, -999, -999, -999, -999, -999},
  116491. {-999, -999, -999, -999, -999, -999, -999, -999,
  116492. -103, -96, -88, -81, -75, -68, -58, -54,
  116493. -56, -54, -56, -56, -58, -60, -63, -66,
  116494. -74, -69, -72, -72, -75, -74, -77, -81,
  116495. -81, -82, -84, -87, -93, -96, -99, -104,
  116496. -110, -999, -999, -999, -999, -999, -999, -999,
  116497. -999, -999, -999, -999, -999, -999, -999, -999},
  116498. {-999, -999, -999, -999, -999, -108, -102, -96,
  116499. -91, -85, -80, -74, -68, -60, -51, -46,
  116500. -48, -46, -43, -45, -47, -47, -49, -48,
  116501. -56, -53, -55, -58, -57, -63, -58, -60,
  116502. -66, -64, -67, -70, -70, -74, -77, -84,
  116503. -86, -89, -91, -93, -94, -101, -109, -118,
  116504. -999, -999, -999, -999, -999, -999, -999, -999},
  116505. {-999, -999, -999, -108, -103, -98, -93, -88,
  116506. -83, -78, -73, -68, -60, -53, -44, -35,
  116507. -38, -38, -34, -34, -36, -40, -41, -44,
  116508. -51, -45, -46, -47, -46, -54, -50, -49,
  116509. -50, -50, -50, -51, -54, -57, -58, -60,
  116510. -66, -66, -66, -64, -65, -68, -77, -82,
  116511. -87, -95, -110, -999, -999, -999, -999, -999}},
  116512. /* 500 Hz */
  116513. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116514. -107, -102, -97, -92, -87, -83, -78, -75,
  116515. -82, -79, -83, -85, -89, -92, -95, -98,
  116516. -101, -105, -109, -113, -999, -999, -999, -999,
  116517. -999, -999, -999, -999, -999, -999, -999, -999,
  116518. -999, -999, -999, -999, -999, -999, -999, -999,
  116519. -999, -999, -999, -999, -999, -999, -999, -999},
  116520. {-999, -999, -999, -999, -999, -999, -999, -106,
  116521. -100, -95, -90, -86, -81, -78, -74, -69,
  116522. -74, -74, -76, -79, -83, -84, -86, -89,
  116523. -92, -97, -93, -100, -103, -107, -110, -999,
  116524. -999, -999, -999, -999, -999, -999, -999, -999,
  116525. -999, -999, -999, -999, -999, -999, -999, -999,
  116526. -999, -999, -999, -999, -999, -999, -999, -999},
  116527. {-999, -999, -999, -999, -999, -999, -106, -100,
  116528. -95, -90, -87, -83, -80, -75, -69, -60,
  116529. -66, -66, -68, -70, -74, -78, -79, -81,
  116530. -81, -83, -84, -87, -93, -96, -99, -103,
  116531. -107, -110, -999, -999, -999, -999, -999, -999,
  116532. -999, -999, -999, -999, -999, -999, -999, -999,
  116533. -999, -999, -999, -999, -999, -999, -999, -999},
  116534. {-999, -999, -999, -999, -999, -108, -103, -98,
  116535. -93, -89, -85, -82, -78, -71, -62, -55,
  116536. -58, -58, -54, -54, -55, -59, -61, -62,
  116537. -70, -66, -66, -67, -70, -72, -75, -78,
  116538. -84, -84, -84, -88, -91, -90, -95, -98,
  116539. -102, -103, -106, -110, -999, -999, -999, -999,
  116540. -999, -999, -999, -999, -999, -999, -999, -999},
  116541. {-999, -999, -999, -999, -108, -103, -98, -94,
  116542. -90, -87, -82, -79, -73, -67, -58, -47,
  116543. -50, -45, -41, -45, -48, -44, -44, -49,
  116544. -54, -51, -48, -47, -49, -50, -51, -57,
  116545. -58, -60, -63, -69, -70, -69, -71, -74,
  116546. -78, -82, -90, -95, -101, -105, -110, -999,
  116547. -999, -999, -999, -999, -999, -999, -999, -999},
  116548. {-999, -999, -999, -105, -101, -97, -93, -90,
  116549. -85, -80, -77, -72, -65, -56, -48, -37,
  116550. -40, -36, -34, -40, -50, -47, -38, -41,
  116551. -47, -38, -35, -39, -38, -43, -40, -45,
  116552. -50, -45, -44, -47, -50, -55, -48, -48,
  116553. -52, -66, -70, -76, -82, -90, -97, -105,
  116554. -110, -999, -999, -999, -999, -999, -999, -999}},
  116555. /* 707 Hz */
  116556. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116557. -999, -108, -103, -98, -93, -86, -79, -76,
  116558. -83, -81, -85, -87, -89, -93, -98, -102,
  116559. -107, -112, -999, -999, -999, -999, -999, -999,
  116560. -999, -999, -999, -999, -999, -999, -999, -999,
  116561. -999, -999, -999, -999, -999, -999, -999, -999,
  116562. -999, -999, -999, -999, -999, -999, -999, -999},
  116563. {-999, -999, -999, -999, -999, -999, -999, -999,
  116564. -999, -108, -103, -98, -93, -86, -79, -71,
  116565. -77, -74, -77, -79, -81, -84, -85, -90,
  116566. -92, -93, -92, -98, -101, -108, -112, -999,
  116567. -999, -999, -999, -999, -999, -999, -999, -999,
  116568. -999, -999, -999, -999, -999, -999, -999, -999,
  116569. -999, -999, -999, -999, -999, -999, -999, -999},
  116570. {-999, -999, -999, -999, -999, -999, -999, -999,
  116571. -108, -103, -98, -93, -87, -78, -68, -65,
  116572. -66, -62, -65, -67, -70, -73, -75, -78,
  116573. -82, -82, -83, -84, -91, -93, -98, -102,
  116574. -106, -110, -999, -999, -999, -999, -999, -999,
  116575. -999, -999, -999, -999, -999, -999, -999, -999,
  116576. -999, -999, -999, -999, -999, -999, -999, -999},
  116577. {-999, -999, -999, -999, -999, -999, -999, -999,
  116578. -105, -100, -95, -90, -82, -74, -62, -57,
  116579. -58, -56, -51, -52, -52, -54, -54, -58,
  116580. -66, -59, -60, -63, -66, -69, -73, -79,
  116581. -83, -84, -80, -81, -81, -82, -88, -92,
  116582. -98, -105, -113, -999, -999, -999, -999, -999,
  116583. -999, -999, -999, -999, -999, -999, -999, -999},
  116584. {-999, -999, -999, -999, -999, -999, -999, -107,
  116585. -102, -97, -92, -84, -79, -69, -57, -47,
  116586. -52, -47, -44, -45, -50, -52, -42, -42,
  116587. -53, -43, -43, -48, -51, -56, -55, -52,
  116588. -57, -59, -61, -62, -67, -71, -78, -83,
  116589. -86, -94, -98, -103, -110, -999, -999, -999,
  116590. -999, -999, -999, -999, -999, -999, -999, -999},
  116591. {-999, -999, -999, -999, -999, -999, -105, -100,
  116592. -95, -90, -84, -78, -70, -61, -51, -41,
  116593. -40, -38, -40, -46, -52, -51, -41, -40,
  116594. -46, -40, -38, -38, -41, -46, -41, -46,
  116595. -47, -43, -43, -45, -41, -45, -56, -67,
  116596. -68, -83, -87, -90, -95, -102, -107, -113,
  116597. -999, -999, -999, -999, -999, -999, -999, -999}},
  116598. /* 1000 Hz */
  116599. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116600. -999, -109, -105, -101, -96, -91, -84, -77,
  116601. -82, -82, -85, -89, -94, -100, -106, -110,
  116602. -999, -999, -999, -999, -999, -999, -999, -999,
  116603. -999, -999, -999, -999, -999, -999, -999, -999,
  116604. -999, -999, -999, -999, -999, -999, -999, -999,
  116605. -999, -999, -999, -999, -999, -999, -999, -999},
  116606. {-999, -999, -999, -999, -999, -999, -999, -999,
  116607. -999, -106, -103, -98, -92, -85, -80, -71,
  116608. -75, -72, -76, -80, -84, -86, -89, -93,
  116609. -100, -107, -113, -999, -999, -999, -999, -999,
  116610. -999, -999, -999, -999, -999, -999, -999, -999,
  116611. -999, -999, -999, -999, -999, -999, -999, -999,
  116612. -999, -999, -999, -999, -999, -999, -999, -999},
  116613. {-999, -999, -999, -999, -999, -999, -999, -107,
  116614. -104, -101, -97, -92, -88, -84, -80, -64,
  116615. -66, -63, -64, -66, -69, -73, -77, -83,
  116616. -83, -86, -91, -98, -104, -111, -999, -999,
  116617. -999, -999, -999, -999, -999, -999, -999, -999,
  116618. -999, -999, -999, -999, -999, -999, -999, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999},
  116620. {-999, -999, -999, -999, -999, -999, -999, -107,
  116621. -104, -101, -97, -92, -90, -84, -74, -57,
  116622. -58, -52, -55, -54, -50, -52, -50, -52,
  116623. -63, -62, -69, -76, -77, -78, -78, -79,
  116624. -82, -88, -94, -100, -106, -111, -999, -999,
  116625. -999, -999, -999, -999, -999, -999, -999, -999,
  116626. -999, -999, -999, -999, -999, -999, -999, -999},
  116627. {-999, -999, -999, -999, -999, -999, -106, -102,
  116628. -98, -95, -90, -85, -83, -78, -70, -50,
  116629. -50, -41, -44, -49, -47, -50, -50, -44,
  116630. -55, -46, -47, -48, -48, -54, -49, -49,
  116631. -58, -62, -71, -81, -87, -92, -97, -102,
  116632. -108, -114, -999, -999, -999, -999, -999, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999},
  116634. {-999, -999, -999, -999, -999, -999, -106, -102,
  116635. -98, -95, -90, -85, -83, -78, -70, -45,
  116636. -43, -41, -47, -50, -51, -50, -49, -45,
  116637. -47, -41, -44, -41, -39, -43, -38, -37,
  116638. -40, -41, -44, -50, -58, -65, -73, -79,
  116639. -85, -92, -97, -101, -105, -109, -113, -999,
  116640. -999, -999, -999, -999, -999, -999, -999, -999}},
  116641. /* 1414 Hz */
  116642. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116643. -999, -999, -999, -107, -100, -95, -87, -81,
  116644. -85, -83, -88, -93, -100, -107, -114, -999,
  116645. -999, -999, -999, -999, -999, -999, -999, -999,
  116646. -999, -999, -999, -999, -999, -999, -999, -999,
  116647. -999, -999, -999, -999, -999, -999, -999, -999,
  116648. -999, -999, -999, -999, -999, -999, -999, -999},
  116649. {-999, -999, -999, -999, -999, -999, -999, -999,
  116650. -999, -999, -107, -101, -95, -88, -83, -76,
  116651. -73, -72, -79, -84, -90, -95, -100, -105,
  116652. -110, -115, -999, -999, -999, -999, -999, -999,
  116653. -999, -999, -999, -999, -999, -999, -999, -999,
  116654. -999, -999, -999, -999, -999, -999, -999, -999,
  116655. -999, -999, -999, -999, -999, -999, -999, -999},
  116656. {-999, -999, -999, -999, -999, -999, -999, -999,
  116657. -999, -999, -104, -98, -92, -87, -81, -70,
  116658. -65, -62, -67, -71, -74, -80, -85, -91,
  116659. -95, -99, -103, -108, -111, -114, -999, -999,
  116660. -999, -999, -999, -999, -999, -999, -999, -999,
  116661. -999, -999, -999, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999},
  116663. {-999, -999, -999, -999, -999, -999, -999, -999,
  116664. -999, -999, -103, -97, -90, -85, -76, -60,
  116665. -56, -54, -60, -62, -61, -56, -63, -65,
  116666. -73, -74, -77, -75, -78, -81, -86, -87,
  116667. -88, -91, -94, -98, -103, -110, -999, -999,
  116668. -999, -999, -999, -999, -999, -999, -999, -999,
  116669. -999, -999, -999, -999, -999, -999, -999, -999},
  116670. {-999, -999, -999, -999, -999, -999, -999, -105,
  116671. -100, -97, -92, -86, -81, -79, -70, -57,
  116672. -51, -47, -51, -58, -60, -56, -53, -50,
  116673. -58, -52, -50, -50, -53, -55, -64, -69,
  116674. -71, -85, -82, -78, -81, -85, -95, -102,
  116675. -112, -999, -999, -999, -999, -999, -999, -999,
  116676. -999, -999, -999, -999, -999, -999, -999, -999},
  116677. {-999, -999, -999, -999, -999, -999, -999, -105,
  116678. -100, -97, -92, -85, -83, -79, -72, -49,
  116679. -40, -43, -43, -54, -56, -51, -50, -40,
  116680. -43, -38, -36, -35, -37, -38, -37, -44,
  116681. -54, -60, -57, -60, -70, -75, -84, -92,
  116682. -103, -112, -999, -999, -999, -999, -999, -999,
  116683. -999, -999, -999, -999, -999, -999, -999, -999}},
  116684. /* 2000 Hz */
  116685. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116686. -999, -999, -999, -110, -102, -95, -89, -82,
  116687. -83, -84, -90, -92, -99, -107, -113, -999,
  116688. -999, -999, -999, -999, -999, -999, -999, -999,
  116689. -999, -999, -999, -999, -999, -999, -999, -999,
  116690. -999, -999, -999, -999, -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, -107, -101, -95, -89, -83, -72,
  116694. -74, -78, -85, -88, -88, -90, -92, -98,
  116695. -105, -111, -999, -999, -999, -999, -999, -999,
  116696. -999, -999, -999, -999, -999, -999, -999, -999,
  116697. -999, -999, -999, -999, -999, -999, -999, -999,
  116698. -999, -999, -999, -999, -999, -999, -999, -999},
  116699. {-999, -999, -999, -999, -999, -999, -999, -999,
  116700. -999, -109, -103, -97, -93, -87, -81, -70,
  116701. -70, -67, -75, -73, -76, -79, -81, -83,
  116702. -88, -89, -97, -103, -110, -999, -999, -999,
  116703. -999, -999, -999, -999, -999, -999, -999, -999,
  116704. -999, -999, -999, -999, -999, -999, -999, -999,
  116705. -999, -999, -999, -999, -999, -999, -999, -999},
  116706. {-999, -999, -999, -999, -999, -999, -999, -999,
  116707. -999, -107, -100, -94, -88, -83, -75, -63,
  116708. -59, -59, -63, -66, -60, -62, -67, -67,
  116709. -77, -76, -81, -88, -86, -92, -96, -102,
  116710. -109, -116, -999, -999, -999, -999, -999, -999,
  116711. -999, -999, -999, -999, -999, -999, -999, -999,
  116712. -999, -999, -999, -999, -999, -999, -999, -999},
  116713. {-999, -999, -999, -999, -999, -999, -999, -999,
  116714. -999, -105, -98, -92, -86, -81, -73, -56,
  116715. -52, -47, -55, -60, -58, -52, -51, -45,
  116716. -49, -50, -53, -54, -61, -71, -70, -69,
  116717. -78, -79, -87, -90, -96, -104, -112, -999,
  116718. -999, -999, -999, -999, -999, -999, -999, -999,
  116719. -999, -999, -999, -999, -999, -999, -999, -999},
  116720. {-999, -999, -999, -999, -999, -999, -999, -999,
  116721. -999, -103, -96, -90, -86, -78, -70, -51,
  116722. -42, -47, -48, -55, -54, -54, -53, -42,
  116723. -35, -28, -33, -38, -37, -44, -47, -49,
  116724. -54, -63, -68, -78, -82, -89, -94, -99,
  116725. -104, -109, -114, -999, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999}},
  116727. /* 2828 Hz */
  116728. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116729. -999, -999, -999, -999, -110, -100, -90, -79,
  116730. -85, -81, -82, -82, -89, -94, -99, -103,
  116731. -109, -115, -999, -999, -999, -999, -999, -999,
  116732. -999, -999, -999, -999, -999, -999, -999, -999,
  116733. -999, -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, -105, -97, -85, -72,
  116737. -74, -70, -70, -70, -76, -85, -91, -93,
  116738. -97, -103, -109, -115, -999, -999, -999, -999,
  116739. -999, -999, -999, -999, -999, -999, -999, -999,
  116740. -999, -999, -999, -999, -999, -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, -112, -93, -81, -68,
  116744. -62, -60, -60, -57, -63, -70, -77, -82,
  116745. -90, -93, -98, -104, -109, -113, -999, -999,
  116746. -999, -999, -999, -999, -999, -999, -999, -999,
  116747. -999, -999, -999, -999, -999, -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, -113, -100, -93, -84, -63,
  116751. -58, -48, -53, -54, -52, -52, -57, -64,
  116752. -66, -76, -83, -81, -85, -85, -90, -95,
  116753. -98, -101, -103, -106, -108, -111, -999, -999,
  116754. -999, -999, -999, -999, -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, -105, -95, -86, -74, -53,
  116758. -50, -38, -43, -49, -43, -42, -39, -39,
  116759. -46, -52, -57, -56, -72, -69, -74, -81,
  116760. -87, -92, -94, -97, -99, -102, -105, -108,
  116761. -999, -999, -999, -999, -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, -108, -99, -90, -76, -66, -45,
  116765. -43, -41, -44, -47, -43, -47, -40, -30,
  116766. -31, -31, -39, -33, -40, -41, -43, -53,
  116767. -59, -70, -73, -77, -79, -82, -84, -87,
  116768. -999, -999, -999, -999, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999}},
  116770. /* 4000 Hz */
  116771. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116772. -999, -999, -999, -999, -999, -110, -91, -76,
  116773. -75, -85, -93, -98, -104, -110, -999, -999,
  116774. -999, -999, -999, -999, -999, -999, -999, -999,
  116775. -999, -999, -999, -999, -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, -110, -91, -70,
  116780. -70, -75, -86, -89, -94, -98, -101, -106,
  116781. -110, -999, -999, -999, -999, -999, -999, -999,
  116782. -999, -999, -999, -999, -999, -999, -999, -999,
  116783. -999, -999, -999, -999, -999, -999, -999, -999,
  116784. -999, -999, -999, -999, -999, -999, -999, -999},
  116785. {-999, -999, -999, -999, -999, -999, -999, -999,
  116786. -999, -999, -999, -999, -110, -95, -80, -60,
  116787. -65, -64, -74, -83, -88, -91, -95, -99,
  116788. -103, -107, -110, -999, -999, -999, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999,
  116790. -999, -999, -999, -999, -999, -999, -999, -999,
  116791. -999, -999, -999, -999, -999, -999, -999, -999},
  116792. {-999, -999, -999, -999, -999, -999, -999, -999,
  116793. -999, -999, -999, -999, -110, -95, -80, -58,
  116794. -55, -49, -66, -68, -71, -78, -78, -80,
  116795. -88, -85, -89, -97, -100, -105, -110, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999,
  116798. -999, -999, -999, -999, -999, -999, -999, -999},
  116799. {-999, -999, -999, -999, -999, -999, -999, -999,
  116800. -999, -999, -999, -999, -110, -95, -80, -53,
  116801. -52, -41, -59, -59, -49, -58, -56, -63,
  116802. -86, -79, -90, -93, -98, -103, -107, -112,
  116803. -999, -999, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999},
  116806. {-999, -999, -999, -999, -999, -999, -999, -999,
  116807. -999, -999, -999, -110, -97, -91, -73, -45,
  116808. -40, -33, -53, -61, -49, -54, -50, -50,
  116809. -60, -52, -67, -74, -81, -92, -96, -100,
  116810. -105, -110, -999, -999, -999, -999, -999, -999,
  116811. -999, -999, -999, -999, -999, -999, -999, -999,
  116812. -999, -999, -999, -999, -999, -999, -999, -999}},
  116813. /* 5657 Hz */
  116814. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116815. -999, -999, -999, -113, -106, -99, -92, -77,
  116816. -80, -88, -97, -106, -115, -999, -999, -999,
  116817. -999, -999, -999, -999, -999, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -999, -999, -999, -999, -999, -999},
  116821. {-999, -999, -999, -999, -999, -999, -999, -999,
  116822. -999, -999, -116, -109, -102, -95, -89, -74,
  116823. -72, -88, -87, -95, -102, -109, -116, -999,
  116824. -999, -999, -999, -999, -999, -999, -999, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999,
  116826. -999, -999, -999, -999, -999, -999, -999, -999,
  116827. -999, -999, -999, -999, -999, -999, -999, -999},
  116828. {-999, -999, -999, -999, -999, -999, -999, -999,
  116829. -999, -999, -116, -109, -102, -95, -89, -75,
  116830. -66, -74, -77, -78, -86, -87, -90, -96,
  116831. -105, -115, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999,
  116833. -999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -999, -999, -999, -999, -999, -999, -999},
  116835. {-999, -999, -999, -999, -999, -999, -999, -999,
  116836. -999, -999, -115, -108, -101, -94, -88, -66,
  116837. -56, -61, -70, -65, -78, -72, -83, -84,
  116838. -93, -98, -105, -110, -999, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999,
  116840. -999, -999, -999, -999, -999, -999, -999, -999,
  116841. -999, -999, -999, -999, -999, -999, -999, -999},
  116842. {-999, -999, -999, -999, -999, -999, -999, -999,
  116843. -999, -999, -110, -105, -95, -89, -82, -57,
  116844. -52, -52, -59, -56, -59, -58, -69, -67,
  116845. -88, -82, -82, -89, -94, -100, -108, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -999, -999, -999, -999},
  116849. {-999, -999, -999, -999, -999, -999, -999, -999,
  116850. -999, -110, -101, -96, -90, -83, -77, -54,
  116851. -43, -38, -50, -48, -52, -48, -42, -42,
  116852. -51, -52, -53, -59, -65, -71, -78, -85,
  116853. -95, -999, -999, -999, -999, -999, -999, -999,
  116854. -999, -999, -999, -999, -999, -999, -999, -999,
  116855. -999, -999, -999, -999, -999, -999, -999, -999}},
  116856. /* 8000 Hz */
  116857. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116858. -999, -999, -999, -999, -120, -105, -86, -68,
  116859. -78, -79, -90, -100, -110, -999, -999, -999,
  116860. -999, -999, -999, -999, -999, -999, -999, -999,
  116861. -999, -999, -999, -999, -999, -999, -999, -999,
  116862. -999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -999, -999, -999, -999, -999, -999},
  116864. {-999, -999, -999, -999, -999, -999, -999, -999,
  116865. -999, -999, -999, -999, -120, -105, -86, -66,
  116866. -73, -77, -88, -96, -105, -115, -999, -999,
  116867. -999, -999, -999, -999, -999, -999, -999, -999,
  116868. -999, -999, -999, -999, -999, -999, -999, -999,
  116869. -999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -999, -999, -999, -999, -999, -999, -999},
  116871. {-999, -999, -999, -999, -999, -999, -999, -999,
  116872. -999, -999, -999, -120, -105, -92, -80, -61,
  116873. -64, -68, -80, -87, -92, -100, -110, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999,
  116876. -999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -999, -999, -999, -999, -999, -999, -999},
  116878. {-999, -999, -999, -999, -999, -999, -999, -999,
  116879. -999, -999, -999, -120, -104, -91, -79, -52,
  116880. -60, -54, -64, -69, -77, -80, -82, -84,
  116881. -85, -87, -88, -90, -999, -999, -999, -999,
  116882. -999, -999, -999, -999, -999, -999, -999, -999,
  116883. -999, -999, -999, -999, -999, -999, -999, -999,
  116884. -999, -999, -999, -999, -999, -999, -999, -999},
  116885. {-999, -999, -999, -999, -999, -999, -999, -999,
  116886. -999, -999, -999, -118, -100, -87, -77, -49,
  116887. -50, -44, -58, -61, -61, -67, -65, -62,
  116888. -62, -62, -65, -68, -999, -999, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999,
  116891. -999, -999, -999, -999, -999, -999, -999, -999},
  116892. {-999, -999, -999, -999, -999, -999, -999, -999,
  116893. -999, -999, -999, -115, -98, -84, -62, -49,
  116894. -44, -38, -46, -49, -49, -46, -39, -37,
  116895. -39, -40, -42, -43, -999, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999,
  116897. -999, -999, -999, -999, -999, -999, -999, -999,
  116898. -999, -999, -999, -999, -999, -999, -999, -999}},
  116899. /* 11314 Hz */
  116900. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116901. -999, -999, -999, -999, -999, -110, -88, -74,
  116902. -77, -82, -82, -85, -90, -94, -99, -104,
  116903. -999, -999, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -999, -999, -999, -999, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -999, -999, -999, -999, -999, -999, -999},
  116907. {-999, -999, -999, -999, -999, -999, -999, -999,
  116908. -999, -999, -999, -999, -999, -110, -88, -66,
  116909. -70, -81, -80, -81, -84, -88, -91, -93,
  116910. -999, -999, -999, -999, -999, -999, -999, -999,
  116911. -999, -999, -999, -999, -999, -999, -999, -999,
  116912. -999, -999, -999, -999, -999, -999, -999, -999,
  116913. -999, -999, -999, -999, -999, -999, -999, -999},
  116914. {-999, -999, -999, -999, -999, -999, -999, -999,
  116915. -999, -999, -999, -999, -999, -110, -88, -61,
  116916. -63, -70, -71, -74, -77, -80, -83, -85,
  116917. -999, -999, -999, -999, -999, -999, -999, -999,
  116918. -999, -999, -999, -999, -999, -999, -999, -999,
  116919. -999, -999, -999, -999, -999, -999, -999, -999,
  116920. -999, -999, -999, -999, -999, -999, -999, -999},
  116921. {-999, -999, -999, -999, -999, -999, -999, -999,
  116922. -999, -999, -999, -999, -999, -110, -86, -62,
  116923. -63, -62, -62, -58, -52, -50, -50, -52,
  116924. -54, -999, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999,
  116926. -999, -999, -999, -999, -999, -999, -999, -999,
  116927. -999, -999, -999, -999, -999, -999, -999, -999},
  116928. {-999, -999, -999, -999, -999, -999, -999, -999,
  116929. -999, -999, -999, -999, -118, -108, -84, -53,
  116930. -50, -50, -50, -55, -47, -45, -40, -40,
  116931. -40, -999, -999, -999, -999, -999, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999,
  116934. -999, -999, -999, -999, -999, -999, -999, -999},
  116935. {-999, -999, -999, -999, -999, -999, -999, -999,
  116936. -999, -999, -999, -999, -118, -100, -73, -43,
  116937. -37, -42, -43, -53, -38, -37, -35, -35,
  116938. -38, -999, -999, -999, -999, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -999, -999, -999, -999, -999, -999}},
  116942. /* 16000 Hz */
  116943. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116944. -999, -999, -999, -110, -100, -91, -84, -74,
  116945. -80, -80, -80, -80, -80, -999, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -999, -999, -999, -999, -999},
  116950. {-999, -999, -999, -999, -999, -999, -999, -999,
  116951. -999, -999, -999, -110, -100, -91, -84, -74,
  116952. -68, -68, -68, -68, -68, -999, -999, -999,
  116953. -999, -999, -999, -999, -999, -999, -999, -999,
  116954. -999, -999, -999, -999, -999, -999, -999, -999,
  116955. -999, -999, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -999, -999, -999, -999, -999, -999},
  116957. {-999, -999, -999, -999, -999, -999, -999, -999,
  116958. -999, -999, -999, -110, -100, -86, -78, -70,
  116959. -60, -45, -30, -21, -999, -999, -999, -999,
  116960. -999, -999, -999, -999, -999, -999, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999,
  116962. -999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -999, -999, -999, -999, -999},
  116964. {-999, -999, -999, -999, -999, -999, -999, -999,
  116965. -999, -999, -999, -110, -100, -87, -78, -67,
  116966. -48, -38, -29, -21, -999, -999, -999, -999,
  116967. -999, -999, -999, -999, -999, -999, -999, -999,
  116968. -999, -999, -999, -999, -999, -999, -999, -999,
  116969. -999, -999, -999, -999, -999, -999, -999, -999,
  116970. -999, -999, -999, -999, -999, -999, -999, -999},
  116971. {-999, -999, -999, -999, -999, -999, -999, -999,
  116972. -999, -999, -999, -110, -100, -86, -69, -56,
  116973. -45, -35, -33, -29, -999, -999, -999, -999,
  116974. -999, -999, -999, -999, -999, -999, -999, -999,
  116975. -999, -999, -999, -999, -999, -999, -999, -999,
  116976. -999, -999, -999, -999, -999, -999, -999, -999,
  116977. -999, -999, -999, -999, -999, -999, -999, -999},
  116978. {-999, -999, -999, -999, -999, -999, -999, -999,
  116979. -999, -999, -999, -110, -100, -83, -71, -48,
  116980. -27, -38, -37, -34, -999, -999, -999, -999,
  116981. -999, -999, -999, -999, -999, -999, -999, -999,
  116982. -999, -999, -999, -999, -999, -999, -999, -999,
  116983. -999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -999, -999, -999, -999, -999, -999}}
  116985. };
  116986. #endif
  116987. /*** End of inlined file: masking.h ***/
  116988. #define NEGINF -9999.f
  116989. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116990. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116991. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116992. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116993. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116994. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116995. look->channels=vi->channels;
  116996. look->ampmax=-9999.;
  116997. look->gi=gi;
  116998. return(look);
  116999. }
  117000. void _vp_global_free(vorbis_look_psy_global *look){
  117001. if(look){
  117002. memset(look,0,sizeof(*look));
  117003. _ogg_free(look);
  117004. }
  117005. }
  117006. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117007. if(i){
  117008. memset(i,0,sizeof(*i));
  117009. _ogg_free(i);
  117010. }
  117011. }
  117012. void _vi_psy_free(vorbis_info_psy *i){
  117013. if(i){
  117014. memset(i,0,sizeof(*i));
  117015. _ogg_free(i);
  117016. }
  117017. }
  117018. static void min_curve(float *c,
  117019. float *c2){
  117020. int i;
  117021. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117022. }
  117023. static void max_curve(float *c,
  117024. float *c2){
  117025. int i;
  117026. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117027. }
  117028. static void attenuate_curve(float *c,float att){
  117029. int i;
  117030. for(i=0;i<EHMER_MAX;i++)
  117031. c[i]+=att;
  117032. }
  117033. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117034. float center_boost, float center_decay_rate){
  117035. int i,j,k,m;
  117036. float ath[EHMER_MAX];
  117037. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117038. float athc[P_LEVELS][EHMER_MAX];
  117039. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117040. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117041. memset(workc,0,sizeof(workc));
  117042. for(i=0;i<P_BANDS;i++){
  117043. /* we add back in the ATH to avoid low level curves falling off to
  117044. -infinity and unnecessarily cutting off high level curves in the
  117045. curve limiting (last step). */
  117046. /* A half-band's settings must be valid over the whole band, and
  117047. it's better to mask too little than too much */
  117048. int ath_offset=i*4;
  117049. for(j=0;j<EHMER_MAX;j++){
  117050. float min=999.;
  117051. for(k=0;k<4;k++)
  117052. if(j+k+ath_offset<MAX_ATH){
  117053. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117054. }else{
  117055. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117056. }
  117057. ath[j]=min;
  117058. }
  117059. /* copy curves into working space, replicate the 50dB curve to 30
  117060. and 40, replicate the 100dB curve to 110 */
  117061. for(j=0;j<6;j++)
  117062. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117063. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117064. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117065. /* apply centered curve boost/decay */
  117066. for(j=0;j<P_LEVELS;j++){
  117067. for(k=0;k<EHMER_MAX;k++){
  117068. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117069. if(adj<0. && center_boost>0)adj=0.;
  117070. if(adj>0. && center_boost<0)adj=0.;
  117071. workc[i][j][k]+=adj;
  117072. }
  117073. }
  117074. /* normalize curves so the driving amplitude is 0dB */
  117075. /* make temp curves with the ATH overlayed */
  117076. for(j=0;j<P_LEVELS;j++){
  117077. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117078. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117079. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117080. max_curve(athc[j],workc[i][j]);
  117081. }
  117082. /* Now limit the louder curves.
  117083. the idea is this: We don't know what the playback attenuation
  117084. will be; 0dB SL moves every time the user twiddles the volume
  117085. knob. So that means we have to use a single 'most pessimal' curve
  117086. for all masking amplitudes, right? Wrong. The *loudest* sound
  117087. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117088. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117089. etc... */
  117090. for(j=1;j<P_LEVELS;j++){
  117091. min_curve(athc[j],athc[j-1]);
  117092. min_curve(workc[i][j],athc[j]);
  117093. }
  117094. }
  117095. for(i=0;i<P_BANDS;i++){
  117096. int hi_curve,lo_curve,bin;
  117097. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117098. /* low frequency curves are measured with greater resolution than
  117099. the MDCT/FFT will actually give us; we want the curve applied
  117100. to the tone data to be pessimistic and thus apply the minimum
  117101. masking possible for a given bin. That means that a single bin
  117102. could span more than one octave and that the curve will be a
  117103. composite of multiple octaves. It also may mean that a single
  117104. bin may span > an eighth of an octave and that the eighth
  117105. octave values may also be composited. */
  117106. /* which octave curves will we be compositing? */
  117107. bin=floor(fromOC(i*.5)/binHz);
  117108. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117109. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117110. if(lo_curve>i)lo_curve=i;
  117111. if(lo_curve<0)lo_curve=0;
  117112. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117113. for(m=0;m<P_LEVELS;m++){
  117114. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117115. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117116. /* render the curve into bins, then pull values back into curve.
  117117. The point is that any inherent subsampling aliasing results in
  117118. a safe minimum */
  117119. for(k=lo_curve;k<=hi_curve;k++){
  117120. int l=0;
  117121. for(j=0;j<EHMER_MAX;j++){
  117122. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117123. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117124. if(lo_bin<0)lo_bin=0;
  117125. if(lo_bin>n)lo_bin=n;
  117126. if(lo_bin<l)l=lo_bin;
  117127. if(hi_bin<0)hi_bin=0;
  117128. if(hi_bin>n)hi_bin=n;
  117129. for(;l<hi_bin && l<n;l++)
  117130. if(brute_buffer[l]>workc[k][m][j])
  117131. brute_buffer[l]=workc[k][m][j];
  117132. }
  117133. for(;l<n;l++)
  117134. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117135. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117136. }
  117137. /* be equally paranoid about being valid up to next half ocatve */
  117138. if(i+1<P_BANDS){
  117139. int l=0;
  117140. k=i+1;
  117141. for(j=0;j<EHMER_MAX;j++){
  117142. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117143. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117144. if(lo_bin<0)lo_bin=0;
  117145. if(lo_bin>n)lo_bin=n;
  117146. if(lo_bin<l)l=lo_bin;
  117147. if(hi_bin<0)hi_bin=0;
  117148. if(hi_bin>n)hi_bin=n;
  117149. for(;l<hi_bin && l<n;l++)
  117150. if(brute_buffer[l]>workc[k][m][j])
  117151. brute_buffer[l]=workc[k][m][j];
  117152. }
  117153. for(;l<n;l++)
  117154. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117155. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117156. }
  117157. for(j=0;j<EHMER_MAX;j++){
  117158. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117159. if(bin<0){
  117160. ret[i][m][j+2]=-999.;
  117161. }else{
  117162. if(bin>=n){
  117163. ret[i][m][j+2]=-999.;
  117164. }else{
  117165. ret[i][m][j+2]=brute_buffer[bin];
  117166. }
  117167. }
  117168. }
  117169. /* add fenceposts */
  117170. for(j=0;j<EHMER_OFFSET;j++)
  117171. if(ret[i][m][j+2]>-200.f)break;
  117172. ret[i][m][0]=j;
  117173. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117174. if(ret[i][m][j+2]>-200.f)
  117175. break;
  117176. ret[i][m][1]=j;
  117177. }
  117178. }
  117179. return(ret);
  117180. }
  117181. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117182. vorbis_info_psy_global *gi,int n,long rate){
  117183. long i,j,lo=-99,hi=1;
  117184. long maxoc;
  117185. memset(p,0,sizeof(*p));
  117186. p->eighth_octave_lines=gi->eighth_octave_lines;
  117187. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117188. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117189. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117190. p->total_octave_lines=maxoc-p->firstoc+1;
  117191. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117192. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117193. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117194. p->vi=vi;
  117195. p->n=n;
  117196. p->rate=rate;
  117197. /* AoTuV HF weighting */
  117198. p->m_val = 1.;
  117199. if(rate < 26000) p->m_val = 0;
  117200. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117201. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117202. /* set up the lookups for a given blocksize and sample rate */
  117203. for(i=0,j=0;i<MAX_ATH-1;i++){
  117204. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117205. float base=ATH[i];
  117206. if(j<endpos){
  117207. float delta=(ATH[i+1]-base)/(endpos-j);
  117208. for(;j<endpos && j<n;j++){
  117209. p->ath[j]=base+100.;
  117210. base+=delta;
  117211. }
  117212. }
  117213. }
  117214. for(i=0;i<n;i++){
  117215. float bark=toBARK(rate/(2*n)*i);
  117216. for(;lo+vi->noisewindowlomin<i &&
  117217. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117218. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117219. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117220. p->bark[i]=((lo-1)<<16)+(hi-1);
  117221. }
  117222. for(i=0;i<n;i++)
  117223. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117224. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117225. vi->tone_centerboost,vi->tone_decay);
  117226. /* set up rolling noise median */
  117227. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117228. for(i=0;i<P_NOISECURVES;i++)
  117229. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117230. for(i=0;i<n;i++){
  117231. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117232. int inthalfoc;
  117233. float del;
  117234. if(halfoc<0)halfoc=0;
  117235. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117236. inthalfoc=(int)halfoc;
  117237. del=halfoc-inthalfoc;
  117238. for(j=0;j<P_NOISECURVES;j++)
  117239. p->noiseoffset[j][i]=
  117240. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117241. p->vi->noiseoff[j][inthalfoc+1]*del;
  117242. }
  117243. #if 0
  117244. {
  117245. static int ls=0;
  117246. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117247. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117248. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117249. }
  117250. #endif
  117251. }
  117252. void _vp_psy_clear(vorbis_look_psy *p){
  117253. int i,j;
  117254. if(p){
  117255. if(p->ath)_ogg_free(p->ath);
  117256. if(p->octave)_ogg_free(p->octave);
  117257. if(p->bark)_ogg_free(p->bark);
  117258. if(p->tonecurves){
  117259. for(i=0;i<P_BANDS;i++){
  117260. for(j=0;j<P_LEVELS;j++){
  117261. _ogg_free(p->tonecurves[i][j]);
  117262. }
  117263. _ogg_free(p->tonecurves[i]);
  117264. }
  117265. _ogg_free(p->tonecurves);
  117266. }
  117267. if(p->noiseoffset){
  117268. for(i=0;i<P_NOISECURVES;i++){
  117269. _ogg_free(p->noiseoffset[i]);
  117270. }
  117271. _ogg_free(p->noiseoffset);
  117272. }
  117273. memset(p,0,sizeof(*p));
  117274. }
  117275. }
  117276. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117277. static void seed_curve(float *seed,
  117278. const float **curves,
  117279. float amp,
  117280. int oc, int n,
  117281. int linesper,float dBoffset){
  117282. int i,post1;
  117283. int seedptr;
  117284. const float *posts,*curve;
  117285. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117286. choice=max(choice,0);
  117287. choice=min(choice,P_LEVELS-1);
  117288. posts=curves[choice];
  117289. curve=posts+2;
  117290. post1=(int)posts[1];
  117291. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117292. for(i=posts[0];i<post1;i++){
  117293. if(seedptr>0){
  117294. float lin=amp+curve[i];
  117295. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117296. }
  117297. seedptr+=linesper;
  117298. if(seedptr>=n)break;
  117299. }
  117300. }
  117301. static void seed_loop(vorbis_look_psy *p,
  117302. const float ***curves,
  117303. const float *f,
  117304. const float *flr,
  117305. float *seed,
  117306. float specmax){
  117307. vorbis_info_psy *vi=p->vi;
  117308. long n=p->n,i;
  117309. float dBoffset=vi->max_curve_dB-specmax;
  117310. /* prime the working vector with peak values */
  117311. for(i=0;i<n;i++){
  117312. float max=f[i];
  117313. long oc=p->octave[i];
  117314. while(i+1<n && p->octave[i+1]==oc){
  117315. i++;
  117316. if(f[i]>max)max=f[i];
  117317. }
  117318. if(max+6.f>flr[i]){
  117319. oc=oc>>p->shiftoc;
  117320. if(oc>=P_BANDS)oc=P_BANDS-1;
  117321. if(oc<0)oc=0;
  117322. seed_curve(seed,
  117323. curves[oc],
  117324. max,
  117325. p->octave[i]-p->firstoc,
  117326. p->total_octave_lines,
  117327. p->eighth_octave_lines,
  117328. dBoffset);
  117329. }
  117330. }
  117331. }
  117332. static void seed_chase(float *seeds, int linesper, long n){
  117333. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117334. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117335. long stack=0;
  117336. long pos=0;
  117337. long i;
  117338. for(i=0;i<n;i++){
  117339. if(stack<2){
  117340. posstack[stack]=i;
  117341. ampstack[stack++]=seeds[i];
  117342. }else{
  117343. while(1){
  117344. if(seeds[i]<ampstack[stack-1]){
  117345. posstack[stack]=i;
  117346. ampstack[stack++]=seeds[i];
  117347. break;
  117348. }else{
  117349. if(i<posstack[stack-1]+linesper){
  117350. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117351. i<posstack[stack-2]+linesper){
  117352. /* we completely overlap, making stack-1 irrelevant. pop it */
  117353. stack--;
  117354. continue;
  117355. }
  117356. }
  117357. posstack[stack]=i;
  117358. ampstack[stack++]=seeds[i];
  117359. break;
  117360. }
  117361. }
  117362. }
  117363. }
  117364. /* the stack now contains only the positions that are relevant. Scan
  117365. 'em straight through */
  117366. for(i=0;i<stack;i++){
  117367. long endpos;
  117368. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117369. endpos=posstack[i+1];
  117370. }else{
  117371. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117372. discarded in short frames */
  117373. }
  117374. if(endpos>n)endpos=n;
  117375. for(;pos<endpos;pos++)
  117376. seeds[pos]=ampstack[i];
  117377. }
  117378. /* there. Linear time. I now remember this was on a problem set I
  117379. had in Grad Skool... I didn't solve it at the time ;-) */
  117380. }
  117381. /* bleaugh, this is more complicated than it needs to be */
  117382. #include<stdio.h>
  117383. static void max_seeds(vorbis_look_psy *p,
  117384. float *seed,
  117385. float *flr){
  117386. long n=p->total_octave_lines;
  117387. int linesper=p->eighth_octave_lines;
  117388. long linpos=0;
  117389. long pos;
  117390. seed_chase(seed,linesper,n); /* for masking */
  117391. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117392. while(linpos+1<p->n){
  117393. float minV=seed[pos];
  117394. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117395. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117396. while(pos+1<=end){
  117397. pos++;
  117398. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117399. minV=seed[pos];
  117400. }
  117401. end=pos+p->firstoc;
  117402. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117403. if(flr[linpos]<minV)flr[linpos]=minV;
  117404. }
  117405. {
  117406. float minV=seed[p->total_octave_lines-1];
  117407. for(;linpos<p->n;linpos++)
  117408. if(flr[linpos]<minV)flr[linpos]=minV;
  117409. }
  117410. }
  117411. static void bark_noise_hybridmp(int n,const long *b,
  117412. const float *f,
  117413. float *noise,
  117414. const float offset,
  117415. const int fixed){
  117416. float *N=(float*) alloca(n*sizeof(*N));
  117417. float *X=(float*) alloca(n*sizeof(*N));
  117418. float *XX=(float*) alloca(n*sizeof(*N));
  117419. float *Y=(float*) alloca(n*sizeof(*N));
  117420. float *XY=(float*) alloca(n*sizeof(*N));
  117421. float tN, tX, tXX, tY, tXY;
  117422. int i;
  117423. int lo, hi;
  117424. float R, A, B, D;
  117425. float w, x, y;
  117426. tN = tX = tXX = tY = tXY = 0.f;
  117427. y = f[0] + offset;
  117428. if (y < 1.f) y = 1.f;
  117429. w = y * y * .5;
  117430. tN += w;
  117431. tX += w;
  117432. tY += w * y;
  117433. N[0] = tN;
  117434. X[0] = tX;
  117435. XX[0] = tXX;
  117436. Y[0] = tY;
  117437. XY[0] = tXY;
  117438. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117439. y = f[i] + offset;
  117440. if (y < 1.f) y = 1.f;
  117441. w = y * y;
  117442. tN += w;
  117443. tX += w * x;
  117444. tXX += w * x * x;
  117445. tY += w * y;
  117446. tXY += w * x * y;
  117447. N[i] = tN;
  117448. X[i] = tX;
  117449. XX[i] = tXX;
  117450. Y[i] = tY;
  117451. XY[i] = tXY;
  117452. }
  117453. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117454. lo = b[i] >> 16;
  117455. if( lo>=0 ) break;
  117456. hi = b[i] & 0xffff;
  117457. tN = N[hi] + N[-lo];
  117458. tX = X[hi] - X[-lo];
  117459. tXX = XX[hi] + XX[-lo];
  117460. tY = Y[hi] + Y[-lo];
  117461. tXY = XY[hi] - XY[-lo];
  117462. A = tY * tXX - tX * tXY;
  117463. B = tN * tXY - tX * tY;
  117464. D = tN * tXX - tX * tX;
  117465. R = (A + x * B) / D;
  117466. if (R < 0.f)
  117467. R = 0.f;
  117468. noise[i] = R - offset;
  117469. }
  117470. for ( ;; i++, x += 1.f) {
  117471. lo = b[i] >> 16;
  117472. hi = b[i] & 0xffff;
  117473. if(hi>=n)break;
  117474. tN = N[hi] - N[lo];
  117475. tX = X[hi] - X[lo];
  117476. tXX = XX[hi] - XX[lo];
  117477. tY = Y[hi] - Y[lo];
  117478. tXY = XY[hi] - XY[lo];
  117479. A = tY * tXX - tX * tXY;
  117480. B = tN * tXY - tX * tY;
  117481. D = tN * tXX - tX * tX;
  117482. R = (A + x * B) / D;
  117483. if (R < 0.f) R = 0.f;
  117484. noise[i] = R - offset;
  117485. }
  117486. for ( ; i < n; i++, x += 1.f) {
  117487. R = (A + x * B) / D;
  117488. if (R < 0.f) R = 0.f;
  117489. noise[i] = R - offset;
  117490. }
  117491. if (fixed <= 0) return;
  117492. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117493. hi = i + fixed / 2;
  117494. lo = hi - fixed;
  117495. if(lo>=0)break;
  117496. tN = N[hi] + N[-lo];
  117497. tX = X[hi] - X[-lo];
  117498. tXX = XX[hi] + XX[-lo];
  117499. tY = Y[hi] + Y[-lo];
  117500. tXY = XY[hi] - XY[-lo];
  117501. A = tY * tXX - tX * tXY;
  117502. B = tN * tXY - tX * tY;
  117503. D = tN * tXX - tX * tX;
  117504. R = (A + x * B) / D;
  117505. if (R - offset < noise[i]) noise[i] = R - offset;
  117506. }
  117507. for ( ;; i++, x += 1.f) {
  117508. hi = i + fixed / 2;
  117509. lo = hi - fixed;
  117510. if(hi>=n)break;
  117511. tN = N[hi] - N[lo];
  117512. tX = X[hi] - X[lo];
  117513. tXX = XX[hi] - XX[lo];
  117514. tY = Y[hi] - Y[lo];
  117515. tXY = XY[hi] - XY[lo];
  117516. A = tY * tXX - tX * tXY;
  117517. B = tN * tXY - tX * tY;
  117518. D = tN * tXX - tX * tX;
  117519. R = (A + x * B) / D;
  117520. if (R - offset < noise[i]) noise[i] = R - offset;
  117521. }
  117522. for ( ; i < n; i++, x += 1.f) {
  117523. R = (A + x * B) / D;
  117524. if (R - offset < noise[i]) noise[i] = R - offset;
  117525. }
  117526. }
  117527. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117528. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117529. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117530. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117531. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117532. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117533. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117534. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117535. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117536. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117537. 973377.F, 913981.F, 858210.F, 805842.F,
  117538. 756669.F, 710497.F, 667142.F, 626433.F,
  117539. 588208.F, 552316.F, 518613.F, 486967.F,
  117540. 457252.F, 429351.F, 403152.F, 378551.F,
  117541. 355452.F, 333762.F, 313396.F, 294273.F,
  117542. 276316.F, 259455.F, 243623.F, 228757.F,
  117543. 214798.F, 201691.F, 189384.F, 177828.F,
  117544. 166977.F, 156788.F, 147221.F, 138237.F,
  117545. 129802.F, 121881.F, 114444.F, 107461.F,
  117546. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117547. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117548. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117549. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117550. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117551. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117552. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117553. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117554. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117555. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117556. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117557. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117558. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117559. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117560. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117561. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117562. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117563. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117564. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117565. 842.910F, 791.475F, 743.179F, 697.830F,
  117566. 655.249F, 615.265F, 577.722F, 542.469F,
  117567. 509.367F, 478.286F, 449.101F, 421.696F,
  117568. 395.964F, 371.803F, 349.115F, 327.812F,
  117569. 307.809F, 289.026F, 271.390F, 254.830F,
  117570. 239.280F, 224.679F, 210.969F, 198.096F,
  117571. 186.008F, 174.658F, 164.000F, 153.993F,
  117572. 144.596F, 135.773F, 127.488F, 119.708F,
  117573. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117574. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117575. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117576. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117577. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117578. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117579. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117580. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117581. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117582. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117583. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117584. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117585. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117586. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117587. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117588. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117589. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117590. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117591. 1.20790F, 1.13419F, 1.06499F, 1.F
  117592. };
  117593. void _vp_remove_floor(vorbis_look_psy *p,
  117594. float *mdct,
  117595. int *codedflr,
  117596. float *residue,
  117597. int sliding_lowpass){
  117598. int i,n=p->n;
  117599. if(sliding_lowpass>n)sliding_lowpass=n;
  117600. for(i=0;i<sliding_lowpass;i++){
  117601. residue[i]=
  117602. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117603. }
  117604. for(;i<n;i++)
  117605. residue[i]=0.;
  117606. }
  117607. void _vp_noisemask(vorbis_look_psy *p,
  117608. float *logmdct,
  117609. float *logmask){
  117610. int i,n=p->n;
  117611. float *work=(float*) alloca(n*sizeof(*work));
  117612. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117613. 140.,-1);
  117614. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117615. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117616. p->vi->noisewindowfixed);
  117617. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117618. #if 0
  117619. {
  117620. static int seq=0;
  117621. float work2[n];
  117622. for(i=0;i<n;i++){
  117623. work2[i]=logmask[i]+work[i];
  117624. }
  117625. if(seq&1)
  117626. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117627. else
  117628. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117629. if(seq&1)
  117630. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117631. else
  117632. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117633. seq++;
  117634. }
  117635. #endif
  117636. for(i=0;i<n;i++){
  117637. int dB=logmask[i]+.5;
  117638. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117639. if(dB<0)dB=0;
  117640. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117641. }
  117642. }
  117643. void _vp_tonemask(vorbis_look_psy *p,
  117644. float *logfft,
  117645. float *logmask,
  117646. float global_specmax,
  117647. float local_specmax){
  117648. int i,n=p->n;
  117649. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117650. float att=local_specmax+p->vi->ath_adjatt;
  117651. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117652. /* set the ATH (floating below localmax, not global max by a
  117653. specified att) */
  117654. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117655. for(i=0;i<n;i++)
  117656. logmask[i]=p->ath[i]+att;
  117657. /* tone masking */
  117658. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117659. max_seeds(p,seed,logmask);
  117660. }
  117661. void _vp_offset_and_mix(vorbis_look_psy *p,
  117662. float *noise,
  117663. float *tone,
  117664. int offset_select,
  117665. float *logmask,
  117666. float *mdct,
  117667. float *logmdct){
  117668. int i,n=p->n;
  117669. float de, coeffi, cx;/* AoTuV */
  117670. float toneatt=p->vi->tone_masteratt[offset_select];
  117671. cx = p->m_val;
  117672. for(i=0;i<n;i++){
  117673. float val= noise[i]+p->noiseoffset[offset_select][i];
  117674. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117675. logmask[i]=max(val,tone[i]+toneatt);
  117676. /* AoTuV */
  117677. /** @ M1 **
  117678. The following codes improve a noise problem.
  117679. A fundamental idea uses the value of masking and carries out
  117680. the relative compensation of the MDCT.
  117681. However, this code is not perfect and all noise problems cannot be solved.
  117682. by Aoyumi @ 2004/04/18
  117683. */
  117684. if(offset_select == 1) {
  117685. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117686. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117687. if(val > coeffi){
  117688. /* mdct value is > -17.2 dB below floor */
  117689. de = 1.0-((val-coeffi)*0.005*cx);
  117690. /* pro-rated attenuation:
  117691. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117692. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117693. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117694. etc... */
  117695. if(de < 0) de = 0.0001;
  117696. }else
  117697. /* mdct value is <= -17.2 dB below floor */
  117698. de = 1.0-((val-coeffi)*0.0003*cx);
  117699. /* pro-rated attenuation:
  117700. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117701. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117702. etc... */
  117703. mdct[i] *= de;
  117704. }
  117705. }
  117706. }
  117707. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117708. vorbis_info *vi=vd->vi;
  117709. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117710. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117711. int n=ci->blocksizes[vd->W]/2;
  117712. float secs=(float)n/vi->rate;
  117713. amp+=secs*gi->ampmax_att_per_sec;
  117714. if(amp<-9999)amp=-9999;
  117715. return(amp);
  117716. }
  117717. static void couple_lossless(float A, float B,
  117718. float *qA, float *qB){
  117719. int test1=fabs(*qA)>fabs(*qB);
  117720. test1-= fabs(*qA)<fabs(*qB);
  117721. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117722. if(test1==1){
  117723. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117724. }else{
  117725. float temp=*qB;
  117726. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117727. *qA=temp;
  117728. }
  117729. if(*qB>fabs(*qA)*1.9999f){
  117730. *qB= -fabs(*qA)*2.f;
  117731. *qA= -*qA;
  117732. }
  117733. }
  117734. static float hypot_lookup[32]={
  117735. -0.009935, -0.011245, -0.012726, -0.014397,
  117736. -0.016282, -0.018407, -0.020800, -0.023494,
  117737. -0.026522, -0.029923, -0.033737, -0.038010,
  117738. -0.042787, -0.048121, -0.054064, -0.060671,
  117739. -0.068000, -0.076109, -0.085054, -0.094892,
  117740. -0.105675, -0.117451, -0.130260, -0.144134,
  117741. -0.159093, -0.175146, -0.192286, -0.210490,
  117742. -0.229718, -0.249913, -0.271001, -0.292893};
  117743. static void precomputed_couple_point(float premag,
  117744. int floorA,int floorB,
  117745. float *mag, float *ang){
  117746. int test=(floorA>floorB)-1;
  117747. int offset=31-abs(floorA-floorB);
  117748. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117749. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117750. *mag=premag*floormag;
  117751. *ang=0.f;
  117752. }
  117753. /* just like below, this is currently set up to only do
  117754. single-step-depth coupling. Otherwise, we'd have to do more
  117755. copying (which will be inevitable later) */
  117756. /* doing the real circular magnitude calculation is audibly superior
  117757. to (A+B)/sqrt(2) */
  117758. static float dipole_hypot(float a, float b){
  117759. if(a>0.){
  117760. if(b>0.)return sqrt(a*a+b*b);
  117761. if(a>-b)return sqrt(a*a-b*b);
  117762. return -sqrt(b*b-a*a);
  117763. }
  117764. if(b<0.)return -sqrt(a*a+b*b);
  117765. if(-a>b)return -sqrt(a*a-b*b);
  117766. return sqrt(b*b-a*a);
  117767. }
  117768. static float round_hypot(float a, float b){
  117769. if(a>0.){
  117770. if(b>0.)return sqrt(a*a+b*b);
  117771. if(a>-b)return sqrt(a*a+b*b);
  117772. return -sqrt(b*b+a*a);
  117773. }
  117774. if(b<0.)return -sqrt(a*a+b*b);
  117775. if(-a>b)return -sqrt(a*a+b*b);
  117776. return sqrt(b*b+a*a);
  117777. }
  117778. /* revert to round hypot for now */
  117779. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117780. vorbis_info_psy_global *g,
  117781. vorbis_look_psy *p,
  117782. vorbis_info_mapping0 *vi,
  117783. float **mdct){
  117784. int i,j,n=p->n;
  117785. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117786. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117787. for(i=0;i<vi->coupling_steps;i++){
  117788. float *mdctM=mdct[vi->coupling_mag[i]];
  117789. float *mdctA=mdct[vi->coupling_ang[i]];
  117790. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117791. for(j=0;j<limit;j++)
  117792. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117793. for(;j<n;j++)
  117794. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117795. }
  117796. return(ret);
  117797. }
  117798. /* this is for per-channel noise normalization */
  117799. static int apsort(const void *a, const void *b){
  117800. float f1=fabs(**(float**)a);
  117801. float f2=fabs(**(float**)b);
  117802. return (f1<f2)-(f1>f2);
  117803. }
  117804. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117805. vorbis_look_psy *p,
  117806. vorbis_info_mapping0 *vi,
  117807. float **mags){
  117808. if(p->vi->normal_point_p){
  117809. int i,j,k,n=p->n;
  117810. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117811. int partition=p->vi->normal_partition;
  117812. float **work=(float**) alloca(sizeof(*work)*partition);
  117813. for(i=0;i<vi->coupling_steps;i++){
  117814. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117815. for(j=0;j<n;j+=partition){
  117816. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117817. qsort(work,partition,sizeof(*work),apsort);
  117818. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117819. }
  117820. }
  117821. return(ret);
  117822. }
  117823. return(NULL);
  117824. }
  117825. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117826. float *magnitudes,int *sortedindex){
  117827. int i,j,n=p->n;
  117828. vorbis_info_psy *vi=p->vi;
  117829. int partition=vi->normal_partition;
  117830. float **work=(float**) alloca(sizeof(*work)*partition);
  117831. int start=vi->normal_start;
  117832. for(j=start;j<n;j+=partition){
  117833. if(j+partition>n)partition=n-j;
  117834. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117835. qsort(work,partition,sizeof(*work),apsort);
  117836. for(i=0;i<partition;i++){
  117837. sortedindex[i+j-start]=work[i]-magnitudes;
  117838. }
  117839. }
  117840. }
  117841. void _vp_noise_normalize(vorbis_look_psy *p,
  117842. float *in,float *out,int *sortedindex){
  117843. int flag=0,i,j=0,n=p->n;
  117844. vorbis_info_psy *vi=p->vi;
  117845. int partition=vi->normal_partition;
  117846. int start=vi->normal_start;
  117847. if(start>n)start=n;
  117848. if(vi->normal_channel_p){
  117849. for(;j<start;j++)
  117850. out[j]=rint(in[j]);
  117851. for(;j+partition<=n;j+=partition){
  117852. float acc=0.;
  117853. int k;
  117854. for(i=j;i<j+partition;i++)
  117855. acc+=in[i]*in[i];
  117856. for(i=0;i<partition;i++){
  117857. k=sortedindex[i+j-start];
  117858. if(in[k]*in[k]>=.25f){
  117859. out[k]=rint(in[k]);
  117860. acc-=in[k]*in[k];
  117861. flag=1;
  117862. }else{
  117863. if(acc<vi->normal_thresh)break;
  117864. out[k]=unitnorm(in[k]);
  117865. acc-=1.;
  117866. }
  117867. }
  117868. for(;i<partition;i++){
  117869. k=sortedindex[i+j-start];
  117870. out[k]=0.;
  117871. }
  117872. }
  117873. }
  117874. for(;j<n;j++)
  117875. out[j]=rint(in[j]);
  117876. }
  117877. void _vp_couple(int blobno,
  117878. vorbis_info_psy_global *g,
  117879. vorbis_look_psy *p,
  117880. vorbis_info_mapping0 *vi,
  117881. float **res,
  117882. float **mag_memo,
  117883. int **mag_sort,
  117884. int **ifloor,
  117885. int *nonzero,
  117886. int sliding_lowpass){
  117887. int i,j,k,n=p->n;
  117888. /* perform any requested channel coupling */
  117889. /* point stereo can only be used in a first stage (in this encoder)
  117890. because of the dependency on floor lookups */
  117891. for(i=0;i<vi->coupling_steps;i++){
  117892. /* once we're doing multistage coupling in which a channel goes
  117893. through more than one coupling step, the floor vector
  117894. magnitudes will also have to be recalculated an propogated
  117895. along with PCM. Right now, we're not (that will wait until 5.1
  117896. most likely), so the code isn't here yet. The memory management
  117897. here is all assuming single depth couplings anyway. */
  117898. /* make sure coupling a zero and a nonzero channel results in two
  117899. nonzero channels. */
  117900. if(nonzero[vi->coupling_mag[i]] ||
  117901. nonzero[vi->coupling_ang[i]]){
  117902. float *rM=res[vi->coupling_mag[i]];
  117903. float *rA=res[vi->coupling_ang[i]];
  117904. float *qM=rM+n;
  117905. float *qA=rA+n;
  117906. int *floorM=ifloor[vi->coupling_mag[i]];
  117907. int *floorA=ifloor[vi->coupling_ang[i]];
  117908. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117909. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117910. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117911. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117912. int pointlimit=limit;
  117913. nonzero[vi->coupling_mag[i]]=1;
  117914. nonzero[vi->coupling_ang[i]]=1;
  117915. /* The threshold of a stereo is changed with the size of n */
  117916. if(n > 1000)
  117917. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117918. for(j=0;j<p->n;j+=partition){
  117919. float acc=0.f;
  117920. for(k=0;k<partition;k++){
  117921. int l=k+j;
  117922. if(l<sliding_lowpass){
  117923. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117924. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117925. precomputed_couple_point(mag_memo[i][l],
  117926. floorM[l],floorA[l],
  117927. qM+l,qA+l);
  117928. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117929. }else{
  117930. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117931. }
  117932. }else{
  117933. qM[l]=0.;
  117934. qA[l]=0.;
  117935. }
  117936. }
  117937. if(p->vi->normal_point_p){
  117938. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117939. int l=mag_sort[i][j+k];
  117940. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117941. qM[l]=unitnorm(qM[l]);
  117942. acc-=1.f;
  117943. }
  117944. }
  117945. }
  117946. }
  117947. }
  117948. }
  117949. }
  117950. /* AoTuV */
  117951. /** @ M2 **
  117952. The boost problem by the combination of noise normalization and point stereo is eased.
  117953. However, this is a temporary patch.
  117954. by Aoyumi @ 2004/04/18
  117955. */
  117956. void hf_reduction(vorbis_info_psy_global *g,
  117957. vorbis_look_psy *p,
  117958. vorbis_info_mapping0 *vi,
  117959. float **mdct){
  117960. int i,j,n=p->n, de=0.3*p->m_val;
  117961. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117962. for(i=0; i<vi->coupling_steps; i++){
  117963. /* for(j=start; j<limit; j++){} // ???*/
  117964. for(j=limit; j<n; j++)
  117965. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117966. }
  117967. }
  117968. #endif
  117969. /*** End of inlined file: psy.c ***/
  117970. /*** Start of inlined file: registry.c ***/
  117971. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117972. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117973. // tasks..
  117974. #if JUCE_MSVC
  117975. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117976. #endif
  117977. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117978. #if JUCE_USE_OGGVORBIS
  117979. /* seems like major overkill now; the backend numbers will grow into
  117980. the infrastructure soon enough */
  117981. extern vorbis_func_floor floor0_exportbundle;
  117982. extern vorbis_func_floor floor1_exportbundle;
  117983. extern vorbis_func_residue residue0_exportbundle;
  117984. extern vorbis_func_residue residue1_exportbundle;
  117985. extern vorbis_func_residue residue2_exportbundle;
  117986. extern vorbis_func_mapping mapping0_exportbundle;
  117987. vorbis_func_floor *_floor_P[]={
  117988. &floor0_exportbundle,
  117989. &floor1_exportbundle,
  117990. };
  117991. vorbis_func_residue *_residue_P[]={
  117992. &residue0_exportbundle,
  117993. &residue1_exportbundle,
  117994. &residue2_exportbundle,
  117995. };
  117996. vorbis_func_mapping *_mapping_P[]={
  117997. &mapping0_exportbundle,
  117998. };
  117999. #endif
  118000. /*** End of inlined file: registry.c ***/
  118001. /*** Start of inlined file: res0.c ***/
  118002. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118003. encode/decode loops are coded for clarity and performance is not
  118004. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118005. it's slow. */
  118006. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118007. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118008. // tasks..
  118009. #if JUCE_MSVC
  118010. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118011. #endif
  118012. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118013. #if JUCE_USE_OGGVORBIS
  118014. #include <stdlib.h>
  118015. #include <string.h>
  118016. #include <math.h>
  118017. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118018. #include <stdio.h>
  118019. #endif
  118020. typedef struct {
  118021. vorbis_info_residue0 *info;
  118022. int parts;
  118023. int stages;
  118024. codebook *fullbooks;
  118025. codebook *phrasebook;
  118026. codebook ***partbooks;
  118027. int partvals;
  118028. int **decodemap;
  118029. long postbits;
  118030. long phrasebits;
  118031. long frames;
  118032. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118033. int train_seq;
  118034. long *training_data[8][64];
  118035. float training_max[8][64];
  118036. float training_min[8][64];
  118037. float tmin;
  118038. float tmax;
  118039. #endif
  118040. } vorbis_look_residue0;
  118041. void res0_free_info(vorbis_info_residue *i){
  118042. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118043. if(info){
  118044. memset(info,0,sizeof(*info));
  118045. _ogg_free(info);
  118046. }
  118047. }
  118048. void res0_free_look(vorbis_look_residue *i){
  118049. int j;
  118050. if(i){
  118051. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118052. #ifdef TRAIN_RES
  118053. {
  118054. int j,k,l;
  118055. for(j=0;j<look->parts;j++){
  118056. /*fprintf(stderr,"partition %d: ",j);*/
  118057. for(k=0;k<8;k++)
  118058. if(look->training_data[k][j]){
  118059. char buffer[80];
  118060. FILE *of;
  118061. codebook *statebook=look->partbooks[j][k];
  118062. /* long and short into the same bucket by current convention */
  118063. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118064. of=fopen(buffer,"a");
  118065. for(l=0;l<statebook->entries;l++)
  118066. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118067. fclose(of);
  118068. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118069. look->training_min[k][j],look->training_max[k][j]);*/
  118070. _ogg_free(look->training_data[k][j]);
  118071. look->training_data[k][j]=NULL;
  118072. }
  118073. /*fprintf(stderr,"\n");*/
  118074. }
  118075. }
  118076. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118077. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118078. (float)look->phrasebits/look->frames,
  118079. (float)look->postbits/look->frames,
  118080. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118081. #endif
  118082. /*vorbis_info_residue0 *info=look->info;
  118083. fprintf(stderr,
  118084. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118085. "(%g/frame) \n",look->frames,look->phrasebits,
  118086. look->resbitsflat,
  118087. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118088. for(j=0;j<look->parts;j++){
  118089. long acc=0;
  118090. fprintf(stderr,"\t[%d] == ",j);
  118091. for(k=0;k<look->stages;k++)
  118092. if((info->secondstages[j]>>k)&1){
  118093. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118094. acc+=look->resbits[j][k];
  118095. }
  118096. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118097. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118098. }
  118099. fprintf(stderr,"\n");*/
  118100. for(j=0;j<look->parts;j++)
  118101. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118102. _ogg_free(look->partbooks);
  118103. for(j=0;j<look->partvals;j++)
  118104. _ogg_free(look->decodemap[j]);
  118105. _ogg_free(look->decodemap);
  118106. memset(look,0,sizeof(*look));
  118107. _ogg_free(look);
  118108. }
  118109. }
  118110. static int icount(unsigned int v){
  118111. int ret=0;
  118112. while(v){
  118113. ret+=v&1;
  118114. v>>=1;
  118115. }
  118116. return(ret);
  118117. }
  118118. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118119. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118120. int j,acc=0;
  118121. oggpack_write(opb,info->begin,24);
  118122. oggpack_write(opb,info->end,24);
  118123. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118124. code with a partitioned book */
  118125. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118126. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118127. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118128. bitmask of one indicates this partition class has bits to write
  118129. this pass */
  118130. for(j=0;j<info->partitions;j++){
  118131. if(ilog(info->secondstages[j])>3){
  118132. /* yes, this is a minor hack due to not thinking ahead */
  118133. oggpack_write(opb,info->secondstages[j],3);
  118134. oggpack_write(opb,1,1);
  118135. oggpack_write(opb,info->secondstages[j]>>3,5);
  118136. }else
  118137. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118138. acc+=icount(info->secondstages[j]);
  118139. }
  118140. for(j=0;j<acc;j++)
  118141. oggpack_write(opb,info->booklist[j],8);
  118142. }
  118143. /* vorbis_info is for range checking */
  118144. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118145. int j,acc=0;
  118146. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118147. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118148. info->begin=oggpack_read(opb,24);
  118149. info->end=oggpack_read(opb,24);
  118150. info->grouping=oggpack_read(opb,24)+1;
  118151. info->partitions=oggpack_read(opb,6)+1;
  118152. info->groupbook=oggpack_read(opb,8);
  118153. for(j=0;j<info->partitions;j++){
  118154. int cascade=oggpack_read(opb,3);
  118155. if(oggpack_read(opb,1))
  118156. cascade|=(oggpack_read(opb,5)<<3);
  118157. info->secondstages[j]=cascade;
  118158. acc+=icount(cascade);
  118159. }
  118160. for(j=0;j<acc;j++)
  118161. info->booklist[j]=oggpack_read(opb,8);
  118162. if(info->groupbook>=ci->books)goto errout;
  118163. for(j=0;j<acc;j++)
  118164. if(info->booklist[j]>=ci->books)goto errout;
  118165. return(info);
  118166. errout:
  118167. res0_free_info(info);
  118168. return(NULL);
  118169. }
  118170. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118171. vorbis_info_residue *vr){
  118172. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118173. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118174. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118175. int j,k,acc=0;
  118176. int dim;
  118177. int maxstage=0;
  118178. look->info=info;
  118179. look->parts=info->partitions;
  118180. look->fullbooks=ci->fullbooks;
  118181. look->phrasebook=ci->fullbooks+info->groupbook;
  118182. dim=look->phrasebook->dim;
  118183. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118184. for(j=0;j<look->parts;j++){
  118185. int stages=ilog(info->secondstages[j]);
  118186. if(stages){
  118187. if(stages>maxstage)maxstage=stages;
  118188. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118189. for(k=0;k<stages;k++)
  118190. if(info->secondstages[j]&(1<<k)){
  118191. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118192. #ifdef TRAIN_RES
  118193. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118194. sizeof(***look->training_data));
  118195. #endif
  118196. }
  118197. }
  118198. }
  118199. look->partvals=rint(pow((float)look->parts,(float)dim));
  118200. look->stages=maxstage;
  118201. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118202. for(j=0;j<look->partvals;j++){
  118203. long val=j;
  118204. long mult=look->partvals/look->parts;
  118205. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118206. for(k=0;k<dim;k++){
  118207. long deco=val/mult;
  118208. val-=deco*mult;
  118209. mult/=look->parts;
  118210. look->decodemap[j][k]=deco;
  118211. }
  118212. }
  118213. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118214. {
  118215. static int train_seq=0;
  118216. look->train_seq=train_seq++;
  118217. }
  118218. #endif
  118219. return(look);
  118220. }
  118221. /* break an abstraction and copy some code for performance purposes */
  118222. static int local_book_besterror(codebook *book,float *a){
  118223. int dim=book->dim,i,k,o;
  118224. int best=0;
  118225. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118226. /* find the quant val of each scalar */
  118227. for(k=0,o=dim;k<dim;++k){
  118228. float val=a[--o];
  118229. i=tt->threshvals>>1;
  118230. if(val<tt->quantthresh[i]){
  118231. if(val<tt->quantthresh[i-1]){
  118232. for(--i;i>0;--i)
  118233. if(val>=tt->quantthresh[i-1])
  118234. break;
  118235. }
  118236. }else{
  118237. for(++i;i<tt->threshvals-1;++i)
  118238. if(val<tt->quantthresh[i])break;
  118239. }
  118240. best=(best*tt->quantvals)+tt->quantmap[i];
  118241. }
  118242. /* regular lattices are easy :-) */
  118243. if(book->c->lengthlist[best]<=0){
  118244. const static_codebook *c=book->c;
  118245. int i,j;
  118246. float bestf=0.f;
  118247. float *e=book->valuelist;
  118248. best=-1;
  118249. for(i=0;i<book->entries;i++){
  118250. if(c->lengthlist[i]>0){
  118251. float thisx=0.f;
  118252. for(j=0;j<dim;j++){
  118253. float val=(e[j]-a[j]);
  118254. thisx+=val*val;
  118255. }
  118256. if(best==-1 || thisx<bestf){
  118257. bestf=thisx;
  118258. best=i;
  118259. }
  118260. }
  118261. e+=dim;
  118262. }
  118263. }
  118264. {
  118265. float *ptr=book->valuelist+best*dim;
  118266. for(i=0;i<dim;i++)
  118267. *a++ -= *ptr++;
  118268. }
  118269. return(best);
  118270. }
  118271. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118272. codebook *book,long *acc){
  118273. int i,bits=0;
  118274. int dim=book->dim;
  118275. int step=n/dim;
  118276. for(i=0;i<step;i++){
  118277. int entry=local_book_besterror(book,vec+i*dim);
  118278. #ifdef TRAIN_RES
  118279. acc[entry]++;
  118280. #endif
  118281. bits+=vorbis_book_encode(book,entry,opb);
  118282. }
  118283. return(bits);
  118284. }
  118285. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118286. float **in,int ch){
  118287. long i,j,k;
  118288. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118289. vorbis_info_residue0 *info=look->info;
  118290. /* move all this setup out later */
  118291. int samples_per_partition=info->grouping;
  118292. int possible_partitions=info->partitions;
  118293. int n=info->end-info->begin;
  118294. int partvals=n/samples_per_partition;
  118295. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118296. float scale=100./samples_per_partition;
  118297. /* we find the partition type for each partition of each
  118298. channel. We'll go back and do the interleaved encoding in a
  118299. bit. For now, clarity */
  118300. for(i=0;i<ch;i++){
  118301. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118302. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118303. }
  118304. for(i=0;i<partvals;i++){
  118305. int offset=i*samples_per_partition+info->begin;
  118306. for(j=0;j<ch;j++){
  118307. float max=0.;
  118308. float ent=0.;
  118309. for(k=0;k<samples_per_partition;k++){
  118310. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118311. ent+=fabs(rint(in[j][offset+k]));
  118312. }
  118313. ent*=scale;
  118314. for(k=0;k<possible_partitions-1;k++)
  118315. if(max<=info->classmetric1[k] &&
  118316. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118317. break;
  118318. partword[j][i]=k;
  118319. }
  118320. }
  118321. #ifdef TRAIN_RESAUX
  118322. {
  118323. FILE *of;
  118324. char buffer[80];
  118325. for(i=0;i<ch;i++){
  118326. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118327. of=fopen(buffer,"a");
  118328. for(j=0;j<partvals;j++)
  118329. fprintf(of,"%ld, ",partword[i][j]);
  118330. fprintf(of,"\n");
  118331. fclose(of);
  118332. }
  118333. }
  118334. #endif
  118335. look->frames++;
  118336. return(partword);
  118337. }
  118338. /* designed for stereo or other modes where the partition size is an
  118339. integer multiple of the number of channels encoded in the current
  118340. submap */
  118341. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118342. int ch){
  118343. long i,j,k,l;
  118344. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118345. vorbis_info_residue0 *info=look->info;
  118346. /* move all this setup out later */
  118347. int samples_per_partition=info->grouping;
  118348. int possible_partitions=info->partitions;
  118349. int n=info->end-info->begin;
  118350. int partvals=n/samples_per_partition;
  118351. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118352. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118353. FILE *of;
  118354. char buffer[80];
  118355. #endif
  118356. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118357. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118358. for(i=0,l=info->begin/ch;i<partvals;i++){
  118359. float magmax=0.f;
  118360. float angmax=0.f;
  118361. for(j=0;j<samples_per_partition;j+=ch){
  118362. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118363. for(k=1;k<ch;k++)
  118364. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118365. l++;
  118366. }
  118367. for(j=0;j<possible_partitions-1;j++)
  118368. if(magmax<=info->classmetric1[j] &&
  118369. angmax<=info->classmetric2[j])
  118370. break;
  118371. partword[0][i]=j;
  118372. }
  118373. #ifdef TRAIN_RESAUX
  118374. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118375. of=fopen(buffer,"a");
  118376. for(i=0;i<partvals;i++)
  118377. fprintf(of,"%ld, ",partword[0][i]);
  118378. fprintf(of,"\n");
  118379. fclose(of);
  118380. #endif
  118381. look->frames++;
  118382. return(partword);
  118383. }
  118384. static int _01forward(oggpack_buffer *opb,
  118385. vorbis_block *vb,vorbis_look_residue *vl,
  118386. float **in,int ch,
  118387. long **partword,
  118388. int (*encode)(oggpack_buffer *,float *,int,
  118389. codebook *,long *)){
  118390. long i,j,k,s;
  118391. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118392. vorbis_info_residue0 *info=look->info;
  118393. /* move all this setup out later */
  118394. int samples_per_partition=info->grouping;
  118395. int possible_partitions=info->partitions;
  118396. int partitions_per_word=look->phrasebook->dim;
  118397. int n=info->end-info->begin;
  118398. int partvals=n/samples_per_partition;
  118399. long resbits[128];
  118400. long resvals[128];
  118401. #ifdef TRAIN_RES
  118402. for(i=0;i<ch;i++)
  118403. for(j=info->begin;j<info->end;j++){
  118404. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118405. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118406. }
  118407. #endif
  118408. memset(resbits,0,sizeof(resbits));
  118409. memset(resvals,0,sizeof(resvals));
  118410. /* we code the partition words for each channel, then the residual
  118411. words for a partition per channel until we've written all the
  118412. residual words for that partition word. Then write the next
  118413. partition channel words... */
  118414. for(s=0;s<look->stages;s++){
  118415. for(i=0;i<partvals;){
  118416. /* first we encode a partition codeword for each channel */
  118417. if(s==0){
  118418. for(j=0;j<ch;j++){
  118419. long val=partword[j][i];
  118420. for(k=1;k<partitions_per_word;k++){
  118421. val*=possible_partitions;
  118422. if(i+k<partvals)
  118423. val+=partword[j][i+k];
  118424. }
  118425. /* training hack */
  118426. if(val<look->phrasebook->entries)
  118427. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118428. #if 0 /*def TRAIN_RES*/
  118429. else
  118430. fprintf(stderr,"!");
  118431. #endif
  118432. }
  118433. }
  118434. /* now we encode interleaved residual values for the partitions */
  118435. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118436. long offset=i*samples_per_partition+info->begin;
  118437. for(j=0;j<ch;j++){
  118438. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118439. if(info->secondstages[partword[j][i]]&(1<<s)){
  118440. codebook *statebook=look->partbooks[partword[j][i]][s];
  118441. if(statebook){
  118442. int ret;
  118443. long *accumulator=NULL;
  118444. #ifdef TRAIN_RES
  118445. accumulator=look->training_data[s][partword[j][i]];
  118446. {
  118447. int l;
  118448. float *samples=in[j]+offset;
  118449. for(l=0;l<samples_per_partition;l++){
  118450. if(samples[l]<look->training_min[s][partword[j][i]])
  118451. look->training_min[s][partword[j][i]]=samples[l];
  118452. if(samples[l]>look->training_max[s][partword[j][i]])
  118453. look->training_max[s][partword[j][i]]=samples[l];
  118454. }
  118455. }
  118456. #endif
  118457. ret=encode(opb,in[j]+offset,samples_per_partition,
  118458. statebook,accumulator);
  118459. look->postbits+=ret;
  118460. resbits[partword[j][i]]+=ret;
  118461. }
  118462. }
  118463. }
  118464. }
  118465. }
  118466. }
  118467. /*{
  118468. long total=0;
  118469. long totalbits=0;
  118470. fprintf(stderr,"%d :: ",vb->mode);
  118471. for(k=0;k<possible_partitions;k++){
  118472. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118473. total+=resvals[k];
  118474. totalbits+=resbits[k];
  118475. }
  118476. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118477. }*/
  118478. return(0);
  118479. }
  118480. /* a truncated packet here just means 'stop working'; it's not an error */
  118481. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118482. float **in,int ch,
  118483. long (*decodepart)(codebook *, float *,
  118484. oggpack_buffer *,int)){
  118485. long i,j,k,l,s;
  118486. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118487. vorbis_info_residue0 *info=look->info;
  118488. /* move all this setup out later */
  118489. int samples_per_partition=info->grouping;
  118490. int partitions_per_word=look->phrasebook->dim;
  118491. int n=info->end-info->begin;
  118492. int partvals=n/samples_per_partition;
  118493. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118494. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118495. for(j=0;j<ch;j++)
  118496. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118497. for(s=0;s<look->stages;s++){
  118498. /* each loop decodes on partition codeword containing
  118499. partitions_pre_word partitions */
  118500. for(i=0,l=0;i<partvals;l++){
  118501. if(s==0){
  118502. /* fetch the partition word for each channel */
  118503. for(j=0;j<ch;j++){
  118504. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118505. if(temp==-1)goto eopbreak;
  118506. partword[j][l]=look->decodemap[temp];
  118507. if(partword[j][l]==NULL)goto errout;
  118508. }
  118509. }
  118510. /* now we decode residual values for the partitions */
  118511. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118512. for(j=0;j<ch;j++){
  118513. long offset=info->begin+i*samples_per_partition;
  118514. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118515. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118516. if(stagebook){
  118517. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118518. samples_per_partition)==-1)goto eopbreak;
  118519. }
  118520. }
  118521. }
  118522. }
  118523. }
  118524. errout:
  118525. eopbreak:
  118526. return(0);
  118527. }
  118528. #if 0
  118529. /* residue 0 and 1 are just slight variants of one another. 0 is
  118530. interleaved, 1 is not */
  118531. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118532. float **in,int *nonzero,int ch){
  118533. /* we encode only the nonzero parts of a bundle */
  118534. int i,used=0;
  118535. for(i=0;i<ch;i++)
  118536. if(nonzero[i])
  118537. in[used++]=in[i];
  118538. if(used)
  118539. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118540. return(_01class(vb,vl,in,used));
  118541. else
  118542. return(0);
  118543. }
  118544. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118545. float **in,float **out,int *nonzero,int ch,
  118546. long **partword){
  118547. /* we encode only the nonzero parts of a bundle */
  118548. int i,j,used=0,n=vb->pcmend/2;
  118549. for(i=0;i<ch;i++)
  118550. if(nonzero[i]){
  118551. if(out)
  118552. for(j=0;j<n;j++)
  118553. out[i][j]+=in[i][j];
  118554. in[used++]=in[i];
  118555. }
  118556. if(used){
  118557. int ret=_01forward(vb,vl,in,used,partword,
  118558. _interleaved_encodepart);
  118559. if(out){
  118560. used=0;
  118561. for(i=0;i<ch;i++)
  118562. if(nonzero[i]){
  118563. for(j=0;j<n;j++)
  118564. out[i][j]-=in[used][j];
  118565. used++;
  118566. }
  118567. }
  118568. return(ret);
  118569. }else{
  118570. return(0);
  118571. }
  118572. }
  118573. #endif
  118574. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118575. float **in,int *nonzero,int ch){
  118576. int i,used=0;
  118577. for(i=0;i<ch;i++)
  118578. if(nonzero[i])
  118579. in[used++]=in[i];
  118580. if(used)
  118581. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118582. else
  118583. return(0);
  118584. }
  118585. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118586. float **in,float **out,int *nonzero,int ch,
  118587. long **partword){
  118588. int i,j,used=0,n=vb->pcmend/2;
  118589. for(i=0;i<ch;i++)
  118590. if(nonzero[i]){
  118591. if(out)
  118592. for(j=0;j<n;j++)
  118593. out[i][j]+=in[i][j];
  118594. in[used++]=in[i];
  118595. }
  118596. if(used){
  118597. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118598. if(out){
  118599. used=0;
  118600. for(i=0;i<ch;i++)
  118601. if(nonzero[i]){
  118602. for(j=0;j<n;j++)
  118603. out[i][j]-=in[used][j];
  118604. used++;
  118605. }
  118606. }
  118607. return(ret);
  118608. }else{
  118609. return(0);
  118610. }
  118611. }
  118612. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118613. float **in,int *nonzero,int ch){
  118614. int i,used=0;
  118615. for(i=0;i<ch;i++)
  118616. if(nonzero[i])
  118617. in[used++]=in[i];
  118618. if(used)
  118619. return(_01class(vb,vl,in,used));
  118620. else
  118621. return(0);
  118622. }
  118623. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118624. float **in,int *nonzero,int ch){
  118625. int i,used=0;
  118626. for(i=0;i<ch;i++)
  118627. if(nonzero[i])
  118628. in[used++]=in[i];
  118629. if(used)
  118630. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118631. else
  118632. return(0);
  118633. }
  118634. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118635. float **in,int *nonzero,int ch){
  118636. int i,used=0;
  118637. for(i=0;i<ch;i++)
  118638. if(nonzero[i])used++;
  118639. if(used)
  118640. return(_2class(vb,vl,in,ch));
  118641. else
  118642. return(0);
  118643. }
  118644. /* res2 is slightly more different; all the channels are interleaved
  118645. into a single vector and encoded. */
  118646. int res2_forward(oggpack_buffer *opb,
  118647. vorbis_block *vb,vorbis_look_residue *vl,
  118648. float **in,float **out,int *nonzero,int ch,
  118649. long **partword){
  118650. long i,j,k,n=vb->pcmend/2,used=0;
  118651. /* don't duplicate the code; use a working vector hack for now and
  118652. reshape ourselves into a single channel res1 */
  118653. /* ugly; reallocs for each coupling pass :-( */
  118654. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118655. for(i=0;i<ch;i++){
  118656. float *pcm=in[i];
  118657. if(nonzero[i])used++;
  118658. for(j=0,k=i;j<n;j++,k+=ch)
  118659. work[k]=pcm[j];
  118660. }
  118661. if(used){
  118662. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118663. /* update the sofar vector */
  118664. if(out){
  118665. for(i=0;i<ch;i++){
  118666. float *pcm=in[i];
  118667. float *sofar=out[i];
  118668. for(j=0,k=i;j<n;j++,k+=ch)
  118669. sofar[j]+=pcm[j]-work[k];
  118670. }
  118671. }
  118672. return(ret);
  118673. }else{
  118674. return(0);
  118675. }
  118676. }
  118677. /* duplicate code here as speed is somewhat more important */
  118678. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118679. float **in,int *nonzero,int ch){
  118680. long i,k,l,s;
  118681. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118682. vorbis_info_residue0 *info=look->info;
  118683. /* move all this setup out later */
  118684. int samples_per_partition=info->grouping;
  118685. int partitions_per_word=look->phrasebook->dim;
  118686. int n=info->end-info->begin;
  118687. int partvals=n/samples_per_partition;
  118688. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118689. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118690. for(i=0;i<ch;i++)if(nonzero[i])break;
  118691. if(i==ch)return(0); /* no nonzero vectors */
  118692. for(s=0;s<look->stages;s++){
  118693. for(i=0,l=0;i<partvals;l++){
  118694. if(s==0){
  118695. /* fetch the partition word */
  118696. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118697. if(temp==-1)goto eopbreak;
  118698. partword[l]=look->decodemap[temp];
  118699. if(partword[l]==NULL)goto errout;
  118700. }
  118701. /* now we decode residual values for the partitions */
  118702. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118703. if(info->secondstages[partword[l][k]]&(1<<s)){
  118704. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118705. if(stagebook){
  118706. if(vorbis_book_decodevv_add(stagebook,in,
  118707. i*samples_per_partition+info->begin,ch,
  118708. &vb->opb,samples_per_partition)==-1)
  118709. goto eopbreak;
  118710. }
  118711. }
  118712. }
  118713. }
  118714. errout:
  118715. eopbreak:
  118716. return(0);
  118717. }
  118718. vorbis_func_residue residue0_exportbundle={
  118719. NULL,
  118720. &res0_unpack,
  118721. &res0_look,
  118722. &res0_free_info,
  118723. &res0_free_look,
  118724. NULL,
  118725. NULL,
  118726. &res0_inverse
  118727. };
  118728. vorbis_func_residue residue1_exportbundle={
  118729. &res0_pack,
  118730. &res0_unpack,
  118731. &res0_look,
  118732. &res0_free_info,
  118733. &res0_free_look,
  118734. &res1_class,
  118735. &res1_forward,
  118736. &res1_inverse
  118737. };
  118738. vorbis_func_residue residue2_exportbundle={
  118739. &res0_pack,
  118740. &res0_unpack,
  118741. &res0_look,
  118742. &res0_free_info,
  118743. &res0_free_look,
  118744. &res2_class,
  118745. &res2_forward,
  118746. &res2_inverse
  118747. };
  118748. #endif
  118749. /*** End of inlined file: res0.c ***/
  118750. /*** Start of inlined file: sharedbook.c ***/
  118751. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118752. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118753. // tasks..
  118754. #if JUCE_MSVC
  118755. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118756. #endif
  118757. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118758. #if JUCE_USE_OGGVORBIS
  118759. #include <stdlib.h>
  118760. #include <math.h>
  118761. #include <string.h>
  118762. /**** pack/unpack helpers ******************************************/
  118763. int _ilog(unsigned int v){
  118764. int ret=0;
  118765. while(v){
  118766. ret++;
  118767. v>>=1;
  118768. }
  118769. return(ret);
  118770. }
  118771. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118772. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118773. Why not IEEE? It's just not that important here. */
  118774. #define VQ_FEXP 10
  118775. #define VQ_FMAN 21
  118776. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118777. /* doesn't currently guard under/overflow */
  118778. long _float32_pack(float val){
  118779. int sign=0;
  118780. long exp;
  118781. long mant;
  118782. if(val<0){
  118783. sign=0x80000000;
  118784. val= -val;
  118785. }
  118786. exp= floor(log(val)/log(2.f));
  118787. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118788. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118789. return(sign|exp|mant);
  118790. }
  118791. float _float32_unpack(long val){
  118792. double mant=val&0x1fffff;
  118793. int sign=val&0x80000000;
  118794. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118795. if(sign)mant= -mant;
  118796. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118797. }
  118798. /* given a list of word lengths, generate a list of codewords. Works
  118799. for length ordered or unordered, always assigns the lowest valued
  118800. codewords first. Extended to handle unused entries (length 0) */
  118801. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118802. long i,j,count=0;
  118803. ogg_uint32_t marker[33];
  118804. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118805. memset(marker,0,sizeof(marker));
  118806. for(i=0;i<n;i++){
  118807. long length=l[i];
  118808. if(length>0){
  118809. ogg_uint32_t entry=marker[length];
  118810. /* when we claim a node for an entry, we also claim the nodes
  118811. below it (pruning off the imagined tree that may have dangled
  118812. from it) as well as blocking the use of any nodes directly
  118813. above for leaves */
  118814. /* update ourself */
  118815. if(length<32 && (entry>>length)){
  118816. /* error condition; the lengths must specify an overpopulated tree */
  118817. _ogg_free(r);
  118818. return(NULL);
  118819. }
  118820. r[count++]=entry;
  118821. /* Look to see if the next shorter marker points to the node
  118822. above. if so, update it and repeat. */
  118823. {
  118824. for(j=length;j>0;j--){
  118825. if(marker[j]&1){
  118826. /* have to jump branches */
  118827. if(j==1)
  118828. marker[1]++;
  118829. else
  118830. marker[j]=marker[j-1]<<1;
  118831. break; /* invariant says next upper marker would already
  118832. have been moved if it was on the same path */
  118833. }
  118834. marker[j]++;
  118835. }
  118836. }
  118837. /* prune the tree; the implicit invariant says all the longer
  118838. markers were dangling from our just-taken node. Dangle them
  118839. from our *new* node. */
  118840. for(j=length+1;j<33;j++)
  118841. if((marker[j]>>1) == entry){
  118842. entry=marker[j];
  118843. marker[j]=marker[j-1]<<1;
  118844. }else
  118845. break;
  118846. }else
  118847. if(sparsecount==0)count++;
  118848. }
  118849. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118850. endian */
  118851. for(i=0,count=0;i<n;i++){
  118852. ogg_uint32_t temp=0;
  118853. for(j=0;j<l[i];j++){
  118854. temp<<=1;
  118855. temp|=(r[count]>>j)&1;
  118856. }
  118857. if(sparsecount){
  118858. if(l[i])
  118859. r[count++]=temp;
  118860. }else
  118861. r[count++]=temp;
  118862. }
  118863. return(r);
  118864. }
  118865. /* there might be a straightforward one-line way to do the below
  118866. that's portable and totally safe against roundoff, but I haven't
  118867. thought of it. Therefore, we opt on the side of caution */
  118868. long _book_maptype1_quantvals(const static_codebook *b){
  118869. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118870. /* the above *should* be reliable, but we'll not assume that FP is
  118871. ever reliable when bitstream sync is at stake; verify via integer
  118872. means that vals really is the greatest value of dim for which
  118873. vals^b->bim <= b->entries */
  118874. /* treat the above as an initial guess */
  118875. while(1){
  118876. long acc=1;
  118877. long acc1=1;
  118878. int i;
  118879. for(i=0;i<b->dim;i++){
  118880. acc*=vals;
  118881. acc1*=vals+1;
  118882. }
  118883. if(acc<=b->entries && acc1>b->entries){
  118884. return(vals);
  118885. }else{
  118886. if(acc>b->entries){
  118887. vals--;
  118888. }else{
  118889. vals++;
  118890. }
  118891. }
  118892. }
  118893. }
  118894. /* unpack the quantized list of values for encode/decode ***********/
  118895. /* we need to deal with two map types: in map type 1, the values are
  118896. generated algorithmically (each column of the vector counts through
  118897. the values in the quant vector). in map type 2, all the values came
  118898. in in an explicit list. Both value lists must be unpacked */
  118899. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118900. long j,k,count=0;
  118901. if(b->maptype==1 || b->maptype==2){
  118902. int quantvals;
  118903. float mindel=_float32_unpack(b->q_min);
  118904. float delta=_float32_unpack(b->q_delta);
  118905. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118906. /* maptype 1 and 2 both use a quantized value vector, but
  118907. different sizes */
  118908. switch(b->maptype){
  118909. case 1:
  118910. /* most of the time, entries%dimensions == 0, but we need to be
  118911. well defined. We define that the possible vales at each
  118912. scalar is values == entries/dim. If entries%dim != 0, we'll
  118913. have 'too few' values (values*dim<entries), which means that
  118914. we'll have 'left over' entries; left over entries use zeroed
  118915. values (and are wasted). So don't generate codebooks like
  118916. that */
  118917. quantvals=_book_maptype1_quantvals(b);
  118918. for(j=0;j<b->entries;j++){
  118919. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118920. float last=0.f;
  118921. int indexdiv=1;
  118922. for(k=0;k<b->dim;k++){
  118923. int index= (j/indexdiv)%quantvals;
  118924. float val=b->quantlist[index];
  118925. val=fabs(val)*delta+mindel+last;
  118926. if(b->q_sequencep)last=val;
  118927. if(sparsemap)
  118928. r[sparsemap[count]*b->dim+k]=val;
  118929. else
  118930. r[count*b->dim+k]=val;
  118931. indexdiv*=quantvals;
  118932. }
  118933. count++;
  118934. }
  118935. }
  118936. break;
  118937. case 2:
  118938. for(j=0;j<b->entries;j++){
  118939. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118940. float last=0.f;
  118941. for(k=0;k<b->dim;k++){
  118942. float val=b->quantlist[j*b->dim+k];
  118943. val=fabs(val)*delta+mindel+last;
  118944. if(b->q_sequencep)last=val;
  118945. if(sparsemap)
  118946. r[sparsemap[count]*b->dim+k]=val;
  118947. else
  118948. r[count*b->dim+k]=val;
  118949. }
  118950. count++;
  118951. }
  118952. }
  118953. break;
  118954. }
  118955. return(r);
  118956. }
  118957. return(NULL);
  118958. }
  118959. void vorbis_staticbook_clear(static_codebook *b){
  118960. if(b->allocedp){
  118961. if(b->quantlist)_ogg_free(b->quantlist);
  118962. if(b->lengthlist)_ogg_free(b->lengthlist);
  118963. if(b->nearest_tree){
  118964. _ogg_free(b->nearest_tree->ptr0);
  118965. _ogg_free(b->nearest_tree->ptr1);
  118966. _ogg_free(b->nearest_tree->p);
  118967. _ogg_free(b->nearest_tree->q);
  118968. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118969. _ogg_free(b->nearest_tree);
  118970. }
  118971. if(b->thresh_tree){
  118972. _ogg_free(b->thresh_tree->quantthresh);
  118973. _ogg_free(b->thresh_tree->quantmap);
  118974. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118975. _ogg_free(b->thresh_tree);
  118976. }
  118977. memset(b,0,sizeof(*b));
  118978. }
  118979. }
  118980. void vorbis_staticbook_destroy(static_codebook *b){
  118981. if(b->allocedp){
  118982. vorbis_staticbook_clear(b);
  118983. _ogg_free(b);
  118984. }
  118985. }
  118986. void vorbis_book_clear(codebook *b){
  118987. /* static book is not cleared; we're likely called on the lookup and
  118988. the static codebook belongs to the info struct */
  118989. if(b->valuelist)_ogg_free(b->valuelist);
  118990. if(b->codelist)_ogg_free(b->codelist);
  118991. if(b->dec_index)_ogg_free(b->dec_index);
  118992. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118993. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118994. memset(b,0,sizeof(*b));
  118995. }
  118996. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118997. memset(c,0,sizeof(*c));
  118998. c->c=s;
  118999. c->entries=s->entries;
  119000. c->used_entries=s->entries;
  119001. c->dim=s->dim;
  119002. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119003. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119004. return(0);
  119005. }
  119006. static int sort32a(const void *a,const void *b){
  119007. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119008. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119009. }
  119010. /* decode codebook arrangement is more heavily optimized than encode */
  119011. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119012. int i,j,n=0,tabn;
  119013. int *sortindex;
  119014. memset(c,0,sizeof(*c));
  119015. /* count actually used entries */
  119016. for(i=0;i<s->entries;i++)
  119017. if(s->lengthlist[i]>0)
  119018. n++;
  119019. c->entries=s->entries;
  119020. c->used_entries=n;
  119021. c->dim=s->dim;
  119022. /* two different remappings go on here.
  119023. First, we collapse the likely sparse codebook down only to
  119024. actually represented values/words. This collapsing needs to be
  119025. indexed as map-valueless books are used to encode original entry
  119026. positions as integers.
  119027. Second, we reorder all vectors, including the entry index above,
  119028. by sorted bitreversed codeword to allow treeless decode. */
  119029. {
  119030. /* perform sort */
  119031. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119032. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119033. if(codes==NULL)goto err_out;
  119034. for(i=0;i<n;i++){
  119035. codes[i]=ogg_bitreverse(codes[i]);
  119036. codep[i]=codes+i;
  119037. }
  119038. qsort(codep,n,sizeof(*codep),sort32a);
  119039. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119040. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119041. /* the index is a reverse index */
  119042. for(i=0;i<n;i++){
  119043. int position=codep[i]-codes;
  119044. sortindex[position]=i;
  119045. }
  119046. for(i=0;i<n;i++)
  119047. c->codelist[sortindex[i]]=codes[i];
  119048. _ogg_free(codes);
  119049. }
  119050. c->valuelist=_book_unquantize(s,n,sortindex);
  119051. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119052. for(n=0,i=0;i<s->entries;i++)
  119053. if(s->lengthlist[i]>0)
  119054. c->dec_index[sortindex[n++]]=i;
  119055. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119056. for(n=0,i=0;i<s->entries;i++)
  119057. if(s->lengthlist[i]>0)
  119058. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119059. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119060. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119061. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119062. tabn=1<<c->dec_firsttablen;
  119063. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119064. c->dec_maxlength=0;
  119065. for(i=0;i<n;i++){
  119066. if(c->dec_maxlength<c->dec_codelengths[i])
  119067. c->dec_maxlength=c->dec_codelengths[i];
  119068. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119069. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119070. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119071. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119072. }
  119073. }
  119074. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119075. hints for the non-direct-hits */
  119076. {
  119077. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119078. long lo=0,hi=0;
  119079. for(i=0;i<tabn;i++){
  119080. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119081. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119082. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119083. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119084. /* we only actually have 15 bits per hint to play with here.
  119085. In order to overflow gracefully (nothing breaks, efficiency
  119086. just drops), encode as the difference from the extremes. */
  119087. {
  119088. unsigned long loval=lo;
  119089. unsigned long hival=n-hi;
  119090. if(loval>0x7fff)loval=0x7fff;
  119091. if(hival>0x7fff)hival=0x7fff;
  119092. c->dec_firsttable[ogg_bitreverse(word)]=
  119093. 0x80000000UL | (loval<<15) | hival;
  119094. }
  119095. }
  119096. }
  119097. }
  119098. return(0);
  119099. err_out:
  119100. vorbis_book_clear(c);
  119101. return(-1);
  119102. }
  119103. static float _dist(int el,float *ref, float *b,int step){
  119104. int i;
  119105. float acc=0.f;
  119106. for(i=0;i<el;i++){
  119107. float val=(ref[i]-b[i*step]);
  119108. acc+=val*val;
  119109. }
  119110. return(acc);
  119111. }
  119112. int _best(codebook *book, float *a, int step){
  119113. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119114. #if 0
  119115. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119116. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119117. #endif
  119118. int dim=book->dim;
  119119. int k,o;
  119120. /*int savebest=-1;
  119121. float saverr;*/
  119122. /* do we have a threshhold encode hint? */
  119123. if(tt){
  119124. int index=0,i;
  119125. /* find the quant val of each scalar */
  119126. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119127. i=tt->threshvals>>1;
  119128. if(a[o]<tt->quantthresh[i]){
  119129. for(;i>0;i--)
  119130. if(a[o]>=tt->quantthresh[i-1])
  119131. break;
  119132. }else{
  119133. for(i++;i<tt->threshvals-1;i++)
  119134. if(a[o]<tt->quantthresh[i])break;
  119135. }
  119136. index=(index*tt->quantvals)+tt->quantmap[i];
  119137. }
  119138. /* regular lattices are easy :-) */
  119139. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119140. use a decision tree after all
  119141. and fall through*/
  119142. return(index);
  119143. }
  119144. #if 0
  119145. /* do we have a pigeonhole encode hint? */
  119146. if(pt){
  119147. const static_codebook *c=book->c;
  119148. int i,besti=-1;
  119149. float best=0.f;
  119150. int entry=0;
  119151. /* dealing with sequentialness is a pain in the ass */
  119152. if(c->q_sequencep){
  119153. int pv;
  119154. long mul=1;
  119155. float qlast=0;
  119156. for(k=0,o=0;k<dim;k++,o+=step){
  119157. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119158. if(pv<0 || pv>=pt->mapentries)break;
  119159. entry+=pt->pigeonmap[pv]*mul;
  119160. mul*=pt->quantvals;
  119161. qlast+=pv*pt->del+pt->min;
  119162. }
  119163. }else{
  119164. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119165. int pv=(int)((a[o]-pt->min)/pt->del);
  119166. if(pv<0 || pv>=pt->mapentries)break;
  119167. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119168. }
  119169. }
  119170. /* must be within the pigeonholable range; if we quant outside (or
  119171. in an entry that we define no list for), brute force it */
  119172. if(k==dim && pt->fitlength[entry]){
  119173. /* search the abbreviated list */
  119174. long *list=pt->fitlist+pt->fitmap[entry];
  119175. for(i=0;i<pt->fitlength[entry];i++){
  119176. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119177. if(besti==-1 || this<best){
  119178. best=this;
  119179. besti=list[i];
  119180. }
  119181. }
  119182. return(besti);
  119183. }
  119184. }
  119185. if(nt){
  119186. /* optimized using the decision tree */
  119187. while(1){
  119188. float c=0.f;
  119189. float *p=book->valuelist+nt->p[ptr];
  119190. float *q=book->valuelist+nt->q[ptr];
  119191. for(k=0,o=0;k<dim;k++,o+=step)
  119192. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119193. if(c>0.f) /* in A */
  119194. ptr= -nt->ptr0[ptr];
  119195. else /* in B */
  119196. ptr= -nt->ptr1[ptr];
  119197. if(ptr<=0)break;
  119198. }
  119199. return(-ptr);
  119200. }
  119201. #endif
  119202. /* brute force it! */
  119203. {
  119204. const static_codebook *c=book->c;
  119205. int i,besti=-1;
  119206. float best=0.f;
  119207. float *e=book->valuelist;
  119208. for(i=0;i<book->entries;i++){
  119209. if(c->lengthlist[i]>0){
  119210. float thisx=_dist(dim,e,a,step);
  119211. if(besti==-1 || thisx<best){
  119212. best=thisx;
  119213. besti=i;
  119214. }
  119215. }
  119216. e+=dim;
  119217. }
  119218. /*if(savebest!=-1 && savebest!=besti){
  119219. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119220. "original:");
  119221. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119222. fprintf(stderr,"\n"
  119223. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119224. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119225. (book->valuelist+savebest*dim)[i]);
  119226. fprintf(stderr,"\n"
  119227. "bruteforce (entry %d, err %g):",besti,best);
  119228. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119229. (book->valuelist+besti*dim)[i]);
  119230. fprintf(stderr,"\n");
  119231. }*/
  119232. return(besti);
  119233. }
  119234. }
  119235. long vorbis_book_codeword(codebook *book,int entry){
  119236. if(book->c) /* only use with encode; decode optimizations are
  119237. allowed to break this */
  119238. return book->codelist[entry];
  119239. return -1;
  119240. }
  119241. long vorbis_book_codelen(codebook *book,int entry){
  119242. if(book->c) /* only use with encode; decode optimizations are
  119243. allowed to break this */
  119244. return book->c->lengthlist[entry];
  119245. return -1;
  119246. }
  119247. #ifdef _V_SELFTEST
  119248. /* Unit tests of the dequantizer; this stuff will be OK
  119249. cross-platform, I simply want to be sure that special mapping cases
  119250. actually work properly; a bug could go unnoticed for a while */
  119251. #include <stdio.h>
  119252. /* cases:
  119253. no mapping
  119254. full, explicit mapping
  119255. algorithmic mapping
  119256. nonsequential
  119257. sequential
  119258. */
  119259. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119260. static long partial_quantlist1[]={0,7,2};
  119261. /* no mapping */
  119262. static_codebook test1={
  119263. 4,16,
  119264. NULL,
  119265. 0,
  119266. 0,0,0,0,
  119267. NULL,
  119268. NULL,NULL
  119269. };
  119270. static float *test1_result=NULL;
  119271. /* linear, full mapping, nonsequential */
  119272. static_codebook test2={
  119273. 4,3,
  119274. NULL,
  119275. 2,
  119276. -533200896,1611661312,4,0,
  119277. full_quantlist1,
  119278. NULL,NULL
  119279. };
  119280. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119281. /* linear, full mapping, sequential */
  119282. static_codebook test3={
  119283. 4,3,
  119284. NULL,
  119285. 2,
  119286. -533200896,1611661312,4,1,
  119287. full_quantlist1,
  119288. NULL,NULL
  119289. };
  119290. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119291. /* linear, algorithmic mapping, nonsequential */
  119292. static_codebook test4={
  119293. 3,27,
  119294. NULL,
  119295. 1,
  119296. -533200896,1611661312,4,0,
  119297. partial_quantlist1,
  119298. NULL,NULL
  119299. };
  119300. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119301. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119302. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119303. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119304. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119305. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119306. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119307. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119308. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119309. /* linear, algorithmic mapping, sequential */
  119310. static_codebook test5={
  119311. 3,27,
  119312. NULL,
  119313. 1,
  119314. -533200896,1611661312,4,1,
  119315. partial_quantlist1,
  119316. NULL,NULL
  119317. };
  119318. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119319. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119320. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119321. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119322. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119323. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119324. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119325. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119326. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119327. void run_test(static_codebook *b,float *comp){
  119328. float *out=_book_unquantize(b,b->entries,NULL);
  119329. int i;
  119330. if(comp){
  119331. if(!out){
  119332. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119333. exit(1);
  119334. }
  119335. for(i=0;i<b->entries*b->dim;i++)
  119336. if(fabs(out[i]-comp[i])>.0001){
  119337. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119338. "position %d, %g != %g\n",i,out[i],comp[i]);
  119339. exit(1);
  119340. }
  119341. }else{
  119342. if(out){
  119343. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119344. " correct result should have been NULL\n");
  119345. exit(1);
  119346. }
  119347. }
  119348. }
  119349. int main(){
  119350. /* run the nine dequant tests, and compare to the hand-rolled results */
  119351. fprintf(stderr,"Dequant test 1... ");
  119352. run_test(&test1,test1_result);
  119353. fprintf(stderr,"OK\nDequant test 2... ");
  119354. run_test(&test2,test2_result);
  119355. fprintf(stderr,"OK\nDequant test 3... ");
  119356. run_test(&test3,test3_result);
  119357. fprintf(stderr,"OK\nDequant test 4... ");
  119358. run_test(&test4,test4_result);
  119359. fprintf(stderr,"OK\nDequant test 5... ");
  119360. run_test(&test5,test5_result);
  119361. fprintf(stderr,"OK\n\n");
  119362. return(0);
  119363. }
  119364. #endif
  119365. #endif
  119366. /*** End of inlined file: sharedbook.c ***/
  119367. /*** Start of inlined file: smallft.c ***/
  119368. /* FFT implementation from OggSquish, minus cosine transforms,
  119369. * minus all but radix 2/4 case. In Vorbis we only need this
  119370. * cut-down version.
  119371. *
  119372. * To do more than just power-of-two sized vectors, see the full
  119373. * version I wrote for NetLib.
  119374. *
  119375. * Note that the packing is a little strange; rather than the FFT r/i
  119376. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119377. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119378. * FORTRAN version
  119379. */
  119380. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119381. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119382. // tasks..
  119383. #if JUCE_MSVC
  119384. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119385. #endif
  119386. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119387. #if JUCE_USE_OGGVORBIS
  119388. #include <stdlib.h>
  119389. #include <string.h>
  119390. #include <math.h>
  119391. static void drfti1(int n, float *wa, int *ifac){
  119392. static int ntryh[4] = { 4,2,3,5 };
  119393. static float tpi = 6.28318530717958648f;
  119394. float arg,argh,argld,fi;
  119395. int ntry=0,i,j=-1;
  119396. int k1, l1, l2, ib;
  119397. int ld, ii, ip, is, nq, nr;
  119398. int ido, ipm, nfm1;
  119399. int nl=n;
  119400. int nf=0;
  119401. L101:
  119402. j++;
  119403. if (j < 4)
  119404. ntry=ntryh[j];
  119405. else
  119406. ntry+=2;
  119407. L104:
  119408. nq=nl/ntry;
  119409. nr=nl-ntry*nq;
  119410. if (nr!=0) goto L101;
  119411. nf++;
  119412. ifac[nf+1]=ntry;
  119413. nl=nq;
  119414. if(ntry!=2)goto L107;
  119415. if(nf==1)goto L107;
  119416. for (i=1;i<nf;i++){
  119417. ib=nf-i+1;
  119418. ifac[ib+1]=ifac[ib];
  119419. }
  119420. ifac[2] = 2;
  119421. L107:
  119422. if(nl!=1)goto L104;
  119423. ifac[0]=n;
  119424. ifac[1]=nf;
  119425. argh=tpi/n;
  119426. is=0;
  119427. nfm1=nf-1;
  119428. l1=1;
  119429. if(nfm1==0)return;
  119430. for (k1=0;k1<nfm1;k1++){
  119431. ip=ifac[k1+2];
  119432. ld=0;
  119433. l2=l1*ip;
  119434. ido=n/l2;
  119435. ipm=ip-1;
  119436. for (j=0;j<ipm;j++){
  119437. ld+=l1;
  119438. i=is;
  119439. argld=(float)ld*argh;
  119440. fi=0.f;
  119441. for (ii=2;ii<ido;ii+=2){
  119442. fi+=1.f;
  119443. arg=fi*argld;
  119444. wa[i++]=cos(arg);
  119445. wa[i++]=sin(arg);
  119446. }
  119447. is+=ido;
  119448. }
  119449. l1=l2;
  119450. }
  119451. }
  119452. static void fdrffti(int n, float *wsave, int *ifac){
  119453. if (n == 1) return;
  119454. drfti1(n, wsave+n, ifac);
  119455. }
  119456. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119457. int i,k;
  119458. float ti2,tr2;
  119459. int t0,t1,t2,t3,t4,t5,t6;
  119460. t1=0;
  119461. t0=(t2=l1*ido);
  119462. t3=ido<<1;
  119463. for(k=0;k<l1;k++){
  119464. ch[t1<<1]=cc[t1]+cc[t2];
  119465. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119466. t1+=ido;
  119467. t2+=ido;
  119468. }
  119469. if(ido<2)return;
  119470. if(ido==2)goto L105;
  119471. t1=0;
  119472. t2=t0;
  119473. for(k=0;k<l1;k++){
  119474. t3=t2;
  119475. t4=(t1<<1)+(ido<<1);
  119476. t5=t1;
  119477. t6=t1+t1;
  119478. for(i=2;i<ido;i+=2){
  119479. t3+=2;
  119480. t4-=2;
  119481. t5+=2;
  119482. t6+=2;
  119483. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119484. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119485. ch[t6]=cc[t5]+ti2;
  119486. ch[t4]=ti2-cc[t5];
  119487. ch[t6-1]=cc[t5-1]+tr2;
  119488. ch[t4-1]=cc[t5-1]-tr2;
  119489. }
  119490. t1+=ido;
  119491. t2+=ido;
  119492. }
  119493. if(ido%2==1)return;
  119494. L105:
  119495. t3=(t2=(t1=ido)-1);
  119496. t2+=t0;
  119497. for(k=0;k<l1;k++){
  119498. ch[t1]=-cc[t2];
  119499. ch[t1-1]=cc[t3];
  119500. t1+=ido<<1;
  119501. t2+=ido;
  119502. t3+=ido;
  119503. }
  119504. }
  119505. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119506. float *wa2,float *wa3){
  119507. static float hsqt2 = .70710678118654752f;
  119508. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119509. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119510. t0=l1*ido;
  119511. t1=t0;
  119512. t4=t1<<1;
  119513. t2=t1+(t1<<1);
  119514. t3=0;
  119515. for(k=0;k<l1;k++){
  119516. tr1=cc[t1]+cc[t2];
  119517. tr2=cc[t3]+cc[t4];
  119518. ch[t5=t3<<2]=tr1+tr2;
  119519. ch[(ido<<2)+t5-1]=tr2-tr1;
  119520. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119521. ch[t5]=cc[t2]-cc[t1];
  119522. t1+=ido;
  119523. t2+=ido;
  119524. t3+=ido;
  119525. t4+=ido;
  119526. }
  119527. if(ido<2)return;
  119528. if(ido==2)goto L105;
  119529. t1=0;
  119530. for(k=0;k<l1;k++){
  119531. t2=t1;
  119532. t4=t1<<2;
  119533. t5=(t6=ido<<1)+t4;
  119534. for(i=2;i<ido;i+=2){
  119535. t3=(t2+=2);
  119536. t4+=2;
  119537. t5-=2;
  119538. t3+=t0;
  119539. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119540. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119541. t3+=t0;
  119542. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119543. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119544. t3+=t0;
  119545. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119546. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119547. tr1=cr2+cr4;
  119548. tr4=cr4-cr2;
  119549. ti1=ci2+ci4;
  119550. ti4=ci2-ci4;
  119551. ti2=cc[t2]+ci3;
  119552. ti3=cc[t2]-ci3;
  119553. tr2=cc[t2-1]+cr3;
  119554. tr3=cc[t2-1]-cr3;
  119555. ch[t4-1]=tr1+tr2;
  119556. ch[t4]=ti1+ti2;
  119557. ch[t5-1]=tr3-ti4;
  119558. ch[t5]=tr4-ti3;
  119559. ch[t4+t6-1]=ti4+tr3;
  119560. ch[t4+t6]=tr4+ti3;
  119561. ch[t5+t6-1]=tr2-tr1;
  119562. ch[t5+t6]=ti1-ti2;
  119563. }
  119564. t1+=ido;
  119565. }
  119566. if(ido&1)return;
  119567. L105:
  119568. t2=(t1=t0+ido-1)+(t0<<1);
  119569. t3=ido<<2;
  119570. t4=ido;
  119571. t5=ido<<1;
  119572. t6=ido;
  119573. for(k=0;k<l1;k++){
  119574. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119575. tr1=hsqt2*(cc[t1]-cc[t2]);
  119576. ch[t4-1]=tr1+cc[t6-1];
  119577. ch[t4+t5-1]=cc[t6-1]-tr1;
  119578. ch[t4]=ti1-cc[t1+t0];
  119579. ch[t4+t5]=ti1+cc[t1+t0];
  119580. t1+=ido;
  119581. t2+=ido;
  119582. t4+=t3;
  119583. t6+=ido;
  119584. }
  119585. }
  119586. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119587. float *c2,float *ch,float *ch2,float *wa){
  119588. static float tpi=6.283185307179586f;
  119589. int idij,ipph,i,j,k,l,ic,ik,is;
  119590. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119591. float dc2,ai1,ai2,ar1,ar2,ds2;
  119592. int nbd;
  119593. float dcp,arg,dsp,ar1h,ar2h;
  119594. int idp2,ipp2;
  119595. arg=tpi/(float)ip;
  119596. dcp=cos(arg);
  119597. dsp=sin(arg);
  119598. ipph=(ip+1)>>1;
  119599. ipp2=ip;
  119600. idp2=ido;
  119601. nbd=(ido-1)>>1;
  119602. t0=l1*ido;
  119603. t10=ip*ido;
  119604. if(ido==1)goto L119;
  119605. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119606. t1=0;
  119607. for(j=1;j<ip;j++){
  119608. t1+=t0;
  119609. t2=t1;
  119610. for(k=0;k<l1;k++){
  119611. ch[t2]=c1[t2];
  119612. t2+=ido;
  119613. }
  119614. }
  119615. is=-ido;
  119616. t1=0;
  119617. if(nbd>l1){
  119618. for(j=1;j<ip;j++){
  119619. t1+=t0;
  119620. is+=ido;
  119621. t2= -ido+t1;
  119622. for(k=0;k<l1;k++){
  119623. idij=is-1;
  119624. t2+=ido;
  119625. t3=t2;
  119626. for(i=2;i<ido;i+=2){
  119627. idij+=2;
  119628. t3+=2;
  119629. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119630. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119631. }
  119632. }
  119633. }
  119634. }else{
  119635. for(j=1;j<ip;j++){
  119636. is+=ido;
  119637. idij=is-1;
  119638. t1+=t0;
  119639. t2=t1;
  119640. for(i=2;i<ido;i+=2){
  119641. idij+=2;
  119642. t2+=2;
  119643. t3=t2;
  119644. for(k=0;k<l1;k++){
  119645. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119646. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119647. t3+=ido;
  119648. }
  119649. }
  119650. }
  119651. }
  119652. t1=0;
  119653. t2=ipp2*t0;
  119654. if(nbd<l1){
  119655. for(j=1;j<ipph;j++){
  119656. t1+=t0;
  119657. t2-=t0;
  119658. t3=t1;
  119659. t4=t2;
  119660. for(i=2;i<ido;i+=2){
  119661. t3+=2;
  119662. t4+=2;
  119663. t5=t3-ido;
  119664. t6=t4-ido;
  119665. for(k=0;k<l1;k++){
  119666. t5+=ido;
  119667. t6+=ido;
  119668. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119669. c1[t6-1]=ch[t5]-ch[t6];
  119670. c1[t5]=ch[t5]+ch[t6];
  119671. c1[t6]=ch[t6-1]-ch[t5-1];
  119672. }
  119673. }
  119674. }
  119675. }else{
  119676. for(j=1;j<ipph;j++){
  119677. t1+=t0;
  119678. t2-=t0;
  119679. t3=t1;
  119680. t4=t2;
  119681. for(k=0;k<l1;k++){
  119682. t5=t3;
  119683. t6=t4;
  119684. for(i=2;i<ido;i+=2){
  119685. t5+=2;
  119686. t6+=2;
  119687. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119688. c1[t6-1]=ch[t5]-ch[t6];
  119689. c1[t5]=ch[t5]+ch[t6];
  119690. c1[t6]=ch[t6-1]-ch[t5-1];
  119691. }
  119692. t3+=ido;
  119693. t4+=ido;
  119694. }
  119695. }
  119696. }
  119697. L119:
  119698. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119699. t1=0;
  119700. t2=ipp2*idl1;
  119701. for(j=1;j<ipph;j++){
  119702. t1+=t0;
  119703. t2-=t0;
  119704. t3=t1-ido;
  119705. t4=t2-ido;
  119706. for(k=0;k<l1;k++){
  119707. t3+=ido;
  119708. t4+=ido;
  119709. c1[t3]=ch[t3]+ch[t4];
  119710. c1[t4]=ch[t4]-ch[t3];
  119711. }
  119712. }
  119713. ar1=1.f;
  119714. ai1=0.f;
  119715. t1=0;
  119716. t2=ipp2*idl1;
  119717. t3=(ip-1)*idl1;
  119718. for(l=1;l<ipph;l++){
  119719. t1+=idl1;
  119720. t2-=idl1;
  119721. ar1h=dcp*ar1-dsp*ai1;
  119722. ai1=dcp*ai1+dsp*ar1;
  119723. ar1=ar1h;
  119724. t4=t1;
  119725. t5=t2;
  119726. t6=t3;
  119727. t7=idl1;
  119728. for(ik=0;ik<idl1;ik++){
  119729. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119730. ch2[t5++]=ai1*c2[t6++];
  119731. }
  119732. dc2=ar1;
  119733. ds2=ai1;
  119734. ar2=ar1;
  119735. ai2=ai1;
  119736. t4=idl1;
  119737. t5=(ipp2-1)*idl1;
  119738. for(j=2;j<ipph;j++){
  119739. t4+=idl1;
  119740. t5-=idl1;
  119741. ar2h=dc2*ar2-ds2*ai2;
  119742. ai2=dc2*ai2+ds2*ar2;
  119743. ar2=ar2h;
  119744. t6=t1;
  119745. t7=t2;
  119746. t8=t4;
  119747. t9=t5;
  119748. for(ik=0;ik<idl1;ik++){
  119749. ch2[t6++]+=ar2*c2[t8++];
  119750. ch2[t7++]+=ai2*c2[t9++];
  119751. }
  119752. }
  119753. }
  119754. t1=0;
  119755. for(j=1;j<ipph;j++){
  119756. t1+=idl1;
  119757. t2=t1;
  119758. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119759. }
  119760. if(ido<l1)goto L132;
  119761. t1=0;
  119762. t2=0;
  119763. for(k=0;k<l1;k++){
  119764. t3=t1;
  119765. t4=t2;
  119766. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119767. t1+=ido;
  119768. t2+=t10;
  119769. }
  119770. goto L135;
  119771. L132:
  119772. for(i=0;i<ido;i++){
  119773. t1=i;
  119774. t2=i;
  119775. for(k=0;k<l1;k++){
  119776. cc[t2]=ch[t1];
  119777. t1+=ido;
  119778. t2+=t10;
  119779. }
  119780. }
  119781. L135:
  119782. t1=0;
  119783. t2=ido<<1;
  119784. t3=0;
  119785. t4=ipp2*t0;
  119786. for(j=1;j<ipph;j++){
  119787. t1+=t2;
  119788. t3+=t0;
  119789. t4-=t0;
  119790. t5=t1;
  119791. t6=t3;
  119792. t7=t4;
  119793. for(k=0;k<l1;k++){
  119794. cc[t5-1]=ch[t6];
  119795. cc[t5]=ch[t7];
  119796. t5+=t10;
  119797. t6+=ido;
  119798. t7+=ido;
  119799. }
  119800. }
  119801. if(ido==1)return;
  119802. if(nbd<l1)goto L141;
  119803. t1=-ido;
  119804. t3=0;
  119805. t4=0;
  119806. t5=ipp2*t0;
  119807. for(j=1;j<ipph;j++){
  119808. t1+=t2;
  119809. t3+=t2;
  119810. t4+=t0;
  119811. t5-=t0;
  119812. t6=t1;
  119813. t7=t3;
  119814. t8=t4;
  119815. t9=t5;
  119816. for(k=0;k<l1;k++){
  119817. for(i=2;i<ido;i+=2){
  119818. ic=idp2-i;
  119819. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119820. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119821. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119822. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119823. }
  119824. t6+=t10;
  119825. t7+=t10;
  119826. t8+=ido;
  119827. t9+=ido;
  119828. }
  119829. }
  119830. return;
  119831. L141:
  119832. t1=-ido;
  119833. t3=0;
  119834. t4=0;
  119835. t5=ipp2*t0;
  119836. for(j=1;j<ipph;j++){
  119837. t1+=t2;
  119838. t3+=t2;
  119839. t4+=t0;
  119840. t5-=t0;
  119841. for(i=2;i<ido;i+=2){
  119842. t6=idp2+t1-i;
  119843. t7=i+t3;
  119844. t8=i+t4;
  119845. t9=i+t5;
  119846. for(k=0;k<l1;k++){
  119847. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119848. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119849. cc[t7]=ch[t8]+ch[t9];
  119850. cc[t6]=ch[t9]-ch[t8];
  119851. t6+=t10;
  119852. t7+=t10;
  119853. t8+=ido;
  119854. t9+=ido;
  119855. }
  119856. }
  119857. }
  119858. }
  119859. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119860. int i,k1,l1,l2;
  119861. int na,kh,nf;
  119862. int ip,iw,ido,idl1,ix2,ix3;
  119863. nf=ifac[1];
  119864. na=1;
  119865. l2=n;
  119866. iw=n;
  119867. for(k1=0;k1<nf;k1++){
  119868. kh=nf-k1;
  119869. ip=ifac[kh+1];
  119870. l1=l2/ip;
  119871. ido=n/l2;
  119872. idl1=ido*l1;
  119873. iw-=(ip-1)*ido;
  119874. na=1-na;
  119875. if(ip!=4)goto L102;
  119876. ix2=iw+ido;
  119877. ix3=ix2+ido;
  119878. if(na!=0)
  119879. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119880. else
  119881. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119882. goto L110;
  119883. L102:
  119884. if(ip!=2)goto L104;
  119885. if(na!=0)goto L103;
  119886. dradf2(ido,l1,c,ch,wa+iw-1);
  119887. goto L110;
  119888. L103:
  119889. dradf2(ido,l1,ch,c,wa+iw-1);
  119890. goto L110;
  119891. L104:
  119892. if(ido==1)na=1-na;
  119893. if(na!=0)goto L109;
  119894. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119895. na=1;
  119896. goto L110;
  119897. L109:
  119898. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119899. na=0;
  119900. L110:
  119901. l2=l1;
  119902. }
  119903. if(na==1)return;
  119904. for(i=0;i<n;i++)c[i]=ch[i];
  119905. }
  119906. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119907. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119908. float ti2,tr2;
  119909. t0=l1*ido;
  119910. t1=0;
  119911. t2=0;
  119912. t3=(ido<<1)-1;
  119913. for(k=0;k<l1;k++){
  119914. ch[t1]=cc[t2]+cc[t3+t2];
  119915. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119916. t2=(t1+=ido)<<1;
  119917. }
  119918. if(ido<2)return;
  119919. if(ido==2)goto L105;
  119920. t1=0;
  119921. t2=0;
  119922. for(k=0;k<l1;k++){
  119923. t3=t1;
  119924. t5=(t4=t2)+(ido<<1);
  119925. t6=t0+t1;
  119926. for(i=2;i<ido;i+=2){
  119927. t3+=2;
  119928. t4+=2;
  119929. t5-=2;
  119930. t6+=2;
  119931. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119932. tr2=cc[t4-1]-cc[t5-1];
  119933. ch[t3]=cc[t4]-cc[t5];
  119934. ti2=cc[t4]+cc[t5];
  119935. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119936. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119937. }
  119938. t2=(t1+=ido)<<1;
  119939. }
  119940. if(ido%2==1)return;
  119941. L105:
  119942. t1=ido-1;
  119943. t2=ido-1;
  119944. for(k=0;k<l1;k++){
  119945. ch[t1]=cc[t2]+cc[t2];
  119946. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119947. t1+=ido;
  119948. t2+=ido<<1;
  119949. }
  119950. }
  119951. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119952. float *wa2){
  119953. static float taur = -.5f;
  119954. static float taui = .8660254037844386f;
  119955. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119956. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119957. t0=l1*ido;
  119958. t1=0;
  119959. t2=t0<<1;
  119960. t3=ido<<1;
  119961. t4=ido+(ido<<1);
  119962. t5=0;
  119963. for(k=0;k<l1;k++){
  119964. tr2=cc[t3-1]+cc[t3-1];
  119965. cr2=cc[t5]+(taur*tr2);
  119966. ch[t1]=cc[t5]+tr2;
  119967. ci3=taui*(cc[t3]+cc[t3]);
  119968. ch[t1+t0]=cr2-ci3;
  119969. ch[t1+t2]=cr2+ci3;
  119970. t1+=ido;
  119971. t3+=t4;
  119972. t5+=t4;
  119973. }
  119974. if(ido==1)return;
  119975. t1=0;
  119976. t3=ido<<1;
  119977. for(k=0;k<l1;k++){
  119978. t7=t1+(t1<<1);
  119979. t6=(t5=t7+t3);
  119980. t8=t1;
  119981. t10=(t9=t1+t0)+t0;
  119982. for(i=2;i<ido;i+=2){
  119983. t5+=2;
  119984. t6-=2;
  119985. t7+=2;
  119986. t8+=2;
  119987. t9+=2;
  119988. t10+=2;
  119989. tr2=cc[t5-1]+cc[t6-1];
  119990. cr2=cc[t7-1]+(taur*tr2);
  119991. ch[t8-1]=cc[t7-1]+tr2;
  119992. ti2=cc[t5]-cc[t6];
  119993. ci2=cc[t7]+(taur*ti2);
  119994. ch[t8]=cc[t7]+ti2;
  119995. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119996. ci3=taui*(cc[t5]+cc[t6]);
  119997. dr2=cr2-ci3;
  119998. dr3=cr2+ci3;
  119999. di2=ci2+cr3;
  120000. di3=ci2-cr3;
  120001. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120002. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120003. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120004. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120005. }
  120006. t1+=ido;
  120007. }
  120008. }
  120009. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120010. float *wa2,float *wa3){
  120011. static float sqrt2=1.414213562373095f;
  120012. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120013. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120014. t0=l1*ido;
  120015. t1=0;
  120016. t2=ido<<2;
  120017. t3=0;
  120018. t6=ido<<1;
  120019. for(k=0;k<l1;k++){
  120020. t4=t3+t6;
  120021. t5=t1;
  120022. tr3=cc[t4-1]+cc[t4-1];
  120023. tr4=cc[t4]+cc[t4];
  120024. tr1=cc[t3]-cc[(t4+=t6)-1];
  120025. tr2=cc[t3]+cc[t4-1];
  120026. ch[t5]=tr2+tr3;
  120027. ch[t5+=t0]=tr1-tr4;
  120028. ch[t5+=t0]=tr2-tr3;
  120029. ch[t5+=t0]=tr1+tr4;
  120030. t1+=ido;
  120031. t3+=t2;
  120032. }
  120033. if(ido<2)return;
  120034. if(ido==2)goto L105;
  120035. t1=0;
  120036. for(k=0;k<l1;k++){
  120037. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120038. t7=t1;
  120039. for(i=2;i<ido;i+=2){
  120040. t2+=2;
  120041. t3+=2;
  120042. t4-=2;
  120043. t5-=2;
  120044. t7+=2;
  120045. ti1=cc[t2]+cc[t5];
  120046. ti2=cc[t2]-cc[t5];
  120047. ti3=cc[t3]-cc[t4];
  120048. tr4=cc[t3]+cc[t4];
  120049. tr1=cc[t2-1]-cc[t5-1];
  120050. tr2=cc[t2-1]+cc[t5-1];
  120051. ti4=cc[t3-1]-cc[t4-1];
  120052. tr3=cc[t3-1]+cc[t4-1];
  120053. ch[t7-1]=tr2+tr3;
  120054. cr3=tr2-tr3;
  120055. ch[t7]=ti2+ti3;
  120056. ci3=ti2-ti3;
  120057. cr2=tr1-tr4;
  120058. cr4=tr1+tr4;
  120059. ci2=ti1+ti4;
  120060. ci4=ti1-ti4;
  120061. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120062. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120063. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120064. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120065. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120066. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120067. }
  120068. t1+=ido;
  120069. }
  120070. if(ido%2 == 1)return;
  120071. L105:
  120072. t1=ido;
  120073. t2=ido<<2;
  120074. t3=ido-1;
  120075. t4=ido+(ido<<1);
  120076. for(k=0;k<l1;k++){
  120077. t5=t3;
  120078. ti1=cc[t1]+cc[t4];
  120079. ti2=cc[t4]-cc[t1];
  120080. tr1=cc[t1-1]-cc[t4-1];
  120081. tr2=cc[t1-1]+cc[t4-1];
  120082. ch[t5]=tr2+tr2;
  120083. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120084. ch[t5+=t0]=ti2+ti2;
  120085. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120086. t3+=ido;
  120087. t1+=t2;
  120088. t4+=t2;
  120089. }
  120090. }
  120091. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120092. float *c2,float *ch,float *ch2,float *wa){
  120093. static float tpi=6.283185307179586f;
  120094. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120095. t11,t12;
  120096. float dc2,ai1,ai2,ar1,ar2,ds2;
  120097. int nbd;
  120098. float dcp,arg,dsp,ar1h,ar2h;
  120099. int ipp2;
  120100. t10=ip*ido;
  120101. t0=l1*ido;
  120102. arg=tpi/(float)ip;
  120103. dcp=cos(arg);
  120104. dsp=sin(arg);
  120105. nbd=(ido-1)>>1;
  120106. ipp2=ip;
  120107. ipph=(ip+1)>>1;
  120108. if(ido<l1)goto L103;
  120109. t1=0;
  120110. t2=0;
  120111. for(k=0;k<l1;k++){
  120112. t3=t1;
  120113. t4=t2;
  120114. for(i=0;i<ido;i++){
  120115. ch[t3]=cc[t4];
  120116. t3++;
  120117. t4++;
  120118. }
  120119. t1+=ido;
  120120. t2+=t10;
  120121. }
  120122. goto L106;
  120123. L103:
  120124. t1=0;
  120125. for(i=0;i<ido;i++){
  120126. t2=t1;
  120127. t3=t1;
  120128. for(k=0;k<l1;k++){
  120129. ch[t2]=cc[t3];
  120130. t2+=ido;
  120131. t3+=t10;
  120132. }
  120133. t1++;
  120134. }
  120135. L106:
  120136. t1=0;
  120137. t2=ipp2*t0;
  120138. t7=(t5=ido<<1);
  120139. for(j=1;j<ipph;j++){
  120140. t1+=t0;
  120141. t2-=t0;
  120142. t3=t1;
  120143. t4=t2;
  120144. t6=t5;
  120145. for(k=0;k<l1;k++){
  120146. ch[t3]=cc[t6-1]+cc[t6-1];
  120147. ch[t4]=cc[t6]+cc[t6];
  120148. t3+=ido;
  120149. t4+=ido;
  120150. t6+=t10;
  120151. }
  120152. t5+=t7;
  120153. }
  120154. if (ido == 1)goto L116;
  120155. if(nbd<l1)goto L112;
  120156. t1=0;
  120157. t2=ipp2*t0;
  120158. t7=0;
  120159. for(j=1;j<ipph;j++){
  120160. t1+=t0;
  120161. t2-=t0;
  120162. t3=t1;
  120163. t4=t2;
  120164. t7+=(ido<<1);
  120165. t8=t7;
  120166. for(k=0;k<l1;k++){
  120167. t5=t3;
  120168. t6=t4;
  120169. t9=t8;
  120170. t11=t8;
  120171. for(i=2;i<ido;i+=2){
  120172. t5+=2;
  120173. t6+=2;
  120174. t9+=2;
  120175. t11-=2;
  120176. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120177. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120178. ch[t5]=cc[t9]-cc[t11];
  120179. ch[t6]=cc[t9]+cc[t11];
  120180. }
  120181. t3+=ido;
  120182. t4+=ido;
  120183. t8+=t10;
  120184. }
  120185. }
  120186. goto L116;
  120187. L112:
  120188. t1=0;
  120189. t2=ipp2*t0;
  120190. t7=0;
  120191. for(j=1;j<ipph;j++){
  120192. t1+=t0;
  120193. t2-=t0;
  120194. t3=t1;
  120195. t4=t2;
  120196. t7+=(ido<<1);
  120197. t8=t7;
  120198. t9=t7;
  120199. for(i=2;i<ido;i+=2){
  120200. t3+=2;
  120201. t4+=2;
  120202. t8+=2;
  120203. t9-=2;
  120204. t5=t3;
  120205. t6=t4;
  120206. t11=t8;
  120207. t12=t9;
  120208. for(k=0;k<l1;k++){
  120209. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120210. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120211. ch[t5]=cc[t11]-cc[t12];
  120212. ch[t6]=cc[t11]+cc[t12];
  120213. t5+=ido;
  120214. t6+=ido;
  120215. t11+=t10;
  120216. t12+=t10;
  120217. }
  120218. }
  120219. }
  120220. L116:
  120221. ar1=1.f;
  120222. ai1=0.f;
  120223. t1=0;
  120224. t9=(t2=ipp2*idl1);
  120225. t3=(ip-1)*idl1;
  120226. for(l=1;l<ipph;l++){
  120227. t1+=idl1;
  120228. t2-=idl1;
  120229. ar1h=dcp*ar1-dsp*ai1;
  120230. ai1=dcp*ai1+dsp*ar1;
  120231. ar1=ar1h;
  120232. t4=t1;
  120233. t5=t2;
  120234. t6=0;
  120235. t7=idl1;
  120236. t8=t3;
  120237. for(ik=0;ik<idl1;ik++){
  120238. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120239. c2[t5++]=ai1*ch2[t8++];
  120240. }
  120241. dc2=ar1;
  120242. ds2=ai1;
  120243. ar2=ar1;
  120244. ai2=ai1;
  120245. t6=idl1;
  120246. t7=t9-idl1;
  120247. for(j=2;j<ipph;j++){
  120248. t6+=idl1;
  120249. t7-=idl1;
  120250. ar2h=dc2*ar2-ds2*ai2;
  120251. ai2=dc2*ai2+ds2*ar2;
  120252. ar2=ar2h;
  120253. t4=t1;
  120254. t5=t2;
  120255. t11=t6;
  120256. t12=t7;
  120257. for(ik=0;ik<idl1;ik++){
  120258. c2[t4++]+=ar2*ch2[t11++];
  120259. c2[t5++]+=ai2*ch2[t12++];
  120260. }
  120261. }
  120262. }
  120263. t1=0;
  120264. for(j=1;j<ipph;j++){
  120265. t1+=idl1;
  120266. t2=t1;
  120267. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120268. }
  120269. t1=0;
  120270. t2=ipp2*t0;
  120271. for(j=1;j<ipph;j++){
  120272. t1+=t0;
  120273. t2-=t0;
  120274. t3=t1;
  120275. t4=t2;
  120276. for(k=0;k<l1;k++){
  120277. ch[t3]=c1[t3]-c1[t4];
  120278. ch[t4]=c1[t3]+c1[t4];
  120279. t3+=ido;
  120280. t4+=ido;
  120281. }
  120282. }
  120283. if(ido==1)goto L132;
  120284. if(nbd<l1)goto L128;
  120285. t1=0;
  120286. t2=ipp2*t0;
  120287. for(j=1;j<ipph;j++){
  120288. t1+=t0;
  120289. t2-=t0;
  120290. t3=t1;
  120291. t4=t2;
  120292. for(k=0;k<l1;k++){
  120293. t5=t3;
  120294. t6=t4;
  120295. for(i=2;i<ido;i+=2){
  120296. t5+=2;
  120297. t6+=2;
  120298. ch[t5-1]=c1[t5-1]-c1[t6];
  120299. ch[t6-1]=c1[t5-1]+c1[t6];
  120300. ch[t5]=c1[t5]+c1[t6-1];
  120301. ch[t6]=c1[t5]-c1[t6-1];
  120302. }
  120303. t3+=ido;
  120304. t4+=ido;
  120305. }
  120306. }
  120307. goto L132;
  120308. L128:
  120309. t1=0;
  120310. t2=ipp2*t0;
  120311. for(j=1;j<ipph;j++){
  120312. t1+=t0;
  120313. t2-=t0;
  120314. t3=t1;
  120315. t4=t2;
  120316. for(i=2;i<ido;i+=2){
  120317. t3+=2;
  120318. t4+=2;
  120319. t5=t3;
  120320. t6=t4;
  120321. for(k=0;k<l1;k++){
  120322. ch[t5-1]=c1[t5-1]-c1[t6];
  120323. ch[t6-1]=c1[t5-1]+c1[t6];
  120324. ch[t5]=c1[t5]+c1[t6-1];
  120325. ch[t6]=c1[t5]-c1[t6-1];
  120326. t5+=ido;
  120327. t6+=ido;
  120328. }
  120329. }
  120330. }
  120331. L132:
  120332. if(ido==1)return;
  120333. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120334. t1=0;
  120335. for(j=1;j<ip;j++){
  120336. t2=(t1+=t0);
  120337. for(k=0;k<l1;k++){
  120338. c1[t2]=ch[t2];
  120339. t2+=ido;
  120340. }
  120341. }
  120342. if(nbd>l1)goto L139;
  120343. is= -ido-1;
  120344. t1=0;
  120345. for(j=1;j<ip;j++){
  120346. is+=ido;
  120347. t1+=t0;
  120348. idij=is;
  120349. t2=t1;
  120350. for(i=2;i<ido;i+=2){
  120351. t2+=2;
  120352. idij+=2;
  120353. t3=t2;
  120354. for(k=0;k<l1;k++){
  120355. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120356. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120357. t3+=ido;
  120358. }
  120359. }
  120360. }
  120361. return;
  120362. L139:
  120363. is= -ido-1;
  120364. t1=0;
  120365. for(j=1;j<ip;j++){
  120366. is+=ido;
  120367. t1+=t0;
  120368. t2=t1;
  120369. for(k=0;k<l1;k++){
  120370. idij=is;
  120371. t3=t2;
  120372. for(i=2;i<ido;i+=2){
  120373. idij+=2;
  120374. t3+=2;
  120375. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120376. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120377. }
  120378. t2+=ido;
  120379. }
  120380. }
  120381. }
  120382. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120383. int i,k1,l1,l2;
  120384. int na;
  120385. int nf,ip,iw,ix2,ix3,ido,idl1;
  120386. nf=ifac[1];
  120387. na=0;
  120388. l1=1;
  120389. iw=1;
  120390. for(k1=0;k1<nf;k1++){
  120391. ip=ifac[k1 + 2];
  120392. l2=ip*l1;
  120393. ido=n/l2;
  120394. idl1=ido*l1;
  120395. if(ip!=4)goto L103;
  120396. ix2=iw+ido;
  120397. ix3=ix2+ido;
  120398. if(na!=0)
  120399. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120400. else
  120401. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120402. na=1-na;
  120403. goto L115;
  120404. L103:
  120405. if(ip!=2)goto L106;
  120406. if(na!=0)
  120407. dradb2(ido,l1,ch,c,wa+iw-1);
  120408. else
  120409. dradb2(ido,l1,c,ch,wa+iw-1);
  120410. na=1-na;
  120411. goto L115;
  120412. L106:
  120413. if(ip!=3)goto L109;
  120414. ix2=iw+ido;
  120415. if(na!=0)
  120416. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120417. else
  120418. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120419. na=1-na;
  120420. goto L115;
  120421. L109:
  120422. /* The radix five case can be translated later..... */
  120423. /* if(ip!=5)goto L112;
  120424. ix2=iw+ido;
  120425. ix3=ix2+ido;
  120426. ix4=ix3+ido;
  120427. if(na!=0)
  120428. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120429. else
  120430. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120431. na=1-na;
  120432. goto L115;
  120433. L112:*/
  120434. if(na!=0)
  120435. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120436. else
  120437. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120438. if(ido==1)na=1-na;
  120439. L115:
  120440. l1=l2;
  120441. iw+=(ip-1)*ido;
  120442. }
  120443. if(na==0)return;
  120444. for(i=0;i<n;i++)c[i]=ch[i];
  120445. }
  120446. void drft_forward(drft_lookup *l,float *data){
  120447. if(l->n==1)return;
  120448. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120449. }
  120450. void drft_backward(drft_lookup *l,float *data){
  120451. if (l->n==1)return;
  120452. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120453. }
  120454. void drft_init(drft_lookup *l,int n){
  120455. l->n=n;
  120456. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120457. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120458. fdrffti(n, l->trigcache, l->splitcache);
  120459. }
  120460. void drft_clear(drft_lookup *l){
  120461. if(l){
  120462. if(l->trigcache)_ogg_free(l->trigcache);
  120463. if(l->splitcache)_ogg_free(l->splitcache);
  120464. memset(l,0,sizeof(*l));
  120465. }
  120466. }
  120467. #endif
  120468. /*** End of inlined file: smallft.c ***/
  120469. /*** Start of inlined file: synthesis.c ***/
  120470. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120471. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120472. // tasks..
  120473. #if JUCE_MSVC
  120474. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120475. #endif
  120476. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120477. #if JUCE_USE_OGGVORBIS
  120478. #include <stdio.h>
  120479. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120480. vorbis_dsp_state *vd=vb->vd;
  120481. private_state *b=(private_state*)vd->backend_state;
  120482. vorbis_info *vi=vd->vi;
  120483. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120484. oggpack_buffer *opb=&vb->opb;
  120485. int type,mode,i;
  120486. /* first things first. Make sure decode is ready */
  120487. _vorbis_block_ripcord(vb);
  120488. oggpack_readinit(opb,op->packet,op->bytes);
  120489. /* Check the packet type */
  120490. if(oggpack_read(opb,1)!=0){
  120491. /* Oops. This is not an audio data packet */
  120492. return(OV_ENOTAUDIO);
  120493. }
  120494. /* read our mode and pre/post windowsize */
  120495. mode=oggpack_read(opb,b->modebits);
  120496. if(mode==-1)return(OV_EBADPACKET);
  120497. vb->mode=mode;
  120498. vb->W=ci->mode_param[mode]->blockflag;
  120499. if(vb->W){
  120500. /* this doesn;t get mapped through mode selection as it's used
  120501. only for window selection */
  120502. vb->lW=oggpack_read(opb,1);
  120503. vb->nW=oggpack_read(opb,1);
  120504. if(vb->nW==-1) return(OV_EBADPACKET);
  120505. }else{
  120506. vb->lW=0;
  120507. vb->nW=0;
  120508. }
  120509. /* more setup */
  120510. vb->granulepos=op->granulepos;
  120511. vb->sequence=op->packetno;
  120512. vb->eofflag=op->e_o_s;
  120513. /* alloc pcm passback storage */
  120514. vb->pcmend=ci->blocksizes[vb->W];
  120515. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120516. for(i=0;i<vi->channels;i++)
  120517. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120518. /* unpack_header enforces range checking */
  120519. type=ci->map_type[ci->mode_param[mode]->mapping];
  120520. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120521. mapping]));
  120522. }
  120523. /* used to track pcm position without actually performing decode.
  120524. Useful for sequential 'fast forward' */
  120525. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120526. vorbis_dsp_state *vd=vb->vd;
  120527. private_state *b=(private_state*)vd->backend_state;
  120528. vorbis_info *vi=vd->vi;
  120529. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120530. oggpack_buffer *opb=&vb->opb;
  120531. int mode;
  120532. /* first things first. Make sure decode is ready */
  120533. _vorbis_block_ripcord(vb);
  120534. oggpack_readinit(opb,op->packet,op->bytes);
  120535. /* Check the packet type */
  120536. if(oggpack_read(opb,1)!=0){
  120537. /* Oops. This is not an audio data packet */
  120538. return(OV_ENOTAUDIO);
  120539. }
  120540. /* read our mode and pre/post windowsize */
  120541. mode=oggpack_read(opb,b->modebits);
  120542. if(mode==-1)return(OV_EBADPACKET);
  120543. vb->mode=mode;
  120544. vb->W=ci->mode_param[mode]->blockflag;
  120545. if(vb->W){
  120546. vb->lW=oggpack_read(opb,1);
  120547. vb->nW=oggpack_read(opb,1);
  120548. if(vb->nW==-1) return(OV_EBADPACKET);
  120549. }else{
  120550. vb->lW=0;
  120551. vb->nW=0;
  120552. }
  120553. /* more setup */
  120554. vb->granulepos=op->granulepos;
  120555. vb->sequence=op->packetno;
  120556. vb->eofflag=op->e_o_s;
  120557. /* no pcm */
  120558. vb->pcmend=0;
  120559. vb->pcm=NULL;
  120560. return(0);
  120561. }
  120562. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120563. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120564. oggpack_buffer opb;
  120565. int mode;
  120566. oggpack_readinit(&opb,op->packet,op->bytes);
  120567. /* Check the packet type */
  120568. if(oggpack_read(&opb,1)!=0){
  120569. /* Oops. This is not an audio data packet */
  120570. return(OV_ENOTAUDIO);
  120571. }
  120572. {
  120573. int modebits=0;
  120574. int v=ci->modes;
  120575. while(v>1){
  120576. modebits++;
  120577. v>>=1;
  120578. }
  120579. /* read our mode and pre/post windowsize */
  120580. mode=oggpack_read(&opb,modebits);
  120581. }
  120582. if(mode==-1)return(OV_EBADPACKET);
  120583. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120584. }
  120585. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120586. /* set / clear half-sample-rate mode */
  120587. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120588. /* right now, our MDCT can't handle < 64 sample windows. */
  120589. if(ci->blocksizes[0]<=64 && flag)return -1;
  120590. ci->halfrate_flag=(flag?1:0);
  120591. return 0;
  120592. }
  120593. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120594. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120595. return ci->halfrate_flag;
  120596. }
  120597. #endif
  120598. /*** End of inlined file: synthesis.c ***/
  120599. /*** Start of inlined file: vorbisenc.c ***/
  120600. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120601. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120602. // tasks..
  120603. #if JUCE_MSVC
  120604. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120605. #endif
  120606. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120607. #if JUCE_USE_OGGVORBIS
  120608. #include <stdlib.h>
  120609. #include <string.h>
  120610. #include <math.h>
  120611. /* careful with this; it's using static array sizing to make managing
  120612. all the modes a little less annoying. If we use a residue backend
  120613. with > 12 partition types, or a different division of iteration,
  120614. this needs to be updated. */
  120615. typedef struct {
  120616. static_codebook *books[12][3];
  120617. } static_bookblock;
  120618. typedef struct {
  120619. int res_type;
  120620. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120621. vorbis_info_residue0 *res;
  120622. static_codebook *book_aux;
  120623. static_codebook *book_aux_managed;
  120624. static_bookblock *books_base;
  120625. static_bookblock *books_base_managed;
  120626. } vorbis_residue_template;
  120627. typedef struct {
  120628. vorbis_info_mapping0 *map;
  120629. vorbis_residue_template *res;
  120630. } vorbis_mapping_template;
  120631. typedef struct vp_adjblock{
  120632. int block[P_BANDS];
  120633. } vp_adjblock;
  120634. typedef struct {
  120635. int data[NOISE_COMPAND_LEVELS];
  120636. } compandblock;
  120637. /* high level configuration information for setting things up
  120638. step-by-step with the detailed vorbis_encode_ctl interface.
  120639. There's a fair amount of redundancy such that interactive setup
  120640. does not directly deal with any vorbis_info or codec_setup_info
  120641. initialization; it's all stored (until full init) in this highlevel
  120642. setup, then flushed out to the real codec setup structs later. */
  120643. typedef struct {
  120644. int att[P_NOISECURVES];
  120645. float boost;
  120646. float decay;
  120647. } att3;
  120648. typedef struct { int data[P_NOISECURVES]; } adj3;
  120649. typedef struct {
  120650. int pre[PACKETBLOBS];
  120651. int post[PACKETBLOBS];
  120652. float kHz[PACKETBLOBS];
  120653. float lowpasskHz[PACKETBLOBS];
  120654. } adj_stereo;
  120655. typedef struct {
  120656. int lo;
  120657. int hi;
  120658. int fixed;
  120659. } noiseguard;
  120660. typedef struct {
  120661. int data[P_NOISECURVES][17];
  120662. } noise3;
  120663. typedef struct {
  120664. int mappings;
  120665. double *rate_mapping;
  120666. double *quality_mapping;
  120667. int coupling_restriction;
  120668. long samplerate_min_restriction;
  120669. long samplerate_max_restriction;
  120670. int *blocksize_short;
  120671. int *blocksize_long;
  120672. att3 *psy_tone_masteratt;
  120673. int *psy_tone_0dB;
  120674. int *psy_tone_dBsuppress;
  120675. vp_adjblock *psy_tone_adj_impulse;
  120676. vp_adjblock *psy_tone_adj_long;
  120677. vp_adjblock *psy_tone_adj_other;
  120678. noiseguard *psy_noiseguards;
  120679. noise3 *psy_noise_bias_impulse;
  120680. noise3 *psy_noise_bias_padding;
  120681. noise3 *psy_noise_bias_trans;
  120682. noise3 *psy_noise_bias_long;
  120683. int *psy_noise_dBsuppress;
  120684. compandblock *psy_noise_compand;
  120685. double *psy_noise_compand_short_mapping;
  120686. double *psy_noise_compand_long_mapping;
  120687. int *psy_noise_normal_start[2];
  120688. int *psy_noise_normal_partition[2];
  120689. double *psy_noise_normal_thresh;
  120690. int *psy_ath_float;
  120691. int *psy_ath_abs;
  120692. double *psy_lowpass;
  120693. vorbis_info_psy_global *global_params;
  120694. double *global_mapping;
  120695. adj_stereo *stereo_modes;
  120696. static_codebook ***floor_books;
  120697. vorbis_info_floor1 *floor_params;
  120698. int *floor_short_mapping;
  120699. int *floor_long_mapping;
  120700. vorbis_mapping_template *maps;
  120701. } ve_setup_data_template;
  120702. /* a few static coder conventions */
  120703. static vorbis_info_mode _mode_template[2]={
  120704. {0,0,0,0},
  120705. {1,0,0,1}
  120706. };
  120707. static vorbis_info_mapping0 _map_nominal[2]={
  120708. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120709. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120710. };
  120711. /*** Start of inlined file: setup_44.h ***/
  120712. /*** Start of inlined file: floor_all.h ***/
  120713. /*** Start of inlined file: floor_books.h ***/
  120714. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120715. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120716. };
  120717. static static_codebook _huff_book_line_256x7_0sub1 = {
  120718. 1, 9,
  120719. _huff_lengthlist_line_256x7_0sub1,
  120720. 0, 0, 0, 0, 0,
  120721. NULL,
  120722. NULL,
  120723. NULL,
  120724. NULL,
  120725. 0
  120726. };
  120727. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120729. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120730. };
  120731. static static_codebook _huff_book_line_256x7_0sub2 = {
  120732. 1, 25,
  120733. _huff_lengthlist_line_256x7_0sub2,
  120734. 0, 0, 0, 0, 0,
  120735. NULL,
  120736. NULL,
  120737. NULL,
  120738. NULL,
  120739. 0
  120740. };
  120741. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120744. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120745. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120746. };
  120747. static static_codebook _huff_book_line_256x7_0sub3 = {
  120748. 1, 64,
  120749. _huff_lengthlist_line_256x7_0sub3,
  120750. 0, 0, 0, 0, 0,
  120751. NULL,
  120752. NULL,
  120753. NULL,
  120754. NULL,
  120755. 0
  120756. };
  120757. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120758. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120759. };
  120760. static static_codebook _huff_book_line_256x7_1sub1 = {
  120761. 1, 9,
  120762. _huff_lengthlist_line_256x7_1sub1,
  120763. 0, 0, 0, 0, 0,
  120764. NULL,
  120765. NULL,
  120766. NULL,
  120767. NULL,
  120768. 0
  120769. };
  120770. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120772. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120773. };
  120774. static static_codebook _huff_book_line_256x7_1sub2 = {
  120775. 1, 25,
  120776. _huff_lengthlist_line_256x7_1sub2,
  120777. 0, 0, 0, 0, 0,
  120778. NULL,
  120779. NULL,
  120780. NULL,
  120781. NULL,
  120782. 0
  120783. };
  120784. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120787. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120788. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120789. };
  120790. static static_codebook _huff_book_line_256x7_1sub3 = {
  120791. 1, 64,
  120792. _huff_lengthlist_line_256x7_1sub3,
  120793. 0, 0, 0, 0, 0,
  120794. NULL,
  120795. NULL,
  120796. NULL,
  120797. NULL,
  120798. 0
  120799. };
  120800. static long _huff_lengthlist_line_256x7_class0[] = {
  120801. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120802. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120803. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120804. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120805. };
  120806. static static_codebook _huff_book_line_256x7_class0 = {
  120807. 1, 64,
  120808. _huff_lengthlist_line_256x7_class0,
  120809. 0, 0, 0, 0, 0,
  120810. NULL,
  120811. NULL,
  120812. NULL,
  120813. NULL,
  120814. 0
  120815. };
  120816. static long _huff_lengthlist_line_256x7_class1[] = {
  120817. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120818. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120819. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120820. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120821. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120822. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120823. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120824. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120825. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120826. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120827. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120828. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120829. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120830. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120831. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120832. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120833. };
  120834. static static_codebook _huff_book_line_256x7_class1 = {
  120835. 1, 256,
  120836. _huff_lengthlist_line_256x7_class1,
  120837. 0, 0, 0, 0, 0,
  120838. NULL,
  120839. NULL,
  120840. NULL,
  120841. NULL,
  120842. 0
  120843. };
  120844. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120845. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120846. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120847. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120848. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120849. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120850. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120851. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120852. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120853. };
  120854. static static_codebook _huff_book_line_512x17_0sub0 = {
  120855. 1, 128,
  120856. _huff_lengthlist_line_512x17_0sub0,
  120857. 0, 0, 0, 0, 0,
  120858. NULL,
  120859. NULL,
  120860. NULL,
  120861. NULL,
  120862. 0
  120863. };
  120864. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120865. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120866. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120867. };
  120868. static static_codebook _huff_book_line_512x17_1sub0 = {
  120869. 1, 32,
  120870. _huff_lengthlist_line_512x17_1sub0,
  120871. 0, 0, 0, 0, 0,
  120872. NULL,
  120873. NULL,
  120874. NULL,
  120875. NULL,
  120876. 0
  120877. };
  120878. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120881. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120882. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120883. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120884. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120885. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120886. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120887. };
  120888. static static_codebook _huff_book_line_512x17_1sub1 = {
  120889. 1, 128,
  120890. _huff_lengthlist_line_512x17_1sub1,
  120891. 0, 0, 0, 0, 0,
  120892. NULL,
  120893. NULL,
  120894. NULL,
  120895. NULL,
  120896. 0
  120897. };
  120898. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120899. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120900. 5, 3,
  120901. };
  120902. static static_codebook _huff_book_line_512x17_2sub1 = {
  120903. 1, 18,
  120904. _huff_lengthlist_line_512x17_2sub1,
  120905. 0, 0, 0, 0, 0,
  120906. NULL,
  120907. NULL,
  120908. NULL,
  120909. NULL,
  120910. 0
  120911. };
  120912. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120914. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120915. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120916. 9, 8,
  120917. };
  120918. static static_codebook _huff_book_line_512x17_2sub2 = {
  120919. 1, 50,
  120920. _huff_lengthlist_line_512x17_2sub2,
  120921. 0, 0, 0, 0, 0,
  120922. NULL,
  120923. NULL,
  120924. NULL,
  120925. NULL,
  120926. 0
  120927. };
  120928. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120932. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120933. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120934. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120935. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120936. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120937. };
  120938. static static_codebook _huff_book_line_512x17_2sub3 = {
  120939. 1, 128,
  120940. _huff_lengthlist_line_512x17_2sub3,
  120941. 0, 0, 0, 0, 0,
  120942. NULL,
  120943. NULL,
  120944. NULL,
  120945. NULL,
  120946. 0
  120947. };
  120948. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120949. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120950. 5, 5,
  120951. };
  120952. static static_codebook _huff_book_line_512x17_3sub1 = {
  120953. 1, 18,
  120954. _huff_lengthlist_line_512x17_3sub1,
  120955. 0, 0, 0, 0, 0,
  120956. NULL,
  120957. NULL,
  120958. NULL,
  120959. NULL,
  120960. 0
  120961. };
  120962. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120964. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120965. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120966. 11,14,
  120967. };
  120968. static static_codebook _huff_book_line_512x17_3sub2 = {
  120969. 1, 50,
  120970. _huff_lengthlist_line_512x17_3sub2,
  120971. 0, 0, 0, 0, 0,
  120972. NULL,
  120973. NULL,
  120974. NULL,
  120975. NULL,
  120976. 0
  120977. };
  120978. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120982. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120983. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120984. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120985. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120986. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120987. };
  120988. static static_codebook _huff_book_line_512x17_3sub3 = {
  120989. 1, 128,
  120990. _huff_lengthlist_line_512x17_3sub3,
  120991. 0, 0, 0, 0, 0,
  120992. NULL,
  120993. NULL,
  120994. NULL,
  120995. NULL,
  120996. 0
  120997. };
  120998. static long _huff_lengthlist_line_512x17_class1[] = {
  120999. 1, 2, 3, 6, 5, 4, 7, 7,
  121000. };
  121001. static static_codebook _huff_book_line_512x17_class1 = {
  121002. 1, 8,
  121003. _huff_lengthlist_line_512x17_class1,
  121004. 0, 0, 0, 0, 0,
  121005. NULL,
  121006. NULL,
  121007. NULL,
  121008. NULL,
  121009. 0
  121010. };
  121011. static long _huff_lengthlist_line_512x17_class2[] = {
  121012. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121013. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121014. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121015. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121016. };
  121017. static static_codebook _huff_book_line_512x17_class2 = {
  121018. 1, 64,
  121019. _huff_lengthlist_line_512x17_class2,
  121020. 0, 0, 0, 0, 0,
  121021. NULL,
  121022. NULL,
  121023. NULL,
  121024. NULL,
  121025. 0
  121026. };
  121027. static long _huff_lengthlist_line_512x17_class3[] = {
  121028. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121029. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121030. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121031. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121032. };
  121033. static static_codebook _huff_book_line_512x17_class3 = {
  121034. 1, 64,
  121035. _huff_lengthlist_line_512x17_class3,
  121036. 0, 0, 0, 0, 0,
  121037. NULL,
  121038. NULL,
  121039. NULL,
  121040. NULL,
  121041. 0
  121042. };
  121043. static long _huff_lengthlist_line_128x4_class0[] = {
  121044. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121045. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121046. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121047. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121048. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121049. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121050. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121051. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121052. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121053. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121054. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121055. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121056. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121057. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121058. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121059. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121060. };
  121061. static static_codebook _huff_book_line_128x4_class0 = {
  121062. 1, 256,
  121063. _huff_lengthlist_line_128x4_class0,
  121064. 0, 0, 0, 0, 0,
  121065. NULL,
  121066. NULL,
  121067. NULL,
  121068. NULL,
  121069. 0
  121070. };
  121071. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121072. 2, 2, 2, 2,
  121073. };
  121074. static static_codebook _huff_book_line_128x4_0sub0 = {
  121075. 1, 4,
  121076. _huff_lengthlist_line_128x4_0sub0,
  121077. 0, 0, 0, 0, 0,
  121078. NULL,
  121079. NULL,
  121080. NULL,
  121081. NULL,
  121082. 0
  121083. };
  121084. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121085. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121086. };
  121087. static static_codebook _huff_book_line_128x4_0sub1 = {
  121088. 1, 10,
  121089. _huff_lengthlist_line_128x4_0sub1,
  121090. 0, 0, 0, 0, 0,
  121091. NULL,
  121092. NULL,
  121093. NULL,
  121094. NULL,
  121095. 0
  121096. };
  121097. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121099. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121100. };
  121101. static static_codebook _huff_book_line_128x4_0sub2 = {
  121102. 1, 25,
  121103. _huff_lengthlist_line_128x4_0sub2,
  121104. 0, 0, 0, 0, 0,
  121105. NULL,
  121106. NULL,
  121107. NULL,
  121108. NULL,
  121109. 0
  121110. };
  121111. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121114. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121115. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121116. };
  121117. static static_codebook _huff_book_line_128x4_0sub3 = {
  121118. 1, 64,
  121119. _huff_lengthlist_line_128x4_0sub3,
  121120. 0, 0, 0, 0, 0,
  121121. NULL,
  121122. NULL,
  121123. NULL,
  121124. NULL,
  121125. 0
  121126. };
  121127. static long _huff_lengthlist_line_256x4_class0[] = {
  121128. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121129. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121130. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121131. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121132. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121133. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121134. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121135. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121136. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121137. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121138. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121139. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121140. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121141. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121142. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121143. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121144. };
  121145. static static_codebook _huff_book_line_256x4_class0 = {
  121146. 1, 256,
  121147. _huff_lengthlist_line_256x4_class0,
  121148. 0, 0, 0, 0, 0,
  121149. NULL,
  121150. NULL,
  121151. NULL,
  121152. NULL,
  121153. 0
  121154. };
  121155. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121156. 2, 2, 2, 2,
  121157. };
  121158. static static_codebook _huff_book_line_256x4_0sub0 = {
  121159. 1, 4,
  121160. _huff_lengthlist_line_256x4_0sub0,
  121161. 0, 0, 0, 0, 0,
  121162. NULL,
  121163. NULL,
  121164. NULL,
  121165. NULL,
  121166. 0
  121167. };
  121168. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121169. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121170. };
  121171. static static_codebook _huff_book_line_256x4_0sub1 = {
  121172. 1, 10,
  121173. _huff_lengthlist_line_256x4_0sub1,
  121174. 0, 0, 0, 0, 0,
  121175. NULL,
  121176. NULL,
  121177. NULL,
  121178. NULL,
  121179. 0
  121180. };
  121181. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121183. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121184. };
  121185. static static_codebook _huff_book_line_256x4_0sub2 = {
  121186. 1, 25,
  121187. _huff_lengthlist_line_256x4_0sub2,
  121188. 0, 0, 0, 0, 0,
  121189. NULL,
  121190. NULL,
  121191. NULL,
  121192. NULL,
  121193. 0
  121194. };
  121195. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121198. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121199. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121200. };
  121201. static static_codebook _huff_book_line_256x4_0sub3 = {
  121202. 1, 64,
  121203. _huff_lengthlist_line_256x4_0sub3,
  121204. 0, 0, 0, 0, 0,
  121205. NULL,
  121206. NULL,
  121207. NULL,
  121208. NULL,
  121209. 0
  121210. };
  121211. static long _huff_lengthlist_line_128x7_class0[] = {
  121212. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121213. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121214. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121215. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121216. };
  121217. static static_codebook _huff_book_line_128x7_class0 = {
  121218. 1, 64,
  121219. _huff_lengthlist_line_128x7_class0,
  121220. 0, 0, 0, 0, 0,
  121221. NULL,
  121222. NULL,
  121223. NULL,
  121224. NULL,
  121225. 0
  121226. };
  121227. static long _huff_lengthlist_line_128x7_class1[] = {
  121228. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121229. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121230. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121231. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121232. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121233. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121234. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121235. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121236. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121237. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121238. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121239. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121240. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121241. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121242. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121243. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121244. };
  121245. static static_codebook _huff_book_line_128x7_class1 = {
  121246. 1, 256,
  121247. _huff_lengthlist_line_128x7_class1,
  121248. 0, 0, 0, 0, 0,
  121249. NULL,
  121250. NULL,
  121251. NULL,
  121252. NULL,
  121253. 0
  121254. };
  121255. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121256. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121257. };
  121258. static static_codebook _huff_book_line_128x7_0sub1 = {
  121259. 1, 9,
  121260. _huff_lengthlist_line_128x7_0sub1,
  121261. 0, 0, 0, 0, 0,
  121262. NULL,
  121263. NULL,
  121264. NULL,
  121265. NULL,
  121266. 0
  121267. };
  121268. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121270. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121271. };
  121272. static static_codebook _huff_book_line_128x7_0sub2 = {
  121273. 1, 25,
  121274. _huff_lengthlist_line_128x7_0sub2,
  121275. 0, 0, 0, 0, 0,
  121276. NULL,
  121277. NULL,
  121278. NULL,
  121279. NULL,
  121280. 0
  121281. };
  121282. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121285. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121286. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121287. };
  121288. static static_codebook _huff_book_line_128x7_0sub3 = {
  121289. 1, 64,
  121290. _huff_lengthlist_line_128x7_0sub3,
  121291. 0, 0, 0, 0, 0,
  121292. NULL,
  121293. NULL,
  121294. NULL,
  121295. NULL,
  121296. 0
  121297. };
  121298. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121299. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121300. };
  121301. static static_codebook _huff_book_line_128x7_1sub1 = {
  121302. 1, 9,
  121303. _huff_lengthlist_line_128x7_1sub1,
  121304. 0, 0, 0, 0, 0,
  121305. NULL,
  121306. NULL,
  121307. NULL,
  121308. NULL,
  121309. 0
  121310. };
  121311. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121313. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121314. };
  121315. static static_codebook _huff_book_line_128x7_1sub2 = {
  121316. 1, 25,
  121317. _huff_lengthlist_line_128x7_1sub2,
  121318. 0, 0, 0, 0, 0,
  121319. NULL,
  121320. NULL,
  121321. NULL,
  121322. NULL,
  121323. 0
  121324. };
  121325. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121328. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121329. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121330. };
  121331. static static_codebook _huff_book_line_128x7_1sub3 = {
  121332. 1, 64,
  121333. _huff_lengthlist_line_128x7_1sub3,
  121334. 0, 0, 0, 0, 0,
  121335. NULL,
  121336. NULL,
  121337. NULL,
  121338. NULL,
  121339. 0
  121340. };
  121341. static long _huff_lengthlist_line_128x11_class1[] = {
  121342. 1, 6, 3, 7, 2, 4, 5, 7,
  121343. };
  121344. static static_codebook _huff_book_line_128x11_class1 = {
  121345. 1, 8,
  121346. _huff_lengthlist_line_128x11_class1,
  121347. 0, 0, 0, 0, 0,
  121348. NULL,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. 0
  121353. };
  121354. static long _huff_lengthlist_line_128x11_class2[] = {
  121355. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121356. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121357. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121358. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121359. };
  121360. static static_codebook _huff_book_line_128x11_class2 = {
  121361. 1, 64,
  121362. _huff_lengthlist_line_128x11_class2,
  121363. 0, 0, 0, 0, 0,
  121364. NULL,
  121365. NULL,
  121366. NULL,
  121367. NULL,
  121368. 0
  121369. };
  121370. static long _huff_lengthlist_line_128x11_class3[] = {
  121371. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121372. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121373. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121374. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121375. };
  121376. static static_codebook _huff_book_line_128x11_class3 = {
  121377. 1, 64,
  121378. _huff_lengthlist_line_128x11_class3,
  121379. 0, 0, 0, 0, 0,
  121380. NULL,
  121381. NULL,
  121382. NULL,
  121383. NULL,
  121384. 0
  121385. };
  121386. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121387. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121388. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121389. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121390. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121391. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121392. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121393. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121394. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121395. };
  121396. static static_codebook _huff_book_line_128x11_0sub0 = {
  121397. 1, 128,
  121398. _huff_lengthlist_line_128x11_0sub0,
  121399. 0, 0, 0, 0, 0,
  121400. NULL,
  121401. NULL,
  121402. NULL,
  121403. NULL,
  121404. 0
  121405. };
  121406. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121407. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121408. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121409. };
  121410. static static_codebook _huff_book_line_128x11_1sub0 = {
  121411. 1, 32,
  121412. _huff_lengthlist_line_128x11_1sub0,
  121413. 0, 0, 0, 0, 0,
  121414. NULL,
  121415. NULL,
  121416. NULL,
  121417. NULL,
  121418. 0
  121419. };
  121420. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121423. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121424. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121425. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121426. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121427. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121428. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121429. };
  121430. static static_codebook _huff_book_line_128x11_1sub1 = {
  121431. 1, 128,
  121432. _huff_lengthlist_line_128x11_1sub1,
  121433. 0, 0, 0, 0, 0,
  121434. NULL,
  121435. NULL,
  121436. NULL,
  121437. NULL,
  121438. 0
  121439. };
  121440. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121441. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121442. 5, 5,
  121443. };
  121444. static static_codebook _huff_book_line_128x11_2sub1 = {
  121445. 1, 18,
  121446. _huff_lengthlist_line_128x11_2sub1,
  121447. 0, 0, 0, 0, 0,
  121448. NULL,
  121449. NULL,
  121450. NULL,
  121451. NULL,
  121452. 0
  121453. };
  121454. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121456. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121457. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121458. 8,11,
  121459. };
  121460. static static_codebook _huff_book_line_128x11_2sub2 = {
  121461. 1, 50,
  121462. _huff_lengthlist_line_128x11_2sub2,
  121463. 0, 0, 0, 0, 0,
  121464. NULL,
  121465. NULL,
  121466. NULL,
  121467. NULL,
  121468. 0
  121469. };
  121470. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121474. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121475. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121476. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121477. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121478. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121479. };
  121480. static static_codebook _huff_book_line_128x11_2sub3 = {
  121481. 1, 128,
  121482. _huff_lengthlist_line_128x11_2sub3,
  121483. 0, 0, 0, 0, 0,
  121484. NULL,
  121485. NULL,
  121486. NULL,
  121487. NULL,
  121488. 0
  121489. };
  121490. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121491. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121492. 5, 4,
  121493. };
  121494. static static_codebook _huff_book_line_128x11_3sub1 = {
  121495. 1, 18,
  121496. _huff_lengthlist_line_128x11_3sub1,
  121497. 0, 0, 0, 0, 0,
  121498. NULL,
  121499. NULL,
  121500. NULL,
  121501. NULL,
  121502. 0
  121503. };
  121504. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121506. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121507. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121508. 12, 6,
  121509. };
  121510. static static_codebook _huff_book_line_128x11_3sub2 = {
  121511. 1, 50,
  121512. _huff_lengthlist_line_128x11_3sub2,
  121513. 0, 0, 0, 0, 0,
  121514. NULL,
  121515. NULL,
  121516. NULL,
  121517. NULL,
  121518. 0
  121519. };
  121520. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121524. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121525. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121526. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121527. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121528. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121529. };
  121530. static static_codebook _huff_book_line_128x11_3sub3 = {
  121531. 1, 128,
  121532. _huff_lengthlist_line_128x11_3sub3,
  121533. 0, 0, 0, 0, 0,
  121534. NULL,
  121535. NULL,
  121536. NULL,
  121537. NULL,
  121538. 0
  121539. };
  121540. static long _huff_lengthlist_line_128x17_class1[] = {
  121541. 1, 3, 4, 7, 2, 5, 6, 7,
  121542. };
  121543. static static_codebook _huff_book_line_128x17_class1 = {
  121544. 1, 8,
  121545. _huff_lengthlist_line_128x17_class1,
  121546. 0, 0, 0, 0, 0,
  121547. NULL,
  121548. NULL,
  121549. NULL,
  121550. NULL,
  121551. 0
  121552. };
  121553. static long _huff_lengthlist_line_128x17_class2[] = {
  121554. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121555. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121556. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121557. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121558. };
  121559. static static_codebook _huff_book_line_128x17_class2 = {
  121560. 1, 64,
  121561. _huff_lengthlist_line_128x17_class2,
  121562. 0, 0, 0, 0, 0,
  121563. NULL,
  121564. NULL,
  121565. NULL,
  121566. NULL,
  121567. 0
  121568. };
  121569. static long _huff_lengthlist_line_128x17_class3[] = {
  121570. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121571. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121572. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121573. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121574. };
  121575. static static_codebook _huff_book_line_128x17_class3 = {
  121576. 1, 64,
  121577. _huff_lengthlist_line_128x17_class3,
  121578. 0, 0, 0, 0, 0,
  121579. NULL,
  121580. NULL,
  121581. NULL,
  121582. NULL,
  121583. 0
  121584. };
  121585. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121586. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121587. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121588. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121589. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121590. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121591. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121592. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121593. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121594. };
  121595. static static_codebook _huff_book_line_128x17_0sub0 = {
  121596. 1, 128,
  121597. _huff_lengthlist_line_128x17_0sub0,
  121598. 0, 0, 0, 0, 0,
  121599. NULL,
  121600. NULL,
  121601. NULL,
  121602. NULL,
  121603. 0
  121604. };
  121605. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121606. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121607. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121608. };
  121609. static static_codebook _huff_book_line_128x17_1sub0 = {
  121610. 1, 32,
  121611. _huff_lengthlist_line_128x17_1sub0,
  121612. 0, 0, 0, 0, 0,
  121613. NULL,
  121614. NULL,
  121615. NULL,
  121616. NULL,
  121617. 0
  121618. };
  121619. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121622. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121623. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121624. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121625. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121626. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121627. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121628. };
  121629. static static_codebook _huff_book_line_128x17_1sub1 = {
  121630. 1, 128,
  121631. _huff_lengthlist_line_128x17_1sub1,
  121632. 0, 0, 0, 0, 0,
  121633. NULL,
  121634. NULL,
  121635. NULL,
  121636. NULL,
  121637. 0
  121638. };
  121639. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121640. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121641. 9, 4,
  121642. };
  121643. static static_codebook _huff_book_line_128x17_2sub1 = {
  121644. 1, 18,
  121645. _huff_lengthlist_line_128x17_2sub1,
  121646. 0, 0, 0, 0, 0,
  121647. NULL,
  121648. NULL,
  121649. NULL,
  121650. NULL,
  121651. 0
  121652. };
  121653. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121655. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121656. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121657. 13,13,
  121658. };
  121659. static static_codebook _huff_book_line_128x17_2sub2 = {
  121660. 1, 50,
  121661. _huff_lengthlist_line_128x17_2sub2,
  121662. 0, 0, 0, 0, 0,
  121663. NULL,
  121664. NULL,
  121665. NULL,
  121666. NULL,
  121667. 0
  121668. };
  121669. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121673. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121674. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121675. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121676. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121677. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121678. };
  121679. static static_codebook _huff_book_line_128x17_2sub3 = {
  121680. 1, 128,
  121681. _huff_lengthlist_line_128x17_2sub3,
  121682. 0, 0, 0, 0, 0,
  121683. NULL,
  121684. NULL,
  121685. NULL,
  121686. NULL,
  121687. 0
  121688. };
  121689. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121690. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121691. 6, 4,
  121692. };
  121693. static static_codebook _huff_book_line_128x17_3sub1 = {
  121694. 1, 18,
  121695. _huff_lengthlist_line_128x17_3sub1,
  121696. 0, 0, 0, 0, 0,
  121697. NULL,
  121698. NULL,
  121699. NULL,
  121700. NULL,
  121701. 0
  121702. };
  121703. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121705. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121706. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121707. 10, 8,
  121708. };
  121709. static static_codebook _huff_book_line_128x17_3sub2 = {
  121710. 1, 50,
  121711. _huff_lengthlist_line_128x17_3sub2,
  121712. 0, 0, 0, 0, 0,
  121713. NULL,
  121714. NULL,
  121715. NULL,
  121716. NULL,
  121717. 0
  121718. };
  121719. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121723. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121724. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121725. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121728. };
  121729. static static_codebook _huff_book_line_128x17_3sub3 = {
  121730. 1, 128,
  121731. _huff_lengthlist_line_128x17_3sub3,
  121732. 0, 0, 0, 0, 0,
  121733. NULL,
  121734. NULL,
  121735. NULL,
  121736. NULL,
  121737. 0
  121738. };
  121739. static long _huff_lengthlist_line_1024x27_class1[] = {
  121740. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121741. };
  121742. static static_codebook _huff_book_line_1024x27_class1 = {
  121743. 1, 16,
  121744. _huff_lengthlist_line_1024x27_class1,
  121745. 0, 0, 0, 0, 0,
  121746. NULL,
  121747. NULL,
  121748. NULL,
  121749. NULL,
  121750. 0
  121751. };
  121752. static long _huff_lengthlist_line_1024x27_class2[] = {
  121753. 1, 4, 2, 6, 3, 7, 5, 7,
  121754. };
  121755. static static_codebook _huff_book_line_1024x27_class2 = {
  121756. 1, 8,
  121757. _huff_lengthlist_line_1024x27_class2,
  121758. 0, 0, 0, 0, 0,
  121759. NULL,
  121760. NULL,
  121761. NULL,
  121762. NULL,
  121763. 0
  121764. };
  121765. static long _huff_lengthlist_line_1024x27_class3[] = {
  121766. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121767. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121768. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121769. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121770. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121771. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121772. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121773. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121774. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121775. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121776. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121777. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121778. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121779. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121780. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121781. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121782. };
  121783. static static_codebook _huff_book_line_1024x27_class3 = {
  121784. 1, 256,
  121785. _huff_lengthlist_line_1024x27_class3,
  121786. 0, 0, 0, 0, 0,
  121787. NULL,
  121788. NULL,
  121789. NULL,
  121790. NULL,
  121791. 0
  121792. };
  121793. static long _huff_lengthlist_line_1024x27_class4[] = {
  121794. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121795. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121796. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121797. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121798. };
  121799. static static_codebook _huff_book_line_1024x27_class4 = {
  121800. 1, 64,
  121801. _huff_lengthlist_line_1024x27_class4,
  121802. 0, 0, 0, 0, 0,
  121803. NULL,
  121804. NULL,
  121805. NULL,
  121806. NULL,
  121807. 0
  121808. };
  121809. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121810. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121811. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121812. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121813. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121814. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121815. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121816. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121817. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121818. };
  121819. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121820. 1, 128,
  121821. _huff_lengthlist_line_1024x27_0sub0,
  121822. 0, 0, 0, 0, 0,
  121823. NULL,
  121824. NULL,
  121825. NULL,
  121826. NULL,
  121827. 0
  121828. };
  121829. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121830. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121831. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121832. };
  121833. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121834. 1, 32,
  121835. _huff_lengthlist_line_1024x27_1sub0,
  121836. 0, 0, 0, 0, 0,
  121837. NULL,
  121838. NULL,
  121839. NULL,
  121840. NULL,
  121841. 0
  121842. };
  121843. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121846. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121847. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121848. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121849. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121850. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121851. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121852. };
  121853. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121854. 1, 128,
  121855. _huff_lengthlist_line_1024x27_1sub1,
  121856. 0, 0, 0, 0, 0,
  121857. NULL,
  121858. NULL,
  121859. NULL,
  121860. NULL,
  121861. 0
  121862. };
  121863. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121864. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121865. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121866. };
  121867. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121868. 1, 32,
  121869. _huff_lengthlist_line_1024x27_2sub0,
  121870. 0, 0, 0, 0, 0,
  121871. NULL,
  121872. NULL,
  121873. NULL,
  121874. NULL,
  121875. 0
  121876. };
  121877. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121880. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121881. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121882. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121883. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121884. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121885. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121886. };
  121887. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121888. 1, 128,
  121889. _huff_lengthlist_line_1024x27_2sub1,
  121890. 0, 0, 0, 0, 0,
  121891. NULL,
  121892. NULL,
  121893. NULL,
  121894. NULL,
  121895. 0
  121896. };
  121897. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121898. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121899. 5, 5,
  121900. };
  121901. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121902. 1, 18,
  121903. _huff_lengthlist_line_1024x27_3sub1,
  121904. 0, 0, 0, 0, 0,
  121905. NULL,
  121906. NULL,
  121907. NULL,
  121908. NULL,
  121909. 0
  121910. };
  121911. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121913. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121914. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121915. 9,11,
  121916. };
  121917. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121918. 1, 50,
  121919. _huff_lengthlist_line_1024x27_3sub2,
  121920. 0, 0, 0, 0, 0,
  121921. NULL,
  121922. NULL,
  121923. NULL,
  121924. NULL,
  121925. 0
  121926. };
  121927. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121931. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121932. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121933. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121934. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121935. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121936. };
  121937. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121938. 1, 128,
  121939. _huff_lengthlist_line_1024x27_3sub3,
  121940. 0, 0, 0, 0, 0,
  121941. NULL,
  121942. NULL,
  121943. NULL,
  121944. NULL,
  121945. 0
  121946. };
  121947. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121948. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121949. 5, 4,
  121950. };
  121951. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121952. 1, 18,
  121953. _huff_lengthlist_line_1024x27_4sub1,
  121954. 0, 0, 0, 0, 0,
  121955. NULL,
  121956. NULL,
  121957. NULL,
  121958. NULL,
  121959. 0
  121960. };
  121961. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121964. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121965. 9,12,
  121966. };
  121967. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121968. 1, 50,
  121969. _huff_lengthlist_line_1024x27_4sub2,
  121970. 0, 0, 0, 0, 0,
  121971. NULL,
  121972. NULL,
  121973. NULL,
  121974. NULL,
  121975. 0
  121976. };
  121977. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121981. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121982. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121983. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121984. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121985. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121986. };
  121987. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121988. 1, 128,
  121989. _huff_lengthlist_line_1024x27_4sub3,
  121990. 0, 0, 0, 0, 0,
  121991. NULL,
  121992. NULL,
  121993. NULL,
  121994. NULL,
  121995. 0
  121996. };
  121997. static long _huff_lengthlist_line_2048x27_class1[] = {
  121998. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121999. };
  122000. static static_codebook _huff_book_line_2048x27_class1 = {
  122001. 1, 16,
  122002. _huff_lengthlist_line_2048x27_class1,
  122003. 0, 0, 0, 0, 0,
  122004. NULL,
  122005. NULL,
  122006. NULL,
  122007. NULL,
  122008. 0
  122009. };
  122010. static long _huff_lengthlist_line_2048x27_class2[] = {
  122011. 1, 2, 3, 6, 4, 7, 5, 7,
  122012. };
  122013. static static_codebook _huff_book_line_2048x27_class2 = {
  122014. 1, 8,
  122015. _huff_lengthlist_line_2048x27_class2,
  122016. 0, 0, 0, 0, 0,
  122017. NULL,
  122018. NULL,
  122019. NULL,
  122020. NULL,
  122021. 0
  122022. };
  122023. static long _huff_lengthlist_line_2048x27_class3[] = {
  122024. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122025. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122026. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122027. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122028. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122029. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122030. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122031. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122032. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122033. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122034. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122035. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122036. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122037. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122038. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122039. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122040. };
  122041. static static_codebook _huff_book_line_2048x27_class3 = {
  122042. 1, 256,
  122043. _huff_lengthlist_line_2048x27_class3,
  122044. 0, 0, 0, 0, 0,
  122045. NULL,
  122046. NULL,
  122047. NULL,
  122048. NULL,
  122049. 0
  122050. };
  122051. static long _huff_lengthlist_line_2048x27_class4[] = {
  122052. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122053. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122054. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122055. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122056. };
  122057. static static_codebook _huff_book_line_2048x27_class4 = {
  122058. 1, 64,
  122059. _huff_lengthlist_line_2048x27_class4,
  122060. 0, 0, 0, 0, 0,
  122061. NULL,
  122062. NULL,
  122063. NULL,
  122064. NULL,
  122065. 0
  122066. };
  122067. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122068. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122069. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122070. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122071. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122072. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122073. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122074. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122075. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122076. };
  122077. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122078. 1, 128,
  122079. _huff_lengthlist_line_2048x27_0sub0,
  122080. 0, 0, 0, 0, 0,
  122081. NULL,
  122082. NULL,
  122083. NULL,
  122084. NULL,
  122085. 0
  122086. };
  122087. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122088. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122089. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122090. };
  122091. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122092. 1, 32,
  122093. _huff_lengthlist_line_2048x27_1sub0,
  122094. 0, 0, 0, 0, 0,
  122095. NULL,
  122096. NULL,
  122097. NULL,
  122098. NULL,
  122099. 0
  122100. };
  122101. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122104. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122105. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122106. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122107. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122108. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122109. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122110. };
  122111. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122112. 1, 128,
  122113. _huff_lengthlist_line_2048x27_1sub1,
  122114. 0, 0, 0, 0, 0,
  122115. NULL,
  122116. NULL,
  122117. NULL,
  122118. NULL,
  122119. 0
  122120. };
  122121. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122122. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122123. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122124. };
  122125. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122126. 1, 32,
  122127. _huff_lengthlist_line_2048x27_2sub0,
  122128. 0, 0, 0, 0, 0,
  122129. NULL,
  122130. NULL,
  122131. NULL,
  122132. NULL,
  122133. 0
  122134. };
  122135. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122138. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122139. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122140. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122141. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122142. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122143. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122144. };
  122145. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122146. 1, 128,
  122147. _huff_lengthlist_line_2048x27_2sub1,
  122148. 0, 0, 0, 0, 0,
  122149. NULL,
  122150. NULL,
  122151. NULL,
  122152. NULL,
  122153. 0
  122154. };
  122155. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122156. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122157. 5, 5,
  122158. };
  122159. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122160. 1, 18,
  122161. _huff_lengthlist_line_2048x27_3sub1,
  122162. 0, 0, 0, 0, 0,
  122163. NULL,
  122164. NULL,
  122165. NULL,
  122166. NULL,
  122167. 0
  122168. };
  122169. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122172. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122173. 10,12,
  122174. };
  122175. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122176. 1, 50,
  122177. _huff_lengthlist_line_2048x27_3sub2,
  122178. 0, 0, 0, 0, 0,
  122179. NULL,
  122180. NULL,
  122181. NULL,
  122182. NULL,
  122183. 0
  122184. };
  122185. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122189. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122190. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122191. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122192. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122193. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122194. };
  122195. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122196. 1, 128,
  122197. _huff_lengthlist_line_2048x27_3sub3,
  122198. 0, 0, 0, 0, 0,
  122199. NULL,
  122200. NULL,
  122201. NULL,
  122202. NULL,
  122203. 0
  122204. };
  122205. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122206. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122207. 4, 5,
  122208. };
  122209. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122210. 1, 18,
  122211. _huff_lengthlist_line_2048x27_4sub1,
  122212. 0, 0, 0, 0, 0,
  122213. NULL,
  122214. NULL,
  122215. NULL,
  122216. NULL,
  122217. 0
  122218. };
  122219. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122222. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122223. 10,10,
  122224. };
  122225. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122226. 1, 50,
  122227. _huff_lengthlist_line_2048x27_4sub2,
  122228. 0, 0, 0, 0, 0,
  122229. NULL,
  122230. NULL,
  122231. NULL,
  122232. NULL,
  122233. 0
  122234. };
  122235. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122239. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122240. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122241. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122242. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122243. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122244. };
  122245. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122246. 1, 128,
  122247. _huff_lengthlist_line_2048x27_4sub3,
  122248. 0, 0, 0, 0, 0,
  122249. NULL,
  122250. NULL,
  122251. NULL,
  122252. NULL,
  122253. 0
  122254. };
  122255. static long _huff_lengthlist_line_256x4low_class0[] = {
  122256. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122257. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122258. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122259. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122260. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122261. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122262. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122263. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122264. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122265. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122266. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122267. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122268. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122269. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122270. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122271. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122272. };
  122273. static static_codebook _huff_book_line_256x4low_class0 = {
  122274. 1, 256,
  122275. _huff_lengthlist_line_256x4low_class0,
  122276. 0, 0, 0, 0, 0,
  122277. NULL,
  122278. NULL,
  122279. NULL,
  122280. NULL,
  122281. 0
  122282. };
  122283. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122284. 1, 3, 2, 3,
  122285. };
  122286. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122287. 1, 4,
  122288. _huff_lengthlist_line_256x4low_0sub0,
  122289. 0, 0, 0, 0, 0,
  122290. NULL,
  122291. NULL,
  122292. NULL,
  122293. NULL,
  122294. 0
  122295. };
  122296. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122297. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122298. };
  122299. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122300. 1, 10,
  122301. _huff_lengthlist_line_256x4low_0sub1,
  122302. 0, 0, 0, 0, 0,
  122303. NULL,
  122304. NULL,
  122305. NULL,
  122306. NULL,
  122307. 0
  122308. };
  122309. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122311. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122312. };
  122313. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122314. 1, 25,
  122315. _huff_lengthlist_line_256x4low_0sub2,
  122316. 0, 0, 0, 0, 0,
  122317. NULL,
  122318. NULL,
  122319. NULL,
  122320. NULL,
  122321. 0
  122322. };
  122323. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122326. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122327. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122328. };
  122329. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122330. 1, 64,
  122331. _huff_lengthlist_line_256x4low_0sub3,
  122332. 0, 0, 0, 0, 0,
  122333. NULL,
  122334. NULL,
  122335. NULL,
  122336. NULL,
  122337. 0
  122338. };
  122339. /*** End of inlined file: floor_books.h ***/
  122340. static static_codebook *_floor_128x4_books[]={
  122341. &_huff_book_line_128x4_class0,
  122342. &_huff_book_line_128x4_0sub0,
  122343. &_huff_book_line_128x4_0sub1,
  122344. &_huff_book_line_128x4_0sub2,
  122345. &_huff_book_line_128x4_0sub3,
  122346. };
  122347. static static_codebook *_floor_256x4_books[]={
  122348. &_huff_book_line_256x4_class0,
  122349. &_huff_book_line_256x4_0sub0,
  122350. &_huff_book_line_256x4_0sub1,
  122351. &_huff_book_line_256x4_0sub2,
  122352. &_huff_book_line_256x4_0sub3,
  122353. };
  122354. static static_codebook *_floor_128x7_books[]={
  122355. &_huff_book_line_128x7_class0,
  122356. &_huff_book_line_128x7_class1,
  122357. &_huff_book_line_128x7_0sub1,
  122358. &_huff_book_line_128x7_0sub2,
  122359. &_huff_book_line_128x7_0sub3,
  122360. &_huff_book_line_128x7_1sub1,
  122361. &_huff_book_line_128x7_1sub2,
  122362. &_huff_book_line_128x7_1sub3,
  122363. };
  122364. static static_codebook *_floor_256x7_books[]={
  122365. &_huff_book_line_256x7_class0,
  122366. &_huff_book_line_256x7_class1,
  122367. &_huff_book_line_256x7_0sub1,
  122368. &_huff_book_line_256x7_0sub2,
  122369. &_huff_book_line_256x7_0sub3,
  122370. &_huff_book_line_256x7_1sub1,
  122371. &_huff_book_line_256x7_1sub2,
  122372. &_huff_book_line_256x7_1sub3,
  122373. };
  122374. static static_codebook *_floor_128x11_books[]={
  122375. &_huff_book_line_128x11_class1,
  122376. &_huff_book_line_128x11_class2,
  122377. &_huff_book_line_128x11_class3,
  122378. &_huff_book_line_128x11_0sub0,
  122379. &_huff_book_line_128x11_1sub0,
  122380. &_huff_book_line_128x11_1sub1,
  122381. &_huff_book_line_128x11_2sub1,
  122382. &_huff_book_line_128x11_2sub2,
  122383. &_huff_book_line_128x11_2sub3,
  122384. &_huff_book_line_128x11_3sub1,
  122385. &_huff_book_line_128x11_3sub2,
  122386. &_huff_book_line_128x11_3sub3,
  122387. };
  122388. static static_codebook *_floor_128x17_books[]={
  122389. &_huff_book_line_128x17_class1,
  122390. &_huff_book_line_128x17_class2,
  122391. &_huff_book_line_128x17_class3,
  122392. &_huff_book_line_128x17_0sub0,
  122393. &_huff_book_line_128x17_1sub0,
  122394. &_huff_book_line_128x17_1sub1,
  122395. &_huff_book_line_128x17_2sub1,
  122396. &_huff_book_line_128x17_2sub2,
  122397. &_huff_book_line_128x17_2sub3,
  122398. &_huff_book_line_128x17_3sub1,
  122399. &_huff_book_line_128x17_3sub2,
  122400. &_huff_book_line_128x17_3sub3,
  122401. };
  122402. static static_codebook *_floor_256x4low_books[]={
  122403. &_huff_book_line_256x4low_class0,
  122404. &_huff_book_line_256x4low_0sub0,
  122405. &_huff_book_line_256x4low_0sub1,
  122406. &_huff_book_line_256x4low_0sub2,
  122407. &_huff_book_line_256x4low_0sub3,
  122408. };
  122409. static static_codebook *_floor_1024x27_books[]={
  122410. &_huff_book_line_1024x27_class1,
  122411. &_huff_book_line_1024x27_class2,
  122412. &_huff_book_line_1024x27_class3,
  122413. &_huff_book_line_1024x27_class4,
  122414. &_huff_book_line_1024x27_0sub0,
  122415. &_huff_book_line_1024x27_1sub0,
  122416. &_huff_book_line_1024x27_1sub1,
  122417. &_huff_book_line_1024x27_2sub0,
  122418. &_huff_book_line_1024x27_2sub1,
  122419. &_huff_book_line_1024x27_3sub1,
  122420. &_huff_book_line_1024x27_3sub2,
  122421. &_huff_book_line_1024x27_3sub3,
  122422. &_huff_book_line_1024x27_4sub1,
  122423. &_huff_book_line_1024x27_4sub2,
  122424. &_huff_book_line_1024x27_4sub3,
  122425. };
  122426. static static_codebook *_floor_2048x27_books[]={
  122427. &_huff_book_line_2048x27_class1,
  122428. &_huff_book_line_2048x27_class2,
  122429. &_huff_book_line_2048x27_class3,
  122430. &_huff_book_line_2048x27_class4,
  122431. &_huff_book_line_2048x27_0sub0,
  122432. &_huff_book_line_2048x27_1sub0,
  122433. &_huff_book_line_2048x27_1sub1,
  122434. &_huff_book_line_2048x27_2sub0,
  122435. &_huff_book_line_2048x27_2sub1,
  122436. &_huff_book_line_2048x27_3sub1,
  122437. &_huff_book_line_2048x27_3sub2,
  122438. &_huff_book_line_2048x27_3sub3,
  122439. &_huff_book_line_2048x27_4sub1,
  122440. &_huff_book_line_2048x27_4sub2,
  122441. &_huff_book_line_2048x27_4sub3,
  122442. };
  122443. static static_codebook *_floor_512x17_books[]={
  122444. &_huff_book_line_512x17_class1,
  122445. &_huff_book_line_512x17_class2,
  122446. &_huff_book_line_512x17_class3,
  122447. &_huff_book_line_512x17_0sub0,
  122448. &_huff_book_line_512x17_1sub0,
  122449. &_huff_book_line_512x17_1sub1,
  122450. &_huff_book_line_512x17_2sub1,
  122451. &_huff_book_line_512x17_2sub2,
  122452. &_huff_book_line_512x17_2sub3,
  122453. &_huff_book_line_512x17_3sub1,
  122454. &_huff_book_line_512x17_3sub2,
  122455. &_huff_book_line_512x17_3sub3,
  122456. };
  122457. static static_codebook **_floor_books[10]={
  122458. _floor_128x4_books,
  122459. _floor_256x4_books,
  122460. _floor_128x7_books,
  122461. _floor_256x7_books,
  122462. _floor_128x11_books,
  122463. _floor_128x17_books,
  122464. _floor_256x4low_books,
  122465. _floor_1024x27_books,
  122466. _floor_2048x27_books,
  122467. _floor_512x17_books,
  122468. };
  122469. static vorbis_info_floor1 _floor[10]={
  122470. /* 128 x 4 */
  122471. {
  122472. 1,{0},{4},{2},{0},
  122473. {{1,2,3,4}},
  122474. 4,{0,128, 33,8,16,70},
  122475. 60,30,500, 1.,18., -1
  122476. },
  122477. /* 256 x 4 */
  122478. {
  122479. 1,{0},{4},{2},{0},
  122480. {{1,2,3,4}},
  122481. 4,{0,256, 66,16,32,140},
  122482. 60,30,500, 1.,18., -1
  122483. },
  122484. /* 128 x 7 */
  122485. {
  122486. 2,{0,1},{3,4},{2,2},{0,1},
  122487. {{-1,2,3,4},{-1,5,6,7}},
  122488. 4,{0,128, 14,4,58, 2,8,28,90},
  122489. 60,30,500, 1.,18., -1
  122490. },
  122491. /* 256 x 7 */
  122492. {
  122493. 2,{0,1},{3,4},{2,2},{0,1},
  122494. {{-1,2,3,4},{-1,5,6,7}},
  122495. 4,{0,256, 28,8,116, 4,16,56,180},
  122496. 60,30,500, 1.,18., -1
  122497. },
  122498. /* 128 x 11 */
  122499. {
  122500. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122501. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122502. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122503. 60,30,500, 1,18., -1
  122504. },
  122505. /* 128 x 17 */
  122506. {
  122507. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122508. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122509. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122510. 60,30,500, 1,18., -1
  122511. },
  122512. /* 256 x 4 (low bitrate version) */
  122513. {
  122514. 1,{0},{4},{2},{0},
  122515. {{1,2,3,4}},
  122516. 4,{0,256, 66,16,32,140},
  122517. 60,30,500, 1.,18., -1
  122518. },
  122519. /* 1024 x 27 */
  122520. {
  122521. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122522. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122523. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122524. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122525. 60,30,500, 3,18., -1 /* lowpass */
  122526. },
  122527. /* 2048 x 27 */
  122528. {
  122529. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122530. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122531. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122532. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122533. 60,30,500, 3,18., -1 /* lowpass */
  122534. },
  122535. /* 512 x 17 */
  122536. {
  122537. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122538. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122539. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122540. 7,23,39, 55,79,110, 156,232,360},
  122541. 60,30,500, 1,18., -1 /* lowpass! */
  122542. },
  122543. };
  122544. /*** End of inlined file: floor_all.h ***/
  122545. /*** Start of inlined file: residue_44.h ***/
  122546. /*** Start of inlined file: res_books_stereo.h ***/
  122547. static long _vq_quantlist__16c0_s_p1_0[] = {
  122548. 1,
  122549. 0,
  122550. 2,
  122551. };
  122552. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122553. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122554. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122559. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122564. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122599. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122604. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122609. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122645. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122650. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122655. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0,
  122964. };
  122965. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122966. -0.5, 0.5,
  122967. };
  122968. static long _vq_quantmap__16c0_s_p1_0[] = {
  122969. 1, 0, 2,
  122970. };
  122971. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122972. _vq_quantthresh__16c0_s_p1_0,
  122973. _vq_quantmap__16c0_s_p1_0,
  122974. 3,
  122975. 3
  122976. };
  122977. static static_codebook _16c0_s_p1_0 = {
  122978. 8, 6561,
  122979. _vq_lengthlist__16c0_s_p1_0,
  122980. 1, -535822336, 1611661312, 2, 0,
  122981. _vq_quantlist__16c0_s_p1_0,
  122982. NULL,
  122983. &_vq_auxt__16c0_s_p1_0,
  122984. NULL,
  122985. 0
  122986. };
  122987. static long _vq_quantlist__16c0_s_p2_0[] = {
  122988. 2,
  122989. 1,
  122990. 3,
  122991. 0,
  122992. 4,
  122993. };
  122994. static long _vq_lengthlist__16c0_s_p2_0[] = {
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0,
  123035. };
  123036. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123037. -1.5, -0.5, 0.5, 1.5,
  123038. };
  123039. static long _vq_quantmap__16c0_s_p2_0[] = {
  123040. 3, 1, 0, 2, 4,
  123041. };
  123042. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123043. _vq_quantthresh__16c0_s_p2_0,
  123044. _vq_quantmap__16c0_s_p2_0,
  123045. 5,
  123046. 5
  123047. };
  123048. static static_codebook _16c0_s_p2_0 = {
  123049. 4, 625,
  123050. _vq_lengthlist__16c0_s_p2_0,
  123051. 1, -533725184, 1611661312, 3, 0,
  123052. _vq_quantlist__16c0_s_p2_0,
  123053. NULL,
  123054. &_vq_auxt__16c0_s_p2_0,
  123055. NULL,
  123056. 0
  123057. };
  123058. static long _vq_quantlist__16c0_s_p3_0[] = {
  123059. 2,
  123060. 1,
  123061. 3,
  123062. 0,
  123063. 4,
  123064. };
  123065. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123066. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0,
  123106. };
  123107. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123108. -1.5, -0.5, 0.5, 1.5,
  123109. };
  123110. static long _vq_quantmap__16c0_s_p3_0[] = {
  123111. 3, 1, 0, 2, 4,
  123112. };
  123113. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123114. _vq_quantthresh__16c0_s_p3_0,
  123115. _vq_quantmap__16c0_s_p3_0,
  123116. 5,
  123117. 5
  123118. };
  123119. static static_codebook _16c0_s_p3_0 = {
  123120. 4, 625,
  123121. _vq_lengthlist__16c0_s_p3_0,
  123122. 1, -533725184, 1611661312, 3, 0,
  123123. _vq_quantlist__16c0_s_p3_0,
  123124. NULL,
  123125. &_vq_auxt__16c0_s_p3_0,
  123126. NULL,
  123127. 0
  123128. };
  123129. static long _vq_quantlist__16c0_s_p4_0[] = {
  123130. 4,
  123131. 3,
  123132. 5,
  123133. 2,
  123134. 6,
  123135. 1,
  123136. 7,
  123137. 0,
  123138. 8,
  123139. };
  123140. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123141. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123142. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123143. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123144. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123145. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0,
  123147. };
  123148. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123149. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123150. };
  123151. static long _vq_quantmap__16c0_s_p4_0[] = {
  123152. 7, 5, 3, 1, 0, 2, 4, 6,
  123153. 8,
  123154. };
  123155. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123156. _vq_quantthresh__16c0_s_p4_0,
  123157. _vq_quantmap__16c0_s_p4_0,
  123158. 9,
  123159. 9
  123160. };
  123161. static static_codebook _16c0_s_p4_0 = {
  123162. 2, 81,
  123163. _vq_lengthlist__16c0_s_p4_0,
  123164. 1, -531628032, 1611661312, 4, 0,
  123165. _vq_quantlist__16c0_s_p4_0,
  123166. NULL,
  123167. &_vq_auxt__16c0_s_p4_0,
  123168. NULL,
  123169. 0
  123170. };
  123171. static long _vq_quantlist__16c0_s_p5_0[] = {
  123172. 4,
  123173. 3,
  123174. 5,
  123175. 2,
  123176. 6,
  123177. 1,
  123178. 7,
  123179. 0,
  123180. 8,
  123181. };
  123182. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123183. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123184. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123185. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123186. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123187. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123188. 10,
  123189. };
  123190. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123191. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123192. };
  123193. static long _vq_quantmap__16c0_s_p5_0[] = {
  123194. 7, 5, 3, 1, 0, 2, 4, 6,
  123195. 8,
  123196. };
  123197. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123198. _vq_quantthresh__16c0_s_p5_0,
  123199. _vq_quantmap__16c0_s_p5_0,
  123200. 9,
  123201. 9
  123202. };
  123203. static static_codebook _16c0_s_p5_0 = {
  123204. 2, 81,
  123205. _vq_lengthlist__16c0_s_p5_0,
  123206. 1, -531628032, 1611661312, 4, 0,
  123207. _vq_quantlist__16c0_s_p5_0,
  123208. NULL,
  123209. &_vq_auxt__16c0_s_p5_0,
  123210. NULL,
  123211. 0
  123212. };
  123213. static long _vq_quantlist__16c0_s_p6_0[] = {
  123214. 8,
  123215. 7,
  123216. 9,
  123217. 6,
  123218. 10,
  123219. 5,
  123220. 11,
  123221. 4,
  123222. 12,
  123223. 3,
  123224. 13,
  123225. 2,
  123226. 14,
  123227. 1,
  123228. 15,
  123229. 0,
  123230. 16,
  123231. };
  123232. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123233. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123234. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123235. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123236. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123237. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123238. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123239. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123240. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123241. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123242. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123243. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123244. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123245. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123246. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123247. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123248. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123249. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123251. 14,
  123252. };
  123253. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123254. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123255. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123256. };
  123257. static long _vq_quantmap__16c0_s_p6_0[] = {
  123258. 15, 13, 11, 9, 7, 5, 3, 1,
  123259. 0, 2, 4, 6, 8, 10, 12, 14,
  123260. 16,
  123261. };
  123262. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123263. _vq_quantthresh__16c0_s_p6_0,
  123264. _vq_quantmap__16c0_s_p6_0,
  123265. 17,
  123266. 17
  123267. };
  123268. static static_codebook _16c0_s_p6_0 = {
  123269. 2, 289,
  123270. _vq_lengthlist__16c0_s_p6_0,
  123271. 1, -529530880, 1611661312, 5, 0,
  123272. _vq_quantlist__16c0_s_p6_0,
  123273. NULL,
  123274. &_vq_auxt__16c0_s_p6_0,
  123275. NULL,
  123276. 0
  123277. };
  123278. static long _vq_quantlist__16c0_s_p7_0[] = {
  123279. 1,
  123280. 0,
  123281. 2,
  123282. };
  123283. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123284. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123285. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123286. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123287. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123288. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123289. 13,
  123290. };
  123291. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123292. -5.5, 5.5,
  123293. };
  123294. static long _vq_quantmap__16c0_s_p7_0[] = {
  123295. 1, 0, 2,
  123296. };
  123297. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123298. _vq_quantthresh__16c0_s_p7_0,
  123299. _vq_quantmap__16c0_s_p7_0,
  123300. 3,
  123301. 3
  123302. };
  123303. static static_codebook _16c0_s_p7_0 = {
  123304. 4, 81,
  123305. _vq_lengthlist__16c0_s_p7_0,
  123306. 1, -529137664, 1618345984, 2, 0,
  123307. _vq_quantlist__16c0_s_p7_0,
  123308. NULL,
  123309. &_vq_auxt__16c0_s_p7_0,
  123310. NULL,
  123311. 0
  123312. };
  123313. static long _vq_quantlist__16c0_s_p7_1[] = {
  123314. 5,
  123315. 4,
  123316. 6,
  123317. 3,
  123318. 7,
  123319. 2,
  123320. 8,
  123321. 1,
  123322. 9,
  123323. 0,
  123324. 10,
  123325. };
  123326. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123327. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123328. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123329. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123330. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123331. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123332. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123333. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123334. 11,11,11, 9, 9, 9, 9,10,10,
  123335. };
  123336. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123337. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123338. 3.5, 4.5,
  123339. };
  123340. static long _vq_quantmap__16c0_s_p7_1[] = {
  123341. 9, 7, 5, 3, 1, 0, 2, 4,
  123342. 6, 8, 10,
  123343. };
  123344. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123345. _vq_quantthresh__16c0_s_p7_1,
  123346. _vq_quantmap__16c0_s_p7_1,
  123347. 11,
  123348. 11
  123349. };
  123350. static static_codebook _16c0_s_p7_1 = {
  123351. 2, 121,
  123352. _vq_lengthlist__16c0_s_p7_1,
  123353. 1, -531365888, 1611661312, 4, 0,
  123354. _vq_quantlist__16c0_s_p7_1,
  123355. NULL,
  123356. &_vq_auxt__16c0_s_p7_1,
  123357. NULL,
  123358. 0
  123359. };
  123360. static long _vq_quantlist__16c0_s_p8_0[] = {
  123361. 6,
  123362. 5,
  123363. 7,
  123364. 4,
  123365. 8,
  123366. 3,
  123367. 9,
  123368. 2,
  123369. 10,
  123370. 1,
  123371. 11,
  123372. 0,
  123373. 12,
  123374. };
  123375. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123376. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123377. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123378. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123379. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123380. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123381. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123382. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123383. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123384. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123385. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123386. 0,12,13,13,12,13,14,14,14,
  123387. };
  123388. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123389. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123390. 12.5, 17.5, 22.5, 27.5,
  123391. };
  123392. static long _vq_quantmap__16c0_s_p8_0[] = {
  123393. 11, 9, 7, 5, 3, 1, 0, 2,
  123394. 4, 6, 8, 10, 12,
  123395. };
  123396. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123397. _vq_quantthresh__16c0_s_p8_0,
  123398. _vq_quantmap__16c0_s_p8_0,
  123399. 13,
  123400. 13
  123401. };
  123402. static static_codebook _16c0_s_p8_0 = {
  123403. 2, 169,
  123404. _vq_lengthlist__16c0_s_p8_0,
  123405. 1, -526516224, 1616117760, 4, 0,
  123406. _vq_quantlist__16c0_s_p8_0,
  123407. NULL,
  123408. &_vq_auxt__16c0_s_p8_0,
  123409. NULL,
  123410. 0
  123411. };
  123412. static long _vq_quantlist__16c0_s_p8_1[] = {
  123413. 2,
  123414. 1,
  123415. 3,
  123416. 0,
  123417. 4,
  123418. };
  123419. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123420. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123421. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123422. };
  123423. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123424. -1.5, -0.5, 0.5, 1.5,
  123425. };
  123426. static long _vq_quantmap__16c0_s_p8_1[] = {
  123427. 3, 1, 0, 2, 4,
  123428. };
  123429. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123430. _vq_quantthresh__16c0_s_p8_1,
  123431. _vq_quantmap__16c0_s_p8_1,
  123432. 5,
  123433. 5
  123434. };
  123435. static static_codebook _16c0_s_p8_1 = {
  123436. 2, 25,
  123437. _vq_lengthlist__16c0_s_p8_1,
  123438. 1, -533725184, 1611661312, 3, 0,
  123439. _vq_quantlist__16c0_s_p8_1,
  123440. NULL,
  123441. &_vq_auxt__16c0_s_p8_1,
  123442. NULL,
  123443. 0
  123444. };
  123445. static long _vq_quantlist__16c0_s_p9_0[] = {
  123446. 1,
  123447. 0,
  123448. 2,
  123449. };
  123450. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123451. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123452. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123453. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123454. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123455. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123456. 7,
  123457. };
  123458. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123459. -157.5, 157.5,
  123460. };
  123461. static long _vq_quantmap__16c0_s_p9_0[] = {
  123462. 1, 0, 2,
  123463. };
  123464. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123465. _vq_quantthresh__16c0_s_p9_0,
  123466. _vq_quantmap__16c0_s_p9_0,
  123467. 3,
  123468. 3
  123469. };
  123470. static static_codebook _16c0_s_p9_0 = {
  123471. 4, 81,
  123472. _vq_lengthlist__16c0_s_p9_0,
  123473. 1, -518803456, 1628680192, 2, 0,
  123474. _vq_quantlist__16c0_s_p9_0,
  123475. NULL,
  123476. &_vq_auxt__16c0_s_p9_0,
  123477. NULL,
  123478. 0
  123479. };
  123480. static long _vq_quantlist__16c0_s_p9_1[] = {
  123481. 7,
  123482. 6,
  123483. 8,
  123484. 5,
  123485. 9,
  123486. 4,
  123487. 10,
  123488. 3,
  123489. 11,
  123490. 2,
  123491. 12,
  123492. 1,
  123493. 13,
  123494. 0,
  123495. 14,
  123496. };
  123497. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123498. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123499. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123500. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123501. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123502. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123503. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123504. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123505. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123506. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123507. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123508. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123509. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123510. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123511. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123512. 10,
  123513. };
  123514. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123515. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123516. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123517. };
  123518. static long _vq_quantmap__16c0_s_p9_1[] = {
  123519. 13, 11, 9, 7, 5, 3, 1, 0,
  123520. 2, 4, 6, 8, 10, 12, 14,
  123521. };
  123522. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123523. _vq_quantthresh__16c0_s_p9_1,
  123524. _vq_quantmap__16c0_s_p9_1,
  123525. 15,
  123526. 15
  123527. };
  123528. static static_codebook _16c0_s_p9_1 = {
  123529. 2, 225,
  123530. _vq_lengthlist__16c0_s_p9_1,
  123531. 1, -520986624, 1620377600, 4, 0,
  123532. _vq_quantlist__16c0_s_p9_1,
  123533. NULL,
  123534. &_vq_auxt__16c0_s_p9_1,
  123535. NULL,
  123536. 0
  123537. };
  123538. static long _vq_quantlist__16c0_s_p9_2[] = {
  123539. 10,
  123540. 9,
  123541. 11,
  123542. 8,
  123543. 12,
  123544. 7,
  123545. 13,
  123546. 6,
  123547. 14,
  123548. 5,
  123549. 15,
  123550. 4,
  123551. 16,
  123552. 3,
  123553. 17,
  123554. 2,
  123555. 18,
  123556. 1,
  123557. 19,
  123558. 0,
  123559. 20,
  123560. };
  123561. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123562. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123563. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123564. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123565. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123566. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123567. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123568. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123569. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123570. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123571. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123572. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123573. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123574. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123575. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123576. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123577. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123578. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123579. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123580. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123581. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123582. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123583. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123584. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123585. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123586. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123587. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123588. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123589. 10,11,10,10,11, 9,10,10,10,
  123590. };
  123591. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123592. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123593. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123594. 6.5, 7.5, 8.5, 9.5,
  123595. };
  123596. static long _vq_quantmap__16c0_s_p9_2[] = {
  123597. 19, 17, 15, 13, 11, 9, 7, 5,
  123598. 3, 1, 0, 2, 4, 6, 8, 10,
  123599. 12, 14, 16, 18, 20,
  123600. };
  123601. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123602. _vq_quantthresh__16c0_s_p9_2,
  123603. _vq_quantmap__16c0_s_p9_2,
  123604. 21,
  123605. 21
  123606. };
  123607. static static_codebook _16c0_s_p9_2 = {
  123608. 2, 441,
  123609. _vq_lengthlist__16c0_s_p9_2,
  123610. 1, -529268736, 1611661312, 5, 0,
  123611. _vq_quantlist__16c0_s_p9_2,
  123612. NULL,
  123613. &_vq_auxt__16c0_s_p9_2,
  123614. NULL,
  123615. 0
  123616. };
  123617. static long _huff_lengthlist__16c0_s_single[] = {
  123618. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123619. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123620. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123621. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123622. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123623. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123624. 16,16,18,18,
  123625. };
  123626. static static_codebook _huff_book__16c0_s_single = {
  123627. 2, 100,
  123628. _huff_lengthlist__16c0_s_single,
  123629. 0, 0, 0, 0, 0,
  123630. NULL,
  123631. NULL,
  123632. NULL,
  123633. NULL,
  123634. 0
  123635. };
  123636. static long _huff_lengthlist__16c1_s_long[] = {
  123637. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123638. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123639. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123640. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123641. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123642. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123643. 12,11,11,13,
  123644. };
  123645. static static_codebook _huff_book__16c1_s_long = {
  123646. 2, 100,
  123647. _huff_lengthlist__16c1_s_long,
  123648. 0, 0, 0, 0, 0,
  123649. NULL,
  123650. NULL,
  123651. NULL,
  123652. NULL,
  123653. 0
  123654. };
  123655. static long _vq_quantlist__16c1_s_p1_0[] = {
  123656. 1,
  123657. 0,
  123658. 2,
  123659. };
  123660. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123661. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123662. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123667. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123672. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123707. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123712. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123717. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123753. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123758. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123763. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0,
  124072. };
  124073. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124074. -0.5, 0.5,
  124075. };
  124076. static long _vq_quantmap__16c1_s_p1_0[] = {
  124077. 1, 0, 2,
  124078. };
  124079. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124080. _vq_quantthresh__16c1_s_p1_0,
  124081. _vq_quantmap__16c1_s_p1_0,
  124082. 3,
  124083. 3
  124084. };
  124085. static static_codebook _16c1_s_p1_0 = {
  124086. 8, 6561,
  124087. _vq_lengthlist__16c1_s_p1_0,
  124088. 1, -535822336, 1611661312, 2, 0,
  124089. _vq_quantlist__16c1_s_p1_0,
  124090. NULL,
  124091. &_vq_auxt__16c1_s_p1_0,
  124092. NULL,
  124093. 0
  124094. };
  124095. static long _vq_quantlist__16c1_s_p2_0[] = {
  124096. 2,
  124097. 1,
  124098. 3,
  124099. 0,
  124100. 4,
  124101. };
  124102. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0,
  124143. };
  124144. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124145. -1.5, -0.5, 0.5, 1.5,
  124146. };
  124147. static long _vq_quantmap__16c1_s_p2_0[] = {
  124148. 3, 1, 0, 2, 4,
  124149. };
  124150. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124151. _vq_quantthresh__16c1_s_p2_0,
  124152. _vq_quantmap__16c1_s_p2_0,
  124153. 5,
  124154. 5
  124155. };
  124156. static static_codebook _16c1_s_p2_0 = {
  124157. 4, 625,
  124158. _vq_lengthlist__16c1_s_p2_0,
  124159. 1, -533725184, 1611661312, 3, 0,
  124160. _vq_quantlist__16c1_s_p2_0,
  124161. NULL,
  124162. &_vq_auxt__16c1_s_p2_0,
  124163. NULL,
  124164. 0
  124165. };
  124166. static long _vq_quantlist__16c1_s_p3_0[] = {
  124167. 2,
  124168. 1,
  124169. 3,
  124170. 0,
  124171. 4,
  124172. };
  124173. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124174. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0,
  124214. };
  124215. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124216. -1.5, -0.5, 0.5, 1.5,
  124217. };
  124218. static long _vq_quantmap__16c1_s_p3_0[] = {
  124219. 3, 1, 0, 2, 4,
  124220. };
  124221. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124222. _vq_quantthresh__16c1_s_p3_0,
  124223. _vq_quantmap__16c1_s_p3_0,
  124224. 5,
  124225. 5
  124226. };
  124227. static static_codebook _16c1_s_p3_0 = {
  124228. 4, 625,
  124229. _vq_lengthlist__16c1_s_p3_0,
  124230. 1, -533725184, 1611661312, 3, 0,
  124231. _vq_quantlist__16c1_s_p3_0,
  124232. NULL,
  124233. &_vq_auxt__16c1_s_p3_0,
  124234. NULL,
  124235. 0
  124236. };
  124237. static long _vq_quantlist__16c1_s_p4_0[] = {
  124238. 4,
  124239. 3,
  124240. 5,
  124241. 2,
  124242. 6,
  124243. 1,
  124244. 7,
  124245. 0,
  124246. 8,
  124247. };
  124248. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124249. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124250. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124251. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124252. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124253. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0,
  124255. };
  124256. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124257. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124258. };
  124259. static long _vq_quantmap__16c1_s_p4_0[] = {
  124260. 7, 5, 3, 1, 0, 2, 4, 6,
  124261. 8,
  124262. };
  124263. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124264. _vq_quantthresh__16c1_s_p4_0,
  124265. _vq_quantmap__16c1_s_p4_0,
  124266. 9,
  124267. 9
  124268. };
  124269. static static_codebook _16c1_s_p4_0 = {
  124270. 2, 81,
  124271. _vq_lengthlist__16c1_s_p4_0,
  124272. 1, -531628032, 1611661312, 4, 0,
  124273. _vq_quantlist__16c1_s_p4_0,
  124274. NULL,
  124275. &_vq_auxt__16c1_s_p4_0,
  124276. NULL,
  124277. 0
  124278. };
  124279. static long _vq_quantlist__16c1_s_p5_0[] = {
  124280. 4,
  124281. 3,
  124282. 5,
  124283. 2,
  124284. 6,
  124285. 1,
  124286. 7,
  124287. 0,
  124288. 8,
  124289. };
  124290. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124291. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124292. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124293. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124294. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124295. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124296. 10,
  124297. };
  124298. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124299. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124300. };
  124301. static long _vq_quantmap__16c1_s_p5_0[] = {
  124302. 7, 5, 3, 1, 0, 2, 4, 6,
  124303. 8,
  124304. };
  124305. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124306. _vq_quantthresh__16c1_s_p5_0,
  124307. _vq_quantmap__16c1_s_p5_0,
  124308. 9,
  124309. 9
  124310. };
  124311. static static_codebook _16c1_s_p5_0 = {
  124312. 2, 81,
  124313. _vq_lengthlist__16c1_s_p5_0,
  124314. 1, -531628032, 1611661312, 4, 0,
  124315. _vq_quantlist__16c1_s_p5_0,
  124316. NULL,
  124317. &_vq_auxt__16c1_s_p5_0,
  124318. NULL,
  124319. 0
  124320. };
  124321. static long _vq_quantlist__16c1_s_p6_0[] = {
  124322. 8,
  124323. 7,
  124324. 9,
  124325. 6,
  124326. 10,
  124327. 5,
  124328. 11,
  124329. 4,
  124330. 12,
  124331. 3,
  124332. 13,
  124333. 2,
  124334. 14,
  124335. 1,
  124336. 15,
  124337. 0,
  124338. 16,
  124339. };
  124340. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124341. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124342. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124343. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124344. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124345. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124346. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124347. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124348. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124349. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124350. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124351. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124352. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124353. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124354. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124355. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124356. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124357. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124358. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124359. 14,
  124360. };
  124361. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124362. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124363. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124364. };
  124365. static long _vq_quantmap__16c1_s_p6_0[] = {
  124366. 15, 13, 11, 9, 7, 5, 3, 1,
  124367. 0, 2, 4, 6, 8, 10, 12, 14,
  124368. 16,
  124369. };
  124370. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124371. _vq_quantthresh__16c1_s_p6_0,
  124372. _vq_quantmap__16c1_s_p6_0,
  124373. 17,
  124374. 17
  124375. };
  124376. static static_codebook _16c1_s_p6_0 = {
  124377. 2, 289,
  124378. _vq_lengthlist__16c1_s_p6_0,
  124379. 1, -529530880, 1611661312, 5, 0,
  124380. _vq_quantlist__16c1_s_p6_0,
  124381. NULL,
  124382. &_vq_auxt__16c1_s_p6_0,
  124383. NULL,
  124384. 0
  124385. };
  124386. static long _vq_quantlist__16c1_s_p7_0[] = {
  124387. 1,
  124388. 0,
  124389. 2,
  124390. };
  124391. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124392. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124393. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124394. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124395. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124396. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124397. 11,
  124398. };
  124399. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124400. -5.5, 5.5,
  124401. };
  124402. static long _vq_quantmap__16c1_s_p7_0[] = {
  124403. 1, 0, 2,
  124404. };
  124405. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124406. _vq_quantthresh__16c1_s_p7_0,
  124407. _vq_quantmap__16c1_s_p7_0,
  124408. 3,
  124409. 3
  124410. };
  124411. static static_codebook _16c1_s_p7_0 = {
  124412. 4, 81,
  124413. _vq_lengthlist__16c1_s_p7_0,
  124414. 1, -529137664, 1618345984, 2, 0,
  124415. _vq_quantlist__16c1_s_p7_0,
  124416. NULL,
  124417. &_vq_auxt__16c1_s_p7_0,
  124418. NULL,
  124419. 0
  124420. };
  124421. static long _vq_quantlist__16c1_s_p7_1[] = {
  124422. 5,
  124423. 4,
  124424. 6,
  124425. 3,
  124426. 7,
  124427. 2,
  124428. 8,
  124429. 1,
  124430. 9,
  124431. 0,
  124432. 10,
  124433. };
  124434. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124435. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124436. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124437. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124438. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124439. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124440. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124441. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124442. 10,10,10, 8, 8, 8, 8, 9, 9,
  124443. };
  124444. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124445. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124446. 3.5, 4.5,
  124447. };
  124448. static long _vq_quantmap__16c1_s_p7_1[] = {
  124449. 9, 7, 5, 3, 1, 0, 2, 4,
  124450. 6, 8, 10,
  124451. };
  124452. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124453. _vq_quantthresh__16c1_s_p7_1,
  124454. _vq_quantmap__16c1_s_p7_1,
  124455. 11,
  124456. 11
  124457. };
  124458. static static_codebook _16c1_s_p7_1 = {
  124459. 2, 121,
  124460. _vq_lengthlist__16c1_s_p7_1,
  124461. 1, -531365888, 1611661312, 4, 0,
  124462. _vq_quantlist__16c1_s_p7_1,
  124463. NULL,
  124464. &_vq_auxt__16c1_s_p7_1,
  124465. NULL,
  124466. 0
  124467. };
  124468. static long _vq_quantlist__16c1_s_p8_0[] = {
  124469. 6,
  124470. 5,
  124471. 7,
  124472. 4,
  124473. 8,
  124474. 3,
  124475. 9,
  124476. 2,
  124477. 10,
  124478. 1,
  124479. 11,
  124480. 0,
  124481. 12,
  124482. };
  124483. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124484. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124485. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124486. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124487. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124488. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124489. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124490. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124491. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124492. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124493. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124494. 0,12,12,12,12,13,13,14,15,
  124495. };
  124496. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124497. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124498. 12.5, 17.5, 22.5, 27.5,
  124499. };
  124500. static long _vq_quantmap__16c1_s_p8_0[] = {
  124501. 11, 9, 7, 5, 3, 1, 0, 2,
  124502. 4, 6, 8, 10, 12,
  124503. };
  124504. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124505. _vq_quantthresh__16c1_s_p8_0,
  124506. _vq_quantmap__16c1_s_p8_0,
  124507. 13,
  124508. 13
  124509. };
  124510. static static_codebook _16c1_s_p8_0 = {
  124511. 2, 169,
  124512. _vq_lengthlist__16c1_s_p8_0,
  124513. 1, -526516224, 1616117760, 4, 0,
  124514. _vq_quantlist__16c1_s_p8_0,
  124515. NULL,
  124516. &_vq_auxt__16c1_s_p8_0,
  124517. NULL,
  124518. 0
  124519. };
  124520. static long _vq_quantlist__16c1_s_p8_1[] = {
  124521. 2,
  124522. 1,
  124523. 3,
  124524. 0,
  124525. 4,
  124526. };
  124527. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124528. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124529. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124530. };
  124531. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124532. -1.5, -0.5, 0.5, 1.5,
  124533. };
  124534. static long _vq_quantmap__16c1_s_p8_1[] = {
  124535. 3, 1, 0, 2, 4,
  124536. };
  124537. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124538. _vq_quantthresh__16c1_s_p8_1,
  124539. _vq_quantmap__16c1_s_p8_1,
  124540. 5,
  124541. 5
  124542. };
  124543. static static_codebook _16c1_s_p8_1 = {
  124544. 2, 25,
  124545. _vq_lengthlist__16c1_s_p8_1,
  124546. 1, -533725184, 1611661312, 3, 0,
  124547. _vq_quantlist__16c1_s_p8_1,
  124548. NULL,
  124549. &_vq_auxt__16c1_s_p8_1,
  124550. NULL,
  124551. 0
  124552. };
  124553. static long _vq_quantlist__16c1_s_p9_0[] = {
  124554. 6,
  124555. 5,
  124556. 7,
  124557. 4,
  124558. 8,
  124559. 3,
  124560. 9,
  124561. 2,
  124562. 10,
  124563. 1,
  124564. 11,
  124565. 0,
  124566. 12,
  124567. };
  124568. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124569. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124570. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124571. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124572. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124573. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124574. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124575. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124576. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124577. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124578. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124579. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124580. };
  124581. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124582. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124583. 787.5, 1102.5, 1417.5, 1732.5,
  124584. };
  124585. static long _vq_quantmap__16c1_s_p9_0[] = {
  124586. 11, 9, 7, 5, 3, 1, 0, 2,
  124587. 4, 6, 8, 10, 12,
  124588. };
  124589. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124590. _vq_quantthresh__16c1_s_p9_0,
  124591. _vq_quantmap__16c1_s_p9_0,
  124592. 13,
  124593. 13
  124594. };
  124595. static static_codebook _16c1_s_p9_0 = {
  124596. 2, 169,
  124597. _vq_lengthlist__16c1_s_p9_0,
  124598. 1, -513964032, 1628680192, 4, 0,
  124599. _vq_quantlist__16c1_s_p9_0,
  124600. NULL,
  124601. &_vq_auxt__16c1_s_p9_0,
  124602. NULL,
  124603. 0
  124604. };
  124605. static long _vq_quantlist__16c1_s_p9_1[] = {
  124606. 7,
  124607. 6,
  124608. 8,
  124609. 5,
  124610. 9,
  124611. 4,
  124612. 10,
  124613. 3,
  124614. 11,
  124615. 2,
  124616. 12,
  124617. 1,
  124618. 13,
  124619. 0,
  124620. 14,
  124621. };
  124622. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124623. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124624. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124625. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124626. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124627. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124628. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124629. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124630. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124631. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124632. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124633. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124634. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124635. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124636. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124637. 13,
  124638. };
  124639. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124640. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124641. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124642. };
  124643. static long _vq_quantmap__16c1_s_p9_1[] = {
  124644. 13, 11, 9, 7, 5, 3, 1, 0,
  124645. 2, 4, 6, 8, 10, 12, 14,
  124646. };
  124647. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124648. _vq_quantthresh__16c1_s_p9_1,
  124649. _vq_quantmap__16c1_s_p9_1,
  124650. 15,
  124651. 15
  124652. };
  124653. static static_codebook _16c1_s_p9_1 = {
  124654. 2, 225,
  124655. _vq_lengthlist__16c1_s_p9_1,
  124656. 1, -520986624, 1620377600, 4, 0,
  124657. _vq_quantlist__16c1_s_p9_1,
  124658. NULL,
  124659. &_vq_auxt__16c1_s_p9_1,
  124660. NULL,
  124661. 0
  124662. };
  124663. static long _vq_quantlist__16c1_s_p9_2[] = {
  124664. 10,
  124665. 9,
  124666. 11,
  124667. 8,
  124668. 12,
  124669. 7,
  124670. 13,
  124671. 6,
  124672. 14,
  124673. 5,
  124674. 15,
  124675. 4,
  124676. 16,
  124677. 3,
  124678. 17,
  124679. 2,
  124680. 18,
  124681. 1,
  124682. 19,
  124683. 0,
  124684. 20,
  124685. };
  124686. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124687. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124688. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124689. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124690. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124691. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124692. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124693. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124694. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124695. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124696. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124697. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124698. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124699. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124700. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124701. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124702. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124703. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124704. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124705. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124706. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124707. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124708. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124709. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124710. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124711. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124712. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124713. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124714. 11,11,11,11,12,11,11,12,11,
  124715. };
  124716. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124717. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124718. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124719. 6.5, 7.5, 8.5, 9.5,
  124720. };
  124721. static long _vq_quantmap__16c1_s_p9_2[] = {
  124722. 19, 17, 15, 13, 11, 9, 7, 5,
  124723. 3, 1, 0, 2, 4, 6, 8, 10,
  124724. 12, 14, 16, 18, 20,
  124725. };
  124726. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124727. _vq_quantthresh__16c1_s_p9_2,
  124728. _vq_quantmap__16c1_s_p9_2,
  124729. 21,
  124730. 21
  124731. };
  124732. static static_codebook _16c1_s_p9_2 = {
  124733. 2, 441,
  124734. _vq_lengthlist__16c1_s_p9_2,
  124735. 1, -529268736, 1611661312, 5, 0,
  124736. _vq_quantlist__16c1_s_p9_2,
  124737. NULL,
  124738. &_vq_auxt__16c1_s_p9_2,
  124739. NULL,
  124740. 0
  124741. };
  124742. static long _huff_lengthlist__16c1_s_short[] = {
  124743. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124744. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124745. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124746. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124747. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124748. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124749. 9, 9,10,13,
  124750. };
  124751. static static_codebook _huff_book__16c1_s_short = {
  124752. 2, 100,
  124753. _huff_lengthlist__16c1_s_short,
  124754. 0, 0, 0, 0, 0,
  124755. NULL,
  124756. NULL,
  124757. NULL,
  124758. NULL,
  124759. 0
  124760. };
  124761. static long _huff_lengthlist__16c2_s_long[] = {
  124762. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124763. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124764. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124765. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124766. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124767. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124768. 14,14,16,18,
  124769. };
  124770. static static_codebook _huff_book__16c2_s_long = {
  124771. 2, 100,
  124772. _huff_lengthlist__16c2_s_long,
  124773. 0, 0, 0, 0, 0,
  124774. NULL,
  124775. NULL,
  124776. NULL,
  124777. NULL,
  124778. 0
  124779. };
  124780. static long _vq_quantlist__16c2_s_p1_0[] = {
  124781. 1,
  124782. 0,
  124783. 2,
  124784. };
  124785. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124786. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124787. 0, 0, 4, 5, 5, 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,
  124792. };
  124793. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124794. -0.5, 0.5,
  124795. };
  124796. static long _vq_quantmap__16c2_s_p1_0[] = {
  124797. 1, 0, 2,
  124798. };
  124799. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124800. _vq_quantthresh__16c2_s_p1_0,
  124801. _vq_quantmap__16c2_s_p1_0,
  124802. 3,
  124803. 3
  124804. };
  124805. static static_codebook _16c2_s_p1_0 = {
  124806. 4, 81,
  124807. _vq_lengthlist__16c2_s_p1_0,
  124808. 1, -535822336, 1611661312, 2, 0,
  124809. _vq_quantlist__16c2_s_p1_0,
  124810. NULL,
  124811. &_vq_auxt__16c2_s_p1_0,
  124812. NULL,
  124813. 0
  124814. };
  124815. static long _vq_quantlist__16c2_s_p2_0[] = {
  124816. 2,
  124817. 1,
  124818. 3,
  124819. 0,
  124820. 4,
  124821. };
  124822. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124823. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124824. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124825. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124826. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124827. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124828. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124829. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124830. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124835. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124836. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124837. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124838. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124843. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124844. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124845. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124846. 13,13, 0, 0, 0,12,13, 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, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124852. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124853. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124854. 0, 0,13,13, 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, 8,
  124859. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124860. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124861. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124862. 13,
  124863. };
  124864. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124865. -1.5, -0.5, 0.5, 1.5,
  124866. };
  124867. static long _vq_quantmap__16c2_s_p2_0[] = {
  124868. 3, 1, 0, 2, 4,
  124869. };
  124870. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124871. _vq_quantthresh__16c2_s_p2_0,
  124872. _vq_quantmap__16c2_s_p2_0,
  124873. 5,
  124874. 5
  124875. };
  124876. static static_codebook _16c2_s_p2_0 = {
  124877. 4, 625,
  124878. _vq_lengthlist__16c2_s_p2_0,
  124879. 1, -533725184, 1611661312, 3, 0,
  124880. _vq_quantlist__16c2_s_p2_0,
  124881. NULL,
  124882. &_vq_auxt__16c2_s_p2_0,
  124883. NULL,
  124884. 0
  124885. };
  124886. static long _vq_quantlist__16c2_s_p3_0[] = {
  124887. 4,
  124888. 3,
  124889. 5,
  124890. 2,
  124891. 6,
  124892. 1,
  124893. 7,
  124894. 0,
  124895. 8,
  124896. };
  124897. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124898. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124899. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124900. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124901. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124903. 0,
  124904. };
  124905. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124906. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124907. };
  124908. static long _vq_quantmap__16c2_s_p3_0[] = {
  124909. 7, 5, 3, 1, 0, 2, 4, 6,
  124910. 8,
  124911. };
  124912. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124913. _vq_quantthresh__16c2_s_p3_0,
  124914. _vq_quantmap__16c2_s_p3_0,
  124915. 9,
  124916. 9
  124917. };
  124918. static static_codebook _16c2_s_p3_0 = {
  124919. 2, 81,
  124920. _vq_lengthlist__16c2_s_p3_0,
  124921. 1, -531628032, 1611661312, 4, 0,
  124922. _vq_quantlist__16c2_s_p3_0,
  124923. NULL,
  124924. &_vq_auxt__16c2_s_p3_0,
  124925. NULL,
  124926. 0
  124927. };
  124928. static long _vq_quantlist__16c2_s_p4_0[] = {
  124929. 8,
  124930. 7,
  124931. 9,
  124932. 6,
  124933. 10,
  124934. 5,
  124935. 11,
  124936. 4,
  124937. 12,
  124938. 3,
  124939. 13,
  124940. 2,
  124941. 14,
  124942. 1,
  124943. 15,
  124944. 0,
  124945. 16,
  124946. };
  124947. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124948. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124949. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124950. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124951. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124952. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124953. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124954. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124955. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124956. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124957. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124966. 0,
  124967. };
  124968. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124969. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124970. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124971. };
  124972. static long _vq_quantmap__16c2_s_p4_0[] = {
  124973. 15, 13, 11, 9, 7, 5, 3, 1,
  124974. 0, 2, 4, 6, 8, 10, 12, 14,
  124975. 16,
  124976. };
  124977. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124978. _vq_quantthresh__16c2_s_p4_0,
  124979. _vq_quantmap__16c2_s_p4_0,
  124980. 17,
  124981. 17
  124982. };
  124983. static static_codebook _16c2_s_p4_0 = {
  124984. 2, 289,
  124985. _vq_lengthlist__16c2_s_p4_0,
  124986. 1, -529530880, 1611661312, 5, 0,
  124987. _vq_quantlist__16c2_s_p4_0,
  124988. NULL,
  124989. &_vq_auxt__16c2_s_p4_0,
  124990. NULL,
  124991. 0
  124992. };
  124993. static long _vq_quantlist__16c2_s_p5_0[] = {
  124994. 1,
  124995. 0,
  124996. 2,
  124997. };
  124998. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124999. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125000. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125001. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125002. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125003. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125004. 12,
  125005. };
  125006. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125007. -5.5, 5.5,
  125008. };
  125009. static long _vq_quantmap__16c2_s_p5_0[] = {
  125010. 1, 0, 2,
  125011. };
  125012. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125013. _vq_quantthresh__16c2_s_p5_0,
  125014. _vq_quantmap__16c2_s_p5_0,
  125015. 3,
  125016. 3
  125017. };
  125018. static static_codebook _16c2_s_p5_0 = {
  125019. 4, 81,
  125020. _vq_lengthlist__16c2_s_p5_0,
  125021. 1, -529137664, 1618345984, 2, 0,
  125022. _vq_quantlist__16c2_s_p5_0,
  125023. NULL,
  125024. &_vq_auxt__16c2_s_p5_0,
  125025. NULL,
  125026. 0
  125027. };
  125028. static long _vq_quantlist__16c2_s_p5_1[] = {
  125029. 5,
  125030. 4,
  125031. 6,
  125032. 3,
  125033. 7,
  125034. 2,
  125035. 8,
  125036. 1,
  125037. 9,
  125038. 0,
  125039. 10,
  125040. };
  125041. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125042. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125043. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125044. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125045. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125046. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125047. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125048. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125049. 11,11,11, 7, 7, 8, 8, 8, 8,
  125050. };
  125051. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125052. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125053. 3.5, 4.5,
  125054. };
  125055. static long _vq_quantmap__16c2_s_p5_1[] = {
  125056. 9, 7, 5, 3, 1, 0, 2, 4,
  125057. 6, 8, 10,
  125058. };
  125059. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125060. _vq_quantthresh__16c2_s_p5_1,
  125061. _vq_quantmap__16c2_s_p5_1,
  125062. 11,
  125063. 11
  125064. };
  125065. static static_codebook _16c2_s_p5_1 = {
  125066. 2, 121,
  125067. _vq_lengthlist__16c2_s_p5_1,
  125068. 1, -531365888, 1611661312, 4, 0,
  125069. _vq_quantlist__16c2_s_p5_1,
  125070. NULL,
  125071. &_vq_auxt__16c2_s_p5_1,
  125072. NULL,
  125073. 0
  125074. };
  125075. static long _vq_quantlist__16c2_s_p6_0[] = {
  125076. 6,
  125077. 5,
  125078. 7,
  125079. 4,
  125080. 8,
  125081. 3,
  125082. 9,
  125083. 2,
  125084. 10,
  125085. 1,
  125086. 11,
  125087. 0,
  125088. 12,
  125089. };
  125090. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125091. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125092. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125093. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125094. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125095. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125096. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. };
  125103. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125104. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125105. 12.5, 17.5, 22.5, 27.5,
  125106. };
  125107. static long _vq_quantmap__16c2_s_p6_0[] = {
  125108. 11, 9, 7, 5, 3, 1, 0, 2,
  125109. 4, 6, 8, 10, 12,
  125110. };
  125111. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125112. _vq_quantthresh__16c2_s_p6_0,
  125113. _vq_quantmap__16c2_s_p6_0,
  125114. 13,
  125115. 13
  125116. };
  125117. static static_codebook _16c2_s_p6_0 = {
  125118. 2, 169,
  125119. _vq_lengthlist__16c2_s_p6_0,
  125120. 1, -526516224, 1616117760, 4, 0,
  125121. _vq_quantlist__16c2_s_p6_0,
  125122. NULL,
  125123. &_vq_auxt__16c2_s_p6_0,
  125124. NULL,
  125125. 0
  125126. };
  125127. static long _vq_quantlist__16c2_s_p6_1[] = {
  125128. 2,
  125129. 1,
  125130. 3,
  125131. 0,
  125132. 4,
  125133. };
  125134. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125135. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125136. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125137. };
  125138. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125139. -1.5, -0.5, 0.5, 1.5,
  125140. };
  125141. static long _vq_quantmap__16c2_s_p6_1[] = {
  125142. 3, 1, 0, 2, 4,
  125143. };
  125144. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125145. _vq_quantthresh__16c2_s_p6_1,
  125146. _vq_quantmap__16c2_s_p6_1,
  125147. 5,
  125148. 5
  125149. };
  125150. static static_codebook _16c2_s_p6_1 = {
  125151. 2, 25,
  125152. _vq_lengthlist__16c2_s_p6_1,
  125153. 1, -533725184, 1611661312, 3, 0,
  125154. _vq_quantlist__16c2_s_p6_1,
  125155. NULL,
  125156. &_vq_auxt__16c2_s_p6_1,
  125157. NULL,
  125158. 0
  125159. };
  125160. static long _vq_quantlist__16c2_s_p7_0[] = {
  125161. 6,
  125162. 5,
  125163. 7,
  125164. 4,
  125165. 8,
  125166. 3,
  125167. 9,
  125168. 2,
  125169. 10,
  125170. 1,
  125171. 11,
  125172. 0,
  125173. 12,
  125174. };
  125175. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125176. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125177. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125178. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125179. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125180. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125181. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125182. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125183. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125184. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125185. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125186. 18,13,14,13,13,14,13,15,14,
  125187. };
  125188. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125189. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125190. 27.5, 38.5, 49.5, 60.5,
  125191. };
  125192. static long _vq_quantmap__16c2_s_p7_0[] = {
  125193. 11, 9, 7, 5, 3, 1, 0, 2,
  125194. 4, 6, 8, 10, 12,
  125195. };
  125196. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125197. _vq_quantthresh__16c2_s_p7_0,
  125198. _vq_quantmap__16c2_s_p7_0,
  125199. 13,
  125200. 13
  125201. };
  125202. static static_codebook _16c2_s_p7_0 = {
  125203. 2, 169,
  125204. _vq_lengthlist__16c2_s_p7_0,
  125205. 1, -523206656, 1618345984, 4, 0,
  125206. _vq_quantlist__16c2_s_p7_0,
  125207. NULL,
  125208. &_vq_auxt__16c2_s_p7_0,
  125209. NULL,
  125210. 0
  125211. };
  125212. static long _vq_quantlist__16c2_s_p7_1[] = {
  125213. 5,
  125214. 4,
  125215. 6,
  125216. 3,
  125217. 7,
  125218. 2,
  125219. 8,
  125220. 1,
  125221. 9,
  125222. 0,
  125223. 10,
  125224. };
  125225. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125226. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125227. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125228. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125229. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125230. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125231. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125232. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125233. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125234. };
  125235. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125236. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125237. 3.5, 4.5,
  125238. };
  125239. static long _vq_quantmap__16c2_s_p7_1[] = {
  125240. 9, 7, 5, 3, 1, 0, 2, 4,
  125241. 6, 8, 10,
  125242. };
  125243. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125244. _vq_quantthresh__16c2_s_p7_1,
  125245. _vq_quantmap__16c2_s_p7_1,
  125246. 11,
  125247. 11
  125248. };
  125249. static static_codebook _16c2_s_p7_1 = {
  125250. 2, 121,
  125251. _vq_lengthlist__16c2_s_p7_1,
  125252. 1, -531365888, 1611661312, 4, 0,
  125253. _vq_quantlist__16c2_s_p7_1,
  125254. NULL,
  125255. &_vq_auxt__16c2_s_p7_1,
  125256. NULL,
  125257. 0
  125258. };
  125259. static long _vq_quantlist__16c2_s_p8_0[] = {
  125260. 7,
  125261. 6,
  125262. 8,
  125263. 5,
  125264. 9,
  125265. 4,
  125266. 10,
  125267. 3,
  125268. 11,
  125269. 2,
  125270. 12,
  125271. 1,
  125272. 13,
  125273. 0,
  125274. 14,
  125275. };
  125276. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125277. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125278. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125279. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125280. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125281. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125282. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125283. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125284. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125285. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125286. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125287. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125288. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125289. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125290. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125291. 13,
  125292. };
  125293. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125294. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125295. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125296. };
  125297. static long _vq_quantmap__16c2_s_p8_0[] = {
  125298. 13, 11, 9, 7, 5, 3, 1, 0,
  125299. 2, 4, 6, 8, 10, 12, 14,
  125300. };
  125301. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125302. _vq_quantthresh__16c2_s_p8_0,
  125303. _vq_quantmap__16c2_s_p8_0,
  125304. 15,
  125305. 15
  125306. };
  125307. static static_codebook _16c2_s_p8_0 = {
  125308. 2, 225,
  125309. _vq_lengthlist__16c2_s_p8_0,
  125310. 1, -520986624, 1620377600, 4, 0,
  125311. _vq_quantlist__16c2_s_p8_0,
  125312. NULL,
  125313. &_vq_auxt__16c2_s_p8_0,
  125314. NULL,
  125315. 0
  125316. };
  125317. static long _vq_quantlist__16c2_s_p8_1[] = {
  125318. 10,
  125319. 9,
  125320. 11,
  125321. 8,
  125322. 12,
  125323. 7,
  125324. 13,
  125325. 6,
  125326. 14,
  125327. 5,
  125328. 15,
  125329. 4,
  125330. 16,
  125331. 3,
  125332. 17,
  125333. 2,
  125334. 18,
  125335. 1,
  125336. 19,
  125337. 0,
  125338. 20,
  125339. };
  125340. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125341. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125342. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125343. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125344. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125345. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125346. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125347. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125348. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125349. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125350. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125351. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125352. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125353. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125354. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125355. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125356. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125357. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125358. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125359. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125360. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125361. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125362. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125363. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125364. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125365. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125366. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125367. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125368. 10,11,10,10,10,10,10,10,10,
  125369. };
  125370. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125371. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125372. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125373. 6.5, 7.5, 8.5, 9.5,
  125374. };
  125375. static long _vq_quantmap__16c2_s_p8_1[] = {
  125376. 19, 17, 15, 13, 11, 9, 7, 5,
  125377. 3, 1, 0, 2, 4, 6, 8, 10,
  125378. 12, 14, 16, 18, 20,
  125379. };
  125380. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125381. _vq_quantthresh__16c2_s_p8_1,
  125382. _vq_quantmap__16c2_s_p8_1,
  125383. 21,
  125384. 21
  125385. };
  125386. static static_codebook _16c2_s_p8_1 = {
  125387. 2, 441,
  125388. _vq_lengthlist__16c2_s_p8_1,
  125389. 1, -529268736, 1611661312, 5, 0,
  125390. _vq_quantlist__16c2_s_p8_1,
  125391. NULL,
  125392. &_vq_auxt__16c2_s_p8_1,
  125393. NULL,
  125394. 0
  125395. };
  125396. static long _vq_quantlist__16c2_s_p9_0[] = {
  125397. 6,
  125398. 5,
  125399. 7,
  125400. 4,
  125401. 8,
  125402. 3,
  125403. 9,
  125404. 2,
  125405. 10,
  125406. 1,
  125407. 11,
  125408. 0,
  125409. 12,
  125410. };
  125411. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125412. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125413. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125414. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125415. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125416. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125417. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125418. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125419. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125420. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125421. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125422. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125423. };
  125424. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125425. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125426. 2327.5, 3258.5, 4189.5, 5120.5,
  125427. };
  125428. static long _vq_quantmap__16c2_s_p9_0[] = {
  125429. 11, 9, 7, 5, 3, 1, 0, 2,
  125430. 4, 6, 8, 10, 12,
  125431. };
  125432. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125433. _vq_quantthresh__16c2_s_p9_0,
  125434. _vq_quantmap__16c2_s_p9_0,
  125435. 13,
  125436. 13
  125437. };
  125438. static static_codebook _16c2_s_p9_0 = {
  125439. 2, 169,
  125440. _vq_lengthlist__16c2_s_p9_0,
  125441. 1, -510275072, 1631393792, 4, 0,
  125442. _vq_quantlist__16c2_s_p9_0,
  125443. NULL,
  125444. &_vq_auxt__16c2_s_p9_0,
  125445. NULL,
  125446. 0
  125447. };
  125448. static long _vq_quantlist__16c2_s_p9_1[] = {
  125449. 8,
  125450. 7,
  125451. 9,
  125452. 6,
  125453. 10,
  125454. 5,
  125455. 11,
  125456. 4,
  125457. 12,
  125458. 3,
  125459. 13,
  125460. 2,
  125461. 14,
  125462. 1,
  125463. 15,
  125464. 0,
  125465. 16,
  125466. };
  125467. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125468. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125469. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125470. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125471. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125472. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125473. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125474. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125475. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125476. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125477. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125478. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125479. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125480. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125481. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125482. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125483. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125484. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125485. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125486. 10,
  125487. };
  125488. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125489. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125490. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125491. };
  125492. static long _vq_quantmap__16c2_s_p9_1[] = {
  125493. 15, 13, 11, 9, 7, 5, 3, 1,
  125494. 0, 2, 4, 6, 8, 10, 12, 14,
  125495. 16,
  125496. };
  125497. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125498. _vq_quantthresh__16c2_s_p9_1,
  125499. _vq_quantmap__16c2_s_p9_1,
  125500. 17,
  125501. 17
  125502. };
  125503. static static_codebook _16c2_s_p9_1 = {
  125504. 2, 289,
  125505. _vq_lengthlist__16c2_s_p9_1,
  125506. 1, -518488064, 1622704128, 5, 0,
  125507. _vq_quantlist__16c2_s_p9_1,
  125508. NULL,
  125509. &_vq_auxt__16c2_s_p9_1,
  125510. NULL,
  125511. 0
  125512. };
  125513. static long _vq_quantlist__16c2_s_p9_2[] = {
  125514. 13,
  125515. 12,
  125516. 14,
  125517. 11,
  125518. 15,
  125519. 10,
  125520. 16,
  125521. 9,
  125522. 17,
  125523. 8,
  125524. 18,
  125525. 7,
  125526. 19,
  125527. 6,
  125528. 20,
  125529. 5,
  125530. 21,
  125531. 4,
  125532. 22,
  125533. 3,
  125534. 23,
  125535. 2,
  125536. 24,
  125537. 1,
  125538. 25,
  125539. 0,
  125540. 26,
  125541. };
  125542. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125543. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125544. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125545. };
  125546. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125547. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125548. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125549. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125550. 11.5, 12.5,
  125551. };
  125552. static long _vq_quantmap__16c2_s_p9_2[] = {
  125553. 25, 23, 21, 19, 17, 15, 13, 11,
  125554. 9, 7, 5, 3, 1, 0, 2, 4,
  125555. 6, 8, 10, 12, 14, 16, 18, 20,
  125556. 22, 24, 26,
  125557. };
  125558. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125559. _vq_quantthresh__16c2_s_p9_2,
  125560. _vq_quantmap__16c2_s_p9_2,
  125561. 27,
  125562. 27
  125563. };
  125564. static static_codebook _16c2_s_p9_2 = {
  125565. 1, 27,
  125566. _vq_lengthlist__16c2_s_p9_2,
  125567. 1, -528875520, 1611661312, 5, 0,
  125568. _vq_quantlist__16c2_s_p9_2,
  125569. NULL,
  125570. &_vq_auxt__16c2_s_p9_2,
  125571. NULL,
  125572. 0
  125573. };
  125574. static long _huff_lengthlist__16c2_s_short[] = {
  125575. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125576. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125577. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125578. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125579. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125580. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125581. 15,12,14,14,
  125582. };
  125583. static static_codebook _huff_book__16c2_s_short = {
  125584. 2, 100,
  125585. _huff_lengthlist__16c2_s_short,
  125586. 0, 0, 0, 0, 0,
  125587. NULL,
  125588. NULL,
  125589. NULL,
  125590. NULL,
  125591. 0
  125592. };
  125593. static long _vq_quantlist__8c0_s_p1_0[] = {
  125594. 1,
  125595. 0,
  125596. 2,
  125597. };
  125598. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125599. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125600. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125605. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125610. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125645. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125650. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125655. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125691. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125696. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125701. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0,
  126010. };
  126011. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126012. -0.5, 0.5,
  126013. };
  126014. static long _vq_quantmap__8c0_s_p1_0[] = {
  126015. 1, 0, 2,
  126016. };
  126017. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126018. _vq_quantthresh__8c0_s_p1_0,
  126019. _vq_quantmap__8c0_s_p1_0,
  126020. 3,
  126021. 3
  126022. };
  126023. static static_codebook _8c0_s_p1_0 = {
  126024. 8, 6561,
  126025. _vq_lengthlist__8c0_s_p1_0,
  126026. 1, -535822336, 1611661312, 2, 0,
  126027. _vq_quantlist__8c0_s_p1_0,
  126028. NULL,
  126029. &_vq_auxt__8c0_s_p1_0,
  126030. NULL,
  126031. 0
  126032. };
  126033. static long _vq_quantlist__8c0_s_p2_0[] = {
  126034. 2,
  126035. 1,
  126036. 3,
  126037. 0,
  126038. 4,
  126039. };
  126040. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0,
  126081. };
  126082. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126083. -1.5, -0.5, 0.5, 1.5,
  126084. };
  126085. static long _vq_quantmap__8c0_s_p2_0[] = {
  126086. 3, 1, 0, 2, 4,
  126087. };
  126088. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126089. _vq_quantthresh__8c0_s_p2_0,
  126090. _vq_quantmap__8c0_s_p2_0,
  126091. 5,
  126092. 5
  126093. };
  126094. static static_codebook _8c0_s_p2_0 = {
  126095. 4, 625,
  126096. _vq_lengthlist__8c0_s_p2_0,
  126097. 1, -533725184, 1611661312, 3, 0,
  126098. _vq_quantlist__8c0_s_p2_0,
  126099. NULL,
  126100. &_vq_auxt__8c0_s_p2_0,
  126101. NULL,
  126102. 0
  126103. };
  126104. static long _vq_quantlist__8c0_s_p3_0[] = {
  126105. 2,
  126106. 1,
  126107. 3,
  126108. 0,
  126109. 4,
  126110. };
  126111. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126112. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0,
  126152. };
  126153. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126154. -1.5, -0.5, 0.5, 1.5,
  126155. };
  126156. static long _vq_quantmap__8c0_s_p3_0[] = {
  126157. 3, 1, 0, 2, 4,
  126158. };
  126159. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126160. _vq_quantthresh__8c0_s_p3_0,
  126161. _vq_quantmap__8c0_s_p3_0,
  126162. 5,
  126163. 5
  126164. };
  126165. static static_codebook _8c0_s_p3_0 = {
  126166. 4, 625,
  126167. _vq_lengthlist__8c0_s_p3_0,
  126168. 1, -533725184, 1611661312, 3, 0,
  126169. _vq_quantlist__8c0_s_p3_0,
  126170. NULL,
  126171. &_vq_auxt__8c0_s_p3_0,
  126172. NULL,
  126173. 0
  126174. };
  126175. static long _vq_quantlist__8c0_s_p4_0[] = {
  126176. 4,
  126177. 3,
  126178. 5,
  126179. 2,
  126180. 6,
  126181. 1,
  126182. 7,
  126183. 0,
  126184. 8,
  126185. };
  126186. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126187. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126188. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126189. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126190. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126191. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0,
  126193. };
  126194. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126195. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126196. };
  126197. static long _vq_quantmap__8c0_s_p4_0[] = {
  126198. 7, 5, 3, 1, 0, 2, 4, 6,
  126199. 8,
  126200. };
  126201. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126202. _vq_quantthresh__8c0_s_p4_0,
  126203. _vq_quantmap__8c0_s_p4_0,
  126204. 9,
  126205. 9
  126206. };
  126207. static static_codebook _8c0_s_p4_0 = {
  126208. 2, 81,
  126209. _vq_lengthlist__8c0_s_p4_0,
  126210. 1, -531628032, 1611661312, 4, 0,
  126211. _vq_quantlist__8c0_s_p4_0,
  126212. NULL,
  126213. &_vq_auxt__8c0_s_p4_0,
  126214. NULL,
  126215. 0
  126216. };
  126217. static long _vq_quantlist__8c0_s_p5_0[] = {
  126218. 4,
  126219. 3,
  126220. 5,
  126221. 2,
  126222. 6,
  126223. 1,
  126224. 7,
  126225. 0,
  126226. 8,
  126227. };
  126228. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126229. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126230. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126231. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126232. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126233. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126234. 10,
  126235. };
  126236. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126237. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126238. };
  126239. static long _vq_quantmap__8c0_s_p5_0[] = {
  126240. 7, 5, 3, 1, 0, 2, 4, 6,
  126241. 8,
  126242. };
  126243. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126244. _vq_quantthresh__8c0_s_p5_0,
  126245. _vq_quantmap__8c0_s_p5_0,
  126246. 9,
  126247. 9
  126248. };
  126249. static static_codebook _8c0_s_p5_0 = {
  126250. 2, 81,
  126251. _vq_lengthlist__8c0_s_p5_0,
  126252. 1, -531628032, 1611661312, 4, 0,
  126253. _vq_quantlist__8c0_s_p5_0,
  126254. NULL,
  126255. &_vq_auxt__8c0_s_p5_0,
  126256. NULL,
  126257. 0
  126258. };
  126259. static long _vq_quantlist__8c0_s_p6_0[] = {
  126260. 8,
  126261. 7,
  126262. 9,
  126263. 6,
  126264. 10,
  126265. 5,
  126266. 11,
  126267. 4,
  126268. 12,
  126269. 3,
  126270. 13,
  126271. 2,
  126272. 14,
  126273. 1,
  126274. 15,
  126275. 0,
  126276. 16,
  126277. };
  126278. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126279. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126280. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126281. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126282. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126283. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126284. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126285. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126286. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126287. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126288. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126289. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126290. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126291. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126292. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126293. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126294. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126295. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126296. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126297. 14,
  126298. };
  126299. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126300. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126301. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126302. };
  126303. static long _vq_quantmap__8c0_s_p6_0[] = {
  126304. 15, 13, 11, 9, 7, 5, 3, 1,
  126305. 0, 2, 4, 6, 8, 10, 12, 14,
  126306. 16,
  126307. };
  126308. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126309. _vq_quantthresh__8c0_s_p6_0,
  126310. _vq_quantmap__8c0_s_p6_0,
  126311. 17,
  126312. 17
  126313. };
  126314. static static_codebook _8c0_s_p6_0 = {
  126315. 2, 289,
  126316. _vq_lengthlist__8c0_s_p6_0,
  126317. 1, -529530880, 1611661312, 5, 0,
  126318. _vq_quantlist__8c0_s_p6_0,
  126319. NULL,
  126320. &_vq_auxt__8c0_s_p6_0,
  126321. NULL,
  126322. 0
  126323. };
  126324. static long _vq_quantlist__8c0_s_p7_0[] = {
  126325. 1,
  126326. 0,
  126327. 2,
  126328. };
  126329. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126330. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126331. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126332. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126333. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126334. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126335. 10,
  126336. };
  126337. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126338. -5.5, 5.5,
  126339. };
  126340. static long _vq_quantmap__8c0_s_p7_0[] = {
  126341. 1, 0, 2,
  126342. };
  126343. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126344. _vq_quantthresh__8c0_s_p7_0,
  126345. _vq_quantmap__8c0_s_p7_0,
  126346. 3,
  126347. 3
  126348. };
  126349. static static_codebook _8c0_s_p7_0 = {
  126350. 4, 81,
  126351. _vq_lengthlist__8c0_s_p7_0,
  126352. 1, -529137664, 1618345984, 2, 0,
  126353. _vq_quantlist__8c0_s_p7_0,
  126354. NULL,
  126355. &_vq_auxt__8c0_s_p7_0,
  126356. NULL,
  126357. 0
  126358. };
  126359. static long _vq_quantlist__8c0_s_p7_1[] = {
  126360. 5,
  126361. 4,
  126362. 6,
  126363. 3,
  126364. 7,
  126365. 2,
  126366. 8,
  126367. 1,
  126368. 9,
  126369. 0,
  126370. 10,
  126371. };
  126372. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126373. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126374. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126375. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126376. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126377. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126378. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126379. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126380. 10,10,10, 9, 9, 9,10,10,10,
  126381. };
  126382. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126383. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126384. 3.5, 4.5,
  126385. };
  126386. static long _vq_quantmap__8c0_s_p7_1[] = {
  126387. 9, 7, 5, 3, 1, 0, 2, 4,
  126388. 6, 8, 10,
  126389. };
  126390. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126391. _vq_quantthresh__8c0_s_p7_1,
  126392. _vq_quantmap__8c0_s_p7_1,
  126393. 11,
  126394. 11
  126395. };
  126396. static static_codebook _8c0_s_p7_1 = {
  126397. 2, 121,
  126398. _vq_lengthlist__8c0_s_p7_1,
  126399. 1, -531365888, 1611661312, 4, 0,
  126400. _vq_quantlist__8c0_s_p7_1,
  126401. NULL,
  126402. &_vq_auxt__8c0_s_p7_1,
  126403. NULL,
  126404. 0
  126405. };
  126406. static long _vq_quantlist__8c0_s_p8_0[] = {
  126407. 6,
  126408. 5,
  126409. 7,
  126410. 4,
  126411. 8,
  126412. 3,
  126413. 9,
  126414. 2,
  126415. 10,
  126416. 1,
  126417. 11,
  126418. 0,
  126419. 12,
  126420. };
  126421. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126422. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126423. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126424. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126425. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126426. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126427. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126428. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126429. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126430. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126431. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126432. 0, 0,13,13,11,13,13,11,12,
  126433. };
  126434. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126435. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126436. 12.5, 17.5, 22.5, 27.5,
  126437. };
  126438. static long _vq_quantmap__8c0_s_p8_0[] = {
  126439. 11, 9, 7, 5, 3, 1, 0, 2,
  126440. 4, 6, 8, 10, 12,
  126441. };
  126442. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126443. _vq_quantthresh__8c0_s_p8_0,
  126444. _vq_quantmap__8c0_s_p8_0,
  126445. 13,
  126446. 13
  126447. };
  126448. static static_codebook _8c0_s_p8_0 = {
  126449. 2, 169,
  126450. _vq_lengthlist__8c0_s_p8_0,
  126451. 1, -526516224, 1616117760, 4, 0,
  126452. _vq_quantlist__8c0_s_p8_0,
  126453. NULL,
  126454. &_vq_auxt__8c0_s_p8_0,
  126455. NULL,
  126456. 0
  126457. };
  126458. static long _vq_quantlist__8c0_s_p8_1[] = {
  126459. 2,
  126460. 1,
  126461. 3,
  126462. 0,
  126463. 4,
  126464. };
  126465. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126466. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126467. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126468. };
  126469. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126470. -1.5, -0.5, 0.5, 1.5,
  126471. };
  126472. static long _vq_quantmap__8c0_s_p8_1[] = {
  126473. 3, 1, 0, 2, 4,
  126474. };
  126475. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126476. _vq_quantthresh__8c0_s_p8_1,
  126477. _vq_quantmap__8c0_s_p8_1,
  126478. 5,
  126479. 5
  126480. };
  126481. static static_codebook _8c0_s_p8_1 = {
  126482. 2, 25,
  126483. _vq_lengthlist__8c0_s_p8_1,
  126484. 1, -533725184, 1611661312, 3, 0,
  126485. _vq_quantlist__8c0_s_p8_1,
  126486. NULL,
  126487. &_vq_auxt__8c0_s_p8_1,
  126488. NULL,
  126489. 0
  126490. };
  126491. static long _vq_quantlist__8c0_s_p9_0[] = {
  126492. 1,
  126493. 0,
  126494. 2,
  126495. };
  126496. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126497. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126498. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126499. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126500. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126501. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126502. 7,
  126503. };
  126504. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126505. -157.5, 157.5,
  126506. };
  126507. static long _vq_quantmap__8c0_s_p9_0[] = {
  126508. 1, 0, 2,
  126509. };
  126510. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126511. _vq_quantthresh__8c0_s_p9_0,
  126512. _vq_quantmap__8c0_s_p9_0,
  126513. 3,
  126514. 3
  126515. };
  126516. static static_codebook _8c0_s_p9_0 = {
  126517. 4, 81,
  126518. _vq_lengthlist__8c0_s_p9_0,
  126519. 1, -518803456, 1628680192, 2, 0,
  126520. _vq_quantlist__8c0_s_p9_0,
  126521. NULL,
  126522. &_vq_auxt__8c0_s_p9_0,
  126523. NULL,
  126524. 0
  126525. };
  126526. static long _vq_quantlist__8c0_s_p9_1[] = {
  126527. 7,
  126528. 6,
  126529. 8,
  126530. 5,
  126531. 9,
  126532. 4,
  126533. 10,
  126534. 3,
  126535. 11,
  126536. 2,
  126537. 12,
  126538. 1,
  126539. 13,
  126540. 0,
  126541. 14,
  126542. };
  126543. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126544. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126545. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126546. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126547. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126548. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126549. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126550. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126551. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126552. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126553. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126554. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126555. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126556. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126557. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126558. 11,
  126559. };
  126560. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126561. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126562. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126563. };
  126564. static long _vq_quantmap__8c0_s_p9_1[] = {
  126565. 13, 11, 9, 7, 5, 3, 1, 0,
  126566. 2, 4, 6, 8, 10, 12, 14,
  126567. };
  126568. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126569. _vq_quantthresh__8c0_s_p9_1,
  126570. _vq_quantmap__8c0_s_p9_1,
  126571. 15,
  126572. 15
  126573. };
  126574. static static_codebook _8c0_s_p9_1 = {
  126575. 2, 225,
  126576. _vq_lengthlist__8c0_s_p9_1,
  126577. 1, -520986624, 1620377600, 4, 0,
  126578. _vq_quantlist__8c0_s_p9_1,
  126579. NULL,
  126580. &_vq_auxt__8c0_s_p9_1,
  126581. NULL,
  126582. 0
  126583. };
  126584. static long _vq_quantlist__8c0_s_p9_2[] = {
  126585. 10,
  126586. 9,
  126587. 11,
  126588. 8,
  126589. 12,
  126590. 7,
  126591. 13,
  126592. 6,
  126593. 14,
  126594. 5,
  126595. 15,
  126596. 4,
  126597. 16,
  126598. 3,
  126599. 17,
  126600. 2,
  126601. 18,
  126602. 1,
  126603. 19,
  126604. 0,
  126605. 20,
  126606. };
  126607. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126608. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126609. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126610. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126611. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126612. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126613. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126614. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126615. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126616. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126617. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126618. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126619. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126620. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126621. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126622. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126623. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126624. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126625. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126626. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126627. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126628. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126629. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126630. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126631. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126632. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126633. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126634. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126635. 10,11, 9,11,10, 9,10, 9,10,
  126636. };
  126637. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126638. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126639. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126640. 6.5, 7.5, 8.5, 9.5,
  126641. };
  126642. static long _vq_quantmap__8c0_s_p9_2[] = {
  126643. 19, 17, 15, 13, 11, 9, 7, 5,
  126644. 3, 1, 0, 2, 4, 6, 8, 10,
  126645. 12, 14, 16, 18, 20,
  126646. };
  126647. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126648. _vq_quantthresh__8c0_s_p9_2,
  126649. _vq_quantmap__8c0_s_p9_2,
  126650. 21,
  126651. 21
  126652. };
  126653. static static_codebook _8c0_s_p9_2 = {
  126654. 2, 441,
  126655. _vq_lengthlist__8c0_s_p9_2,
  126656. 1, -529268736, 1611661312, 5, 0,
  126657. _vq_quantlist__8c0_s_p9_2,
  126658. NULL,
  126659. &_vq_auxt__8c0_s_p9_2,
  126660. NULL,
  126661. 0
  126662. };
  126663. static long _huff_lengthlist__8c0_s_single[] = {
  126664. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126665. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126666. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126667. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126668. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126669. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126670. 17,16,17,17,
  126671. };
  126672. static static_codebook _huff_book__8c0_s_single = {
  126673. 2, 100,
  126674. _huff_lengthlist__8c0_s_single,
  126675. 0, 0, 0, 0, 0,
  126676. NULL,
  126677. NULL,
  126678. NULL,
  126679. NULL,
  126680. 0
  126681. };
  126682. static long _vq_quantlist__8c1_s_p1_0[] = {
  126683. 1,
  126684. 0,
  126685. 2,
  126686. };
  126687. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126688. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126689. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126694. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126699. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  126734. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  126739. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  126744. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126780. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126785. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126790. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0,
  127099. };
  127100. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127101. -0.5, 0.5,
  127102. };
  127103. static long _vq_quantmap__8c1_s_p1_0[] = {
  127104. 1, 0, 2,
  127105. };
  127106. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127107. _vq_quantthresh__8c1_s_p1_0,
  127108. _vq_quantmap__8c1_s_p1_0,
  127109. 3,
  127110. 3
  127111. };
  127112. static static_codebook _8c1_s_p1_0 = {
  127113. 8, 6561,
  127114. _vq_lengthlist__8c1_s_p1_0,
  127115. 1, -535822336, 1611661312, 2, 0,
  127116. _vq_quantlist__8c1_s_p1_0,
  127117. NULL,
  127118. &_vq_auxt__8c1_s_p1_0,
  127119. NULL,
  127120. 0
  127121. };
  127122. static long _vq_quantlist__8c1_s_p2_0[] = {
  127123. 2,
  127124. 1,
  127125. 3,
  127126. 0,
  127127. 4,
  127128. };
  127129. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0,
  127170. };
  127171. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127172. -1.5, -0.5, 0.5, 1.5,
  127173. };
  127174. static long _vq_quantmap__8c1_s_p2_0[] = {
  127175. 3, 1, 0, 2, 4,
  127176. };
  127177. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127178. _vq_quantthresh__8c1_s_p2_0,
  127179. _vq_quantmap__8c1_s_p2_0,
  127180. 5,
  127181. 5
  127182. };
  127183. static static_codebook _8c1_s_p2_0 = {
  127184. 4, 625,
  127185. _vq_lengthlist__8c1_s_p2_0,
  127186. 1, -533725184, 1611661312, 3, 0,
  127187. _vq_quantlist__8c1_s_p2_0,
  127188. NULL,
  127189. &_vq_auxt__8c1_s_p2_0,
  127190. NULL,
  127191. 0
  127192. };
  127193. static long _vq_quantlist__8c1_s_p3_0[] = {
  127194. 2,
  127195. 1,
  127196. 3,
  127197. 0,
  127198. 4,
  127199. };
  127200. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127201. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0,
  127241. };
  127242. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127243. -1.5, -0.5, 0.5, 1.5,
  127244. };
  127245. static long _vq_quantmap__8c1_s_p3_0[] = {
  127246. 3, 1, 0, 2, 4,
  127247. };
  127248. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127249. _vq_quantthresh__8c1_s_p3_0,
  127250. _vq_quantmap__8c1_s_p3_0,
  127251. 5,
  127252. 5
  127253. };
  127254. static static_codebook _8c1_s_p3_0 = {
  127255. 4, 625,
  127256. _vq_lengthlist__8c1_s_p3_0,
  127257. 1, -533725184, 1611661312, 3, 0,
  127258. _vq_quantlist__8c1_s_p3_0,
  127259. NULL,
  127260. &_vq_auxt__8c1_s_p3_0,
  127261. NULL,
  127262. 0
  127263. };
  127264. static long _vq_quantlist__8c1_s_p4_0[] = {
  127265. 4,
  127266. 3,
  127267. 5,
  127268. 2,
  127269. 6,
  127270. 1,
  127271. 7,
  127272. 0,
  127273. 8,
  127274. };
  127275. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127276. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127277. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127278. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127279. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127280. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0,
  127282. };
  127283. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127284. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127285. };
  127286. static long _vq_quantmap__8c1_s_p4_0[] = {
  127287. 7, 5, 3, 1, 0, 2, 4, 6,
  127288. 8,
  127289. };
  127290. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127291. _vq_quantthresh__8c1_s_p4_0,
  127292. _vq_quantmap__8c1_s_p4_0,
  127293. 9,
  127294. 9
  127295. };
  127296. static static_codebook _8c1_s_p4_0 = {
  127297. 2, 81,
  127298. _vq_lengthlist__8c1_s_p4_0,
  127299. 1, -531628032, 1611661312, 4, 0,
  127300. _vq_quantlist__8c1_s_p4_0,
  127301. NULL,
  127302. &_vq_auxt__8c1_s_p4_0,
  127303. NULL,
  127304. 0
  127305. };
  127306. static long _vq_quantlist__8c1_s_p5_0[] = {
  127307. 4,
  127308. 3,
  127309. 5,
  127310. 2,
  127311. 6,
  127312. 1,
  127313. 7,
  127314. 0,
  127315. 8,
  127316. };
  127317. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127318. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127319. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127320. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127321. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127322. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127323. 10,
  127324. };
  127325. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127326. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127327. };
  127328. static long _vq_quantmap__8c1_s_p5_0[] = {
  127329. 7, 5, 3, 1, 0, 2, 4, 6,
  127330. 8,
  127331. };
  127332. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127333. _vq_quantthresh__8c1_s_p5_0,
  127334. _vq_quantmap__8c1_s_p5_0,
  127335. 9,
  127336. 9
  127337. };
  127338. static static_codebook _8c1_s_p5_0 = {
  127339. 2, 81,
  127340. _vq_lengthlist__8c1_s_p5_0,
  127341. 1, -531628032, 1611661312, 4, 0,
  127342. _vq_quantlist__8c1_s_p5_0,
  127343. NULL,
  127344. &_vq_auxt__8c1_s_p5_0,
  127345. NULL,
  127346. 0
  127347. };
  127348. static long _vq_quantlist__8c1_s_p6_0[] = {
  127349. 8,
  127350. 7,
  127351. 9,
  127352. 6,
  127353. 10,
  127354. 5,
  127355. 11,
  127356. 4,
  127357. 12,
  127358. 3,
  127359. 13,
  127360. 2,
  127361. 14,
  127362. 1,
  127363. 15,
  127364. 0,
  127365. 16,
  127366. };
  127367. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127368. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127369. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127370. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127371. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127372. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127373. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127374. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127375. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127376. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127377. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127378. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127379. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127380. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127381. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127382. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127383. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127384. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127385. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127386. 14,
  127387. };
  127388. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127389. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127390. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127391. };
  127392. static long _vq_quantmap__8c1_s_p6_0[] = {
  127393. 15, 13, 11, 9, 7, 5, 3, 1,
  127394. 0, 2, 4, 6, 8, 10, 12, 14,
  127395. 16,
  127396. };
  127397. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127398. _vq_quantthresh__8c1_s_p6_0,
  127399. _vq_quantmap__8c1_s_p6_0,
  127400. 17,
  127401. 17
  127402. };
  127403. static static_codebook _8c1_s_p6_0 = {
  127404. 2, 289,
  127405. _vq_lengthlist__8c1_s_p6_0,
  127406. 1, -529530880, 1611661312, 5, 0,
  127407. _vq_quantlist__8c1_s_p6_0,
  127408. NULL,
  127409. &_vq_auxt__8c1_s_p6_0,
  127410. NULL,
  127411. 0
  127412. };
  127413. static long _vq_quantlist__8c1_s_p7_0[] = {
  127414. 1,
  127415. 0,
  127416. 2,
  127417. };
  127418. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127419. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127420. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127421. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127422. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127423. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127424. 9,
  127425. };
  127426. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127427. -5.5, 5.5,
  127428. };
  127429. static long _vq_quantmap__8c1_s_p7_0[] = {
  127430. 1, 0, 2,
  127431. };
  127432. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127433. _vq_quantthresh__8c1_s_p7_0,
  127434. _vq_quantmap__8c1_s_p7_0,
  127435. 3,
  127436. 3
  127437. };
  127438. static static_codebook _8c1_s_p7_0 = {
  127439. 4, 81,
  127440. _vq_lengthlist__8c1_s_p7_0,
  127441. 1, -529137664, 1618345984, 2, 0,
  127442. _vq_quantlist__8c1_s_p7_0,
  127443. NULL,
  127444. &_vq_auxt__8c1_s_p7_0,
  127445. NULL,
  127446. 0
  127447. };
  127448. static long _vq_quantlist__8c1_s_p7_1[] = {
  127449. 5,
  127450. 4,
  127451. 6,
  127452. 3,
  127453. 7,
  127454. 2,
  127455. 8,
  127456. 1,
  127457. 9,
  127458. 0,
  127459. 10,
  127460. };
  127461. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127462. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127463. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127464. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127465. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127466. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127467. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127468. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127469. 10,10,10, 8, 8, 8, 8, 8, 8,
  127470. };
  127471. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127472. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127473. 3.5, 4.5,
  127474. };
  127475. static long _vq_quantmap__8c1_s_p7_1[] = {
  127476. 9, 7, 5, 3, 1, 0, 2, 4,
  127477. 6, 8, 10,
  127478. };
  127479. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127480. _vq_quantthresh__8c1_s_p7_1,
  127481. _vq_quantmap__8c1_s_p7_1,
  127482. 11,
  127483. 11
  127484. };
  127485. static static_codebook _8c1_s_p7_1 = {
  127486. 2, 121,
  127487. _vq_lengthlist__8c1_s_p7_1,
  127488. 1, -531365888, 1611661312, 4, 0,
  127489. _vq_quantlist__8c1_s_p7_1,
  127490. NULL,
  127491. &_vq_auxt__8c1_s_p7_1,
  127492. NULL,
  127493. 0
  127494. };
  127495. static long _vq_quantlist__8c1_s_p8_0[] = {
  127496. 6,
  127497. 5,
  127498. 7,
  127499. 4,
  127500. 8,
  127501. 3,
  127502. 9,
  127503. 2,
  127504. 10,
  127505. 1,
  127506. 11,
  127507. 0,
  127508. 12,
  127509. };
  127510. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127511. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127512. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127513. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127514. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127515. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127516. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127517. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127518. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127519. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127520. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127521. 0,12,12,11,10,12,11,13,12,
  127522. };
  127523. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127524. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127525. 12.5, 17.5, 22.5, 27.5,
  127526. };
  127527. static long _vq_quantmap__8c1_s_p8_0[] = {
  127528. 11, 9, 7, 5, 3, 1, 0, 2,
  127529. 4, 6, 8, 10, 12,
  127530. };
  127531. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127532. _vq_quantthresh__8c1_s_p8_0,
  127533. _vq_quantmap__8c1_s_p8_0,
  127534. 13,
  127535. 13
  127536. };
  127537. static static_codebook _8c1_s_p8_0 = {
  127538. 2, 169,
  127539. _vq_lengthlist__8c1_s_p8_0,
  127540. 1, -526516224, 1616117760, 4, 0,
  127541. _vq_quantlist__8c1_s_p8_0,
  127542. NULL,
  127543. &_vq_auxt__8c1_s_p8_0,
  127544. NULL,
  127545. 0
  127546. };
  127547. static long _vq_quantlist__8c1_s_p8_1[] = {
  127548. 2,
  127549. 1,
  127550. 3,
  127551. 0,
  127552. 4,
  127553. };
  127554. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127555. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127556. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127557. };
  127558. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127559. -1.5, -0.5, 0.5, 1.5,
  127560. };
  127561. static long _vq_quantmap__8c1_s_p8_1[] = {
  127562. 3, 1, 0, 2, 4,
  127563. };
  127564. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127565. _vq_quantthresh__8c1_s_p8_1,
  127566. _vq_quantmap__8c1_s_p8_1,
  127567. 5,
  127568. 5
  127569. };
  127570. static static_codebook _8c1_s_p8_1 = {
  127571. 2, 25,
  127572. _vq_lengthlist__8c1_s_p8_1,
  127573. 1, -533725184, 1611661312, 3, 0,
  127574. _vq_quantlist__8c1_s_p8_1,
  127575. NULL,
  127576. &_vq_auxt__8c1_s_p8_1,
  127577. NULL,
  127578. 0
  127579. };
  127580. static long _vq_quantlist__8c1_s_p9_0[] = {
  127581. 6,
  127582. 5,
  127583. 7,
  127584. 4,
  127585. 8,
  127586. 3,
  127587. 9,
  127588. 2,
  127589. 10,
  127590. 1,
  127591. 11,
  127592. 0,
  127593. 12,
  127594. };
  127595. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127596. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127597. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127598. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127599. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127600. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127601. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127602. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127603. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127604. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127605. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127606. 10,10,10,10,10, 9, 9, 9, 9,
  127607. };
  127608. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127609. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127610. 787.5, 1102.5, 1417.5, 1732.5,
  127611. };
  127612. static long _vq_quantmap__8c1_s_p9_0[] = {
  127613. 11, 9, 7, 5, 3, 1, 0, 2,
  127614. 4, 6, 8, 10, 12,
  127615. };
  127616. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127617. _vq_quantthresh__8c1_s_p9_0,
  127618. _vq_quantmap__8c1_s_p9_0,
  127619. 13,
  127620. 13
  127621. };
  127622. static static_codebook _8c1_s_p9_0 = {
  127623. 2, 169,
  127624. _vq_lengthlist__8c1_s_p9_0,
  127625. 1, -513964032, 1628680192, 4, 0,
  127626. _vq_quantlist__8c1_s_p9_0,
  127627. NULL,
  127628. &_vq_auxt__8c1_s_p9_0,
  127629. NULL,
  127630. 0
  127631. };
  127632. static long _vq_quantlist__8c1_s_p9_1[] = {
  127633. 7,
  127634. 6,
  127635. 8,
  127636. 5,
  127637. 9,
  127638. 4,
  127639. 10,
  127640. 3,
  127641. 11,
  127642. 2,
  127643. 12,
  127644. 1,
  127645. 13,
  127646. 0,
  127647. 14,
  127648. };
  127649. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127650. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127651. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127652. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127653. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127654. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127655. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127656. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127657. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127658. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127659. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127660. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127661. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127662. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127663. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127664. 15,
  127665. };
  127666. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127667. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127668. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127669. };
  127670. static long _vq_quantmap__8c1_s_p9_1[] = {
  127671. 13, 11, 9, 7, 5, 3, 1, 0,
  127672. 2, 4, 6, 8, 10, 12, 14,
  127673. };
  127674. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127675. _vq_quantthresh__8c1_s_p9_1,
  127676. _vq_quantmap__8c1_s_p9_1,
  127677. 15,
  127678. 15
  127679. };
  127680. static static_codebook _8c1_s_p9_1 = {
  127681. 2, 225,
  127682. _vq_lengthlist__8c1_s_p9_1,
  127683. 1, -520986624, 1620377600, 4, 0,
  127684. _vq_quantlist__8c1_s_p9_1,
  127685. NULL,
  127686. &_vq_auxt__8c1_s_p9_1,
  127687. NULL,
  127688. 0
  127689. };
  127690. static long _vq_quantlist__8c1_s_p9_2[] = {
  127691. 10,
  127692. 9,
  127693. 11,
  127694. 8,
  127695. 12,
  127696. 7,
  127697. 13,
  127698. 6,
  127699. 14,
  127700. 5,
  127701. 15,
  127702. 4,
  127703. 16,
  127704. 3,
  127705. 17,
  127706. 2,
  127707. 18,
  127708. 1,
  127709. 19,
  127710. 0,
  127711. 20,
  127712. };
  127713. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127714. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127715. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127716. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127717. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127718. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127719. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127720. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127721. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127722. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127723. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127724. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127725. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127726. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127727. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127728. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127729. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127730. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127731. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127732. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127733. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127734. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127735. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127736. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127737. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127738. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127739. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127740. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127741. 10,10,10,10,10,10,10,10,10,
  127742. };
  127743. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127744. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127745. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127746. 6.5, 7.5, 8.5, 9.5,
  127747. };
  127748. static long _vq_quantmap__8c1_s_p9_2[] = {
  127749. 19, 17, 15, 13, 11, 9, 7, 5,
  127750. 3, 1, 0, 2, 4, 6, 8, 10,
  127751. 12, 14, 16, 18, 20,
  127752. };
  127753. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127754. _vq_quantthresh__8c1_s_p9_2,
  127755. _vq_quantmap__8c1_s_p9_2,
  127756. 21,
  127757. 21
  127758. };
  127759. static static_codebook _8c1_s_p9_2 = {
  127760. 2, 441,
  127761. _vq_lengthlist__8c1_s_p9_2,
  127762. 1, -529268736, 1611661312, 5, 0,
  127763. _vq_quantlist__8c1_s_p9_2,
  127764. NULL,
  127765. &_vq_auxt__8c1_s_p9_2,
  127766. NULL,
  127767. 0
  127768. };
  127769. static long _huff_lengthlist__8c1_s_single[] = {
  127770. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127771. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127772. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127773. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127774. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127775. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127776. 9, 7, 7, 8,
  127777. };
  127778. static static_codebook _huff_book__8c1_s_single = {
  127779. 2, 100,
  127780. _huff_lengthlist__8c1_s_single,
  127781. 0, 0, 0, 0, 0,
  127782. NULL,
  127783. NULL,
  127784. NULL,
  127785. NULL,
  127786. 0
  127787. };
  127788. static long _huff_lengthlist__44c2_s_long[] = {
  127789. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127790. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127791. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127792. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127793. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127794. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127795. 10, 8, 8, 9,
  127796. };
  127797. static static_codebook _huff_book__44c2_s_long = {
  127798. 2, 100,
  127799. _huff_lengthlist__44c2_s_long,
  127800. 0, 0, 0, 0, 0,
  127801. NULL,
  127802. NULL,
  127803. NULL,
  127804. NULL,
  127805. 0
  127806. };
  127807. static long _vq_quantlist__44c2_s_p1_0[] = {
  127808. 1,
  127809. 0,
  127810. 2,
  127811. };
  127812. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127813. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127814. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127819. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127824. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127859. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127864. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127869. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127905. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127910. 0, 0, 0, 0, 0, 8, 8, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127915. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0,
  128224. };
  128225. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128226. -0.5, 0.5,
  128227. };
  128228. static long _vq_quantmap__44c2_s_p1_0[] = {
  128229. 1, 0, 2,
  128230. };
  128231. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128232. _vq_quantthresh__44c2_s_p1_0,
  128233. _vq_quantmap__44c2_s_p1_0,
  128234. 3,
  128235. 3
  128236. };
  128237. static static_codebook _44c2_s_p1_0 = {
  128238. 8, 6561,
  128239. _vq_lengthlist__44c2_s_p1_0,
  128240. 1, -535822336, 1611661312, 2, 0,
  128241. _vq_quantlist__44c2_s_p1_0,
  128242. NULL,
  128243. &_vq_auxt__44c2_s_p1_0,
  128244. NULL,
  128245. 0
  128246. };
  128247. static long _vq_quantlist__44c2_s_p2_0[] = {
  128248. 2,
  128249. 1,
  128250. 3,
  128251. 0,
  128252. 4,
  128253. };
  128254. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128255. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128256. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128257. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128258. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128259. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128265. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128266. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128267. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128273. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128274. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128281. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128282. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0,
  128295. };
  128296. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128297. -1.5, -0.5, 0.5, 1.5,
  128298. };
  128299. static long _vq_quantmap__44c2_s_p2_0[] = {
  128300. 3, 1, 0, 2, 4,
  128301. };
  128302. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128303. _vq_quantthresh__44c2_s_p2_0,
  128304. _vq_quantmap__44c2_s_p2_0,
  128305. 5,
  128306. 5
  128307. };
  128308. static static_codebook _44c2_s_p2_0 = {
  128309. 4, 625,
  128310. _vq_lengthlist__44c2_s_p2_0,
  128311. 1, -533725184, 1611661312, 3, 0,
  128312. _vq_quantlist__44c2_s_p2_0,
  128313. NULL,
  128314. &_vq_auxt__44c2_s_p2_0,
  128315. NULL,
  128316. 0
  128317. };
  128318. static long _vq_quantlist__44c2_s_p3_0[] = {
  128319. 2,
  128320. 1,
  128321. 3,
  128322. 0,
  128323. 4,
  128324. };
  128325. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128326. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0,
  128366. };
  128367. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128368. -1.5, -0.5, 0.5, 1.5,
  128369. };
  128370. static long _vq_quantmap__44c2_s_p3_0[] = {
  128371. 3, 1, 0, 2, 4,
  128372. };
  128373. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128374. _vq_quantthresh__44c2_s_p3_0,
  128375. _vq_quantmap__44c2_s_p3_0,
  128376. 5,
  128377. 5
  128378. };
  128379. static static_codebook _44c2_s_p3_0 = {
  128380. 4, 625,
  128381. _vq_lengthlist__44c2_s_p3_0,
  128382. 1, -533725184, 1611661312, 3, 0,
  128383. _vq_quantlist__44c2_s_p3_0,
  128384. NULL,
  128385. &_vq_auxt__44c2_s_p3_0,
  128386. NULL,
  128387. 0
  128388. };
  128389. static long _vq_quantlist__44c2_s_p4_0[] = {
  128390. 4,
  128391. 3,
  128392. 5,
  128393. 2,
  128394. 6,
  128395. 1,
  128396. 7,
  128397. 0,
  128398. 8,
  128399. };
  128400. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128401. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128402. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128403. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128404. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128405. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0,
  128407. };
  128408. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128409. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128410. };
  128411. static long _vq_quantmap__44c2_s_p4_0[] = {
  128412. 7, 5, 3, 1, 0, 2, 4, 6,
  128413. 8,
  128414. };
  128415. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128416. _vq_quantthresh__44c2_s_p4_0,
  128417. _vq_quantmap__44c2_s_p4_0,
  128418. 9,
  128419. 9
  128420. };
  128421. static static_codebook _44c2_s_p4_0 = {
  128422. 2, 81,
  128423. _vq_lengthlist__44c2_s_p4_0,
  128424. 1, -531628032, 1611661312, 4, 0,
  128425. _vq_quantlist__44c2_s_p4_0,
  128426. NULL,
  128427. &_vq_auxt__44c2_s_p4_0,
  128428. NULL,
  128429. 0
  128430. };
  128431. static long _vq_quantlist__44c2_s_p5_0[] = {
  128432. 4,
  128433. 3,
  128434. 5,
  128435. 2,
  128436. 6,
  128437. 1,
  128438. 7,
  128439. 0,
  128440. 8,
  128441. };
  128442. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128443. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128444. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128445. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128446. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128447. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128448. 11,
  128449. };
  128450. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128451. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128452. };
  128453. static long _vq_quantmap__44c2_s_p5_0[] = {
  128454. 7, 5, 3, 1, 0, 2, 4, 6,
  128455. 8,
  128456. };
  128457. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128458. _vq_quantthresh__44c2_s_p5_0,
  128459. _vq_quantmap__44c2_s_p5_0,
  128460. 9,
  128461. 9
  128462. };
  128463. static static_codebook _44c2_s_p5_0 = {
  128464. 2, 81,
  128465. _vq_lengthlist__44c2_s_p5_0,
  128466. 1, -531628032, 1611661312, 4, 0,
  128467. _vq_quantlist__44c2_s_p5_0,
  128468. NULL,
  128469. &_vq_auxt__44c2_s_p5_0,
  128470. NULL,
  128471. 0
  128472. };
  128473. static long _vq_quantlist__44c2_s_p6_0[] = {
  128474. 8,
  128475. 7,
  128476. 9,
  128477. 6,
  128478. 10,
  128479. 5,
  128480. 11,
  128481. 4,
  128482. 12,
  128483. 3,
  128484. 13,
  128485. 2,
  128486. 14,
  128487. 1,
  128488. 15,
  128489. 0,
  128490. 16,
  128491. };
  128492. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128493. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128494. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128495. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128496. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128497. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128498. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128499. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128500. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128501. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128502. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128503. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128504. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128505. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128506. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128507. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128508. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128509. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128510. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128511. 14,
  128512. };
  128513. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128514. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128515. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128516. };
  128517. static long _vq_quantmap__44c2_s_p6_0[] = {
  128518. 15, 13, 11, 9, 7, 5, 3, 1,
  128519. 0, 2, 4, 6, 8, 10, 12, 14,
  128520. 16,
  128521. };
  128522. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128523. _vq_quantthresh__44c2_s_p6_0,
  128524. _vq_quantmap__44c2_s_p6_0,
  128525. 17,
  128526. 17
  128527. };
  128528. static static_codebook _44c2_s_p6_0 = {
  128529. 2, 289,
  128530. _vq_lengthlist__44c2_s_p6_0,
  128531. 1, -529530880, 1611661312, 5, 0,
  128532. _vq_quantlist__44c2_s_p6_0,
  128533. NULL,
  128534. &_vq_auxt__44c2_s_p6_0,
  128535. NULL,
  128536. 0
  128537. };
  128538. static long _vq_quantlist__44c2_s_p7_0[] = {
  128539. 1,
  128540. 0,
  128541. 2,
  128542. };
  128543. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128544. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128545. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128546. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128547. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128548. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128549. 11,
  128550. };
  128551. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128552. -5.5, 5.5,
  128553. };
  128554. static long _vq_quantmap__44c2_s_p7_0[] = {
  128555. 1, 0, 2,
  128556. };
  128557. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128558. _vq_quantthresh__44c2_s_p7_0,
  128559. _vq_quantmap__44c2_s_p7_0,
  128560. 3,
  128561. 3
  128562. };
  128563. static static_codebook _44c2_s_p7_0 = {
  128564. 4, 81,
  128565. _vq_lengthlist__44c2_s_p7_0,
  128566. 1, -529137664, 1618345984, 2, 0,
  128567. _vq_quantlist__44c2_s_p7_0,
  128568. NULL,
  128569. &_vq_auxt__44c2_s_p7_0,
  128570. NULL,
  128571. 0
  128572. };
  128573. static long _vq_quantlist__44c2_s_p7_1[] = {
  128574. 5,
  128575. 4,
  128576. 6,
  128577. 3,
  128578. 7,
  128579. 2,
  128580. 8,
  128581. 1,
  128582. 9,
  128583. 0,
  128584. 10,
  128585. };
  128586. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128587. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128588. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128589. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128590. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128591. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128592. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128593. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128594. 10,10,10, 8, 8, 8, 8, 8, 8,
  128595. };
  128596. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128597. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128598. 3.5, 4.5,
  128599. };
  128600. static long _vq_quantmap__44c2_s_p7_1[] = {
  128601. 9, 7, 5, 3, 1, 0, 2, 4,
  128602. 6, 8, 10,
  128603. };
  128604. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128605. _vq_quantthresh__44c2_s_p7_1,
  128606. _vq_quantmap__44c2_s_p7_1,
  128607. 11,
  128608. 11
  128609. };
  128610. static static_codebook _44c2_s_p7_1 = {
  128611. 2, 121,
  128612. _vq_lengthlist__44c2_s_p7_1,
  128613. 1, -531365888, 1611661312, 4, 0,
  128614. _vq_quantlist__44c2_s_p7_1,
  128615. NULL,
  128616. &_vq_auxt__44c2_s_p7_1,
  128617. NULL,
  128618. 0
  128619. };
  128620. static long _vq_quantlist__44c2_s_p8_0[] = {
  128621. 6,
  128622. 5,
  128623. 7,
  128624. 4,
  128625. 8,
  128626. 3,
  128627. 9,
  128628. 2,
  128629. 10,
  128630. 1,
  128631. 11,
  128632. 0,
  128633. 12,
  128634. };
  128635. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128636. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128637. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128638. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128639. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128640. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128641. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128642. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128643. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128644. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128645. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128646. 0,12,12,12,12,13,12,14,14,
  128647. };
  128648. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128649. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128650. 12.5, 17.5, 22.5, 27.5,
  128651. };
  128652. static long _vq_quantmap__44c2_s_p8_0[] = {
  128653. 11, 9, 7, 5, 3, 1, 0, 2,
  128654. 4, 6, 8, 10, 12,
  128655. };
  128656. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128657. _vq_quantthresh__44c2_s_p8_0,
  128658. _vq_quantmap__44c2_s_p8_0,
  128659. 13,
  128660. 13
  128661. };
  128662. static static_codebook _44c2_s_p8_0 = {
  128663. 2, 169,
  128664. _vq_lengthlist__44c2_s_p8_0,
  128665. 1, -526516224, 1616117760, 4, 0,
  128666. _vq_quantlist__44c2_s_p8_0,
  128667. NULL,
  128668. &_vq_auxt__44c2_s_p8_0,
  128669. NULL,
  128670. 0
  128671. };
  128672. static long _vq_quantlist__44c2_s_p8_1[] = {
  128673. 2,
  128674. 1,
  128675. 3,
  128676. 0,
  128677. 4,
  128678. };
  128679. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128680. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128681. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128682. };
  128683. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128684. -1.5, -0.5, 0.5, 1.5,
  128685. };
  128686. static long _vq_quantmap__44c2_s_p8_1[] = {
  128687. 3, 1, 0, 2, 4,
  128688. };
  128689. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128690. _vq_quantthresh__44c2_s_p8_1,
  128691. _vq_quantmap__44c2_s_p8_1,
  128692. 5,
  128693. 5
  128694. };
  128695. static static_codebook _44c2_s_p8_1 = {
  128696. 2, 25,
  128697. _vq_lengthlist__44c2_s_p8_1,
  128698. 1, -533725184, 1611661312, 3, 0,
  128699. _vq_quantlist__44c2_s_p8_1,
  128700. NULL,
  128701. &_vq_auxt__44c2_s_p8_1,
  128702. NULL,
  128703. 0
  128704. };
  128705. static long _vq_quantlist__44c2_s_p9_0[] = {
  128706. 6,
  128707. 5,
  128708. 7,
  128709. 4,
  128710. 8,
  128711. 3,
  128712. 9,
  128713. 2,
  128714. 10,
  128715. 1,
  128716. 11,
  128717. 0,
  128718. 12,
  128719. };
  128720. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128721. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128722. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128724. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128731. 11,11,11,11,11,11,11,11,11,
  128732. };
  128733. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128734. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128735. 552.5, 773.5, 994.5, 1215.5,
  128736. };
  128737. static long _vq_quantmap__44c2_s_p9_0[] = {
  128738. 11, 9, 7, 5, 3, 1, 0, 2,
  128739. 4, 6, 8, 10, 12,
  128740. };
  128741. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128742. _vq_quantthresh__44c2_s_p9_0,
  128743. _vq_quantmap__44c2_s_p9_0,
  128744. 13,
  128745. 13
  128746. };
  128747. static static_codebook _44c2_s_p9_0 = {
  128748. 2, 169,
  128749. _vq_lengthlist__44c2_s_p9_0,
  128750. 1, -514541568, 1627103232, 4, 0,
  128751. _vq_quantlist__44c2_s_p9_0,
  128752. NULL,
  128753. &_vq_auxt__44c2_s_p9_0,
  128754. NULL,
  128755. 0
  128756. };
  128757. static long _vq_quantlist__44c2_s_p9_1[] = {
  128758. 6,
  128759. 5,
  128760. 7,
  128761. 4,
  128762. 8,
  128763. 3,
  128764. 9,
  128765. 2,
  128766. 10,
  128767. 1,
  128768. 11,
  128769. 0,
  128770. 12,
  128771. };
  128772. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128773. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128774. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128775. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128776. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128777. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128778. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128779. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128780. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128781. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128782. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128783. 17,13,12,12,10,13,11,14,14,
  128784. };
  128785. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128786. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128787. 42.5, 59.5, 76.5, 93.5,
  128788. };
  128789. static long _vq_quantmap__44c2_s_p9_1[] = {
  128790. 11, 9, 7, 5, 3, 1, 0, 2,
  128791. 4, 6, 8, 10, 12,
  128792. };
  128793. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128794. _vq_quantthresh__44c2_s_p9_1,
  128795. _vq_quantmap__44c2_s_p9_1,
  128796. 13,
  128797. 13
  128798. };
  128799. static static_codebook _44c2_s_p9_1 = {
  128800. 2, 169,
  128801. _vq_lengthlist__44c2_s_p9_1,
  128802. 1, -522616832, 1620115456, 4, 0,
  128803. _vq_quantlist__44c2_s_p9_1,
  128804. NULL,
  128805. &_vq_auxt__44c2_s_p9_1,
  128806. NULL,
  128807. 0
  128808. };
  128809. static long _vq_quantlist__44c2_s_p9_2[] = {
  128810. 8,
  128811. 7,
  128812. 9,
  128813. 6,
  128814. 10,
  128815. 5,
  128816. 11,
  128817. 4,
  128818. 12,
  128819. 3,
  128820. 13,
  128821. 2,
  128822. 14,
  128823. 1,
  128824. 15,
  128825. 0,
  128826. 16,
  128827. };
  128828. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128829. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128830. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128831. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128832. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128833. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128834. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128835. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128836. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128837. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128838. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128839. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128840. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128841. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128842. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128843. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128844. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128845. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128846. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128847. 10,
  128848. };
  128849. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128850. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128851. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128852. };
  128853. static long _vq_quantmap__44c2_s_p9_2[] = {
  128854. 15, 13, 11, 9, 7, 5, 3, 1,
  128855. 0, 2, 4, 6, 8, 10, 12, 14,
  128856. 16,
  128857. };
  128858. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128859. _vq_quantthresh__44c2_s_p9_2,
  128860. _vq_quantmap__44c2_s_p9_2,
  128861. 17,
  128862. 17
  128863. };
  128864. static static_codebook _44c2_s_p9_2 = {
  128865. 2, 289,
  128866. _vq_lengthlist__44c2_s_p9_2,
  128867. 1, -529530880, 1611661312, 5, 0,
  128868. _vq_quantlist__44c2_s_p9_2,
  128869. NULL,
  128870. &_vq_auxt__44c2_s_p9_2,
  128871. NULL,
  128872. 0
  128873. };
  128874. static long _huff_lengthlist__44c2_s_short[] = {
  128875. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128876. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128877. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128878. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128879. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128880. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128881. 6, 8, 9,12,
  128882. };
  128883. static static_codebook _huff_book__44c2_s_short = {
  128884. 2, 100,
  128885. _huff_lengthlist__44c2_s_short,
  128886. 0, 0, 0, 0, 0,
  128887. NULL,
  128888. NULL,
  128889. NULL,
  128890. NULL,
  128891. 0
  128892. };
  128893. static long _huff_lengthlist__44c3_s_long[] = {
  128894. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128895. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128896. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128897. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128898. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128899. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128900. 9, 8, 8, 8,
  128901. };
  128902. static static_codebook _huff_book__44c3_s_long = {
  128903. 2, 100,
  128904. _huff_lengthlist__44c3_s_long,
  128905. 0, 0, 0, 0, 0,
  128906. NULL,
  128907. NULL,
  128908. NULL,
  128909. NULL,
  128910. 0
  128911. };
  128912. static long _vq_quantlist__44c3_s_p1_0[] = {
  128913. 1,
  128914. 0,
  128915. 2,
  128916. };
  128917. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128918. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128919. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128924. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128929. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  128964. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128969. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128974. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129002. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129010. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129015. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129020. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0,
  129329. };
  129330. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129331. -0.5, 0.5,
  129332. };
  129333. static long _vq_quantmap__44c3_s_p1_0[] = {
  129334. 1, 0, 2,
  129335. };
  129336. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129337. _vq_quantthresh__44c3_s_p1_0,
  129338. _vq_quantmap__44c3_s_p1_0,
  129339. 3,
  129340. 3
  129341. };
  129342. static static_codebook _44c3_s_p1_0 = {
  129343. 8, 6561,
  129344. _vq_lengthlist__44c3_s_p1_0,
  129345. 1, -535822336, 1611661312, 2, 0,
  129346. _vq_quantlist__44c3_s_p1_0,
  129347. NULL,
  129348. &_vq_auxt__44c3_s_p1_0,
  129349. NULL,
  129350. 0
  129351. };
  129352. static long _vq_quantlist__44c3_s_p2_0[] = {
  129353. 2,
  129354. 1,
  129355. 3,
  129356. 0,
  129357. 4,
  129358. };
  129359. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129360. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129361. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129362. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129363. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129364. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129370. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129371. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129372. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129378. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129379. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129386. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129387. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0,
  129400. };
  129401. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129402. -1.5, -0.5, 0.5, 1.5,
  129403. };
  129404. static long _vq_quantmap__44c3_s_p2_0[] = {
  129405. 3, 1, 0, 2, 4,
  129406. };
  129407. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129408. _vq_quantthresh__44c3_s_p2_0,
  129409. _vq_quantmap__44c3_s_p2_0,
  129410. 5,
  129411. 5
  129412. };
  129413. static static_codebook _44c3_s_p2_0 = {
  129414. 4, 625,
  129415. _vq_lengthlist__44c3_s_p2_0,
  129416. 1, -533725184, 1611661312, 3, 0,
  129417. _vq_quantlist__44c3_s_p2_0,
  129418. NULL,
  129419. &_vq_auxt__44c3_s_p2_0,
  129420. NULL,
  129421. 0
  129422. };
  129423. static long _vq_quantlist__44c3_s_p3_0[] = {
  129424. 2,
  129425. 1,
  129426. 3,
  129427. 0,
  129428. 4,
  129429. };
  129430. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129431. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0,
  129471. };
  129472. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129473. -1.5, -0.5, 0.5, 1.5,
  129474. };
  129475. static long _vq_quantmap__44c3_s_p3_0[] = {
  129476. 3, 1, 0, 2, 4,
  129477. };
  129478. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129479. _vq_quantthresh__44c3_s_p3_0,
  129480. _vq_quantmap__44c3_s_p3_0,
  129481. 5,
  129482. 5
  129483. };
  129484. static static_codebook _44c3_s_p3_0 = {
  129485. 4, 625,
  129486. _vq_lengthlist__44c3_s_p3_0,
  129487. 1, -533725184, 1611661312, 3, 0,
  129488. _vq_quantlist__44c3_s_p3_0,
  129489. NULL,
  129490. &_vq_auxt__44c3_s_p3_0,
  129491. NULL,
  129492. 0
  129493. };
  129494. static long _vq_quantlist__44c3_s_p4_0[] = {
  129495. 4,
  129496. 3,
  129497. 5,
  129498. 2,
  129499. 6,
  129500. 1,
  129501. 7,
  129502. 0,
  129503. 8,
  129504. };
  129505. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129506. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129507. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129508. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129509. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129510. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0,
  129512. };
  129513. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129514. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129515. };
  129516. static long _vq_quantmap__44c3_s_p4_0[] = {
  129517. 7, 5, 3, 1, 0, 2, 4, 6,
  129518. 8,
  129519. };
  129520. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129521. _vq_quantthresh__44c3_s_p4_0,
  129522. _vq_quantmap__44c3_s_p4_0,
  129523. 9,
  129524. 9
  129525. };
  129526. static static_codebook _44c3_s_p4_0 = {
  129527. 2, 81,
  129528. _vq_lengthlist__44c3_s_p4_0,
  129529. 1, -531628032, 1611661312, 4, 0,
  129530. _vq_quantlist__44c3_s_p4_0,
  129531. NULL,
  129532. &_vq_auxt__44c3_s_p4_0,
  129533. NULL,
  129534. 0
  129535. };
  129536. static long _vq_quantlist__44c3_s_p5_0[] = {
  129537. 4,
  129538. 3,
  129539. 5,
  129540. 2,
  129541. 6,
  129542. 1,
  129543. 7,
  129544. 0,
  129545. 8,
  129546. };
  129547. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129548. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129549. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129550. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129551. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129552. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129553. 11,
  129554. };
  129555. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129556. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129557. };
  129558. static long _vq_quantmap__44c3_s_p5_0[] = {
  129559. 7, 5, 3, 1, 0, 2, 4, 6,
  129560. 8,
  129561. };
  129562. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129563. _vq_quantthresh__44c3_s_p5_0,
  129564. _vq_quantmap__44c3_s_p5_0,
  129565. 9,
  129566. 9
  129567. };
  129568. static static_codebook _44c3_s_p5_0 = {
  129569. 2, 81,
  129570. _vq_lengthlist__44c3_s_p5_0,
  129571. 1, -531628032, 1611661312, 4, 0,
  129572. _vq_quantlist__44c3_s_p5_0,
  129573. NULL,
  129574. &_vq_auxt__44c3_s_p5_0,
  129575. NULL,
  129576. 0
  129577. };
  129578. static long _vq_quantlist__44c3_s_p6_0[] = {
  129579. 8,
  129580. 7,
  129581. 9,
  129582. 6,
  129583. 10,
  129584. 5,
  129585. 11,
  129586. 4,
  129587. 12,
  129588. 3,
  129589. 13,
  129590. 2,
  129591. 14,
  129592. 1,
  129593. 15,
  129594. 0,
  129595. 16,
  129596. };
  129597. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129598. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129599. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129600. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129601. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129602. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129603. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129604. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129605. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129606. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129607. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129608. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129609. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129610. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129611. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129612. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129613. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129614. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129615. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129616. 13,
  129617. };
  129618. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129619. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129620. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129621. };
  129622. static long _vq_quantmap__44c3_s_p6_0[] = {
  129623. 15, 13, 11, 9, 7, 5, 3, 1,
  129624. 0, 2, 4, 6, 8, 10, 12, 14,
  129625. 16,
  129626. };
  129627. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129628. _vq_quantthresh__44c3_s_p6_0,
  129629. _vq_quantmap__44c3_s_p6_0,
  129630. 17,
  129631. 17
  129632. };
  129633. static static_codebook _44c3_s_p6_0 = {
  129634. 2, 289,
  129635. _vq_lengthlist__44c3_s_p6_0,
  129636. 1, -529530880, 1611661312, 5, 0,
  129637. _vq_quantlist__44c3_s_p6_0,
  129638. NULL,
  129639. &_vq_auxt__44c3_s_p6_0,
  129640. NULL,
  129641. 0
  129642. };
  129643. static long _vq_quantlist__44c3_s_p7_0[] = {
  129644. 1,
  129645. 0,
  129646. 2,
  129647. };
  129648. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129649. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129650. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129651. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129652. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129653. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129654. 10,
  129655. };
  129656. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129657. -5.5, 5.5,
  129658. };
  129659. static long _vq_quantmap__44c3_s_p7_0[] = {
  129660. 1, 0, 2,
  129661. };
  129662. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129663. _vq_quantthresh__44c3_s_p7_0,
  129664. _vq_quantmap__44c3_s_p7_0,
  129665. 3,
  129666. 3
  129667. };
  129668. static static_codebook _44c3_s_p7_0 = {
  129669. 4, 81,
  129670. _vq_lengthlist__44c3_s_p7_0,
  129671. 1, -529137664, 1618345984, 2, 0,
  129672. _vq_quantlist__44c3_s_p7_0,
  129673. NULL,
  129674. &_vq_auxt__44c3_s_p7_0,
  129675. NULL,
  129676. 0
  129677. };
  129678. static long _vq_quantlist__44c3_s_p7_1[] = {
  129679. 5,
  129680. 4,
  129681. 6,
  129682. 3,
  129683. 7,
  129684. 2,
  129685. 8,
  129686. 1,
  129687. 9,
  129688. 0,
  129689. 10,
  129690. };
  129691. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129692. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129693. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129694. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129695. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129696. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129697. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129698. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129699. 10,10,10, 8, 8, 8, 8, 8, 8,
  129700. };
  129701. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129702. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129703. 3.5, 4.5,
  129704. };
  129705. static long _vq_quantmap__44c3_s_p7_1[] = {
  129706. 9, 7, 5, 3, 1, 0, 2, 4,
  129707. 6, 8, 10,
  129708. };
  129709. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129710. _vq_quantthresh__44c3_s_p7_1,
  129711. _vq_quantmap__44c3_s_p7_1,
  129712. 11,
  129713. 11
  129714. };
  129715. static static_codebook _44c3_s_p7_1 = {
  129716. 2, 121,
  129717. _vq_lengthlist__44c3_s_p7_1,
  129718. 1, -531365888, 1611661312, 4, 0,
  129719. _vq_quantlist__44c3_s_p7_1,
  129720. NULL,
  129721. &_vq_auxt__44c3_s_p7_1,
  129722. NULL,
  129723. 0
  129724. };
  129725. static long _vq_quantlist__44c3_s_p8_0[] = {
  129726. 6,
  129727. 5,
  129728. 7,
  129729. 4,
  129730. 8,
  129731. 3,
  129732. 9,
  129733. 2,
  129734. 10,
  129735. 1,
  129736. 11,
  129737. 0,
  129738. 12,
  129739. };
  129740. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129741. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129742. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129743. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129744. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129745. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129746. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129747. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129748. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129749. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129750. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129751. 0,13,13,12,12,13,12,14,13,
  129752. };
  129753. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129754. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129755. 12.5, 17.5, 22.5, 27.5,
  129756. };
  129757. static long _vq_quantmap__44c3_s_p8_0[] = {
  129758. 11, 9, 7, 5, 3, 1, 0, 2,
  129759. 4, 6, 8, 10, 12,
  129760. };
  129761. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129762. _vq_quantthresh__44c3_s_p8_0,
  129763. _vq_quantmap__44c3_s_p8_0,
  129764. 13,
  129765. 13
  129766. };
  129767. static static_codebook _44c3_s_p8_0 = {
  129768. 2, 169,
  129769. _vq_lengthlist__44c3_s_p8_0,
  129770. 1, -526516224, 1616117760, 4, 0,
  129771. _vq_quantlist__44c3_s_p8_0,
  129772. NULL,
  129773. &_vq_auxt__44c3_s_p8_0,
  129774. NULL,
  129775. 0
  129776. };
  129777. static long _vq_quantlist__44c3_s_p8_1[] = {
  129778. 2,
  129779. 1,
  129780. 3,
  129781. 0,
  129782. 4,
  129783. };
  129784. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129785. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129786. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129787. };
  129788. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129789. -1.5, -0.5, 0.5, 1.5,
  129790. };
  129791. static long _vq_quantmap__44c3_s_p8_1[] = {
  129792. 3, 1, 0, 2, 4,
  129793. };
  129794. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129795. _vq_quantthresh__44c3_s_p8_1,
  129796. _vq_quantmap__44c3_s_p8_1,
  129797. 5,
  129798. 5
  129799. };
  129800. static static_codebook _44c3_s_p8_1 = {
  129801. 2, 25,
  129802. _vq_lengthlist__44c3_s_p8_1,
  129803. 1, -533725184, 1611661312, 3, 0,
  129804. _vq_quantlist__44c3_s_p8_1,
  129805. NULL,
  129806. &_vq_auxt__44c3_s_p8_1,
  129807. NULL,
  129808. 0
  129809. };
  129810. static long _vq_quantlist__44c3_s_p9_0[] = {
  129811. 6,
  129812. 5,
  129813. 7,
  129814. 4,
  129815. 8,
  129816. 3,
  129817. 9,
  129818. 2,
  129819. 10,
  129820. 1,
  129821. 11,
  129822. 0,
  129823. 12,
  129824. };
  129825. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129826. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129827. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129828. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129829. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129830. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129831. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129832. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129833. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129834. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129836. 11,11,11,11,11,11,11,11,11,
  129837. };
  129838. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129839. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129840. 637.5, 892.5, 1147.5, 1402.5,
  129841. };
  129842. static long _vq_quantmap__44c3_s_p9_0[] = {
  129843. 11, 9, 7, 5, 3, 1, 0, 2,
  129844. 4, 6, 8, 10, 12,
  129845. };
  129846. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129847. _vq_quantthresh__44c3_s_p9_0,
  129848. _vq_quantmap__44c3_s_p9_0,
  129849. 13,
  129850. 13
  129851. };
  129852. static static_codebook _44c3_s_p9_0 = {
  129853. 2, 169,
  129854. _vq_lengthlist__44c3_s_p9_0,
  129855. 1, -514332672, 1627381760, 4, 0,
  129856. _vq_quantlist__44c3_s_p9_0,
  129857. NULL,
  129858. &_vq_auxt__44c3_s_p9_0,
  129859. NULL,
  129860. 0
  129861. };
  129862. static long _vq_quantlist__44c3_s_p9_1[] = {
  129863. 7,
  129864. 6,
  129865. 8,
  129866. 5,
  129867. 9,
  129868. 4,
  129869. 10,
  129870. 3,
  129871. 11,
  129872. 2,
  129873. 12,
  129874. 1,
  129875. 13,
  129876. 0,
  129877. 14,
  129878. };
  129879. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129880. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129881. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129882. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129883. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129884. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129885. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129886. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129887. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129888. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129889. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129890. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129891. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129892. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129893. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129894. 15,
  129895. };
  129896. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129897. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129898. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129899. };
  129900. static long _vq_quantmap__44c3_s_p9_1[] = {
  129901. 13, 11, 9, 7, 5, 3, 1, 0,
  129902. 2, 4, 6, 8, 10, 12, 14,
  129903. };
  129904. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129905. _vq_quantthresh__44c3_s_p9_1,
  129906. _vq_quantmap__44c3_s_p9_1,
  129907. 15,
  129908. 15
  129909. };
  129910. static static_codebook _44c3_s_p9_1 = {
  129911. 2, 225,
  129912. _vq_lengthlist__44c3_s_p9_1,
  129913. 1, -522338304, 1620115456, 4, 0,
  129914. _vq_quantlist__44c3_s_p9_1,
  129915. NULL,
  129916. &_vq_auxt__44c3_s_p9_1,
  129917. NULL,
  129918. 0
  129919. };
  129920. static long _vq_quantlist__44c3_s_p9_2[] = {
  129921. 8,
  129922. 7,
  129923. 9,
  129924. 6,
  129925. 10,
  129926. 5,
  129927. 11,
  129928. 4,
  129929. 12,
  129930. 3,
  129931. 13,
  129932. 2,
  129933. 14,
  129934. 1,
  129935. 15,
  129936. 0,
  129937. 16,
  129938. };
  129939. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129940. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129941. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129942. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129943. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129944. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129945. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129946. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129947. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129948. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129949. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129950. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129951. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129952. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129953. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129954. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129955. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129956. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129957. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129958. 10,
  129959. };
  129960. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129961. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129962. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129963. };
  129964. static long _vq_quantmap__44c3_s_p9_2[] = {
  129965. 15, 13, 11, 9, 7, 5, 3, 1,
  129966. 0, 2, 4, 6, 8, 10, 12, 14,
  129967. 16,
  129968. };
  129969. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129970. _vq_quantthresh__44c3_s_p9_2,
  129971. _vq_quantmap__44c3_s_p9_2,
  129972. 17,
  129973. 17
  129974. };
  129975. static static_codebook _44c3_s_p9_2 = {
  129976. 2, 289,
  129977. _vq_lengthlist__44c3_s_p9_2,
  129978. 1, -529530880, 1611661312, 5, 0,
  129979. _vq_quantlist__44c3_s_p9_2,
  129980. NULL,
  129981. &_vq_auxt__44c3_s_p9_2,
  129982. NULL,
  129983. 0
  129984. };
  129985. static long _huff_lengthlist__44c3_s_short[] = {
  129986. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129987. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129988. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129989. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129990. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129991. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129992. 6, 8, 9,11,
  129993. };
  129994. static static_codebook _huff_book__44c3_s_short = {
  129995. 2, 100,
  129996. _huff_lengthlist__44c3_s_short,
  129997. 0, 0, 0, 0, 0,
  129998. NULL,
  129999. NULL,
  130000. NULL,
  130001. NULL,
  130002. 0
  130003. };
  130004. static long _huff_lengthlist__44c4_s_long[] = {
  130005. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130006. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130007. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130008. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130009. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130010. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130011. 9, 8, 7, 7,
  130012. };
  130013. static static_codebook _huff_book__44c4_s_long = {
  130014. 2, 100,
  130015. _huff_lengthlist__44c4_s_long,
  130016. 0, 0, 0, 0, 0,
  130017. NULL,
  130018. NULL,
  130019. NULL,
  130020. NULL,
  130021. 0
  130022. };
  130023. static long _vq_quantlist__44c4_s_p1_0[] = {
  130024. 1,
  130025. 0,
  130026. 2,
  130027. };
  130028. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130029. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130030. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130035. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130040. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130075. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130080. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130085. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130121. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130126. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130131. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0,
  130440. };
  130441. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130442. -0.5, 0.5,
  130443. };
  130444. static long _vq_quantmap__44c4_s_p1_0[] = {
  130445. 1, 0, 2,
  130446. };
  130447. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130448. _vq_quantthresh__44c4_s_p1_0,
  130449. _vq_quantmap__44c4_s_p1_0,
  130450. 3,
  130451. 3
  130452. };
  130453. static static_codebook _44c4_s_p1_0 = {
  130454. 8, 6561,
  130455. _vq_lengthlist__44c4_s_p1_0,
  130456. 1, -535822336, 1611661312, 2, 0,
  130457. _vq_quantlist__44c4_s_p1_0,
  130458. NULL,
  130459. &_vq_auxt__44c4_s_p1_0,
  130460. NULL,
  130461. 0
  130462. };
  130463. static long _vq_quantlist__44c4_s_p2_0[] = {
  130464. 2,
  130465. 1,
  130466. 3,
  130467. 0,
  130468. 4,
  130469. };
  130470. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130471. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130472. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130473. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130474. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130475. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130481. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130482. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130483. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130489. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130490. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130497. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130498. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0,
  130511. };
  130512. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130513. -1.5, -0.5, 0.5, 1.5,
  130514. };
  130515. static long _vq_quantmap__44c4_s_p2_0[] = {
  130516. 3, 1, 0, 2, 4,
  130517. };
  130518. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130519. _vq_quantthresh__44c4_s_p2_0,
  130520. _vq_quantmap__44c4_s_p2_0,
  130521. 5,
  130522. 5
  130523. };
  130524. static static_codebook _44c4_s_p2_0 = {
  130525. 4, 625,
  130526. _vq_lengthlist__44c4_s_p2_0,
  130527. 1, -533725184, 1611661312, 3, 0,
  130528. _vq_quantlist__44c4_s_p2_0,
  130529. NULL,
  130530. &_vq_auxt__44c4_s_p2_0,
  130531. NULL,
  130532. 0
  130533. };
  130534. static long _vq_quantlist__44c4_s_p3_0[] = {
  130535. 2,
  130536. 1,
  130537. 3,
  130538. 0,
  130539. 4,
  130540. };
  130541. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130542. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0,
  130582. };
  130583. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130584. -1.5, -0.5, 0.5, 1.5,
  130585. };
  130586. static long _vq_quantmap__44c4_s_p3_0[] = {
  130587. 3, 1, 0, 2, 4,
  130588. };
  130589. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130590. _vq_quantthresh__44c4_s_p3_0,
  130591. _vq_quantmap__44c4_s_p3_0,
  130592. 5,
  130593. 5
  130594. };
  130595. static static_codebook _44c4_s_p3_0 = {
  130596. 4, 625,
  130597. _vq_lengthlist__44c4_s_p3_0,
  130598. 1, -533725184, 1611661312, 3, 0,
  130599. _vq_quantlist__44c4_s_p3_0,
  130600. NULL,
  130601. &_vq_auxt__44c4_s_p3_0,
  130602. NULL,
  130603. 0
  130604. };
  130605. static long _vq_quantlist__44c4_s_p4_0[] = {
  130606. 4,
  130607. 3,
  130608. 5,
  130609. 2,
  130610. 6,
  130611. 1,
  130612. 7,
  130613. 0,
  130614. 8,
  130615. };
  130616. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130617. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130618. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130619. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130620. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130621. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0,
  130623. };
  130624. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130625. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130626. };
  130627. static long _vq_quantmap__44c4_s_p4_0[] = {
  130628. 7, 5, 3, 1, 0, 2, 4, 6,
  130629. 8,
  130630. };
  130631. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130632. _vq_quantthresh__44c4_s_p4_0,
  130633. _vq_quantmap__44c4_s_p4_0,
  130634. 9,
  130635. 9
  130636. };
  130637. static static_codebook _44c4_s_p4_0 = {
  130638. 2, 81,
  130639. _vq_lengthlist__44c4_s_p4_0,
  130640. 1, -531628032, 1611661312, 4, 0,
  130641. _vq_quantlist__44c4_s_p4_0,
  130642. NULL,
  130643. &_vq_auxt__44c4_s_p4_0,
  130644. NULL,
  130645. 0
  130646. };
  130647. static long _vq_quantlist__44c4_s_p5_0[] = {
  130648. 4,
  130649. 3,
  130650. 5,
  130651. 2,
  130652. 6,
  130653. 1,
  130654. 7,
  130655. 0,
  130656. 8,
  130657. };
  130658. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130659. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130660. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130661. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130662. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130663. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130664. 10,
  130665. };
  130666. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130667. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130668. };
  130669. static long _vq_quantmap__44c4_s_p5_0[] = {
  130670. 7, 5, 3, 1, 0, 2, 4, 6,
  130671. 8,
  130672. };
  130673. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130674. _vq_quantthresh__44c4_s_p5_0,
  130675. _vq_quantmap__44c4_s_p5_0,
  130676. 9,
  130677. 9
  130678. };
  130679. static static_codebook _44c4_s_p5_0 = {
  130680. 2, 81,
  130681. _vq_lengthlist__44c4_s_p5_0,
  130682. 1, -531628032, 1611661312, 4, 0,
  130683. _vq_quantlist__44c4_s_p5_0,
  130684. NULL,
  130685. &_vq_auxt__44c4_s_p5_0,
  130686. NULL,
  130687. 0
  130688. };
  130689. static long _vq_quantlist__44c4_s_p6_0[] = {
  130690. 8,
  130691. 7,
  130692. 9,
  130693. 6,
  130694. 10,
  130695. 5,
  130696. 11,
  130697. 4,
  130698. 12,
  130699. 3,
  130700. 13,
  130701. 2,
  130702. 14,
  130703. 1,
  130704. 15,
  130705. 0,
  130706. 16,
  130707. };
  130708. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130709. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130710. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130711. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130712. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130713. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130714. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130715. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130716. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130717. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130718. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130719. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130720. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130721. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130722. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130723. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130724. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130725. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130726. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130727. 13,
  130728. };
  130729. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130730. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130731. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130732. };
  130733. static long _vq_quantmap__44c4_s_p6_0[] = {
  130734. 15, 13, 11, 9, 7, 5, 3, 1,
  130735. 0, 2, 4, 6, 8, 10, 12, 14,
  130736. 16,
  130737. };
  130738. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130739. _vq_quantthresh__44c4_s_p6_0,
  130740. _vq_quantmap__44c4_s_p6_0,
  130741. 17,
  130742. 17
  130743. };
  130744. static static_codebook _44c4_s_p6_0 = {
  130745. 2, 289,
  130746. _vq_lengthlist__44c4_s_p6_0,
  130747. 1, -529530880, 1611661312, 5, 0,
  130748. _vq_quantlist__44c4_s_p6_0,
  130749. NULL,
  130750. &_vq_auxt__44c4_s_p6_0,
  130751. NULL,
  130752. 0
  130753. };
  130754. static long _vq_quantlist__44c4_s_p7_0[] = {
  130755. 1,
  130756. 0,
  130757. 2,
  130758. };
  130759. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130760. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130761. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130762. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130763. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130764. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130765. 10,
  130766. };
  130767. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130768. -5.5, 5.5,
  130769. };
  130770. static long _vq_quantmap__44c4_s_p7_0[] = {
  130771. 1, 0, 2,
  130772. };
  130773. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130774. _vq_quantthresh__44c4_s_p7_0,
  130775. _vq_quantmap__44c4_s_p7_0,
  130776. 3,
  130777. 3
  130778. };
  130779. static static_codebook _44c4_s_p7_0 = {
  130780. 4, 81,
  130781. _vq_lengthlist__44c4_s_p7_0,
  130782. 1, -529137664, 1618345984, 2, 0,
  130783. _vq_quantlist__44c4_s_p7_0,
  130784. NULL,
  130785. &_vq_auxt__44c4_s_p7_0,
  130786. NULL,
  130787. 0
  130788. };
  130789. static long _vq_quantlist__44c4_s_p7_1[] = {
  130790. 5,
  130791. 4,
  130792. 6,
  130793. 3,
  130794. 7,
  130795. 2,
  130796. 8,
  130797. 1,
  130798. 9,
  130799. 0,
  130800. 10,
  130801. };
  130802. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130803. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130804. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130805. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130806. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130807. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130808. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130809. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130810. 10,10,10, 8, 8, 8, 8, 9, 9,
  130811. };
  130812. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130813. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130814. 3.5, 4.5,
  130815. };
  130816. static long _vq_quantmap__44c4_s_p7_1[] = {
  130817. 9, 7, 5, 3, 1, 0, 2, 4,
  130818. 6, 8, 10,
  130819. };
  130820. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130821. _vq_quantthresh__44c4_s_p7_1,
  130822. _vq_quantmap__44c4_s_p7_1,
  130823. 11,
  130824. 11
  130825. };
  130826. static static_codebook _44c4_s_p7_1 = {
  130827. 2, 121,
  130828. _vq_lengthlist__44c4_s_p7_1,
  130829. 1, -531365888, 1611661312, 4, 0,
  130830. _vq_quantlist__44c4_s_p7_1,
  130831. NULL,
  130832. &_vq_auxt__44c4_s_p7_1,
  130833. NULL,
  130834. 0
  130835. };
  130836. static long _vq_quantlist__44c4_s_p8_0[] = {
  130837. 6,
  130838. 5,
  130839. 7,
  130840. 4,
  130841. 8,
  130842. 3,
  130843. 9,
  130844. 2,
  130845. 10,
  130846. 1,
  130847. 11,
  130848. 0,
  130849. 12,
  130850. };
  130851. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130852. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130853. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130854. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130855. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130856. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130857. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130858. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130859. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130860. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130861. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130862. 0,13,12,12,12,12,12,13,13,
  130863. };
  130864. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130865. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130866. 12.5, 17.5, 22.5, 27.5,
  130867. };
  130868. static long _vq_quantmap__44c4_s_p8_0[] = {
  130869. 11, 9, 7, 5, 3, 1, 0, 2,
  130870. 4, 6, 8, 10, 12,
  130871. };
  130872. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130873. _vq_quantthresh__44c4_s_p8_0,
  130874. _vq_quantmap__44c4_s_p8_0,
  130875. 13,
  130876. 13
  130877. };
  130878. static static_codebook _44c4_s_p8_0 = {
  130879. 2, 169,
  130880. _vq_lengthlist__44c4_s_p8_0,
  130881. 1, -526516224, 1616117760, 4, 0,
  130882. _vq_quantlist__44c4_s_p8_0,
  130883. NULL,
  130884. &_vq_auxt__44c4_s_p8_0,
  130885. NULL,
  130886. 0
  130887. };
  130888. static long _vq_quantlist__44c4_s_p8_1[] = {
  130889. 2,
  130890. 1,
  130891. 3,
  130892. 0,
  130893. 4,
  130894. };
  130895. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130896. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130897. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130898. };
  130899. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130900. -1.5, -0.5, 0.5, 1.5,
  130901. };
  130902. static long _vq_quantmap__44c4_s_p8_1[] = {
  130903. 3, 1, 0, 2, 4,
  130904. };
  130905. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130906. _vq_quantthresh__44c4_s_p8_1,
  130907. _vq_quantmap__44c4_s_p8_1,
  130908. 5,
  130909. 5
  130910. };
  130911. static static_codebook _44c4_s_p8_1 = {
  130912. 2, 25,
  130913. _vq_lengthlist__44c4_s_p8_1,
  130914. 1, -533725184, 1611661312, 3, 0,
  130915. _vq_quantlist__44c4_s_p8_1,
  130916. NULL,
  130917. &_vq_auxt__44c4_s_p8_1,
  130918. NULL,
  130919. 0
  130920. };
  130921. static long _vq_quantlist__44c4_s_p9_0[] = {
  130922. 6,
  130923. 5,
  130924. 7,
  130925. 4,
  130926. 8,
  130927. 3,
  130928. 9,
  130929. 2,
  130930. 10,
  130931. 1,
  130932. 11,
  130933. 0,
  130934. 12,
  130935. };
  130936. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130937. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130938. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130939. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130940. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130941. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130942. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130943. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130944. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130945. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130946. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130947. 12,12,12,12,12,12,12,12,12,
  130948. };
  130949. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130950. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130951. 787.5, 1102.5, 1417.5, 1732.5,
  130952. };
  130953. static long _vq_quantmap__44c4_s_p9_0[] = {
  130954. 11, 9, 7, 5, 3, 1, 0, 2,
  130955. 4, 6, 8, 10, 12,
  130956. };
  130957. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130958. _vq_quantthresh__44c4_s_p9_0,
  130959. _vq_quantmap__44c4_s_p9_0,
  130960. 13,
  130961. 13
  130962. };
  130963. static static_codebook _44c4_s_p9_0 = {
  130964. 2, 169,
  130965. _vq_lengthlist__44c4_s_p9_0,
  130966. 1, -513964032, 1628680192, 4, 0,
  130967. _vq_quantlist__44c4_s_p9_0,
  130968. NULL,
  130969. &_vq_auxt__44c4_s_p9_0,
  130970. NULL,
  130971. 0
  130972. };
  130973. static long _vq_quantlist__44c4_s_p9_1[] = {
  130974. 7,
  130975. 6,
  130976. 8,
  130977. 5,
  130978. 9,
  130979. 4,
  130980. 10,
  130981. 3,
  130982. 11,
  130983. 2,
  130984. 12,
  130985. 1,
  130986. 13,
  130987. 0,
  130988. 14,
  130989. };
  130990. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130991. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130992. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130993. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130994. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130995. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130996. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130997. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130998. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130999. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131000. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131001. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131002. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131003. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131004. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131005. 15,
  131006. };
  131007. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131008. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131009. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131010. };
  131011. static long _vq_quantmap__44c4_s_p9_1[] = {
  131012. 13, 11, 9, 7, 5, 3, 1, 0,
  131013. 2, 4, 6, 8, 10, 12, 14,
  131014. };
  131015. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131016. _vq_quantthresh__44c4_s_p9_1,
  131017. _vq_quantmap__44c4_s_p9_1,
  131018. 15,
  131019. 15
  131020. };
  131021. static static_codebook _44c4_s_p9_1 = {
  131022. 2, 225,
  131023. _vq_lengthlist__44c4_s_p9_1,
  131024. 1, -520986624, 1620377600, 4, 0,
  131025. _vq_quantlist__44c4_s_p9_1,
  131026. NULL,
  131027. &_vq_auxt__44c4_s_p9_1,
  131028. NULL,
  131029. 0
  131030. };
  131031. static long _vq_quantlist__44c4_s_p9_2[] = {
  131032. 10,
  131033. 9,
  131034. 11,
  131035. 8,
  131036. 12,
  131037. 7,
  131038. 13,
  131039. 6,
  131040. 14,
  131041. 5,
  131042. 15,
  131043. 4,
  131044. 16,
  131045. 3,
  131046. 17,
  131047. 2,
  131048. 18,
  131049. 1,
  131050. 19,
  131051. 0,
  131052. 20,
  131053. };
  131054. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131055. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131056. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131057. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131058. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131059. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131060. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131061. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131062. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131063. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131064. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131065. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131066. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131067. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131068. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131069. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131070. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131071. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131072. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131073. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131074. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131075. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131076. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131077. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131078. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131079. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131080. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131081. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131082. 10,10,10,10,10,10,10,10,10,
  131083. };
  131084. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131085. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131086. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131087. 6.5, 7.5, 8.5, 9.5,
  131088. };
  131089. static long _vq_quantmap__44c4_s_p9_2[] = {
  131090. 19, 17, 15, 13, 11, 9, 7, 5,
  131091. 3, 1, 0, 2, 4, 6, 8, 10,
  131092. 12, 14, 16, 18, 20,
  131093. };
  131094. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131095. _vq_quantthresh__44c4_s_p9_2,
  131096. _vq_quantmap__44c4_s_p9_2,
  131097. 21,
  131098. 21
  131099. };
  131100. static static_codebook _44c4_s_p9_2 = {
  131101. 2, 441,
  131102. _vq_lengthlist__44c4_s_p9_2,
  131103. 1, -529268736, 1611661312, 5, 0,
  131104. _vq_quantlist__44c4_s_p9_2,
  131105. NULL,
  131106. &_vq_auxt__44c4_s_p9_2,
  131107. NULL,
  131108. 0
  131109. };
  131110. static long _huff_lengthlist__44c4_s_short[] = {
  131111. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131112. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131113. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131114. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131115. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131116. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131117. 7, 9,12,17,
  131118. };
  131119. static static_codebook _huff_book__44c4_s_short = {
  131120. 2, 100,
  131121. _huff_lengthlist__44c4_s_short,
  131122. 0, 0, 0, 0, 0,
  131123. NULL,
  131124. NULL,
  131125. NULL,
  131126. NULL,
  131127. 0
  131128. };
  131129. static long _huff_lengthlist__44c5_s_long[] = {
  131130. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131131. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131132. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131133. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131134. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131135. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131136. 9, 8, 7, 7,
  131137. };
  131138. static static_codebook _huff_book__44c5_s_long = {
  131139. 2, 100,
  131140. _huff_lengthlist__44c5_s_long,
  131141. 0, 0, 0, 0, 0,
  131142. NULL,
  131143. NULL,
  131144. NULL,
  131145. NULL,
  131146. 0
  131147. };
  131148. static long _vq_quantlist__44c5_s_p1_0[] = {
  131149. 1,
  131150. 0,
  131151. 2,
  131152. };
  131153. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131154. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131155. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131160. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131165. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131200. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131205. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131210. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131246. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131251. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131256. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0,
  131565. };
  131566. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131567. -0.5, 0.5,
  131568. };
  131569. static long _vq_quantmap__44c5_s_p1_0[] = {
  131570. 1, 0, 2,
  131571. };
  131572. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131573. _vq_quantthresh__44c5_s_p1_0,
  131574. _vq_quantmap__44c5_s_p1_0,
  131575. 3,
  131576. 3
  131577. };
  131578. static static_codebook _44c5_s_p1_0 = {
  131579. 8, 6561,
  131580. _vq_lengthlist__44c5_s_p1_0,
  131581. 1, -535822336, 1611661312, 2, 0,
  131582. _vq_quantlist__44c5_s_p1_0,
  131583. NULL,
  131584. &_vq_auxt__44c5_s_p1_0,
  131585. NULL,
  131586. 0
  131587. };
  131588. static long _vq_quantlist__44c5_s_p2_0[] = {
  131589. 2,
  131590. 1,
  131591. 3,
  131592. 0,
  131593. 4,
  131594. };
  131595. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131596. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131597. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131598. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131599. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131600. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131606. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131607. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131608. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131614. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131615. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131622. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131623. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0,
  131636. };
  131637. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131638. -1.5, -0.5, 0.5, 1.5,
  131639. };
  131640. static long _vq_quantmap__44c5_s_p2_0[] = {
  131641. 3, 1, 0, 2, 4,
  131642. };
  131643. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131644. _vq_quantthresh__44c5_s_p2_0,
  131645. _vq_quantmap__44c5_s_p2_0,
  131646. 5,
  131647. 5
  131648. };
  131649. static static_codebook _44c5_s_p2_0 = {
  131650. 4, 625,
  131651. _vq_lengthlist__44c5_s_p2_0,
  131652. 1, -533725184, 1611661312, 3, 0,
  131653. _vq_quantlist__44c5_s_p2_0,
  131654. NULL,
  131655. &_vq_auxt__44c5_s_p2_0,
  131656. NULL,
  131657. 0
  131658. };
  131659. static long _vq_quantlist__44c5_s_p3_0[] = {
  131660. 2,
  131661. 1,
  131662. 3,
  131663. 0,
  131664. 4,
  131665. };
  131666. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131667. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0,
  131707. };
  131708. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131709. -1.5, -0.5, 0.5, 1.5,
  131710. };
  131711. static long _vq_quantmap__44c5_s_p3_0[] = {
  131712. 3, 1, 0, 2, 4,
  131713. };
  131714. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131715. _vq_quantthresh__44c5_s_p3_0,
  131716. _vq_quantmap__44c5_s_p3_0,
  131717. 5,
  131718. 5
  131719. };
  131720. static static_codebook _44c5_s_p3_0 = {
  131721. 4, 625,
  131722. _vq_lengthlist__44c5_s_p3_0,
  131723. 1, -533725184, 1611661312, 3, 0,
  131724. _vq_quantlist__44c5_s_p3_0,
  131725. NULL,
  131726. &_vq_auxt__44c5_s_p3_0,
  131727. NULL,
  131728. 0
  131729. };
  131730. static long _vq_quantlist__44c5_s_p4_0[] = {
  131731. 4,
  131732. 3,
  131733. 5,
  131734. 2,
  131735. 6,
  131736. 1,
  131737. 7,
  131738. 0,
  131739. 8,
  131740. };
  131741. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131742. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131743. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131744. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131745. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131746. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0,
  131748. };
  131749. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131750. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131751. };
  131752. static long _vq_quantmap__44c5_s_p4_0[] = {
  131753. 7, 5, 3, 1, 0, 2, 4, 6,
  131754. 8,
  131755. };
  131756. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131757. _vq_quantthresh__44c5_s_p4_0,
  131758. _vq_quantmap__44c5_s_p4_0,
  131759. 9,
  131760. 9
  131761. };
  131762. static static_codebook _44c5_s_p4_0 = {
  131763. 2, 81,
  131764. _vq_lengthlist__44c5_s_p4_0,
  131765. 1, -531628032, 1611661312, 4, 0,
  131766. _vq_quantlist__44c5_s_p4_0,
  131767. NULL,
  131768. &_vq_auxt__44c5_s_p4_0,
  131769. NULL,
  131770. 0
  131771. };
  131772. static long _vq_quantlist__44c5_s_p5_0[] = {
  131773. 4,
  131774. 3,
  131775. 5,
  131776. 2,
  131777. 6,
  131778. 1,
  131779. 7,
  131780. 0,
  131781. 8,
  131782. };
  131783. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131784. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131785. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131786. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131787. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131788. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131789. 10,
  131790. };
  131791. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131792. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131793. };
  131794. static long _vq_quantmap__44c5_s_p5_0[] = {
  131795. 7, 5, 3, 1, 0, 2, 4, 6,
  131796. 8,
  131797. };
  131798. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131799. _vq_quantthresh__44c5_s_p5_0,
  131800. _vq_quantmap__44c5_s_p5_0,
  131801. 9,
  131802. 9
  131803. };
  131804. static static_codebook _44c5_s_p5_0 = {
  131805. 2, 81,
  131806. _vq_lengthlist__44c5_s_p5_0,
  131807. 1, -531628032, 1611661312, 4, 0,
  131808. _vq_quantlist__44c5_s_p5_0,
  131809. NULL,
  131810. &_vq_auxt__44c5_s_p5_0,
  131811. NULL,
  131812. 0
  131813. };
  131814. static long _vq_quantlist__44c5_s_p6_0[] = {
  131815. 8,
  131816. 7,
  131817. 9,
  131818. 6,
  131819. 10,
  131820. 5,
  131821. 11,
  131822. 4,
  131823. 12,
  131824. 3,
  131825. 13,
  131826. 2,
  131827. 14,
  131828. 1,
  131829. 15,
  131830. 0,
  131831. 16,
  131832. };
  131833. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131834. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131835. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131836. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131837. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131838. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131839. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131840. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131841. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131842. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131843. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131844. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131845. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131846. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131847. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131848. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131849. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131850. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131851. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131852. 13,
  131853. };
  131854. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131855. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131856. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131857. };
  131858. static long _vq_quantmap__44c5_s_p6_0[] = {
  131859. 15, 13, 11, 9, 7, 5, 3, 1,
  131860. 0, 2, 4, 6, 8, 10, 12, 14,
  131861. 16,
  131862. };
  131863. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131864. _vq_quantthresh__44c5_s_p6_0,
  131865. _vq_quantmap__44c5_s_p6_0,
  131866. 17,
  131867. 17
  131868. };
  131869. static static_codebook _44c5_s_p6_0 = {
  131870. 2, 289,
  131871. _vq_lengthlist__44c5_s_p6_0,
  131872. 1, -529530880, 1611661312, 5, 0,
  131873. _vq_quantlist__44c5_s_p6_0,
  131874. NULL,
  131875. &_vq_auxt__44c5_s_p6_0,
  131876. NULL,
  131877. 0
  131878. };
  131879. static long _vq_quantlist__44c5_s_p7_0[] = {
  131880. 1,
  131881. 0,
  131882. 2,
  131883. };
  131884. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131885. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131886. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131887. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131888. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131889. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131890. 10,
  131891. };
  131892. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131893. -5.5, 5.5,
  131894. };
  131895. static long _vq_quantmap__44c5_s_p7_0[] = {
  131896. 1, 0, 2,
  131897. };
  131898. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131899. _vq_quantthresh__44c5_s_p7_0,
  131900. _vq_quantmap__44c5_s_p7_0,
  131901. 3,
  131902. 3
  131903. };
  131904. static static_codebook _44c5_s_p7_0 = {
  131905. 4, 81,
  131906. _vq_lengthlist__44c5_s_p7_0,
  131907. 1, -529137664, 1618345984, 2, 0,
  131908. _vq_quantlist__44c5_s_p7_0,
  131909. NULL,
  131910. &_vq_auxt__44c5_s_p7_0,
  131911. NULL,
  131912. 0
  131913. };
  131914. static long _vq_quantlist__44c5_s_p7_1[] = {
  131915. 5,
  131916. 4,
  131917. 6,
  131918. 3,
  131919. 7,
  131920. 2,
  131921. 8,
  131922. 1,
  131923. 9,
  131924. 0,
  131925. 10,
  131926. };
  131927. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131928. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131929. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131930. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131931. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131932. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131933. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131934. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131935. 10,10,10, 8, 8, 8, 8, 8, 8,
  131936. };
  131937. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131938. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131939. 3.5, 4.5,
  131940. };
  131941. static long _vq_quantmap__44c5_s_p7_1[] = {
  131942. 9, 7, 5, 3, 1, 0, 2, 4,
  131943. 6, 8, 10,
  131944. };
  131945. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131946. _vq_quantthresh__44c5_s_p7_1,
  131947. _vq_quantmap__44c5_s_p7_1,
  131948. 11,
  131949. 11
  131950. };
  131951. static static_codebook _44c5_s_p7_1 = {
  131952. 2, 121,
  131953. _vq_lengthlist__44c5_s_p7_1,
  131954. 1, -531365888, 1611661312, 4, 0,
  131955. _vq_quantlist__44c5_s_p7_1,
  131956. NULL,
  131957. &_vq_auxt__44c5_s_p7_1,
  131958. NULL,
  131959. 0
  131960. };
  131961. static long _vq_quantlist__44c5_s_p8_0[] = {
  131962. 6,
  131963. 5,
  131964. 7,
  131965. 4,
  131966. 8,
  131967. 3,
  131968. 9,
  131969. 2,
  131970. 10,
  131971. 1,
  131972. 11,
  131973. 0,
  131974. 12,
  131975. };
  131976. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131977. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131978. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131979. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131980. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131981. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131982. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131983. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131984. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131985. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131986. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131987. 0,12,12,12,12,12,12,13,13,
  131988. };
  131989. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131990. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131991. 12.5, 17.5, 22.5, 27.5,
  131992. };
  131993. static long _vq_quantmap__44c5_s_p8_0[] = {
  131994. 11, 9, 7, 5, 3, 1, 0, 2,
  131995. 4, 6, 8, 10, 12,
  131996. };
  131997. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131998. _vq_quantthresh__44c5_s_p8_0,
  131999. _vq_quantmap__44c5_s_p8_0,
  132000. 13,
  132001. 13
  132002. };
  132003. static static_codebook _44c5_s_p8_0 = {
  132004. 2, 169,
  132005. _vq_lengthlist__44c5_s_p8_0,
  132006. 1, -526516224, 1616117760, 4, 0,
  132007. _vq_quantlist__44c5_s_p8_0,
  132008. NULL,
  132009. &_vq_auxt__44c5_s_p8_0,
  132010. NULL,
  132011. 0
  132012. };
  132013. static long _vq_quantlist__44c5_s_p8_1[] = {
  132014. 2,
  132015. 1,
  132016. 3,
  132017. 0,
  132018. 4,
  132019. };
  132020. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132021. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132022. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132023. };
  132024. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132025. -1.5, -0.5, 0.5, 1.5,
  132026. };
  132027. static long _vq_quantmap__44c5_s_p8_1[] = {
  132028. 3, 1, 0, 2, 4,
  132029. };
  132030. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132031. _vq_quantthresh__44c5_s_p8_1,
  132032. _vq_quantmap__44c5_s_p8_1,
  132033. 5,
  132034. 5
  132035. };
  132036. static static_codebook _44c5_s_p8_1 = {
  132037. 2, 25,
  132038. _vq_lengthlist__44c5_s_p8_1,
  132039. 1, -533725184, 1611661312, 3, 0,
  132040. _vq_quantlist__44c5_s_p8_1,
  132041. NULL,
  132042. &_vq_auxt__44c5_s_p8_1,
  132043. NULL,
  132044. 0
  132045. };
  132046. static long _vq_quantlist__44c5_s_p9_0[] = {
  132047. 7,
  132048. 6,
  132049. 8,
  132050. 5,
  132051. 9,
  132052. 4,
  132053. 10,
  132054. 3,
  132055. 11,
  132056. 2,
  132057. 12,
  132058. 1,
  132059. 13,
  132060. 0,
  132061. 14,
  132062. };
  132063. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132064. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132065. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132066. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132067. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132068. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132069. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132070. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132071. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132072. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132073. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132074. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132075. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132076. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132077. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132078. 12,
  132079. };
  132080. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132081. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132082. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132083. };
  132084. static long _vq_quantmap__44c5_s_p9_0[] = {
  132085. 13, 11, 9, 7, 5, 3, 1, 0,
  132086. 2, 4, 6, 8, 10, 12, 14,
  132087. };
  132088. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132089. _vq_quantthresh__44c5_s_p9_0,
  132090. _vq_quantmap__44c5_s_p9_0,
  132091. 15,
  132092. 15
  132093. };
  132094. static static_codebook _44c5_s_p9_0 = {
  132095. 2, 225,
  132096. _vq_lengthlist__44c5_s_p9_0,
  132097. 1, -512522752, 1628852224, 4, 0,
  132098. _vq_quantlist__44c5_s_p9_0,
  132099. NULL,
  132100. &_vq_auxt__44c5_s_p9_0,
  132101. NULL,
  132102. 0
  132103. };
  132104. static long _vq_quantlist__44c5_s_p9_1[] = {
  132105. 8,
  132106. 7,
  132107. 9,
  132108. 6,
  132109. 10,
  132110. 5,
  132111. 11,
  132112. 4,
  132113. 12,
  132114. 3,
  132115. 13,
  132116. 2,
  132117. 14,
  132118. 1,
  132119. 15,
  132120. 0,
  132121. 16,
  132122. };
  132123. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132124. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132125. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132126. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132127. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132128. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132129. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132130. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132131. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132132. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132133. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132134. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132135. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132136. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132137. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132138. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132139. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132140. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132141. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132142. 15,
  132143. };
  132144. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132145. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132146. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132147. };
  132148. static long _vq_quantmap__44c5_s_p9_1[] = {
  132149. 15, 13, 11, 9, 7, 5, 3, 1,
  132150. 0, 2, 4, 6, 8, 10, 12, 14,
  132151. 16,
  132152. };
  132153. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132154. _vq_quantthresh__44c5_s_p9_1,
  132155. _vq_quantmap__44c5_s_p9_1,
  132156. 17,
  132157. 17
  132158. };
  132159. static static_codebook _44c5_s_p9_1 = {
  132160. 2, 289,
  132161. _vq_lengthlist__44c5_s_p9_1,
  132162. 1, -520814592, 1620377600, 5, 0,
  132163. _vq_quantlist__44c5_s_p9_1,
  132164. NULL,
  132165. &_vq_auxt__44c5_s_p9_1,
  132166. NULL,
  132167. 0
  132168. };
  132169. static long _vq_quantlist__44c5_s_p9_2[] = {
  132170. 10,
  132171. 9,
  132172. 11,
  132173. 8,
  132174. 12,
  132175. 7,
  132176. 13,
  132177. 6,
  132178. 14,
  132179. 5,
  132180. 15,
  132181. 4,
  132182. 16,
  132183. 3,
  132184. 17,
  132185. 2,
  132186. 18,
  132187. 1,
  132188. 19,
  132189. 0,
  132190. 20,
  132191. };
  132192. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132193. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132194. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132195. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132196. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132197. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132198. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132199. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132200. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132201. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132202. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132203. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132204. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132205. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132206. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132207. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132208. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132209. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132210. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132211. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132212. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132213. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132214. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132215. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132216. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132217. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132218. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132219. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132220. 10,10,10,10,10,10,10,10,10,
  132221. };
  132222. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132223. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132224. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132225. 6.5, 7.5, 8.5, 9.5,
  132226. };
  132227. static long _vq_quantmap__44c5_s_p9_2[] = {
  132228. 19, 17, 15, 13, 11, 9, 7, 5,
  132229. 3, 1, 0, 2, 4, 6, 8, 10,
  132230. 12, 14, 16, 18, 20,
  132231. };
  132232. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132233. _vq_quantthresh__44c5_s_p9_2,
  132234. _vq_quantmap__44c5_s_p9_2,
  132235. 21,
  132236. 21
  132237. };
  132238. static static_codebook _44c5_s_p9_2 = {
  132239. 2, 441,
  132240. _vq_lengthlist__44c5_s_p9_2,
  132241. 1, -529268736, 1611661312, 5, 0,
  132242. _vq_quantlist__44c5_s_p9_2,
  132243. NULL,
  132244. &_vq_auxt__44c5_s_p9_2,
  132245. NULL,
  132246. 0
  132247. };
  132248. static long _huff_lengthlist__44c5_s_short[] = {
  132249. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132250. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132251. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132252. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132253. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132254. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132255. 6, 8,11,16,
  132256. };
  132257. static static_codebook _huff_book__44c5_s_short = {
  132258. 2, 100,
  132259. _huff_lengthlist__44c5_s_short,
  132260. 0, 0, 0, 0, 0,
  132261. NULL,
  132262. NULL,
  132263. NULL,
  132264. NULL,
  132265. 0
  132266. };
  132267. static long _huff_lengthlist__44c6_s_long[] = {
  132268. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132269. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132270. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132271. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132272. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132273. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132274. 11,10,10,12,
  132275. };
  132276. static static_codebook _huff_book__44c6_s_long = {
  132277. 2, 100,
  132278. _huff_lengthlist__44c6_s_long,
  132279. 0, 0, 0, 0, 0,
  132280. NULL,
  132281. NULL,
  132282. NULL,
  132283. NULL,
  132284. 0
  132285. };
  132286. static long _vq_quantlist__44c6_s_p1_0[] = {
  132287. 1,
  132288. 0,
  132289. 2,
  132290. };
  132291. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132292. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132293. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132294. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132295. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132296. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132297. 8,
  132298. };
  132299. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132300. -0.5, 0.5,
  132301. };
  132302. static long _vq_quantmap__44c6_s_p1_0[] = {
  132303. 1, 0, 2,
  132304. };
  132305. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132306. _vq_quantthresh__44c6_s_p1_0,
  132307. _vq_quantmap__44c6_s_p1_0,
  132308. 3,
  132309. 3
  132310. };
  132311. static static_codebook _44c6_s_p1_0 = {
  132312. 4, 81,
  132313. _vq_lengthlist__44c6_s_p1_0,
  132314. 1, -535822336, 1611661312, 2, 0,
  132315. _vq_quantlist__44c6_s_p1_0,
  132316. NULL,
  132317. &_vq_auxt__44c6_s_p1_0,
  132318. NULL,
  132319. 0
  132320. };
  132321. static long _vq_quantlist__44c6_s_p2_0[] = {
  132322. 2,
  132323. 1,
  132324. 3,
  132325. 0,
  132326. 4,
  132327. };
  132328. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132329. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132330. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132331. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132332. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132333. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132334. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132335. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132336. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132338. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132339. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132340. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132341. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132342. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132343. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132344. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132347. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132348. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132349. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132350. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132351. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132352. 13,13, 0, 0, 0,13,13, 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. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132355. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132356. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132357. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132358. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132359. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132360. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132365. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132366. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132367. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132368. 13,
  132369. };
  132370. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132371. -1.5, -0.5, 0.5, 1.5,
  132372. };
  132373. static long _vq_quantmap__44c6_s_p2_0[] = {
  132374. 3, 1, 0, 2, 4,
  132375. };
  132376. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132377. _vq_quantthresh__44c6_s_p2_0,
  132378. _vq_quantmap__44c6_s_p2_0,
  132379. 5,
  132380. 5
  132381. };
  132382. static static_codebook _44c6_s_p2_0 = {
  132383. 4, 625,
  132384. _vq_lengthlist__44c6_s_p2_0,
  132385. 1, -533725184, 1611661312, 3, 0,
  132386. _vq_quantlist__44c6_s_p2_0,
  132387. NULL,
  132388. &_vq_auxt__44c6_s_p2_0,
  132389. NULL,
  132390. 0
  132391. };
  132392. static long _vq_quantlist__44c6_s_p3_0[] = {
  132393. 4,
  132394. 3,
  132395. 5,
  132396. 2,
  132397. 6,
  132398. 1,
  132399. 7,
  132400. 0,
  132401. 8,
  132402. };
  132403. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132404. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132405. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132406. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132407. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132409. 0,
  132410. };
  132411. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132412. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132413. };
  132414. static long _vq_quantmap__44c6_s_p3_0[] = {
  132415. 7, 5, 3, 1, 0, 2, 4, 6,
  132416. 8,
  132417. };
  132418. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132419. _vq_quantthresh__44c6_s_p3_0,
  132420. _vq_quantmap__44c6_s_p3_0,
  132421. 9,
  132422. 9
  132423. };
  132424. static static_codebook _44c6_s_p3_0 = {
  132425. 2, 81,
  132426. _vq_lengthlist__44c6_s_p3_0,
  132427. 1, -531628032, 1611661312, 4, 0,
  132428. _vq_quantlist__44c6_s_p3_0,
  132429. NULL,
  132430. &_vq_auxt__44c6_s_p3_0,
  132431. NULL,
  132432. 0
  132433. };
  132434. static long _vq_quantlist__44c6_s_p4_0[] = {
  132435. 8,
  132436. 7,
  132437. 9,
  132438. 6,
  132439. 10,
  132440. 5,
  132441. 11,
  132442. 4,
  132443. 12,
  132444. 3,
  132445. 13,
  132446. 2,
  132447. 14,
  132448. 1,
  132449. 15,
  132450. 0,
  132451. 16,
  132452. };
  132453. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132454. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132455. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132456. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132457. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132458. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132459. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132460. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132461. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132462. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132463. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132472. 0,
  132473. };
  132474. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132475. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132476. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132477. };
  132478. static long _vq_quantmap__44c6_s_p4_0[] = {
  132479. 15, 13, 11, 9, 7, 5, 3, 1,
  132480. 0, 2, 4, 6, 8, 10, 12, 14,
  132481. 16,
  132482. };
  132483. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132484. _vq_quantthresh__44c6_s_p4_0,
  132485. _vq_quantmap__44c6_s_p4_0,
  132486. 17,
  132487. 17
  132488. };
  132489. static static_codebook _44c6_s_p4_0 = {
  132490. 2, 289,
  132491. _vq_lengthlist__44c6_s_p4_0,
  132492. 1, -529530880, 1611661312, 5, 0,
  132493. _vq_quantlist__44c6_s_p4_0,
  132494. NULL,
  132495. &_vq_auxt__44c6_s_p4_0,
  132496. NULL,
  132497. 0
  132498. };
  132499. static long _vq_quantlist__44c6_s_p5_0[] = {
  132500. 1,
  132501. 0,
  132502. 2,
  132503. };
  132504. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132505. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132506. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132507. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132508. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132509. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132510. 12,
  132511. };
  132512. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132513. -5.5, 5.5,
  132514. };
  132515. static long _vq_quantmap__44c6_s_p5_0[] = {
  132516. 1, 0, 2,
  132517. };
  132518. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132519. _vq_quantthresh__44c6_s_p5_0,
  132520. _vq_quantmap__44c6_s_p5_0,
  132521. 3,
  132522. 3
  132523. };
  132524. static static_codebook _44c6_s_p5_0 = {
  132525. 4, 81,
  132526. _vq_lengthlist__44c6_s_p5_0,
  132527. 1, -529137664, 1618345984, 2, 0,
  132528. _vq_quantlist__44c6_s_p5_0,
  132529. NULL,
  132530. &_vq_auxt__44c6_s_p5_0,
  132531. NULL,
  132532. 0
  132533. };
  132534. static long _vq_quantlist__44c6_s_p5_1[] = {
  132535. 5,
  132536. 4,
  132537. 6,
  132538. 3,
  132539. 7,
  132540. 2,
  132541. 8,
  132542. 1,
  132543. 9,
  132544. 0,
  132545. 10,
  132546. };
  132547. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132548. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132549. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132550. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132551. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132552. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132553. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132554. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132555. 11,10,10, 7, 7, 8, 8, 8, 8,
  132556. };
  132557. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132558. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132559. 3.5, 4.5,
  132560. };
  132561. static long _vq_quantmap__44c6_s_p5_1[] = {
  132562. 9, 7, 5, 3, 1, 0, 2, 4,
  132563. 6, 8, 10,
  132564. };
  132565. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132566. _vq_quantthresh__44c6_s_p5_1,
  132567. _vq_quantmap__44c6_s_p5_1,
  132568. 11,
  132569. 11
  132570. };
  132571. static static_codebook _44c6_s_p5_1 = {
  132572. 2, 121,
  132573. _vq_lengthlist__44c6_s_p5_1,
  132574. 1, -531365888, 1611661312, 4, 0,
  132575. _vq_quantlist__44c6_s_p5_1,
  132576. NULL,
  132577. &_vq_auxt__44c6_s_p5_1,
  132578. NULL,
  132579. 0
  132580. };
  132581. static long _vq_quantlist__44c6_s_p6_0[] = {
  132582. 6,
  132583. 5,
  132584. 7,
  132585. 4,
  132586. 8,
  132587. 3,
  132588. 9,
  132589. 2,
  132590. 10,
  132591. 1,
  132592. 11,
  132593. 0,
  132594. 12,
  132595. };
  132596. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132597. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132598. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132599. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132600. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132601. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132602. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132607. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132608. };
  132609. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132610. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132611. 12.5, 17.5, 22.5, 27.5,
  132612. };
  132613. static long _vq_quantmap__44c6_s_p6_0[] = {
  132614. 11, 9, 7, 5, 3, 1, 0, 2,
  132615. 4, 6, 8, 10, 12,
  132616. };
  132617. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132618. _vq_quantthresh__44c6_s_p6_0,
  132619. _vq_quantmap__44c6_s_p6_0,
  132620. 13,
  132621. 13
  132622. };
  132623. static static_codebook _44c6_s_p6_0 = {
  132624. 2, 169,
  132625. _vq_lengthlist__44c6_s_p6_0,
  132626. 1, -526516224, 1616117760, 4, 0,
  132627. _vq_quantlist__44c6_s_p6_0,
  132628. NULL,
  132629. &_vq_auxt__44c6_s_p6_0,
  132630. NULL,
  132631. 0
  132632. };
  132633. static long _vq_quantlist__44c6_s_p6_1[] = {
  132634. 2,
  132635. 1,
  132636. 3,
  132637. 0,
  132638. 4,
  132639. };
  132640. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132641. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132642. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132643. };
  132644. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132645. -1.5, -0.5, 0.5, 1.5,
  132646. };
  132647. static long _vq_quantmap__44c6_s_p6_1[] = {
  132648. 3, 1, 0, 2, 4,
  132649. };
  132650. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132651. _vq_quantthresh__44c6_s_p6_1,
  132652. _vq_quantmap__44c6_s_p6_1,
  132653. 5,
  132654. 5
  132655. };
  132656. static static_codebook _44c6_s_p6_1 = {
  132657. 2, 25,
  132658. _vq_lengthlist__44c6_s_p6_1,
  132659. 1, -533725184, 1611661312, 3, 0,
  132660. _vq_quantlist__44c6_s_p6_1,
  132661. NULL,
  132662. &_vq_auxt__44c6_s_p6_1,
  132663. NULL,
  132664. 0
  132665. };
  132666. static long _vq_quantlist__44c6_s_p7_0[] = {
  132667. 6,
  132668. 5,
  132669. 7,
  132670. 4,
  132671. 8,
  132672. 3,
  132673. 9,
  132674. 2,
  132675. 10,
  132676. 1,
  132677. 11,
  132678. 0,
  132679. 12,
  132680. };
  132681. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132682. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132683. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132684. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132685. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132686. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132687. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132688. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132689. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132690. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132691. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132692. 20,13,13,13,13,13,13,14,14,
  132693. };
  132694. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132695. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132696. 27.5, 38.5, 49.5, 60.5,
  132697. };
  132698. static long _vq_quantmap__44c6_s_p7_0[] = {
  132699. 11, 9, 7, 5, 3, 1, 0, 2,
  132700. 4, 6, 8, 10, 12,
  132701. };
  132702. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132703. _vq_quantthresh__44c6_s_p7_0,
  132704. _vq_quantmap__44c6_s_p7_0,
  132705. 13,
  132706. 13
  132707. };
  132708. static static_codebook _44c6_s_p7_0 = {
  132709. 2, 169,
  132710. _vq_lengthlist__44c6_s_p7_0,
  132711. 1, -523206656, 1618345984, 4, 0,
  132712. _vq_quantlist__44c6_s_p7_0,
  132713. NULL,
  132714. &_vq_auxt__44c6_s_p7_0,
  132715. NULL,
  132716. 0
  132717. };
  132718. static long _vq_quantlist__44c6_s_p7_1[] = {
  132719. 5,
  132720. 4,
  132721. 6,
  132722. 3,
  132723. 7,
  132724. 2,
  132725. 8,
  132726. 1,
  132727. 9,
  132728. 0,
  132729. 10,
  132730. };
  132731. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132732. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132733. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132734. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132735. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132736. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132737. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132738. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132739. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132740. };
  132741. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132742. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132743. 3.5, 4.5,
  132744. };
  132745. static long _vq_quantmap__44c6_s_p7_1[] = {
  132746. 9, 7, 5, 3, 1, 0, 2, 4,
  132747. 6, 8, 10,
  132748. };
  132749. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132750. _vq_quantthresh__44c6_s_p7_1,
  132751. _vq_quantmap__44c6_s_p7_1,
  132752. 11,
  132753. 11
  132754. };
  132755. static static_codebook _44c6_s_p7_1 = {
  132756. 2, 121,
  132757. _vq_lengthlist__44c6_s_p7_1,
  132758. 1, -531365888, 1611661312, 4, 0,
  132759. _vq_quantlist__44c6_s_p7_1,
  132760. NULL,
  132761. &_vq_auxt__44c6_s_p7_1,
  132762. NULL,
  132763. 0
  132764. };
  132765. static long _vq_quantlist__44c6_s_p8_0[] = {
  132766. 7,
  132767. 6,
  132768. 8,
  132769. 5,
  132770. 9,
  132771. 4,
  132772. 10,
  132773. 3,
  132774. 11,
  132775. 2,
  132776. 12,
  132777. 1,
  132778. 13,
  132779. 0,
  132780. 14,
  132781. };
  132782. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132783. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132784. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132785. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132786. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132787. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132788. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132789. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132790. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132791. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132792. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132793. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132794. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132795. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132796. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132797. 14,
  132798. };
  132799. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132800. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132801. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132802. };
  132803. static long _vq_quantmap__44c6_s_p8_0[] = {
  132804. 13, 11, 9, 7, 5, 3, 1, 0,
  132805. 2, 4, 6, 8, 10, 12, 14,
  132806. };
  132807. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132808. _vq_quantthresh__44c6_s_p8_0,
  132809. _vq_quantmap__44c6_s_p8_0,
  132810. 15,
  132811. 15
  132812. };
  132813. static static_codebook _44c6_s_p8_0 = {
  132814. 2, 225,
  132815. _vq_lengthlist__44c6_s_p8_0,
  132816. 1, -520986624, 1620377600, 4, 0,
  132817. _vq_quantlist__44c6_s_p8_0,
  132818. NULL,
  132819. &_vq_auxt__44c6_s_p8_0,
  132820. NULL,
  132821. 0
  132822. };
  132823. static long _vq_quantlist__44c6_s_p8_1[] = {
  132824. 10,
  132825. 9,
  132826. 11,
  132827. 8,
  132828. 12,
  132829. 7,
  132830. 13,
  132831. 6,
  132832. 14,
  132833. 5,
  132834. 15,
  132835. 4,
  132836. 16,
  132837. 3,
  132838. 17,
  132839. 2,
  132840. 18,
  132841. 1,
  132842. 19,
  132843. 0,
  132844. 20,
  132845. };
  132846. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132847. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132848. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132849. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132850. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132851. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132852. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132853. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132854. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132855. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132856. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132857. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132858. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132859. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132860. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132861. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132862. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132863. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132864. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132865. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132866. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132867. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132868. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132869. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132870. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132871. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132872. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132873. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132874. 10,10,10,10,10,10,10,10,10,
  132875. };
  132876. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132877. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132878. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132879. 6.5, 7.5, 8.5, 9.5,
  132880. };
  132881. static long _vq_quantmap__44c6_s_p8_1[] = {
  132882. 19, 17, 15, 13, 11, 9, 7, 5,
  132883. 3, 1, 0, 2, 4, 6, 8, 10,
  132884. 12, 14, 16, 18, 20,
  132885. };
  132886. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132887. _vq_quantthresh__44c6_s_p8_1,
  132888. _vq_quantmap__44c6_s_p8_1,
  132889. 21,
  132890. 21
  132891. };
  132892. static static_codebook _44c6_s_p8_1 = {
  132893. 2, 441,
  132894. _vq_lengthlist__44c6_s_p8_1,
  132895. 1, -529268736, 1611661312, 5, 0,
  132896. _vq_quantlist__44c6_s_p8_1,
  132897. NULL,
  132898. &_vq_auxt__44c6_s_p8_1,
  132899. NULL,
  132900. 0
  132901. };
  132902. static long _vq_quantlist__44c6_s_p9_0[] = {
  132903. 6,
  132904. 5,
  132905. 7,
  132906. 4,
  132907. 8,
  132908. 3,
  132909. 9,
  132910. 2,
  132911. 10,
  132912. 1,
  132913. 11,
  132914. 0,
  132915. 12,
  132916. };
  132917. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132918. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132919. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132921. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132922. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132923. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132924. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132925. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132926. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132927. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132928. 10,10,10,10,10,10,10,10,10,
  132929. };
  132930. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132931. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132932. 1592.5, 2229.5, 2866.5, 3503.5,
  132933. };
  132934. static long _vq_quantmap__44c6_s_p9_0[] = {
  132935. 11, 9, 7, 5, 3, 1, 0, 2,
  132936. 4, 6, 8, 10, 12,
  132937. };
  132938. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132939. _vq_quantthresh__44c6_s_p9_0,
  132940. _vq_quantmap__44c6_s_p9_0,
  132941. 13,
  132942. 13
  132943. };
  132944. static static_codebook _44c6_s_p9_0 = {
  132945. 2, 169,
  132946. _vq_lengthlist__44c6_s_p9_0,
  132947. 1, -511845376, 1630791680, 4, 0,
  132948. _vq_quantlist__44c6_s_p9_0,
  132949. NULL,
  132950. &_vq_auxt__44c6_s_p9_0,
  132951. NULL,
  132952. 0
  132953. };
  132954. static long _vq_quantlist__44c6_s_p9_1[] = {
  132955. 6,
  132956. 5,
  132957. 7,
  132958. 4,
  132959. 8,
  132960. 3,
  132961. 9,
  132962. 2,
  132963. 10,
  132964. 1,
  132965. 11,
  132966. 0,
  132967. 12,
  132968. };
  132969. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132970. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132971. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132972. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132973. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132974. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132975. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132976. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132977. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132978. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132979. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132980. 15,12,10,11,11,13,11,12,13,
  132981. };
  132982. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132983. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132984. 122.5, 171.5, 220.5, 269.5,
  132985. };
  132986. static long _vq_quantmap__44c6_s_p9_1[] = {
  132987. 11, 9, 7, 5, 3, 1, 0, 2,
  132988. 4, 6, 8, 10, 12,
  132989. };
  132990. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132991. _vq_quantthresh__44c6_s_p9_1,
  132992. _vq_quantmap__44c6_s_p9_1,
  132993. 13,
  132994. 13
  132995. };
  132996. static static_codebook _44c6_s_p9_1 = {
  132997. 2, 169,
  132998. _vq_lengthlist__44c6_s_p9_1,
  132999. 1, -518889472, 1622704128, 4, 0,
  133000. _vq_quantlist__44c6_s_p9_1,
  133001. NULL,
  133002. &_vq_auxt__44c6_s_p9_1,
  133003. NULL,
  133004. 0
  133005. };
  133006. static long _vq_quantlist__44c6_s_p9_2[] = {
  133007. 24,
  133008. 23,
  133009. 25,
  133010. 22,
  133011. 26,
  133012. 21,
  133013. 27,
  133014. 20,
  133015. 28,
  133016. 19,
  133017. 29,
  133018. 18,
  133019. 30,
  133020. 17,
  133021. 31,
  133022. 16,
  133023. 32,
  133024. 15,
  133025. 33,
  133026. 14,
  133027. 34,
  133028. 13,
  133029. 35,
  133030. 12,
  133031. 36,
  133032. 11,
  133033. 37,
  133034. 10,
  133035. 38,
  133036. 9,
  133037. 39,
  133038. 8,
  133039. 40,
  133040. 7,
  133041. 41,
  133042. 6,
  133043. 42,
  133044. 5,
  133045. 43,
  133046. 4,
  133047. 44,
  133048. 3,
  133049. 45,
  133050. 2,
  133051. 46,
  133052. 1,
  133053. 47,
  133054. 0,
  133055. 48,
  133056. };
  133057. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133058. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133059. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133060. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133061. 7,
  133062. };
  133063. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133064. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133065. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133066. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133067. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133068. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133069. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133070. };
  133071. static long _vq_quantmap__44c6_s_p9_2[] = {
  133072. 47, 45, 43, 41, 39, 37, 35, 33,
  133073. 31, 29, 27, 25, 23, 21, 19, 17,
  133074. 15, 13, 11, 9, 7, 5, 3, 1,
  133075. 0, 2, 4, 6, 8, 10, 12, 14,
  133076. 16, 18, 20, 22, 24, 26, 28, 30,
  133077. 32, 34, 36, 38, 40, 42, 44, 46,
  133078. 48,
  133079. };
  133080. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133081. _vq_quantthresh__44c6_s_p9_2,
  133082. _vq_quantmap__44c6_s_p9_2,
  133083. 49,
  133084. 49
  133085. };
  133086. static static_codebook _44c6_s_p9_2 = {
  133087. 1, 49,
  133088. _vq_lengthlist__44c6_s_p9_2,
  133089. 1, -526909440, 1611661312, 6, 0,
  133090. _vq_quantlist__44c6_s_p9_2,
  133091. NULL,
  133092. &_vq_auxt__44c6_s_p9_2,
  133093. NULL,
  133094. 0
  133095. };
  133096. static long _huff_lengthlist__44c6_s_short[] = {
  133097. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133098. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133099. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133100. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133101. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133102. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133103. 9,10,17,18,
  133104. };
  133105. static static_codebook _huff_book__44c6_s_short = {
  133106. 2, 100,
  133107. _huff_lengthlist__44c6_s_short,
  133108. 0, 0, 0, 0, 0,
  133109. NULL,
  133110. NULL,
  133111. NULL,
  133112. NULL,
  133113. 0
  133114. };
  133115. static long _huff_lengthlist__44c7_s_long[] = {
  133116. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133117. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133118. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133119. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133120. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133121. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133122. 11,10,10,12,
  133123. };
  133124. static static_codebook _huff_book__44c7_s_long = {
  133125. 2, 100,
  133126. _huff_lengthlist__44c7_s_long,
  133127. 0, 0, 0, 0, 0,
  133128. NULL,
  133129. NULL,
  133130. NULL,
  133131. NULL,
  133132. 0
  133133. };
  133134. static long _vq_quantlist__44c7_s_p1_0[] = {
  133135. 1,
  133136. 0,
  133137. 2,
  133138. };
  133139. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133140. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133141. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133142. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133143. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133144. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133145. 8,
  133146. };
  133147. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133148. -0.5, 0.5,
  133149. };
  133150. static long _vq_quantmap__44c7_s_p1_0[] = {
  133151. 1, 0, 2,
  133152. };
  133153. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133154. _vq_quantthresh__44c7_s_p1_0,
  133155. _vq_quantmap__44c7_s_p1_0,
  133156. 3,
  133157. 3
  133158. };
  133159. static static_codebook _44c7_s_p1_0 = {
  133160. 4, 81,
  133161. _vq_lengthlist__44c7_s_p1_0,
  133162. 1, -535822336, 1611661312, 2, 0,
  133163. _vq_quantlist__44c7_s_p1_0,
  133164. NULL,
  133165. &_vq_auxt__44c7_s_p1_0,
  133166. NULL,
  133167. 0
  133168. };
  133169. static long _vq_quantlist__44c7_s_p2_0[] = {
  133170. 2,
  133171. 1,
  133172. 3,
  133173. 0,
  133174. 4,
  133175. };
  133176. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133177. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133178. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133179. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133180. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133181. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133182. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133183. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133184. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133186. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133187. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133188. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133189. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133190. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133191. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133192. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133194. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133195. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133196. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133197. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133198. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133199. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133200. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133202. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133203. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133204. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133205. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133206. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133207. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133208. 0, 0,13,13, 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, 9,
  133213. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133214. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133215. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133216. 13,
  133217. };
  133218. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133219. -1.5, -0.5, 0.5, 1.5,
  133220. };
  133221. static long _vq_quantmap__44c7_s_p2_0[] = {
  133222. 3, 1, 0, 2, 4,
  133223. };
  133224. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133225. _vq_quantthresh__44c7_s_p2_0,
  133226. _vq_quantmap__44c7_s_p2_0,
  133227. 5,
  133228. 5
  133229. };
  133230. static static_codebook _44c7_s_p2_0 = {
  133231. 4, 625,
  133232. _vq_lengthlist__44c7_s_p2_0,
  133233. 1, -533725184, 1611661312, 3, 0,
  133234. _vq_quantlist__44c7_s_p2_0,
  133235. NULL,
  133236. &_vq_auxt__44c7_s_p2_0,
  133237. NULL,
  133238. 0
  133239. };
  133240. static long _vq_quantlist__44c7_s_p3_0[] = {
  133241. 4,
  133242. 3,
  133243. 5,
  133244. 2,
  133245. 6,
  133246. 1,
  133247. 7,
  133248. 0,
  133249. 8,
  133250. };
  133251. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133252. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133253. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133254. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133255. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133257. 0,
  133258. };
  133259. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133260. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133261. };
  133262. static long _vq_quantmap__44c7_s_p3_0[] = {
  133263. 7, 5, 3, 1, 0, 2, 4, 6,
  133264. 8,
  133265. };
  133266. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133267. _vq_quantthresh__44c7_s_p3_0,
  133268. _vq_quantmap__44c7_s_p3_0,
  133269. 9,
  133270. 9
  133271. };
  133272. static static_codebook _44c7_s_p3_0 = {
  133273. 2, 81,
  133274. _vq_lengthlist__44c7_s_p3_0,
  133275. 1, -531628032, 1611661312, 4, 0,
  133276. _vq_quantlist__44c7_s_p3_0,
  133277. NULL,
  133278. &_vq_auxt__44c7_s_p3_0,
  133279. NULL,
  133280. 0
  133281. };
  133282. static long _vq_quantlist__44c7_s_p4_0[] = {
  133283. 8,
  133284. 7,
  133285. 9,
  133286. 6,
  133287. 10,
  133288. 5,
  133289. 11,
  133290. 4,
  133291. 12,
  133292. 3,
  133293. 13,
  133294. 2,
  133295. 14,
  133296. 1,
  133297. 15,
  133298. 0,
  133299. 16,
  133300. };
  133301. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133302. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133303. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133304. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133305. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133306. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133307. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133308. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133309. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133310. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133311. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133320. 0,
  133321. };
  133322. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133323. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133324. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133325. };
  133326. static long _vq_quantmap__44c7_s_p4_0[] = {
  133327. 15, 13, 11, 9, 7, 5, 3, 1,
  133328. 0, 2, 4, 6, 8, 10, 12, 14,
  133329. 16,
  133330. };
  133331. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133332. _vq_quantthresh__44c7_s_p4_0,
  133333. _vq_quantmap__44c7_s_p4_0,
  133334. 17,
  133335. 17
  133336. };
  133337. static static_codebook _44c7_s_p4_0 = {
  133338. 2, 289,
  133339. _vq_lengthlist__44c7_s_p4_0,
  133340. 1, -529530880, 1611661312, 5, 0,
  133341. _vq_quantlist__44c7_s_p4_0,
  133342. NULL,
  133343. &_vq_auxt__44c7_s_p4_0,
  133344. NULL,
  133345. 0
  133346. };
  133347. static long _vq_quantlist__44c7_s_p5_0[] = {
  133348. 1,
  133349. 0,
  133350. 2,
  133351. };
  133352. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133353. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133354. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133355. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133356. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133357. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133358. 12,
  133359. };
  133360. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133361. -5.5, 5.5,
  133362. };
  133363. static long _vq_quantmap__44c7_s_p5_0[] = {
  133364. 1, 0, 2,
  133365. };
  133366. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133367. _vq_quantthresh__44c7_s_p5_0,
  133368. _vq_quantmap__44c7_s_p5_0,
  133369. 3,
  133370. 3
  133371. };
  133372. static static_codebook _44c7_s_p5_0 = {
  133373. 4, 81,
  133374. _vq_lengthlist__44c7_s_p5_0,
  133375. 1, -529137664, 1618345984, 2, 0,
  133376. _vq_quantlist__44c7_s_p5_0,
  133377. NULL,
  133378. &_vq_auxt__44c7_s_p5_0,
  133379. NULL,
  133380. 0
  133381. };
  133382. static long _vq_quantlist__44c7_s_p5_1[] = {
  133383. 5,
  133384. 4,
  133385. 6,
  133386. 3,
  133387. 7,
  133388. 2,
  133389. 8,
  133390. 1,
  133391. 9,
  133392. 0,
  133393. 10,
  133394. };
  133395. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133396. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133397. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133398. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133399. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133400. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133401. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133402. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133403. 11,11,11, 7, 7, 8, 8, 8, 8,
  133404. };
  133405. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133406. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133407. 3.5, 4.5,
  133408. };
  133409. static long _vq_quantmap__44c7_s_p5_1[] = {
  133410. 9, 7, 5, 3, 1, 0, 2, 4,
  133411. 6, 8, 10,
  133412. };
  133413. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133414. _vq_quantthresh__44c7_s_p5_1,
  133415. _vq_quantmap__44c7_s_p5_1,
  133416. 11,
  133417. 11
  133418. };
  133419. static static_codebook _44c7_s_p5_1 = {
  133420. 2, 121,
  133421. _vq_lengthlist__44c7_s_p5_1,
  133422. 1, -531365888, 1611661312, 4, 0,
  133423. _vq_quantlist__44c7_s_p5_1,
  133424. NULL,
  133425. &_vq_auxt__44c7_s_p5_1,
  133426. NULL,
  133427. 0
  133428. };
  133429. static long _vq_quantlist__44c7_s_p6_0[] = {
  133430. 6,
  133431. 5,
  133432. 7,
  133433. 4,
  133434. 8,
  133435. 3,
  133436. 9,
  133437. 2,
  133438. 10,
  133439. 1,
  133440. 11,
  133441. 0,
  133442. 12,
  133443. };
  133444. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133445. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133446. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133447. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133448. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133449. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133450. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133455. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133456. };
  133457. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133458. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133459. 12.5, 17.5, 22.5, 27.5,
  133460. };
  133461. static long _vq_quantmap__44c7_s_p6_0[] = {
  133462. 11, 9, 7, 5, 3, 1, 0, 2,
  133463. 4, 6, 8, 10, 12,
  133464. };
  133465. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133466. _vq_quantthresh__44c7_s_p6_0,
  133467. _vq_quantmap__44c7_s_p6_0,
  133468. 13,
  133469. 13
  133470. };
  133471. static static_codebook _44c7_s_p6_0 = {
  133472. 2, 169,
  133473. _vq_lengthlist__44c7_s_p6_0,
  133474. 1, -526516224, 1616117760, 4, 0,
  133475. _vq_quantlist__44c7_s_p6_0,
  133476. NULL,
  133477. &_vq_auxt__44c7_s_p6_0,
  133478. NULL,
  133479. 0
  133480. };
  133481. static long _vq_quantlist__44c7_s_p6_1[] = {
  133482. 2,
  133483. 1,
  133484. 3,
  133485. 0,
  133486. 4,
  133487. };
  133488. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133489. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133490. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133491. };
  133492. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133493. -1.5, -0.5, 0.5, 1.5,
  133494. };
  133495. static long _vq_quantmap__44c7_s_p6_1[] = {
  133496. 3, 1, 0, 2, 4,
  133497. };
  133498. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133499. _vq_quantthresh__44c7_s_p6_1,
  133500. _vq_quantmap__44c7_s_p6_1,
  133501. 5,
  133502. 5
  133503. };
  133504. static static_codebook _44c7_s_p6_1 = {
  133505. 2, 25,
  133506. _vq_lengthlist__44c7_s_p6_1,
  133507. 1, -533725184, 1611661312, 3, 0,
  133508. _vq_quantlist__44c7_s_p6_1,
  133509. NULL,
  133510. &_vq_auxt__44c7_s_p6_1,
  133511. NULL,
  133512. 0
  133513. };
  133514. static long _vq_quantlist__44c7_s_p7_0[] = {
  133515. 6,
  133516. 5,
  133517. 7,
  133518. 4,
  133519. 8,
  133520. 3,
  133521. 9,
  133522. 2,
  133523. 10,
  133524. 1,
  133525. 11,
  133526. 0,
  133527. 12,
  133528. };
  133529. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133530. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133531. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133532. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133533. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133534. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133535. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133536. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133537. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133538. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133539. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133540. 19,13,13,13,13,14,14,15,15,
  133541. };
  133542. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133543. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133544. 27.5, 38.5, 49.5, 60.5,
  133545. };
  133546. static long _vq_quantmap__44c7_s_p7_0[] = {
  133547. 11, 9, 7, 5, 3, 1, 0, 2,
  133548. 4, 6, 8, 10, 12,
  133549. };
  133550. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133551. _vq_quantthresh__44c7_s_p7_0,
  133552. _vq_quantmap__44c7_s_p7_0,
  133553. 13,
  133554. 13
  133555. };
  133556. static static_codebook _44c7_s_p7_0 = {
  133557. 2, 169,
  133558. _vq_lengthlist__44c7_s_p7_0,
  133559. 1, -523206656, 1618345984, 4, 0,
  133560. _vq_quantlist__44c7_s_p7_0,
  133561. NULL,
  133562. &_vq_auxt__44c7_s_p7_0,
  133563. NULL,
  133564. 0
  133565. };
  133566. static long _vq_quantlist__44c7_s_p7_1[] = {
  133567. 5,
  133568. 4,
  133569. 6,
  133570. 3,
  133571. 7,
  133572. 2,
  133573. 8,
  133574. 1,
  133575. 9,
  133576. 0,
  133577. 10,
  133578. };
  133579. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133580. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133581. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133582. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133583. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133584. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133585. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133586. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133587. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133588. };
  133589. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133590. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133591. 3.5, 4.5,
  133592. };
  133593. static long _vq_quantmap__44c7_s_p7_1[] = {
  133594. 9, 7, 5, 3, 1, 0, 2, 4,
  133595. 6, 8, 10,
  133596. };
  133597. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133598. _vq_quantthresh__44c7_s_p7_1,
  133599. _vq_quantmap__44c7_s_p7_1,
  133600. 11,
  133601. 11
  133602. };
  133603. static static_codebook _44c7_s_p7_1 = {
  133604. 2, 121,
  133605. _vq_lengthlist__44c7_s_p7_1,
  133606. 1, -531365888, 1611661312, 4, 0,
  133607. _vq_quantlist__44c7_s_p7_1,
  133608. NULL,
  133609. &_vq_auxt__44c7_s_p7_1,
  133610. NULL,
  133611. 0
  133612. };
  133613. static long _vq_quantlist__44c7_s_p8_0[] = {
  133614. 7,
  133615. 6,
  133616. 8,
  133617. 5,
  133618. 9,
  133619. 4,
  133620. 10,
  133621. 3,
  133622. 11,
  133623. 2,
  133624. 12,
  133625. 1,
  133626. 13,
  133627. 0,
  133628. 14,
  133629. };
  133630. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133631. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133632. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133633. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133634. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133635. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133636. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133637. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133638. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133639. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133640. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133641. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133642. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133643. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133644. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133645. 14,
  133646. };
  133647. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133648. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133649. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133650. };
  133651. static long _vq_quantmap__44c7_s_p8_0[] = {
  133652. 13, 11, 9, 7, 5, 3, 1, 0,
  133653. 2, 4, 6, 8, 10, 12, 14,
  133654. };
  133655. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133656. _vq_quantthresh__44c7_s_p8_0,
  133657. _vq_quantmap__44c7_s_p8_0,
  133658. 15,
  133659. 15
  133660. };
  133661. static static_codebook _44c7_s_p8_0 = {
  133662. 2, 225,
  133663. _vq_lengthlist__44c7_s_p8_0,
  133664. 1, -520986624, 1620377600, 4, 0,
  133665. _vq_quantlist__44c7_s_p8_0,
  133666. NULL,
  133667. &_vq_auxt__44c7_s_p8_0,
  133668. NULL,
  133669. 0
  133670. };
  133671. static long _vq_quantlist__44c7_s_p8_1[] = {
  133672. 10,
  133673. 9,
  133674. 11,
  133675. 8,
  133676. 12,
  133677. 7,
  133678. 13,
  133679. 6,
  133680. 14,
  133681. 5,
  133682. 15,
  133683. 4,
  133684. 16,
  133685. 3,
  133686. 17,
  133687. 2,
  133688. 18,
  133689. 1,
  133690. 19,
  133691. 0,
  133692. 20,
  133693. };
  133694. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133695. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133696. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133697. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133698. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133699. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133700. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133701. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133702. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133703. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133704. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133705. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133706. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133707. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133708. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133709. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133710. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133711. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133712. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133713. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133714. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133715. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133716. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133717. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133718. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133719. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133720. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133721. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133722. 10,10,10,10,10,10,10,10,10,
  133723. };
  133724. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133725. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133726. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133727. 6.5, 7.5, 8.5, 9.5,
  133728. };
  133729. static long _vq_quantmap__44c7_s_p8_1[] = {
  133730. 19, 17, 15, 13, 11, 9, 7, 5,
  133731. 3, 1, 0, 2, 4, 6, 8, 10,
  133732. 12, 14, 16, 18, 20,
  133733. };
  133734. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133735. _vq_quantthresh__44c7_s_p8_1,
  133736. _vq_quantmap__44c7_s_p8_1,
  133737. 21,
  133738. 21
  133739. };
  133740. static static_codebook _44c7_s_p8_1 = {
  133741. 2, 441,
  133742. _vq_lengthlist__44c7_s_p8_1,
  133743. 1, -529268736, 1611661312, 5, 0,
  133744. _vq_quantlist__44c7_s_p8_1,
  133745. NULL,
  133746. &_vq_auxt__44c7_s_p8_1,
  133747. NULL,
  133748. 0
  133749. };
  133750. static long _vq_quantlist__44c7_s_p9_0[] = {
  133751. 6,
  133752. 5,
  133753. 7,
  133754. 4,
  133755. 8,
  133756. 3,
  133757. 9,
  133758. 2,
  133759. 10,
  133760. 1,
  133761. 11,
  133762. 0,
  133763. 12,
  133764. };
  133765. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133766. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133767. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133768. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133769. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133770. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133771. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133772. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133773. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133775. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133776. 11,11,11,11,11,11,11,11,11,
  133777. };
  133778. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133779. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133780. 1592.5, 2229.5, 2866.5, 3503.5,
  133781. };
  133782. static long _vq_quantmap__44c7_s_p9_0[] = {
  133783. 11, 9, 7, 5, 3, 1, 0, 2,
  133784. 4, 6, 8, 10, 12,
  133785. };
  133786. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133787. _vq_quantthresh__44c7_s_p9_0,
  133788. _vq_quantmap__44c7_s_p9_0,
  133789. 13,
  133790. 13
  133791. };
  133792. static static_codebook _44c7_s_p9_0 = {
  133793. 2, 169,
  133794. _vq_lengthlist__44c7_s_p9_0,
  133795. 1, -511845376, 1630791680, 4, 0,
  133796. _vq_quantlist__44c7_s_p9_0,
  133797. NULL,
  133798. &_vq_auxt__44c7_s_p9_0,
  133799. NULL,
  133800. 0
  133801. };
  133802. static long _vq_quantlist__44c7_s_p9_1[] = {
  133803. 6,
  133804. 5,
  133805. 7,
  133806. 4,
  133807. 8,
  133808. 3,
  133809. 9,
  133810. 2,
  133811. 10,
  133812. 1,
  133813. 11,
  133814. 0,
  133815. 12,
  133816. };
  133817. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133818. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133819. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133820. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133821. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133822. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133823. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133824. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133825. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133826. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133827. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133828. 15,11,11,10,10,12,12,12,12,
  133829. };
  133830. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133831. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133832. 122.5, 171.5, 220.5, 269.5,
  133833. };
  133834. static long _vq_quantmap__44c7_s_p9_1[] = {
  133835. 11, 9, 7, 5, 3, 1, 0, 2,
  133836. 4, 6, 8, 10, 12,
  133837. };
  133838. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133839. _vq_quantthresh__44c7_s_p9_1,
  133840. _vq_quantmap__44c7_s_p9_1,
  133841. 13,
  133842. 13
  133843. };
  133844. static static_codebook _44c7_s_p9_1 = {
  133845. 2, 169,
  133846. _vq_lengthlist__44c7_s_p9_1,
  133847. 1, -518889472, 1622704128, 4, 0,
  133848. _vq_quantlist__44c7_s_p9_1,
  133849. NULL,
  133850. &_vq_auxt__44c7_s_p9_1,
  133851. NULL,
  133852. 0
  133853. };
  133854. static long _vq_quantlist__44c7_s_p9_2[] = {
  133855. 24,
  133856. 23,
  133857. 25,
  133858. 22,
  133859. 26,
  133860. 21,
  133861. 27,
  133862. 20,
  133863. 28,
  133864. 19,
  133865. 29,
  133866. 18,
  133867. 30,
  133868. 17,
  133869. 31,
  133870. 16,
  133871. 32,
  133872. 15,
  133873. 33,
  133874. 14,
  133875. 34,
  133876. 13,
  133877. 35,
  133878. 12,
  133879. 36,
  133880. 11,
  133881. 37,
  133882. 10,
  133883. 38,
  133884. 9,
  133885. 39,
  133886. 8,
  133887. 40,
  133888. 7,
  133889. 41,
  133890. 6,
  133891. 42,
  133892. 5,
  133893. 43,
  133894. 4,
  133895. 44,
  133896. 3,
  133897. 45,
  133898. 2,
  133899. 46,
  133900. 1,
  133901. 47,
  133902. 0,
  133903. 48,
  133904. };
  133905. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133906. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133907. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133908. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133909. 7,
  133910. };
  133911. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133912. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133913. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133914. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133915. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133916. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133917. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133918. };
  133919. static long _vq_quantmap__44c7_s_p9_2[] = {
  133920. 47, 45, 43, 41, 39, 37, 35, 33,
  133921. 31, 29, 27, 25, 23, 21, 19, 17,
  133922. 15, 13, 11, 9, 7, 5, 3, 1,
  133923. 0, 2, 4, 6, 8, 10, 12, 14,
  133924. 16, 18, 20, 22, 24, 26, 28, 30,
  133925. 32, 34, 36, 38, 40, 42, 44, 46,
  133926. 48,
  133927. };
  133928. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133929. _vq_quantthresh__44c7_s_p9_2,
  133930. _vq_quantmap__44c7_s_p9_2,
  133931. 49,
  133932. 49
  133933. };
  133934. static static_codebook _44c7_s_p9_2 = {
  133935. 1, 49,
  133936. _vq_lengthlist__44c7_s_p9_2,
  133937. 1, -526909440, 1611661312, 6, 0,
  133938. _vq_quantlist__44c7_s_p9_2,
  133939. NULL,
  133940. &_vq_auxt__44c7_s_p9_2,
  133941. NULL,
  133942. 0
  133943. };
  133944. static long _huff_lengthlist__44c7_s_short[] = {
  133945. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133946. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133947. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133948. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133949. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133950. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133951. 10, 9,11,14,
  133952. };
  133953. static static_codebook _huff_book__44c7_s_short = {
  133954. 2, 100,
  133955. _huff_lengthlist__44c7_s_short,
  133956. 0, 0, 0, 0, 0,
  133957. NULL,
  133958. NULL,
  133959. NULL,
  133960. NULL,
  133961. 0
  133962. };
  133963. static long _huff_lengthlist__44c8_s_long[] = {
  133964. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133965. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133966. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133967. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133968. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133969. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133970. 11, 9, 9,10,
  133971. };
  133972. static static_codebook _huff_book__44c8_s_long = {
  133973. 2, 100,
  133974. _huff_lengthlist__44c8_s_long,
  133975. 0, 0, 0, 0, 0,
  133976. NULL,
  133977. NULL,
  133978. NULL,
  133979. NULL,
  133980. 0
  133981. };
  133982. static long _vq_quantlist__44c8_s_p1_0[] = {
  133983. 1,
  133984. 0,
  133985. 2,
  133986. };
  133987. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133988. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133989. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133990. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133991. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133992. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133993. 8,
  133994. };
  133995. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133996. -0.5, 0.5,
  133997. };
  133998. static long _vq_quantmap__44c8_s_p1_0[] = {
  133999. 1, 0, 2,
  134000. };
  134001. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134002. _vq_quantthresh__44c8_s_p1_0,
  134003. _vq_quantmap__44c8_s_p1_0,
  134004. 3,
  134005. 3
  134006. };
  134007. static static_codebook _44c8_s_p1_0 = {
  134008. 4, 81,
  134009. _vq_lengthlist__44c8_s_p1_0,
  134010. 1, -535822336, 1611661312, 2, 0,
  134011. _vq_quantlist__44c8_s_p1_0,
  134012. NULL,
  134013. &_vq_auxt__44c8_s_p1_0,
  134014. NULL,
  134015. 0
  134016. };
  134017. static long _vq_quantlist__44c8_s_p2_0[] = {
  134018. 2,
  134019. 1,
  134020. 3,
  134021. 0,
  134022. 4,
  134023. };
  134024. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134025. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134026. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134027. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134028. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134029. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134030. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134031. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134032. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134034. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134035. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134036. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134037. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134038. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134039. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134040. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134042. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134043. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134044. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134045. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134046. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134047. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134048. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134050. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134051. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134052. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134053. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134054. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134055. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134056. 0, 0,13,13, 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, 9,
  134061. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134062. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134063. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134064. 13,
  134065. };
  134066. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134067. -1.5, -0.5, 0.5, 1.5,
  134068. };
  134069. static long _vq_quantmap__44c8_s_p2_0[] = {
  134070. 3, 1, 0, 2, 4,
  134071. };
  134072. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134073. _vq_quantthresh__44c8_s_p2_0,
  134074. _vq_quantmap__44c8_s_p2_0,
  134075. 5,
  134076. 5
  134077. };
  134078. static static_codebook _44c8_s_p2_0 = {
  134079. 4, 625,
  134080. _vq_lengthlist__44c8_s_p2_0,
  134081. 1, -533725184, 1611661312, 3, 0,
  134082. _vq_quantlist__44c8_s_p2_0,
  134083. NULL,
  134084. &_vq_auxt__44c8_s_p2_0,
  134085. NULL,
  134086. 0
  134087. };
  134088. static long _vq_quantlist__44c8_s_p3_0[] = {
  134089. 4,
  134090. 3,
  134091. 5,
  134092. 2,
  134093. 6,
  134094. 1,
  134095. 7,
  134096. 0,
  134097. 8,
  134098. };
  134099. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134100. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134101. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134102. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134103. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134105. 0,
  134106. };
  134107. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134108. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134109. };
  134110. static long _vq_quantmap__44c8_s_p3_0[] = {
  134111. 7, 5, 3, 1, 0, 2, 4, 6,
  134112. 8,
  134113. };
  134114. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134115. _vq_quantthresh__44c8_s_p3_0,
  134116. _vq_quantmap__44c8_s_p3_0,
  134117. 9,
  134118. 9
  134119. };
  134120. static static_codebook _44c8_s_p3_0 = {
  134121. 2, 81,
  134122. _vq_lengthlist__44c8_s_p3_0,
  134123. 1, -531628032, 1611661312, 4, 0,
  134124. _vq_quantlist__44c8_s_p3_0,
  134125. NULL,
  134126. &_vq_auxt__44c8_s_p3_0,
  134127. NULL,
  134128. 0
  134129. };
  134130. static long _vq_quantlist__44c8_s_p4_0[] = {
  134131. 8,
  134132. 7,
  134133. 9,
  134134. 6,
  134135. 10,
  134136. 5,
  134137. 11,
  134138. 4,
  134139. 12,
  134140. 3,
  134141. 13,
  134142. 2,
  134143. 14,
  134144. 1,
  134145. 15,
  134146. 0,
  134147. 16,
  134148. };
  134149. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134150. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134151. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134152. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134153. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134154. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134155. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134156. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134157. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134158. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134159. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134168. 0,
  134169. };
  134170. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134171. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134172. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134173. };
  134174. static long _vq_quantmap__44c8_s_p4_0[] = {
  134175. 15, 13, 11, 9, 7, 5, 3, 1,
  134176. 0, 2, 4, 6, 8, 10, 12, 14,
  134177. 16,
  134178. };
  134179. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134180. _vq_quantthresh__44c8_s_p4_0,
  134181. _vq_quantmap__44c8_s_p4_0,
  134182. 17,
  134183. 17
  134184. };
  134185. static static_codebook _44c8_s_p4_0 = {
  134186. 2, 289,
  134187. _vq_lengthlist__44c8_s_p4_0,
  134188. 1, -529530880, 1611661312, 5, 0,
  134189. _vq_quantlist__44c8_s_p4_0,
  134190. NULL,
  134191. &_vq_auxt__44c8_s_p4_0,
  134192. NULL,
  134193. 0
  134194. };
  134195. static long _vq_quantlist__44c8_s_p5_0[] = {
  134196. 1,
  134197. 0,
  134198. 2,
  134199. };
  134200. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134201. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134202. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134203. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134204. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134205. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134206. 12,
  134207. };
  134208. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134209. -5.5, 5.5,
  134210. };
  134211. static long _vq_quantmap__44c8_s_p5_0[] = {
  134212. 1, 0, 2,
  134213. };
  134214. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134215. _vq_quantthresh__44c8_s_p5_0,
  134216. _vq_quantmap__44c8_s_p5_0,
  134217. 3,
  134218. 3
  134219. };
  134220. static static_codebook _44c8_s_p5_0 = {
  134221. 4, 81,
  134222. _vq_lengthlist__44c8_s_p5_0,
  134223. 1, -529137664, 1618345984, 2, 0,
  134224. _vq_quantlist__44c8_s_p5_0,
  134225. NULL,
  134226. &_vq_auxt__44c8_s_p5_0,
  134227. NULL,
  134228. 0
  134229. };
  134230. static long _vq_quantlist__44c8_s_p5_1[] = {
  134231. 5,
  134232. 4,
  134233. 6,
  134234. 3,
  134235. 7,
  134236. 2,
  134237. 8,
  134238. 1,
  134239. 9,
  134240. 0,
  134241. 10,
  134242. };
  134243. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134244. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134245. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134246. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134247. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134248. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134249. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134250. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134251. 11,11,11, 7, 7, 7, 7, 8, 8,
  134252. };
  134253. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134254. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134255. 3.5, 4.5,
  134256. };
  134257. static long _vq_quantmap__44c8_s_p5_1[] = {
  134258. 9, 7, 5, 3, 1, 0, 2, 4,
  134259. 6, 8, 10,
  134260. };
  134261. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134262. _vq_quantthresh__44c8_s_p5_1,
  134263. _vq_quantmap__44c8_s_p5_1,
  134264. 11,
  134265. 11
  134266. };
  134267. static static_codebook _44c8_s_p5_1 = {
  134268. 2, 121,
  134269. _vq_lengthlist__44c8_s_p5_1,
  134270. 1, -531365888, 1611661312, 4, 0,
  134271. _vq_quantlist__44c8_s_p5_1,
  134272. NULL,
  134273. &_vq_auxt__44c8_s_p5_1,
  134274. NULL,
  134275. 0
  134276. };
  134277. static long _vq_quantlist__44c8_s_p6_0[] = {
  134278. 6,
  134279. 5,
  134280. 7,
  134281. 4,
  134282. 8,
  134283. 3,
  134284. 9,
  134285. 2,
  134286. 10,
  134287. 1,
  134288. 11,
  134289. 0,
  134290. 12,
  134291. };
  134292. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134293. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134294. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134295. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134296. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134297. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134298. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134303. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134304. };
  134305. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134306. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134307. 12.5, 17.5, 22.5, 27.5,
  134308. };
  134309. static long _vq_quantmap__44c8_s_p6_0[] = {
  134310. 11, 9, 7, 5, 3, 1, 0, 2,
  134311. 4, 6, 8, 10, 12,
  134312. };
  134313. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134314. _vq_quantthresh__44c8_s_p6_0,
  134315. _vq_quantmap__44c8_s_p6_0,
  134316. 13,
  134317. 13
  134318. };
  134319. static static_codebook _44c8_s_p6_0 = {
  134320. 2, 169,
  134321. _vq_lengthlist__44c8_s_p6_0,
  134322. 1, -526516224, 1616117760, 4, 0,
  134323. _vq_quantlist__44c8_s_p6_0,
  134324. NULL,
  134325. &_vq_auxt__44c8_s_p6_0,
  134326. NULL,
  134327. 0
  134328. };
  134329. static long _vq_quantlist__44c8_s_p6_1[] = {
  134330. 2,
  134331. 1,
  134332. 3,
  134333. 0,
  134334. 4,
  134335. };
  134336. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134337. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134338. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134339. };
  134340. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134341. -1.5, -0.5, 0.5, 1.5,
  134342. };
  134343. static long _vq_quantmap__44c8_s_p6_1[] = {
  134344. 3, 1, 0, 2, 4,
  134345. };
  134346. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134347. _vq_quantthresh__44c8_s_p6_1,
  134348. _vq_quantmap__44c8_s_p6_1,
  134349. 5,
  134350. 5
  134351. };
  134352. static static_codebook _44c8_s_p6_1 = {
  134353. 2, 25,
  134354. _vq_lengthlist__44c8_s_p6_1,
  134355. 1, -533725184, 1611661312, 3, 0,
  134356. _vq_quantlist__44c8_s_p6_1,
  134357. NULL,
  134358. &_vq_auxt__44c8_s_p6_1,
  134359. NULL,
  134360. 0
  134361. };
  134362. static long _vq_quantlist__44c8_s_p7_0[] = {
  134363. 6,
  134364. 5,
  134365. 7,
  134366. 4,
  134367. 8,
  134368. 3,
  134369. 9,
  134370. 2,
  134371. 10,
  134372. 1,
  134373. 11,
  134374. 0,
  134375. 12,
  134376. };
  134377. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134378. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134379. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134380. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134381. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134382. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134383. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134384. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134385. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134386. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134387. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134388. 20,13,13,13,13,14,13,15,15,
  134389. };
  134390. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134391. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134392. 27.5, 38.5, 49.5, 60.5,
  134393. };
  134394. static long _vq_quantmap__44c8_s_p7_0[] = {
  134395. 11, 9, 7, 5, 3, 1, 0, 2,
  134396. 4, 6, 8, 10, 12,
  134397. };
  134398. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134399. _vq_quantthresh__44c8_s_p7_0,
  134400. _vq_quantmap__44c8_s_p7_0,
  134401. 13,
  134402. 13
  134403. };
  134404. static static_codebook _44c8_s_p7_0 = {
  134405. 2, 169,
  134406. _vq_lengthlist__44c8_s_p7_0,
  134407. 1, -523206656, 1618345984, 4, 0,
  134408. _vq_quantlist__44c8_s_p7_0,
  134409. NULL,
  134410. &_vq_auxt__44c8_s_p7_0,
  134411. NULL,
  134412. 0
  134413. };
  134414. static long _vq_quantlist__44c8_s_p7_1[] = {
  134415. 5,
  134416. 4,
  134417. 6,
  134418. 3,
  134419. 7,
  134420. 2,
  134421. 8,
  134422. 1,
  134423. 9,
  134424. 0,
  134425. 10,
  134426. };
  134427. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134428. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134429. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134430. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134431. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134432. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134433. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134434. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134435. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134436. };
  134437. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134438. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134439. 3.5, 4.5,
  134440. };
  134441. static long _vq_quantmap__44c8_s_p7_1[] = {
  134442. 9, 7, 5, 3, 1, 0, 2, 4,
  134443. 6, 8, 10,
  134444. };
  134445. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134446. _vq_quantthresh__44c8_s_p7_1,
  134447. _vq_quantmap__44c8_s_p7_1,
  134448. 11,
  134449. 11
  134450. };
  134451. static static_codebook _44c8_s_p7_1 = {
  134452. 2, 121,
  134453. _vq_lengthlist__44c8_s_p7_1,
  134454. 1, -531365888, 1611661312, 4, 0,
  134455. _vq_quantlist__44c8_s_p7_1,
  134456. NULL,
  134457. &_vq_auxt__44c8_s_p7_1,
  134458. NULL,
  134459. 0
  134460. };
  134461. static long _vq_quantlist__44c8_s_p8_0[] = {
  134462. 7,
  134463. 6,
  134464. 8,
  134465. 5,
  134466. 9,
  134467. 4,
  134468. 10,
  134469. 3,
  134470. 11,
  134471. 2,
  134472. 12,
  134473. 1,
  134474. 13,
  134475. 0,
  134476. 14,
  134477. };
  134478. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134479. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134480. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134481. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134482. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134483. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134484. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134485. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134486. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134487. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134488. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134489. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134490. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134491. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134492. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134493. 15,
  134494. };
  134495. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134496. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134497. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134498. };
  134499. static long _vq_quantmap__44c8_s_p8_0[] = {
  134500. 13, 11, 9, 7, 5, 3, 1, 0,
  134501. 2, 4, 6, 8, 10, 12, 14,
  134502. };
  134503. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134504. _vq_quantthresh__44c8_s_p8_0,
  134505. _vq_quantmap__44c8_s_p8_0,
  134506. 15,
  134507. 15
  134508. };
  134509. static static_codebook _44c8_s_p8_0 = {
  134510. 2, 225,
  134511. _vq_lengthlist__44c8_s_p8_0,
  134512. 1, -520986624, 1620377600, 4, 0,
  134513. _vq_quantlist__44c8_s_p8_0,
  134514. NULL,
  134515. &_vq_auxt__44c8_s_p8_0,
  134516. NULL,
  134517. 0
  134518. };
  134519. static long _vq_quantlist__44c8_s_p8_1[] = {
  134520. 10,
  134521. 9,
  134522. 11,
  134523. 8,
  134524. 12,
  134525. 7,
  134526. 13,
  134527. 6,
  134528. 14,
  134529. 5,
  134530. 15,
  134531. 4,
  134532. 16,
  134533. 3,
  134534. 17,
  134535. 2,
  134536. 18,
  134537. 1,
  134538. 19,
  134539. 0,
  134540. 20,
  134541. };
  134542. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134543. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134544. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134545. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134546. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134547. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134548. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134549. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134550. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134551. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134552. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134553. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134554. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134555. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134556. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134557. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134558. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134559. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134560. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134561. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134562. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134563. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134564. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134565. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134566. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134567. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134568. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134569. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134570. 10, 9, 9,10,10, 9,10, 9, 9,
  134571. };
  134572. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134573. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134574. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134575. 6.5, 7.5, 8.5, 9.5,
  134576. };
  134577. static long _vq_quantmap__44c8_s_p8_1[] = {
  134578. 19, 17, 15, 13, 11, 9, 7, 5,
  134579. 3, 1, 0, 2, 4, 6, 8, 10,
  134580. 12, 14, 16, 18, 20,
  134581. };
  134582. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134583. _vq_quantthresh__44c8_s_p8_1,
  134584. _vq_quantmap__44c8_s_p8_1,
  134585. 21,
  134586. 21
  134587. };
  134588. static static_codebook _44c8_s_p8_1 = {
  134589. 2, 441,
  134590. _vq_lengthlist__44c8_s_p8_1,
  134591. 1, -529268736, 1611661312, 5, 0,
  134592. _vq_quantlist__44c8_s_p8_1,
  134593. NULL,
  134594. &_vq_auxt__44c8_s_p8_1,
  134595. NULL,
  134596. 0
  134597. };
  134598. static long _vq_quantlist__44c8_s_p9_0[] = {
  134599. 8,
  134600. 7,
  134601. 9,
  134602. 6,
  134603. 10,
  134604. 5,
  134605. 11,
  134606. 4,
  134607. 12,
  134608. 3,
  134609. 13,
  134610. 2,
  134611. 14,
  134612. 1,
  134613. 15,
  134614. 0,
  134615. 16,
  134616. };
  134617. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134618. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134619. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134620. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134621. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134622. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134624. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134627. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134631. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134632. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134633. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134634. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134635. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134636. 10,
  134637. };
  134638. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134639. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134640. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134641. };
  134642. static long _vq_quantmap__44c8_s_p9_0[] = {
  134643. 15, 13, 11, 9, 7, 5, 3, 1,
  134644. 0, 2, 4, 6, 8, 10, 12, 14,
  134645. 16,
  134646. };
  134647. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134648. _vq_quantthresh__44c8_s_p9_0,
  134649. _vq_quantmap__44c8_s_p9_0,
  134650. 17,
  134651. 17
  134652. };
  134653. static static_codebook _44c8_s_p9_0 = {
  134654. 2, 289,
  134655. _vq_lengthlist__44c8_s_p9_0,
  134656. 1, -509798400, 1631393792, 5, 0,
  134657. _vq_quantlist__44c8_s_p9_0,
  134658. NULL,
  134659. &_vq_auxt__44c8_s_p9_0,
  134660. NULL,
  134661. 0
  134662. };
  134663. static long _vq_quantlist__44c8_s_p9_1[] = {
  134664. 9,
  134665. 8,
  134666. 10,
  134667. 7,
  134668. 11,
  134669. 6,
  134670. 12,
  134671. 5,
  134672. 13,
  134673. 4,
  134674. 14,
  134675. 3,
  134676. 15,
  134677. 2,
  134678. 16,
  134679. 1,
  134680. 17,
  134681. 0,
  134682. 18,
  134683. };
  134684. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134685. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134686. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134687. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134688. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134689. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134690. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134691. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134692. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134693. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134694. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134695. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134696. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134697. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134698. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134699. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134700. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134701. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134702. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134703. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134704. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134705. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134706. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134707. 14,13,13,14,14,15,14,15,14,
  134708. };
  134709. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134710. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134711. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134712. 367.5, 416.5,
  134713. };
  134714. static long _vq_quantmap__44c8_s_p9_1[] = {
  134715. 17, 15, 13, 11, 9, 7, 5, 3,
  134716. 1, 0, 2, 4, 6, 8, 10, 12,
  134717. 14, 16, 18,
  134718. };
  134719. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134720. _vq_quantthresh__44c8_s_p9_1,
  134721. _vq_quantmap__44c8_s_p9_1,
  134722. 19,
  134723. 19
  134724. };
  134725. static static_codebook _44c8_s_p9_1 = {
  134726. 2, 361,
  134727. _vq_lengthlist__44c8_s_p9_1,
  134728. 1, -518287360, 1622704128, 5, 0,
  134729. _vq_quantlist__44c8_s_p9_1,
  134730. NULL,
  134731. &_vq_auxt__44c8_s_p9_1,
  134732. NULL,
  134733. 0
  134734. };
  134735. static long _vq_quantlist__44c8_s_p9_2[] = {
  134736. 24,
  134737. 23,
  134738. 25,
  134739. 22,
  134740. 26,
  134741. 21,
  134742. 27,
  134743. 20,
  134744. 28,
  134745. 19,
  134746. 29,
  134747. 18,
  134748. 30,
  134749. 17,
  134750. 31,
  134751. 16,
  134752. 32,
  134753. 15,
  134754. 33,
  134755. 14,
  134756. 34,
  134757. 13,
  134758. 35,
  134759. 12,
  134760. 36,
  134761. 11,
  134762. 37,
  134763. 10,
  134764. 38,
  134765. 9,
  134766. 39,
  134767. 8,
  134768. 40,
  134769. 7,
  134770. 41,
  134771. 6,
  134772. 42,
  134773. 5,
  134774. 43,
  134775. 4,
  134776. 44,
  134777. 3,
  134778. 45,
  134779. 2,
  134780. 46,
  134781. 1,
  134782. 47,
  134783. 0,
  134784. 48,
  134785. };
  134786. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134787. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134788. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134789. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134790. 7,
  134791. };
  134792. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134793. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134794. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134795. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134796. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134797. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134798. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134799. };
  134800. static long _vq_quantmap__44c8_s_p9_2[] = {
  134801. 47, 45, 43, 41, 39, 37, 35, 33,
  134802. 31, 29, 27, 25, 23, 21, 19, 17,
  134803. 15, 13, 11, 9, 7, 5, 3, 1,
  134804. 0, 2, 4, 6, 8, 10, 12, 14,
  134805. 16, 18, 20, 22, 24, 26, 28, 30,
  134806. 32, 34, 36, 38, 40, 42, 44, 46,
  134807. 48,
  134808. };
  134809. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134810. _vq_quantthresh__44c8_s_p9_2,
  134811. _vq_quantmap__44c8_s_p9_2,
  134812. 49,
  134813. 49
  134814. };
  134815. static static_codebook _44c8_s_p9_2 = {
  134816. 1, 49,
  134817. _vq_lengthlist__44c8_s_p9_2,
  134818. 1, -526909440, 1611661312, 6, 0,
  134819. _vq_quantlist__44c8_s_p9_2,
  134820. NULL,
  134821. &_vq_auxt__44c8_s_p9_2,
  134822. NULL,
  134823. 0
  134824. };
  134825. static long _huff_lengthlist__44c8_s_short[] = {
  134826. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134827. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134828. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134829. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134830. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134831. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134832. 10, 9,11,14,
  134833. };
  134834. static static_codebook _huff_book__44c8_s_short = {
  134835. 2, 100,
  134836. _huff_lengthlist__44c8_s_short,
  134837. 0, 0, 0, 0, 0,
  134838. NULL,
  134839. NULL,
  134840. NULL,
  134841. NULL,
  134842. 0
  134843. };
  134844. static long _huff_lengthlist__44c9_s_long[] = {
  134845. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134846. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134847. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134848. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134849. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134850. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134851. 10, 9, 8, 9,
  134852. };
  134853. static static_codebook _huff_book__44c9_s_long = {
  134854. 2, 100,
  134855. _huff_lengthlist__44c9_s_long,
  134856. 0, 0, 0, 0, 0,
  134857. NULL,
  134858. NULL,
  134859. NULL,
  134860. NULL,
  134861. 0
  134862. };
  134863. static long _vq_quantlist__44c9_s_p1_0[] = {
  134864. 1,
  134865. 0,
  134866. 2,
  134867. };
  134868. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134869. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134870. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134871. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134872. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134873. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134874. 7,
  134875. };
  134876. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134877. -0.5, 0.5,
  134878. };
  134879. static long _vq_quantmap__44c9_s_p1_0[] = {
  134880. 1, 0, 2,
  134881. };
  134882. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134883. _vq_quantthresh__44c9_s_p1_0,
  134884. _vq_quantmap__44c9_s_p1_0,
  134885. 3,
  134886. 3
  134887. };
  134888. static static_codebook _44c9_s_p1_0 = {
  134889. 4, 81,
  134890. _vq_lengthlist__44c9_s_p1_0,
  134891. 1, -535822336, 1611661312, 2, 0,
  134892. _vq_quantlist__44c9_s_p1_0,
  134893. NULL,
  134894. &_vq_auxt__44c9_s_p1_0,
  134895. NULL,
  134896. 0
  134897. };
  134898. static long _vq_quantlist__44c9_s_p2_0[] = {
  134899. 2,
  134900. 1,
  134901. 3,
  134902. 0,
  134903. 4,
  134904. };
  134905. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134906. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134907. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134908. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134909. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134910. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134911. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134912. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134913. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134915. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134916. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134917. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134918. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134919. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134920. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134921. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134923. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134924. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134925. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134926. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134927. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134928. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134929. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134931. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134932. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134933. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134934. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134935. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134936. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134937. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134942. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134943. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134944. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134945. 12,
  134946. };
  134947. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134948. -1.5, -0.5, 0.5, 1.5,
  134949. };
  134950. static long _vq_quantmap__44c9_s_p2_0[] = {
  134951. 3, 1, 0, 2, 4,
  134952. };
  134953. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134954. _vq_quantthresh__44c9_s_p2_0,
  134955. _vq_quantmap__44c9_s_p2_0,
  134956. 5,
  134957. 5
  134958. };
  134959. static static_codebook _44c9_s_p2_0 = {
  134960. 4, 625,
  134961. _vq_lengthlist__44c9_s_p2_0,
  134962. 1, -533725184, 1611661312, 3, 0,
  134963. _vq_quantlist__44c9_s_p2_0,
  134964. NULL,
  134965. &_vq_auxt__44c9_s_p2_0,
  134966. NULL,
  134967. 0
  134968. };
  134969. static long _vq_quantlist__44c9_s_p3_0[] = {
  134970. 4,
  134971. 3,
  134972. 5,
  134973. 2,
  134974. 6,
  134975. 1,
  134976. 7,
  134977. 0,
  134978. 8,
  134979. };
  134980. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134981. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134982. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134983. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134984. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134986. 0,
  134987. };
  134988. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134989. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134990. };
  134991. static long _vq_quantmap__44c9_s_p3_0[] = {
  134992. 7, 5, 3, 1, 0, 2, 4, 6,
  134993. 8,
  134994. };
  134995. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134996. _vq_quantthresh__44c9_s_p3_0,
  134997. _vq_quantmap__44c9_s_p3_0,
  134998. 9,
  134999. 9
  135000. };
  135001. static static_codebook _44c9_s_p3_0 = {
  135002. 2, 81,
  135003. _vq_lengthlist__44c9_s_p3_0,
  135004. 1, -531628032, 1611661312, 4, 0,
  135005. _vq_quantlist__44c9_s_p3_0,
  135006. NULL,
  135007. &_vq_auxt__44c9_s_p3_0,
  135008. NULL,
  135009. 0
  135010. };
  135011. static long _vq_quantlist__44c9_s_p4_0[] = {
  135012. 8,
  135013. 7,
  135014. 9,
  135015. 6,
  135016. 10,
  135017. 5,
  135018. 11,
  135019. 4,
  135020. 12,
  135021. 3,
  135022. 13,
  135023. 2,
  135024. 14,
  135025. 1,
  135026. 15,
  135027. 0,
  135028. 16,
  135029. };
  135030. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135031. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135032. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135033. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135034. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135035. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135036. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135037. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135038. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135039. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135040. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  135047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135049. 0,
  135050. };
  135051. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135052. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135053. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135054. };
  135055. static long _vq_quantmap__44c9_s_p4_0[] = {
  135056. 15, 13, 11, 9, 7, 5, 3, 1,
  135057. 0, 2, 4, 6, 8, 10, 12, 14,
  135058. 16,
  135059. };
  135060. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135061. _vq_quantthresh__44c9_s_p4_0,
  135062. _vq_quantmap__44c9_s_p4_0,
  135063. 17,
  135064. 17
  135065. };
  135066. static static_codebook _44c9_s_p4_0 = {
  135067. 2, 289,
  135068. _vq_lengthlist__44c9_s_p4_0,
  135069. 1, -529530880, 1611661312, 5, 0,
  135070. _vq_quantlist__44c9_s_p4_0,
  135071. NULL,
  135072. &_vq_auxt__44c9_s_p4_0,
  135073. NULL,
  135074. 0
  135075. };
  135076. static long _vq_quantlist__44c9_s_p5_0[] = {
  135077. 1,
  135078. 0,
  135079. 2,
  135080. };
  135081. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135082. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135083. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135084. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135085. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135086. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135087. 12,
  135088. };
  135089. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135090. -5.5, 5.5,
  135091. };
  135092. static long _vq_quantmap__44c9_s_p5_0[] = {
  135093. 1, 0, 2,
  135094. };
  135095. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135096. _vq_quantthresh__44c9_s_p5_0,
  135097. _vq_quantmap__44c9_s_p5_0,
  135098. 3,
  135099. 3
  135100. };
  135101. static static_codebook _44c9_s_p5_0 = {
  135102. 4, 81,
  135103. _vq_lengthlist__44c9_s_p5_0,
  135104. 1, -529137664, 1618345984, 2, 0,
  135105. _vq_quantlist__44c9_s_p5_0,
  135106. NULL,
  135107. &_vq_auxt__44c9_s_p5_0,
  135108. NULL,
  135109. 0
  135110. };
  135111. static long _vq_quantlist__44c9_s_p5_1[] = {
  135112. 5,
  135113. 4,
  135114. 6,
  135115. 3,
  135116. 7,
  135117. 2,
  135118. 8,
  135119. 1,
  135120. 9,
  135121. 0,
  135122. 10,
  135123. };
  135124. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135125. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135126. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135127. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135128. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135129. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135130. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135131. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135132. 11,11,11, 7, 7, 7, 7, 7, 7,
  135133. };
  135134. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135135. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135136. 3.5, 4.5,
  135137. };
  135138. static long _vq_quantmap__44c9_s_p5_1[] = {
  135139. 9, 7, 5, 3, 1, 0, 2, 4,
  135140. 6, 8, 10,
  135141. };
  135142. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135143. _vq_quantthresh__44c9_s_p5_1,
  135144. _vq_quantmap__44c9_s_p5_1,
  135145. 11,
  135146. 11
  135147. };
  135148. static static_codebook _44c9_s_p5_1 = {
  135149. 2, 121,
  135150. _vq_lengthlist__44c9_s_p5_1,
  135151. 1, -531365888, 1611661312, 4, 0,
  135152. _vq_quantlist__44c9_s_p5_1,
  135153. NULL,
  135154. &_vq_auxt__44c9_s_p5_1,
  135155. NULL,
  135156. 0
  135157. };
  135158. static long _vq_quantlist__44c9_s_p6_0[] = {
  135159. 6,
  135160. 5,
  135161. 7,
  135162. 4,
  135163. 8,
  135164. 3,
  135165. 9,
  135166. 2,
  135167. 10,
  135168. 1,
  135169. 11,
  135170. 0,
  135171. 12,
  135172. };
  135173. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135174. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135175. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135176. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135177. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135178. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135179. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135184. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135185. };
  135186. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135187. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135188. 12.5, 17.5, 22.5, 27.5,
  135189. };
  135190. static long _vq_quantmap__44c9_s_p6_0[] = {
  135191. 11, 9, 7, 5, 3, 1, 0, 2,
  135192. 4, 6, 8, 10, 12,
  135193. };
  135194. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135195. _vq_quantthresh__44c9_s_p6_0,
  135196. _vq_quantmap__44c9_s_p6_0,
  135197. 13,
  135198. 13
  135199. };
  135200. static static_codebook _44c9_s_p6_0 = {
  135201. 2, 169,
  135202. _vq_lengthlist__44c9_s_p6_0,
  135203. 1, -526516224, 1616117760, 4, 0,
  135204. _vq_quantlist__44c9_s_p6_0,
  135205. NULL,
  135206. &_vq_auxt__44c9_s_p6_0,
  135207. NULL,
  135208. 0
  135209. };
  135210. static long _vq_quantlist__44c9_s_p6_1[] = {
  135211. 2,
  135212. 1,
  135213. 3,
  135214. 0,
  135215. 4,
  135216. };
  135217. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135218. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135219. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135220. };
  135221. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135222. -1.5, -0.5, 0.5, 1.5,
  135223. };
  135224. static long _vq_quantmap__44c9_s_p6_1[] = {
  135225. 3, 1, 0, 2, 4,
  135226. };
  135227. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135228. _vq_quantthresh__44c9_s_p6_1,
  135229. _vq_quantmap__44c9_s_p6_1,
  135230. 5,
  135231. 5
  135232. };
  135233. static static_codebook _44c9_s_p6_1 = {
  135234. 2, 25,
  135235. _vq_lengthlist__44c9_s_p6_1,
  135236. 1, -533725184, 1611661312, 3, 0,
  135237. _vq_quantlist__44c9_s_p6_1,
  135238. NULL,
  135239. &_vq_auxt__44c9_s_p6_1,
  135240. NULL,
  135241. 0
  135242. };
  135243. static long _vq_quantlist__44c9_s_p7_0[] = {
  135244. 6,
  135245. 5,
  135246. 7,
  135247. 4,
  135248. 8,
  135249. 3,
  135250. 9,
  135251. 2,
  135252. 10,
  135253. 1,
  135254. 11,
  135255. 0,
  135256. 12,
  135257. };
  135258. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135259. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135260. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135261. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135262. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135263. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135264. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135265. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135266. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135267. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135268. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135269. 19,12,12,12,12,13,13,14,14,
  135270. };
  135271. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135272. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135273. 27.5, 38.5, 49.5, 60.5,
  135274. };
  135275. static long _vq_quantmap__44c9_s_p7_0[] = {
  135276. 11, 9, 7, 5, 3, 1, 0, 2,
  135277. 4, 6, 8, 10, 12,
  135278. };
  135279. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135280. _vq_quantthresh__44c9_s_p7_0,
  135281. _vq_quantmap__44c9_s_p7_0,
  135282. 13,
  135283. 13
  135284. };
  135285. static static_codebook _44c9_s_p7_0 = {
  135286. 2, 169,
  135287. _vq_lengthlist__44c9_s_p7_0,
  135288. 1, -523206656, 1618345984, 4, 0,
  135289. _vq_quantlist__44c9_s_p7_0,
  135290. NULL,
  135291. &_vq_auxt__44c9_s_p7_0,
  135292. NULL,
  135293. 0
  135294. };
  135295. static long _vq_quantlist__44c9_s_p7_1[] = {
  135296. 5,
  135297. 4,
  135298. 6,
  135299. 3,
  135300. 7,
  135301. 2,
  135302. 8,
  135303. 1,
  135304. 9,
  135305. 0,
  135306. 10,
  135307. };
  135308. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135309. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135310. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135311. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135312. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135313. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135314. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135315. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135316. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135317. };
  135318. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135319. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135320. 3.5, 4.5,
  135321. };
  135322. static long _vq_quantmap__44c9_s_p7_1[] = {
  135323. 9, 7, 5, 3, 1, 0, 2, 4,
  135324. 6, 8, 10,
  135325. };
  135326. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135327. _vq_quantthresh__44c9_s_p7_1,
  135328. _vq_quantmap__44c9_s_p7_1,
  135329. 11,
  135330. 11
  135331. };
  135332. static static_codebook _44c9_s_p7_1 = {
  135333. 2, 121,
  135334. _vq_lengthlist__44c9_s_p7_1,
  135335. 1, -531365888, 1611661312, 4, 0,
  135336. _vq_quantlist__44c9_s_p7_1,
  135337. NULL,
  135338. &_vq_auxt__44c9_s_p7_1,
  135339. NULL,
  135340. 0
  135341. };
  135342. static long _vq_quantlist__44c9_s_p8_0[] = {
  135343. 7,
  135344. 6,
  135345. 8,
  135346. 5,
  135347. 9,
  135348. 4,
  135349. 10,
  135350. 3,
  135351. 11,
  135352. 2,
  135353. 12,
  135354. 1,
  135355. 13,
  135356. 0,
  135357. 14,
  135358. };
  135359. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135360. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135361. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135362. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135363. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135364. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135365. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135366. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135367. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135368. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135369. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135370. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135371. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135372. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135373. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135374. 14,
  135375. };
  135376. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135377. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135378. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135379. };
  135380. static long _vq_quantmap__44c9_s_p8_0[] = {
  135381. 13, 11, 9, 7, 5, 3, 1, 0,
  135382. 2, 4, 6, 8, 10, 12, 14,
  135383. };
  135384. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135385. _vq_quantthresh__44c9_s_p8_0,
  135386. _vq_quantmap__44c9_s_p8_0,
  135387. 15,
  135388. 15
  135389. };
  135390. static static_codebook _44c9_s_p8_0 = {
  135391. 2, 225,
  135392. _vq_lengthlist__44c9_s_p8_0,
  135393. 1, -520986624, 1620377600, 4, 0,
  135394. _vq_quantlist__44c9_s_p8_0,
  135395. NULL,
  135396. &_vq_auxt__44c9_s_p8_0,
  135397. NULL,
  135398. 0
  135399. };
  135400. static long _vq_quantlist__44c9_s_p8_1[] = {
  135401. 10,
  135402. 9,
  135403. 11,
  135404. 8,
  135405. 12,
  135406. 7,
  135407. 13,
  135408. 6,
  135409. 14,
  135410. 5,
  135411. 15,
  135412. 4,
  135413. 16,
  135414. 3,
  135415. 17,
  135416. 2,
  135417. 18,
  135418. 1,
  135419. 19,
  135420. 0,
  135421. 20,
  135422. };
  135423. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135424. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135425. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135426. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135427. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135428. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135429. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135430. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135431. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135432. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135433. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135434. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135435. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135436. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135437. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135438. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135439. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135440. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135441. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135442. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135443. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135444. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135445. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135446. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135447. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135448. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135449. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135450. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135451. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135452. };
  135453. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135454. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135455. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135456. 6.5, 7.5, 8.5, 9.5,
  135457. };
  135458. static long _vq_quantmap__44c9_s_p8_1[] = {
  135459. 19, 17, 15, 13, 11, 9, 7, 5,
  135460. 3, 1, 0, 2, 4, 6, 8, 10,
  135461. 12, 14, 16, 18, 20,
  135462. };
  135463. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135464. _vq_quantthresh__44c9_s_p8_1,
  135465. _vq_quantmap__44c9_s_p8_1,
  135466. 21,
  135467. 21
  135468. };
  135469. static static_codebook _44c9_s_p8_1 = {
  135470. 2, 441,
  135471. _vq_lengthlist__44c9_s_p8_1,
  135472. 1, -529268736, 1611661312, 5, 0,
  135473. _vq_quantlist__44c9_s_p8_1,
  135474. NULL,
  135475. &_vq_auxt__44c9_s_p8_1,
  135476. NULL,
  135477. 0
  135478. };
  135479. static long _vq_quantlist__44c9_s_p9_0[] = {
  135480. 9,
  135481. 8,
  135482. 10,
  135483. 7,
  135484. 11,
  135485. 6,
  135486. 12,
  135487. 5,
  135488. 13,
  135489. 4,
  135490. 14,
  135491. 3,
  135492. 15,
  135493. 2,
  135494. 16,
  135495. 1,
  135496. 17,
  135497. 0,
  135498. 18,
  135499. };
  135500. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135501. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135502. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135503. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135504. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135505. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135506. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135507. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135508. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135509. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135510. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135511. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135512. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135513. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135514. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135515. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135516. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135517. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135519. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135520. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135521. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135522. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135523. 11,11,11,11,11,11,11,11,11,
  135524. };
  135525. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135526. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135527. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135528. 6982.5, 7913.5,
  135529. };
  135530. static long _vq_quantmap__44c9_s_p9_0[] = {
  135531. 17, 15, 13, 11, 9, 7, 5, 3,
  135532. 1, 0, 2, 4, 6, 8, 10, 12,
  135533. 14, 16, 18,
  135534. };
  135535. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135536. _vq_quantthresh__44c9_s_p9_0,
  135537. _vq_quantmap__44c9_s_p9_0,
  135538. 19,
  135539. 19
  135540. };
  135541. static static_codebook _44c9_s_p9_0 = {
  135542. 2, 361,
  135543. _vq_lengthlist__44c9_s_p9_0,
  135544. 1, -508535424, 1631393792, 5, 0,
  135545. _vq_quantlist__44c9_s_p9_0,
  135546. NULL,
  135547. &_vq_auxt__44c9_s_p9_0,
  135548. NULL,
  135549. 0
  135550. };
  135551. static long _vq_quantlist__44c9_s_p9_1[] = {
  135552. 9,
  135553. 8,
  135554. 10,
  135555. 7,
  135556. 11,
  135557. 6,
  135558. 12,
  135559. 5,
  135560. 13,
  135561. 4,
  135562. 14,
  135563. 3,
  135564. 15,
  135565. 2,
  135566. 16,
  135567. 1,
  135568. 17,
  135569. 0,
  135570. 18,
  135571. };
  135572. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135573. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135574. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135575. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135576. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135577. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135578. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135579. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135580. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135581. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135582. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135583. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135584. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135585. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135586. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135587. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135588. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135589. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135590. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135591. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135592. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135593. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135594. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135595. 13,13,13,14,13,14,15,15,15,
  135596. };
  135597. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135598. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135599. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135600. 367.5, 416.5,
  135601. };
  135602. static long _vq_quantmap__44c9_s_p9_1[] = {
  135603. 17, 15, 13, 11, 9, 7, 5, 3,
  135604. 1, 0, 2, 4, 6, 8, 10, 12,
  135605. 14, 16, 18,
  135606. };
  135607. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135608. _vq_quantthresh__44c9_s_p9_1,
  135609. _vq_quantmap__44c9_s_p9_1,
  135610. 19,
  135611. 19
  135612. };
  135613. static static_codebook _44c9_s_p9_1 = {
  135614. 2, 361,
  135615. _vq_lengthlist__44c9_s_p9_1,
  135616. 1, -518287360, 1622704128, 5, 0,
  135617. _vq_quantlist__44c9_s_p9_1,
  135618. NULL,
  135619. &_vq_auxt__44c9_s_p9_1,
  135620. NULL,
  135621. 0
  135622. };
  135623. static long _vq_quantlist__44c9_s_p9_2[] = {
  135624. 24,
  135625. 23,
  135626. 25,
  135627. 22,
  135628. 26,
  135629. 21,
  135630. 27,
  135631. 20,
  135632. 28,
  135633. 19,
  135634. 29,
  135635. 18,
  135636. 30,
  135637. 17,
  135638. 31,
  135639. 16,
  135640. 32,
  135641. 15,
  135642. 33,
  135643. 14,
  135644. 34,
  135645. 13,
  135646. 35,
  135647. 12,
  135648. 36,
  135649. 11,
  135650. 37,
  135651. 10,
  135652. 38,
  135653. 9,
  135654. 39,
  135655. 8,
  135656. 40,
  135657. 7,
  135658. 41,
  135659. 6,
  135660. 42,
  135661. 5,
  135662. 43,
  135663. 4,
  135664. 44,
  135665. 3,
  135666. 45,
  135667. 2,
  135668. 46,
  135669. 1,
  135670. 47,
  135671. 0,
  135672. 48,
  135673. };
  135674. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135675. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135676. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135677. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135678. 7,
  135679. };
  135680. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135681. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135682. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135683. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135684. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135685. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135686. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135687. };
  135688. static long _vq_quantmap__44c9_s_p9_2[] = {
  135689. 47, 45, 43, 41, 39, 37, 35, 33,
  135690. 31, 29, 27, 25, 23, 21, 19, 17,
  135691. 15, 13, 11, 9, 7, 5, 3, 1,
  135692. 0, 2, 4, 6, 8, 10, 12, 14,
  135693. 16, 18, 20, 22, 24, 26, 28, 30,
  135694. 32, 34, 36, 38, 40, 42, 44, 46,
  135695. 48,
  135696. };
  135697. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135698. _vq_quantthresh__44c9_s_p9_2,
  135699. _vq_quantmap__44c9_s_p9_2,
  135700. 49,
  135701. 49
  135702. };
  135703. static static_codebook _44c9_s_p9_2 = {
  135704. 1, 49,
  135705. _vq_lengthlist__44c9_s_p9_2,
  135706. 1, -526909440, 1611661312, 6, 0,
  135707. _vq_quantlist__44c9_s_p9_2,
  135708. NULL,
  135709. &_vq_auxt__44c9_s_p9_2,
  135710. NULL,
  135711. 0
  135712. };
  135713. static long _huff_lengthlist__44c9_s_short[] = {
  135714. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135715. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135716. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135717. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135718. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135719. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135720. 9, 8,10,13,
  135721. };
  135722. static static_codebook _huff_book__44c9_s_short = {
  135723. 2, 100,
  135724. _huff_lengthlist__44c9_s_short,
  135725. 0, 0, 0, 0, 0,
  135726. NULL,
  135727. NULL,
  135728. NULL,
  135729. NULL,
  135730. 0
  135731. };
  135732. static long _huff_lengthlist__44c0_s_long[] = {
  135733. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135734. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135735. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135736. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135737. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135738. 12,
  135739. };
  135740. static static_codebook _huff_book__44c0_s_long = {
  135741. 2, 81,
  135742. _huff_lengthlist__44c0_s_long,
  135743. 0, 0, 0, 0, 0,
  135744. NULL,
  135745. NULL,
  135746. NULL,
  135747. NULL,
  135748. 0
  135749. };
  135750. static long _vq_quantlist__44c0_s_p1_0[] = {
  135751. 1,
  135752. 0,
  135753. 2,
  135754. };
  135755. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135756. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135757. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135762. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135767. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135802. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135807. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135812. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135848. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135853. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135858. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0,
  136167. };
  136168. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136169. -0.5, 0.5,
  136170. };
  136171. static long _vq_quantmap__44c0_s_p1_0[] = {
  136172. 1, 0, 2,
  136173. };
  136174. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136175. _vq_quantthresh__44c0_s_p1_0,
  136176. _vq_quantmap__44c0_s_p1_0,
  136177. 3,
  136178. 3
  136179. };
  136180. static static_codebook _44c0_s_p1_0 = {
  136181. 8, 6561,
  136182. _vq_lengthlist__44c0_s_p1_0,
  136183. 1, -535822336, 1611661312, 2, 0,
  136184. _vq_quantlist__44c0_s_p1_0,
  136185. NULL,
  136186. &_vq_auxt__44c0_s_p1_0,
  136187. NULL,
  136188. 0
  136189. };
  136190. static long _vq_quantlist__44c0_s_p2_0[] = {
  136191. 2,
  136192. 1,
  136193. 3,
  136194. 0,
  136195. 4,
  136196. };
  136197. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136198. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0,
  136238. };
  136239. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136240. -1.5, -0.5, 0.5, 1.5,
  136241. };
  136242. static long _vq_quantmap__44c0_s_p2_0[] = {
  136243. 3, 1, 0, 2, 4,
  136244. };
  136245. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136246. _vq_quantthresh__44c0_s_p2_0,
  136247. _vq_quantmap__44c0_s_p2_0,
  136248. 5,
  136249. 5
  136250. };
  136251. static static_codebook _44c0_s_p2_0 = {
  136252. 4, 625,
  136253. _vq_lengthlist__44c0_s_p2_0,
  136254. 1, -533725184, 1611661312, 3, 0,
  136255. _vq_quantlist__44c0_s_p2_0,
  136256. NULL,
  136257. &_vq_auxt__44c0_s_p2_0,
  136258. NULL,
  136259. 0
  136260. };
  136261. static long _vq_quantlist__44c0_s_p3_0[] = {
  136262. 4,
  136263. 3,
  136264. 5,
  136265. 2,
  136266. 6,
  136267. 1,
  136268. 7,
  136269. 0,
  136270. 8,
  136271. };
  136272. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136273. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136274. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136275. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136276. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136277. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0,
  136279. };
  136280. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136281. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136282. };
  136283. static long _vq_quantmap__44c0_s_p3_0[] = {
  136284. 7, 5, 3, 1, 0, 2, 4, 6,
  136285. 8,
  136286. };
  136287. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136288. _vq_quantthresh__44c0_s_p3_0,
  136289. _vq_quantmap__44c0_s_p3_0,
  136290. 9,
  136291. 9
  136292. };
  136293. static static_codebook _44c0_s_p3_0 = {
  136294. 2, 81,
  136295. _vq_lengthlist__44c0_s_p3_0,
  136296. 1, -531628032, 1611661312, 4, 0,
  136297. _vq_quantlist__44c0_s_p3_0,
  136298. NULL,
  136299. &_vq_auxt__44c0_s_p3_0,
  136300. NULL,
  136301. 0
  136302. };
  136303. static long _vq_quantlist__44c0_s_p4_0[] = {
  136304. 4,
  136305. 3,
  136306. 5,
  136307. 2,
  136308. 6,
  136309. 1,
  136310. 7,
  136311. 0,
  136312. 8,
  136313. };
  136314. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136315. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136316. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136317. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136318. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136319. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136320. 10,
  136321. };
  136322. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136323. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136324. };
  136325. static long _vq_quantmap__44c0_s_p4_0[] = {
  136326. 7, 5, 3, 1, 0, 2, 4, 6,
  136327. 8,
  136328. };
  136329. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136330. _vq_quantthresh__44c0_s_p4_0,
  136331. _vq_quantmap__44c0_s_p4_0,
  136332. 9,
  136333. 9
  136334. };
  136335. static static_codebook _44c0_s_p4_0 = {
  136336. 2, 81,
  136337. _vq_lengthlist__44c0_s_p4_0,
  136338. 1, -531628032, 1611661312, 4, 0,
  136339. _vq_quantlist__44c0_s_p4_0,
  136340. NULL,
  136341. &_vq_auxt__44c0_s_p4_0,
  136342. NULL,
  136343. 0
  136344. };
  136345. static long _vq_quantlist__44c0_s_p5_0[] = {
  136346. 8,
  136347. 7,
  136348. 9,
  136349. 6,
  136350. 10,
  136351. 5,
  136352. 11,
  136353. 4,
  136354. 12,
  136355. 3,
  136356. 13,
  136357. 2,
  136358. 14,
  136359. 1,
  136360. 15,
  136361. 0,
  136362. 16,
  136363. };
  136364. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136365. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136366. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136367. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136368. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136369. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136370. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136371. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136372. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136373. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136374. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136375. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136376. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136377. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136378. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136379. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136380. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136381. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136383. 14,
  136384. };
  136385. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136386. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136387. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136388. };
  136389. static long _vq_quantmap__44c0_s_p5_0[] = {
  136390. 15, 13, 11, 9, 7, 5, 3, 1,
  136391. 0, 2, 4, 6, 8, 10, 12, 14,
  136392. 16,
  136393. };
  136394. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136395. _vq_quantthresh__44c0_s_p5_0,
  136396. _vq_quantmap__44c0_s_p5_0,
  136397. 17,
  136398. 17
  136399. };
  136400. static static_codebook _44c0_s_p5_0 = {
  136401. 2, 289,
  136402. _vq_lengthlist__44c0_s_p5_0,
  136403. 1, -529530880, 1611661312, 5, 0,
  136404. _vq_quantlist__44c0_s_p5_0,
  136405. NULL,
  136406. &_vq_auxt__44c0_s_p5_0,
  136407. NULL,
  136408. 0
  136409. };
  136410. static long _vq_quantlist__44c0_s_p6_0[] = {
  136411. 1,
  136412. 0,
  136413. 2,
  136414. };
  136415. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136416. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136417. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136418. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136419. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136420. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136421. 10,
  136422. };
  136423. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136424. -5.5, 5.5,
  136425. };
  136426. static long _vq_quantmap__44c0_s_p6_0[] = {
  136427. 1, 0, 2,
  136428. };
  136429. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136430. _vq_quantthresh__44c0_s_p6_0,
  136431. _vq_quantmap__44c0_s_p6_0,
  136432. 3,
  136433. 3
  136434. };
  136435. static static_codebook _44c0_s_p6_0 = {
  136436. 4, 81,
  136437. _vq_lengthlist__44c0_s_p6_0,
  136438. 1, -529137664, 1618345984, 2, 0,
  136439. _vq_quantlist__44c0_s_p6_0,
  136440. NULL,
  136441. &_vq_auxt__44c0_s_p6_0,
  136442. NULL,
  136443. 0
  136444. };
  136445. static long _vq_quantlist__44c0_s_p6_1[] = {
  136446. 5,
  136447. 4,
  136448. 6,
  136449. 3,
  136450. 7,
  136451. 2,
  136452. 8,
  136453. 1,
  136454. 9,
  136455. 0,
  136456. 10,
  136457. };
  136458. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136459. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136460. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136461. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136462. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136463. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136464. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136465. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136466. 10,10,10, 8, 8, 8, 8, 8, 8,
  136467. };
  136468. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136469. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136470. 3.5, 4.5,
  136471. };
  136472. static long _vq_quantmap__44c0_s_p6_1[] = {
  136473. 9, 7, 5, 3, 1, 0, 2, 4,
  136474. 6, 8, 10,
  136475. };
  136476. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136477. _vq_quantthresh__44c0_s_p6_1,
  136478. _vq_quantmap__44c0_s_p6_1,
  136479. 11,
  136480. 11
  136481. };
  136482. static static_codebook _44c0_s_p6_1 = {
  136483. 2, 121,
  136484. _vq_lengthlist__44c0_s_p6_1,
  136485. 1, -531365888, 1611661312, 4, 0,
  136486. _vq_quantlist__44c0_s_p6_1,
  136487. NULL,
  136488. &_vq_auxt__44c0_s_p6_1,
  136489. NULL,
  136490. 0
  136491. };
  136492. static long _vq_quantlist__44c0_s_p7_0[] = {
  136493. 6,
  136494. 5,
  136495. 7,
  136496. 4,
  136497. 8,
  136498. 3,
  136499. 9,
  136500. 2,
  136501. 10,
  136502. 1,
  136503. 11,
  136504. 0,
  136505. 12,
  136506. };
  136507. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136508. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136509. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136510. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136511. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136512. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136513. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136514. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136515. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136516. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136517. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136518. 0,12,12,11,11,12,12,13,13,
  136519. };
  136520. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136521. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136522. 12.5, 17.5, 22.5, 27.5,
  136523. };
  136524. static long _vq_quantmap__44c0_s_p7_0[] = {
  136525. 11, 9, 7, 5, 3, 1, 0, 2,
  136526. 4, 6, 8, 10, 12,
  136527. };
  136528. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136529. _vq_quantthresh__44c0_s_p7_0,
  136530. _vq_quantmap__44c0_s_p7_0,
  136531. 13,
  136532. 13
  136533. };
  136534. static static_codebook _44c0_s_p7_0 = {
  136535. 2, 169,
  136536. _vq_lengthlist__44c0_s_p7_0,
  136537. 1, -526516224, 1616117760, 4, 0,
  136538. _vq_quantlist__44c0_s_p7_0,
  136539. NULL,
  136540. &_vq_auxt__44c0_s_p7_0,
  136541. NULL,
  136542. 0
  136543. };
  136544. static long _vq_quantlist__44c0_s_p7_1[] = {
  136545. 2,
  136546. 1,
  136547. 3,
  136548. 0,
  136549. 4,
  136550. };
  136551. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136552. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136553. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136554. };
  136555. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136556. -1.5, -0.5, 0.5, 1.5,
  136557. };
  136558. static long _vq_quantmap__44c0_s_p7_1[] = {
  136559. 3, 1, 0, 2, 4,
  136560. };
  136561. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136562. _vq_quantthresh__44c0_s_p7_1,
  136563. _vq_quantmap__44c0_s_p7_1,
  136564. 5,
  136565. 5
  136566. };
  136567. static static_codebook _44c0_s_p7_1 = {
  136568. 2, 25,
  136569. _vq_lengthlist__44c0_s_p7_1,
  136570. 1, -533725184, 1611661312, 3, 0,
  136571. _vq_quantlist__44c0_s_p7_1,
  136572. NULL,
  136573. &_vq_auxt__44c0_s_p7_1,
  136574. NULL,
  136575. 0
  136576. };
  136577. static long _vq_quantlist__44c0_s_p8_0[] = {
  136578. 2,
  136579. 1,
  136580. 3,
  136581. 0,
  136582. 4,
  136583. };
  136584. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136585. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136586. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136587. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136588. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136589. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136590. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136591. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136592. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136593. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136594. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136595. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136596. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136597. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136600. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136604. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136612. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136613. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136614. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136615. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136616. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136618. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136620. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136621. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136622. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136624. 11,
  136625. };
  136626. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136627. -331.5, -110.5, 110.5, 331.5,
  136628. };
  136629. static long _vq_quantmap__44c0_s_p8_0[] = {
  136630. 3, 1, 0, 2, 4,
  136631. };
  136632. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136633. _vq_quantthresh__44c0_s_p8_0,
  136634. _vq_quantmap__44c0_s_p8_0,
  136635. 5,
  136636. 5
  136637. };
  136638. static static_codebook _44c0_s_p8_0 = {
  136639. 4, 625,
  136640. _vq_lengthlist__44c0_s_p8_0,
  136641. 1, -518283264, 1627103232, 3, 0,
  136642. _vq_quantlist__44c0_s_p8_0,
  136643. NULL,
  136644. &_vq_auxt__44c0_s_p8_0,
  136645. NULL,
  136646. 0
  136647. };
  136648. static long _vq_quantlist__44c0_s_p8_1[] = {
  136649. 6,
  136650. 5,
  136651. 7,
  136652. 4,
  136653. 8,
  136654. 3,
  136655. 9,
  136656. 2,
  136657. 10,
  136658. 1,
  136659. 11,
  136660. 0,
  136661. 12,
  136662. };
  136663. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136664. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136665. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136666. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136667. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136668. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136669. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136670. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136671. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136672. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136673. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136674. 16,13,13,12,12,14,14,15,13,
  136675. };
  136676. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136677. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136678. 42.5, 59.5, 76.5, 93.5,
  136679. };
  136680. static long _vq_quantmap__44c0_s_p8_1[] = {
  136681. 11, 9, 7, 5, 3, 1, 0, 2,
  136682. 4, 6, 8, 10, 12,
  136683. };
  136684. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136685. _vq_quantthresh__44c0_s_p8_1,
  136686. _vq_quantmap__44c0_s_p8_1,
  136687. 13,
  136688. 13
  136689. };
  136690. static static_codebook _44c0_s_p8_1 = {
  136691. 2, 169,
  136692. _vq_lengthlist__44c0_s_p8_1,
  136693. 1, -522616832, 1620115456, 4, 0,
  136694. _vq_quantlist__44c0_s_p8_1,
  136695. NULL,
  136696. &_vq_auxt__44c0_s_p8_1,
  136697. NULL,
  136698. 0
  136699. };
  136700. static long _vq_quantlist__44c0_s_p8_2[] = {
  136701. 8,
  136702. 7,
  136703. 9,
  136704. 6,
  136705. 10,
  136706. 5,
  136707. 11,
  136708. 4,
  136709. 12,
  136710. 3,
  136711. 13,
  136712. 2,
  136713. 14,
  136714. 1,
  136715. 15,
  136716. 0,
  136717. 16,
  136718. };
  136719. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136720. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136721. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136722. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136723. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136724. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136725. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136726. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136727. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136728. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136729. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136730. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136731. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136732. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136733. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136734. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136735. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136736. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136737. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136738. 10,
  136739. };
  136740. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136741. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136742. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136743. };
  136744. static long _vq_quantmap__44c0_s_p8_2[] = {
  136745. 15, 13, 11, 9, 7, 5, 3, 1,
  136746. 0, 2, 4, 6, 8, 10, 12, 14,
  136747. 16,
  136748. };
  136749. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136750. _vq_quantthresh__44c0_s_p8_2,
  136751. _vq_quantmap__44c0_s_p8_2,
  136752. 17,
  136753. 17
  136754. };
  136755. static static_codebook _44c0_s_p8_2 = {
  136756. 2, 289,
  136757. _vq_lengthlist__44c0_s_p8_2,
  136758. 1, -529530880, 1611661312, 5, 0,
  136759. _vq_quantlist__44c0_s_p8_2,
  136760. NULL,
  136761. &_vq_auxt__44c0_s_p8_2,
  136762. NULL,
  136763. 0
  136764. };
  136765. static long _huff_lengthlist__44c0_s_short[] = {
  136766. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136767. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136768. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136769. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136770. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136771. 12,
  136772. };
  136773. static static_codebook _huff_book__44c0_s_short = {
  136774. 2, 81,
  136775. _huff_lengthlist__44c0_s_short,
  136776. 0, 0, 0, 0, 0,
  136777. NULL,
  136778. NULL,
  136779. NULL,
  136780. NULL,
  136781. 0
  136782. };
  136783. static long _huff_lengthlist__44c0_sm_long[] = {
  136784. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136785. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136786. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136787. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136788. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136789. 13,
  136790. };
  136791. static static_codebook _huff_book__44c0_sm_long = {
  136792. 2, 81,
  136793. _huff_lengthlist__44c0_sm_long,
  136794. 0, 0, 0, 0, 0,
  136795. NULL,
  136796. NULL,
  136797. NULL,
  136798. NULL,
  136799. 0
  136800. };
  136801. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136802. 1,
  136803. 0,
  136804. 2,
  136805. };
  136806. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136807. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136808. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136813. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136818. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  136853. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136858. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  136863. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136899. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136904. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136909. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0,
  137218. };
  137219. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137220. -0.5, 0.5,
  137221. };
  137222. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137223. 1, 0, 2,
  137224. };
  137225. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137226. _vq_quantthresh__44c0_sm_p1_0,
  137227. _vq_quantmap__44c0_sm_p1_0,
  137228. 3,
  137229. 3
  137230. };
  137231. static static_codebook _44c0_sm_p1_0 = {
  137232. 8, 6561,
  137233. _vq_lengthlist__44c0_sm_p1_0,
  137234. 1, -535822336, 1611661312, 2, 0,
  137235. _vq_quantlist__44c0_sm_p1_0,
  137236. NULL,
  137237. &_vq_auxt__44c0_sm_p1_0,
  137238. NULL,
  137239. 0
  137240. };
  137241. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137242. 2,
  137243. 1,
  137244. 3,
  137245. 0,
  137246. 4,
  137247. };
  137248. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137249. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0,
  137289. };
  137290. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137291. -1.5, -0.5, 0.5, 1.5,
  137292. };
  137293. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137294. 3, 1, 0, 2, 4,
  137295. };
  137296. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137297. _vq_quantthresh__44c0_sm_p2_0,
  137298. _vq_quantmap__44c0_sm_p2_0,
  137299. 5,
  137300. 5
  137301. };
  137302. static static_codebook _44c0_sm_p2_0 = {
  137303. 4, 625,
  137304. _vq_lengthlist__44c0_sm_p2_0,
  137305. 1, -533725184, 1611661312, 3, 0,
  137306. _vq_quantlist__44c0_sm_p2_0,
  137307. NULL,
  137308. &_vq_auxt__44c0_sm_p2_0,
  137309. NULL,
  137310. 0
  137311. };
  137312. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137313. 4,
  137314. 3,
  137315. 5,
  137316. 2,
  137317. 6,
  137318. 1,
  137319. 7,
  137320. 0,
  137321. 8,
  137322. };
  137323. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137324. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137325. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137326. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137327. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137328. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0,
  137330. };
  137331. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137332. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137333. };
  137334. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137335. 7, 5, 3, 1, 0, 2, 4, 6,
  137336. 8,
  137337. };
  137338. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137339. _vq_quantthresh__44c0_sm_p3_0,
  137340. _vq_quantmap__44c0_sm_p3_0,
  137341. 9,
  137342. 9
  137343. };
  137344. static static_codebook _44c0_sm_p3_0 = {
  137345. 2, 81,
  137346. _vq_lengthlist__44c0_sm_p3_0,
  137347. 1, -531628032, 1611661312, 4, 0,
  137348. _vq_quantlist__44c0_sm_p3_0,
  137349. NULL,
  137350. &_vq_auxt__44c0_sm_p3_0,
  137351. NULL,
  137352. 0
  137353. };
  137354. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137355. 4,
  137356. 3,
  137357. 5,
  137358. 2,
  137359. 6,
  137360. 1,
  137361. 7,
  137362. 0,
  137363. 8,
  137364. };
  137365. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137366. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137367. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137368. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137369. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137370. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137371. 11,
  137372. };
  137373. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137374. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137375. };
  137376. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137377. 7, 5, 3, 1, 0, 2, 4, 6,
  137378. 8,
  137379. };
  137380. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137381. _vq_quantthresh__44c0_sm_p4_0,
  137382. _vq_quantmap__44c0_sm_p4_0,
  137383. 9,
  137384. 9
  137385. };
  137386. static static_codebook _44c0_sm_p4_0 = {
  137387. 2, 81,
  137388. _vq_lengthlist__44c0_sm_p4_0,
  137389. 1, -531628032, 1611661312, 4, 0,
  137390. _vq_quantlist__44c0_sm_p4_0,
  137391. NULL,
  137392. &_vq_auxt__44c0_sm_p4_0,
  137393. NULL,
  137394. 0
  137395. };
  137396. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137397. 8,
  137398. 7,
  137399. 9,
  137400. 6,
  137401. 10,
  137402. 5,
  137403. 11,
  137404. 4,
  137405. 12,
  137406. 3,
  137407. 13,
  137408. 2,
  137409. 14,
  137410. 1,
  137411. 15,
  137412. 0,
  137413. 16,
  137414. };
  137415. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137416. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137417. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137418. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137419. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137420. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137421. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137422. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137423. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137424. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137425. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137426. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137427. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137428. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137429. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137430. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137431. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137432. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137434. 14,
  137435. };
  137436. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137437. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137438. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137439. };
  137440. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137441. 15, 13, 11, 9, 7, 5, 3, 1,
  137442. 0, 2, 4, 6, 8, 10, 12, 14,
  137443. 16,
  137444. };
  137445. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137446. _vq_quantthresh__44c0_sm_p5_0,
  137447. _vq_quantmap__44c0_sm_p5_0,
  137448. 17,
  137449. 17
  137450. };
  137451. static static_codebook _44c0_sm_p5_0 = {
  137452. 2, 289,
  137453. _vq_lengthlist__44c0_sm_p5_0,
  137454. 1, -529530880, 1611661312, 5, 0,
  137455. _vq_quantlist__44c0_sm_p5_0,
  137456. NULL,
  137457. &_vq_auxt__44c0_sm_p5_0,
  137458. NULL,
  137459. 0
  137460. };
  137461. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137462. 1,
  137463. 0,
  137464. 2,
  137465. };
  137466. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137467. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137468. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137469. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137470. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137471. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137472. 11,
  137473. };
  137474. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137475. -5.5, 5.5,
  137476. };
  137477. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137478. 1, 0, 2,
  137479. };
  137480. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137481. _vq_quantthresh__44c0_sm_p6_0,
  137482. _vq_quantmap__44c0_sm_p6_0,
  137483. 3,
  137484. 3
  137485. };
  137486. static static_codebook _44c0_sm_p6_0 = {
  137487. 4, 81,
  137488. _vq_lengthlist__44c0_sm_p6_0,
  137489. 1, -529137664, 1618345984, 2, 0,
  137490. _vq_quantlist__44c0_sm_p6_0,
  137491. NULL,
  137492. &_vq_auxt__44c0_sm_p6_0,
  137493. NULL,
  137494. 0
  137495. };
  137496. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137497. 5,
  137498. 4,
  137499. 6,
  137500. 3,
  137501. 7,
  137502. 2,
  137503. 8,
  137504. 1,
  137505. 9,
  137506. 0,
  137507. 10,
  137508. };
  137509. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137510. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137511. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137512. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137513. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137514. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137515. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137516. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137517. 10,10,10, 8, 8, 8, 8, 8, 8,
  137518. };
  137519. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137520. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137521. 3.5, 4.5,
  137522. };
  137523. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137524. 9, 7, 5, 3, 1, 0, 2, 4,
  137525. 6, 8, 10,
  137526. };
  137527. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137528. _vq_quantthresh__44c0_sm_p6_1,
  137529. _vq_quantmap__44c0_sm_p6_1,
  137530. 11,
  137531. 11
  137532. };
  137533. static static_codebook _44c0_sm_p6_1 = {
  137534. 2, 121,
  137535. _vq_lengthlist__44c0_sm_p6_1,
  137536. 1, -531365888, 1611661312, 4, 0,
  137537. _vq_quantlist__44c0_sm_p6_1,
  137538. NULL,
  137539. &_vq_auxt__44c0_sm_p6_1,
  137540. NULL,
  137541. 0
  137542. };
  137543. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137544. 6,
  137545. 5,
  137546. 7,
  137547. 4,
  137548. 8,
  137549. 3,
  137550. 9,
  137551. 2,
  137552. 10,
  137553. 1,
  137554. 11,
  137555. 0,
  137556. 12,
  137557. };
  137558. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137559. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137560. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137561. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137562. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137563. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137564. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137565. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137566. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137567. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137568. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137569. 0,12,12,11,11,13,12,14,14,
  137570. };
  137571. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137572. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137573. 12.5, 17.5, 22.5, 27.5,
  137574. };
  137575. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137576. 11, 9, 7, 5, 3, 1, 0, 2,
  137577. 4, 6, 8, 10, 12,
  137578. };
  137579. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137580. _vq_quantthresh__44c0_sm_p7_0,
  137581. _vq_quantmap__44c0_sm_p7_0,
  137582. 13,
  137583. 13
  137584. };
  137585. static static_codebook _44c0_sm_p7_0 = {
  137586. 2, 169,
  137587. _vq_lengthlist__44c0_sm_p7_0,
  137588. 1, -526516224, 1616117760, 4, 0,
  137589. _vq_quantlist__44c0_sm_p7_0,
  137590. NULL,
  137591. &_vq_auxt__44c0_sm_p7_0,
  137592. NULL,
  137593. 0
  137594. };
  137595. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137596. 2,
  137597. 1,
  137598. 3,
  137599. 0,
  137600. 4,
  137601. };
  137602. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137603. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137604. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137605. };
  137606. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137607. -1.5, -0.5, 0.5, 1.5,
  137608. };
  137609. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137610. 3, 1, 0, 2, 4,
  137611. };
  137612. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137613. _vq_quantthresh__44c0_sm_p7_1,
  137614. _vq_quantmap__44c0_sm_p7_1,
  137615. 5,
  137616. 5
  137617. };
  137618. static static_codebook _44c0_sm_p7_1 = {
  137619. 2, 25,
  137620. _vq_lengthlist__44c0_sm_p7_1,
  137621. 1, -533725184, 1611661312, 3, 0,
  137622. _vq_quantlist__44c0_sm_p7_1,
  137623. NULL,
  137624. &_vq_auxt__44c0_sm_p7_1,
  137625. NULL,
  137626. 0
  137627. };
  137628. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137629. 4,
  137630. 3,
  137631. 5,
  137632. 2,
  137633. 6,
  137634. 1,
  137635. 7,
  137636. 0,
  137637. 8,
  137638. };
  137639. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137640. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137641. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137643. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137644. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137645. 12,
  137646. };
  137647. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137648. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137649. };
  137650. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137651. 7, 5, 3, 1, 0, 2, 4, 6,
  137652. 8,
  137653. };
  137654. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137655. _vq_quantthresh__44c0_sm_p8_0,
  137656. _vq_quantmap__44c0_sm_p8_0,
  137657. 9,
  137658. 9
  137659. };
  137660. static static_codebook _44c0_sm_p8_0 = {
  137661. 2, 81,
  137662. _vq_lengthlist__44c0_sm_p8_0,
  137663. 1, -516186112, 1627103232, 4, 0,
  137664. _vq_quantlist__44c0_sm_p8_0,
  137665. NULL,
  137666. &_vq_auxt__44c0_sm_p8_0,
  137667. NULL,
  137668. 0
  137669. };
  137670. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137671. 6,
  137672. 5,
  137673. 7,
  137674. 4,
  137675. 8,
  137676. 3,
  137677. 9,
  137678. 2,
  137679. 10,
  137680. 1,
  137681. 11,
  137682. 0,
  137683. 12,
  137684. };
  137685. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137686. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137687. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137688. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137689. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137690. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137691. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137692. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137693. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137694. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137695. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137696. 20,13,13,12,12,16,13,15,13,
  137697. };
  137698. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137699. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137700. 42.5, 59.5, 76.5, 93.5,
  137701. };
  137702. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137703. 11, 9, 7, 5, 3, 1, 0, 2,
  137704. 4, 6, 8, 10, 12,
  137705. };
  137706. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137707. _vq_quantthresh__44c0_sm_p8_1,
  137708. _vq_quantmap__44c0_sm_p8_1,
  137709. 13,
  137710. 13
  137711. };
  137712. static static_codebook _44c0_sm_p8_1 = {
  137713. 2, 169,
  137714. _vq_lengthlist__44c0_sm_p8_1,
  137715. 1, -522616832, 1620115456, 4, 0,
  137716. _vq_quantlist__44c0_sm_p8_1,
  137717. NULL,
  137718. &_vq_auxt__44c0_sm_p8_1,
  137719. NULL,
  137720. 0
  137721. };
  137722. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137723. 8,
  137724. 7,
  137725. 9,
  137726. 6,
  137727. 10,
  137728. 5,
  137729. 11,
  137730. 4,
  137731. 12,
  137732. 3,
  137733. 13,
  137734. 2,
  137735. 14,
  137736. 1,
  137737. 15,
  137738. 0,
  137739. 16,
  137740. };
  137741. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137742. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137743. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137744. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137745. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137746. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137747. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137748. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137749. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137750. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137751. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137752. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137753. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137754. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137755. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137756. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137757. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137758. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137759. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137760. 9,
  137761. };
  137762. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137763. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137764. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137765. };
  137766. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137767. 15, 13, 11, 9, 7, 5, 3, 1,
  137768. 0, 2, 4, 6, 8, 10, 12, 14,
  137769. 16,
  137770. };
  137771. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137772. _vq_quantthresh__44c0_sm_p8_2,
  137773. _vq_quantmap__44c0_sm_p8_2,
  137774. 17,
  137775. 17
  137776. };
  137777. static static_codebook _44c0_sm_p8_2 = {
  137778. 2, 289,
  137779. _vq_lengthlist__44c0_sm_p8_2,
  137780. 1, -529530880, 1611661312, 5, 0,
  137781. _vq_quantlist__44c0_sm_p8_2,
  137782. NULL,
  137783. &_vq_auxt__44c0_sm_p8_2,
  137784. NULL,
  137785. 0
  137786. };
  137787. static long _huff_lengthlist__44c0_sm_short[] = {
  137788. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137789. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137790. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137791. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137792. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137793. 12,
  137794. };
  137795. static static_codebook _huff_book__44c0_sm_short = {
  137796. 2, 81,
  137797. _huff_lengthlist__44c0_sm_short,
  137798. 0, 0, 0, 0, 0,
  137799. NULL,
  137800. NULL,
  137801. NULL,
  137802. NULL,
  137803. 0
  137804. };
  137805. static long _huff_lengthlist__44c1_s_long[] = {
  137806. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137807. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137808. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137809. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137810. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137811. 11,
  137812. };
  137813. static static_codebook _huff_book__44c1_s_long = {
  137814. 2, 81,
  137815. _huff_lengthlist__44c1_s_long,
  137816. 0, 0, 0, 0, 0,
  137817. NULL,
  137818. NULL,
  137819. NULL,
  137820. NULL,
  137821. 0
  137822. };
  137823. static long _vq_quantlist__44c1_s_p1_0[] = {
  137824. 1,
  137825. 0,
  137826. 2,
  137827. };
  137828. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137829. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137830. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137835. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137840. 0, 0, 0, 0, 7, 8, 8, 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, 4, 7, 7, 0, 0, 0, 0,
  137875. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  137880. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  137885. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137921. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137926. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137931. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0,
  138240. };
  138241. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138242. -0.5, 0.5,
  138243. };
  138244. static long _vq_quantmap__44c1_s_p1_0[] = {
  138245. 1, 0, 2,
  138246. };
  138247. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138248. _vq_quantthresh__44c1_s_p1_0,
  138249. _vq_quantmap__44c1_s_p1_0,
  138250. 3,
  138251. 3
  138252. };
  138253. static static_codebook _44c1_s_p1_0 = {
  138254. 8, 6561,
  138255. _vq_lengthlist__44c1_s_p1_0,
  138256. 1, -535822336, 1611661312, 2, 0,
  138257. _vq_quantlist__44c1_s_p1_0,
  138258. NULL,
  138259. &_vq_auxt__44c1_s_p1_0,
  138260. NULL,
  138261. 0
  138262. };
  138263. static long _vq_quantlist__44c1_s_p2_0[] = {
  138264. 2,
  138265. 1,
  138266. 3,
  138267. 0,
  138268. 4,
  138269. };
  138270. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138271. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0,
  138311. };
  138312. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138313. -1.5, -0.5, 0.5, 1.5,
  138314. };
  138315. static long _vq_quantmap__44c1_s_p2_0[] = {
  138316. 3, 1, 0, 2, 4,
  138317. };
  138318. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138319. _vq_quantthresh__44c1_s_p2_0,
  138320. _vq_quantmap__44c1_s_p2_0,
  138321. 5,
  138322. 5
  138323. };
  138324. static static_codebook _44c1_s_p2_0 = {
  138325. 4, 625,
  138326. _vq_lengthlist__44c1_s_p2_0,
  138327. 1, -533725184, 1611661312, 3, 0,
  138328. _vq_quantlist__44c1_s_p2_0,
  138329. NULL,
  138330. &_vq_auxt__44c1_s_p2_0,
  138331. NULL,
  138332. 0
  138333. };
  138334. static long _vq_quantlist__44c1_s_p3_0[] = {
  138335. 4,
  138336. 3,
  138337. 5,
  138338. 2,
  138339. 6,
  138340. 1,
  138341. 7,
  138342. 0,
  138343. 8,
  138344. };
  138345. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138346. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138347. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138348. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138349. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138350. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0,
  138352. };
  138353. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138354. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138355. };
  138356. static long _vq_quantmap__44c1_s_p3_0[] = {
  138357. 7, 5, 3, 1, 0, 2, 4, 6,
  138358. 8,
  138359. };
  138360. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138361. _vq_quantthresh__44c1_s_p3_0,
  138362. _vq_quantmap__44c1_s_p3_0,
  138363. 9,
  138364. 9
  138365. };
  138366. static static_codebook _44c1_s_p3_0 = {
  138367. 2, 81,
  138368. _vq_lengthlist__44c1_s_p3_0,
  138369. 1, -531628032, 1611661312, 4, 0,
  138370. _vq_quantlist__44c1_s_p3_0,
  138371. NULL,
  138372. &_vq_auxt__44c1_s_p3_0,
  138373. NULL,
  138374. 0
  138375. };
  138376. static long _vq_quantlist__44c1_s_p4_0[] = {
  138377. 4,
  138378. 3,
  138379. 5,
  138380. 2,
  138381. 6,
  138382. 1,
  138383. 7,
  138384. 0,
  138385. 8,
  138386. };
  138387. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138388. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138389. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138390. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138391. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138392. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138393. 11,
  138394. };
  138395. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138396. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138397. };
  138398. static long _vq_quantmap__44c1_s_p4_0[] = {
  138399. 7, 5, 3, 1, 0, 2, 4, 6,
  138400. 8,
  138401. };
  138402. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138403. _vq_quantthresh__44c1_s_p4_0,
  138404. _vq_quantmap__44c1_s_p4_0,
  138405. 9,
  138406. 9
  138407. };
  138408. static static_codebook _44c1_s_p4_0 = {
  138409. 2, 81,
  138410. _vq_lengthlist__44c1_s_p4_0,
  138411. 1, -531628032, 1611661312, 4, 0,
  138412. _vq_quantlist__44c1_s_p4_0,
  138413. NULL,
  138414. &_vq_auxt__44c1_s_p4_0,
  138415. NULL,
  138416. 0
  138417. };
  138418. static long _vq_quantlist__44c1_s_p5_0[] = {
  138419. 8,
  138420. 7,
  138421. 9,
  138422. 6,
  138423. 10,
  138424. 5,
  138425. 11,
  138426. 4,
  138427. 12,
  138428. 3,
  138429. 13,
  138430. 2,
  138431. 14,
  138432. 1,
  138433. 15,
  138434. 0,
  138435. 16,
  138436. };
  138437. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138438. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138439. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138440. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138441. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138442. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138443. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138444. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138445. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138446. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138447. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138448. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138449. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138450. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138451. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138452. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138453. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138454. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138456. 14,
  138457. };
  138458. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138459. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138460. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138461. };
  138462. static long _vq_quantmap__44c1_s_p5_0[] = {
  138463. 15, 13, 11, 9, 7, 5, 3, 1,
  138464. 0, 2, 4, 6, 8, 10, 12, 14,
  138465. 16,
  138466. };
  138467. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138468. _vq_quantthresh__44c1_s_p5_0,
  138469. _vq_quantmap__44c1_s_p5_0,
  138470. 17,
  138471. 17
  138472. };
  138473. static static_codebook _44c1_s_p5_0 = {
  138474. 2, 289,
  138475. _vq_lengthlist__44c1_s_p5_0,
  138476. 1, -529530880, 1611661312, 5, 0,
  138477. _vq_quantlist__44c1_s_p5_0,
  138478. NULL,
  138479. &_vq_auxt__44c1_s_p5_0,
  138480. NULL,
  138481. 0
  138482. };
  138483. static long _vq_quantlist__44c1_s_p6_0[] = {
  138484. 1,
  138485. 0,
  138486. 2,
  138487. };
  138488. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138489. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138490. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138491. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138492. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138493. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138494. 11,
  138495. };
  138496. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138497. -5.5, 5.5,
  138498. };
  138499. static long _vq_quantmap__44c1_s_p6_0[] = {
  138500. 1, 0, 2,
  138501. };
  138502. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138503. _vq_quantthresh__44c1_s_p6_0,
  138504. _vq_quantmap__44c1_s_p6_0,
  138505. 3,
  138506. 3
  138507. };
  138508. static static_codebook _44c1_s_p6_0 = {
  138509. 4, 81,
  138510. _vq_lengthlist__44c1_s_p6_0,
  138511. 1, -529137664, 1618345984, 2, 0,
  138512. _vq_quantlist__44c1_s_p6_0,
  138513. NULL,
  138514. &_vq_auxt__44c1_s_p6_0,
  138515. NULL,
  138516. 0
  138517. };
  138518. static long _vq_quantlist__44c1_s_p6_1[] = {
  138519. 5,
  138520. 4,
  138521. 6,
  138522. 3,
  138523. 7,
  138524. 2,
  138525. 8,
  138526. 1,
  138527. 9,
  138528. 0,
  138529. 10,
  138530. };
  138531. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138532. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138533. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138534. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138535. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138536. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138537. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138538. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138539. 10,10,10, 8, 8, 8, 8, 8, 8,
  138540. };
  138541. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138542. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138543. 3.5, 4.5,
  138544. };
  138545. static long _vq_quantmap__44c1_s_p6_1[] = {
  138546. 9, 7, 5, 3, 1, 0, 2, 4,
  138547. 6, 8, 10,
  138548. };
  138549. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138550. _vq_quantthresh__44c1_s_p6_1,
  138551. _vq_quantmap__44c1_s_p6_1,
  138552. 11,
  138553. 11
  138554. };
  138555. static static_codebook _44c1_s_p6_1 = {
  138556. 2, 121,
  138557. _vq_lengthlist__44c1_s_p6_1,
  138558. 1, -531365888, 1611661312, 4, 0,
  138559. _vq_quantlist__44c1_s_p6_1,
  138560. NULL,
  138561. &_vq_auxt__44c1_s_p6_1,
  138562. NULL,
  138563. 0
  138564. };
  138565. static long _vq_quantlist__44c1_s_p7_0[] = {
  138566. 6,
  138567. 5,
  138568. 7,
  138569. 4,
  138570. 8,
  138571. 3,
  138572. 9,
  138573. 2,
  138574. 10,
  138575. 1,
  138576. 11,
  138577. 0,
  138578. 12,
  138579. };
  138580. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138581. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138582. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138583. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138584. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138585. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138586. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138587. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138588. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138589. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138590. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138591. 0,12,11,11,11,13,10,14,13,
  138592. };
  138593. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138594. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138595. 12.5, 17.5, 22.5, 27.5,
  138596. };
  138597. static long _vq_quantmap__44c1_s_p7_0[] = {
  138598. 11, 9, 7, 5, 3, 1, 0, 2,
  138599. 4, 6, 8, 10, 12,
  138600. };
  138601. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138602. _vq_quantthresh__44c1_s_p7_0,
  138603. _vq_quantmap__44c1_s_p7_0,
  138604. 13,
  138605. 13
  138606. };
  138607. static static_codebook _44c1_s_p7_0 = {
  138608. 2, 169,
  138609. _vq_lengthlist__44c1_s_p7_0,
  138610. 1, -526516224, 1616117760, 4, 0,
  138611. _vq_quantlist__44c1_s_p7_0,
  138612. NULL,
  138613. &_vq_auxt__44c1_s_p7_0,
  138614. NULL,
  138615. 0
  138616. };
  138617. static long _vq_quantlist__44c1_s_p7_1[] = {
  138618. 2,
  138619. 1,
  138620. 3,
  138621. 0,
  138622. 4,
  138623. };
  138624. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138625. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138626. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138627. };
  138628. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138629. -1.5, -0.5, 0.5, 1.5,
  138630. };
  138631. static long _vq_quantmap__44c1_s_p7_1[] = {
  138632. 3, 1, 0, 2, 4,
  138633. };
  138634. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138635. _vq_quantthresh__44c1_s_p7_1,
  138636. _vq_quantmap__44c1_s_p7_1,
  138637. 5,
  138638. 5
  138639. };
  138640. static static_codebook _44c1_s_p7_1 = {
  138641. 2, 25,
  138642. _vq_lengthlist__44c1_s_p7_1,
  138643. 1, -533725184, 1611661312, 3, 0,
  138644. _vq_quantlist__44c1_s_p7_1,
  138645. NULL,
  138646. &_vq_auxt__44c1_s_p7_1,
  138647. NULL,
  138648. 0
  138649. };
  138650. static long _vq_quantlist__44c1_s_p8_0[] = {
  138651. 6,
  138652. 5,
  138653. 7,
  138654. 4,
  138655. 8,
  138656. 3,
  138657. 9,
  138658. 2,
  138659. 10,
  138660. 1,
  138661. 11,
  138662. 0,
  138663. 12,
  138664. };
  138665. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138666. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138667. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138668. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138669. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138670. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138671. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138672. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138673. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138674. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138675. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138676. 10,10,10,10,10,10,10,10,10,
  138677. };
  138678. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138679. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138680. 552.5, 773.5, 994.5, 1215.5,
  138681. };
  138682. static long _vq_quantmap__44c1_s_p8_0[] = {
  138683. 11, 9, 7, 5, 3, 1, 0, 2,
  138684. 4, 6, 8, 10, 12,
  138685. };
  138686. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138687. _vq_quantthresh__44c1_s_p8_0,
  138688. _vq_quantmap__44c1_s_p8_0,
  138689. 13,
  138690. 13
  138691. };
  138692. static static_codebook _44c1_s_p8_0 = {
  138693. 2, 169,
  138694. _vq_lengthlist__44c1_s_p8_0,
  138695. 1, -514541568, 1627103232, 4, 0,
  138696. _vq_quantlist__44c1_s_p8_0,
  138697. NULL,
  138698. &_vq_auxt__44c1_s_p8_0,
  138699. NULL,
  138700. 0
  138701. };
  138702. static long _vq_quantlist__44c1_s_p8_1[] = {
  138703. 6,
  138704. 5,
  138705. 7,
  138706. 4,
  138707. 8,
  138708. 3,
  138709. 9,
  138710. 2,
  138711. 10,
  138712. 1,
  138713. 11,
  138714. 0,
  138715. 12,
  138716. };
  138717. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138718. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138719. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138720. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138721. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138722. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138723. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138724. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138725. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138726. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138727. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138728. 16,13,12,12,11,14,12,15,13,
  138729. };
  138730. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138731. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138732. 42.5, 59.5, 76.5, 93.5,
  138733. };
  138734. static long _vq_quantmap__44c1_s_p8_1[] = {
  138735. 11, 9, 7, 5, 3, 1, 0, 2,
  138736. 4, 6, 8, 10, 12,
  138737. };
  138738. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138739. _vq_quantthresh__44c1_s_p8_1,
  138740. _vq_quantmap__44c1_s_p8_1,
  138741. 13,
  138742. 13
  138743. };
  138744. static static_codebook _44c1_s_p8_1 = {
  138745. 2, 169,
  138746. _vq_lengthlist__44c1_s_p8_1,
  138747. 1, -522616832, 1620115456, 4, 0,
  138748. _vq_quantlist__44c1_s_p8_1,
  138749. NULL,
  138750. &_vq_auxt__44c1_s_p8_1,
  138751. NULL,
  138752. 0
  138753. };
  138754. static long _vq_quantlist__44c1_s_p8_2[] = {
  138755. 8,
  138756. 7,
  138757. 9,
  138758. 6,
  138759. 10,
  138760. 5,
  138761. 11,
  138762. 4,
  138763. 12,
  138764. 3,
  138765. 13,
  138766. 2,
  138767. 14,
  138768. 1,
  138769. 15,
  138770. 0,
  138771. 16,
  138772. };
  138773. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138774. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138775. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138776. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138777. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138778. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138779. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138780. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138781. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138782. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138783. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138784. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138785. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138786. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138787. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138788. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138789. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138790. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138791. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138792. 9,
  138793. };
  138794. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138795. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138796. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138797. };
  138798. static long _vq_quantmap__44c1_s_p8_2[] = {
  138799. 15, 13, 11, 9, 7, 5, 3, 1,
  138800. 0, 2, 4, 6, 8, 10, 12, 14,
  138801. 16,
  138802. };
  138803. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138804. _vq_quantthresh__44c1_s_p8_2,
  138805. _vq_quantmap__44c1_s_p8_2,
  138806. 17,
  138807. 17
  138808. };
  138809. static static_codebook _44c1_s_p8_2 = {
  138810. 2, 289,
  138811. _vq_lengthlist__44c1_s_p8_2,
  138812. 1, -529530880, 1611661312, 5, 0,
  138813. _vq_quantlist__44c1_s_p8_2,
  138814. NULL,
  138815. &_vq_auxt__44c1_s_p8_2,
  138816. NULL,
  138817. 0
  138818. };
  138819. static long _huff_lengthlist__44c1_s_short[] = {
  138820. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138821. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138822. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138823. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138824. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138825. 11,
  138826. };
  138827. static static_codebook _huff_book__44c1_s_short = {
  138828. 2, 81,
  138829. _huff_lengthlist__44c1_s_short,
  138830. 0, 0, 0, 0, 0,
  138831. NULL,
  138832. NULL,
  138833. NULL,
  138834. NULL,
  138835. 0
  138836. };
  138837. static long _huff_lengthlist__44c1_sm_long[] = {
  138838. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138839. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138840. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138841. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138842. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138843. 11,
  138844. };
  138845. static static_codebook _huff_book__44c1_sm_long = {
  138846. 2, 81,
  138847. _huff_lengthlist__44c1_sm_long,
  138848. 0, 0, 0, 0, 0,
  138849. NULL,
  138850. NULL,
  138851. NULL,
  138852. NULL,
  138853. 0
  138854. };
  138855. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138856. 1,
  138857. 0,
  138858. 2,
  138859. };
  138860. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138861. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138862. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138867. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138872. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  138907. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  138912. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  138917. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138953. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138958. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138963. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0,
  139272. };
  139273. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139274. -0.5, 0.5,
  139275. };
  139276. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139277. 1, 0, 2,
  139278. };
  139279. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139280. _vq_quantthresh__44c1_sm_p1_0,
  139281. _vq_quantmap__44c1_sm_p1_0,
  139282. 3,
  139283. 3
  139284. };
  139285. static static_codebook _44c1_sm_p1_0 = {
  139286. 8, 6561,
  139287. _vq_lengthlist__44c1_sm_p1_0,
  139288. 1, -535822336, 1611661312, 2, 0,
  139289. _vq_quantlist__44c1_sm_p1_0,
  139290. NULL,
  139291. &_vq_auxt__44c1_sm_p1_0,
  139292. NULL,
  139293. 0
  139294. };
  139295. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139296. 2,
  139297. 1,
  139298. 3,
  139299. 0,
  139300. 4,
  139301. };
  139302. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139303. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0,
  139343. };
  139344. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139345. -1.5, -0.5, 0.5, 1.5,
  139346. };
  139347. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139348. 3, 1, 0, 2, 4,
  139349. };
  139350. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139351. _vq_quantthresh__44c1_sm_p2_0,
  139352. _vq_quantmap__44c1_sm_p2_0,
  139353. 5,
  139354. 5
  139355. };
  139356. static static_codebook _44c1_sm_p2_0 = {
  139357. 4, 625,
  139358. _vq_lengthlist__44c1_sm_p2_0,
  139359. 1, -533725184, 1611661312, 3, 0,
  139360. _vq_quantlist__44c1_sm_p2_0,
  139361. NULL,
  139362. &_vq_auxt__44c1_sm_p2_0,
  139363. NULL,
  139364. 0
  139365. };
  139366. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139367. 4,
  139368. 3,
  139369. 5,
  139370. 2,
  139371. 6,
  139372. 1,
  139373. 7,
  139374. 0,
  139375. 8,
  139376. };
  139377. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139378. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139379. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139380. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139381. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139382. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0,
  139384. };
  139385. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139386. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139387. };
  139388. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139389. 7, 5, 3, 1, 0, 2, 4, 6,
  139390. 8,
  139391. };
  139392. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139393. _vq_quantthresh__44c1_sm_p3_0,
  139394. _vq_quantmap__44c1_sm_p3_0,
  139395. 9,
  139396. 9
  139397. };
  139398. static static_codebook _44c1_sm_p3_0 = {
  139399. 2, 81,
  139400. _vq_lengthlist__44c1_sm_p3_0,
  139401. 1, -531628032, 1611661312, 4, 0,
  139402. _vq_quantlist__44c1_sm_p3_0,
  139403. NULL,
  139404. &_vq_auxt__44c1_sm_p3_0,
  139405. NULL,
  139406. 0
  139407. };
  139408. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139409. 4,
  139410. 3,
  139411. 5,
  139412. 2,
  139413. 6,
  139414. 1,
  139415. 7,
  139416. 0,
  139417. 8,
  139418. };
  139419. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139420. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139421. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139422. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139423. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139424. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139425. 11,
  139426. };
  139427. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139428. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139429. };
  139430. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139431. 7, 5, 3, 1, 0, 2, 4, 6,
  139432. 8,
  139433. };
  139434. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139435. _vq_quantthresh__44c1_sm_p4_0,
  139436. _vq_quantmap__44c1_sm_p4_0,
  139437. 9,
  139438. 9
  139439. };
  139440. static static_codebook _44c1_sm_p4_0 = {
  139441. 2, 81,
  139442. _vq_lengthlist__44c1_sm_p4_0,
  139443. 1, -531628032, 1611661312, 4, 0,
  139444. _vq_quantlist__44c1_sm_p4_0,
  139445. NULL,
  139446. &_vq_auxt__44c1_sm_p4_0,
  139447. NULL,
  139448. 0
  139449. };
  139450. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139451. 8,
  139452. 7,
  139453. 9,
  139454. 6,
  139455. 10,
  139456. 5,
  139457. 11,
  139458. 4,
  139459. 12,
  139460. 3,
  139461. 13,
  139462. 2,
  139463. 14,
  139464. 1,
  139465. 15,
  139466. 0,
  139467. 16,
  139468. };
  139469. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139470. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139471. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139472. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139473. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139474. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139475. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139476. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139477. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139478. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139479. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139480. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139481. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139482. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139483. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139484. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139485. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139486. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139488. 14,
  139489. };
  139490. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139491. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139492. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139493. };
  139494. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139495. 15, 13, 11, 9, 7, 5, 3, 1,
  139496. 0, 2, 4, 6, 8, 10, 12, 14,
  139497. 16,
  139498. };
  139499. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139500. _vq_quantthresh__44c1_sm_p5_0,
  139501. _vq_quantmap__44c1_sm_p5_0,
  139502. 17,
  139503. 17
  139504. };
  139505. static static_codebook _44c1_sm_p5_0 = {
  139506. 2, 289,
  139507. _vq_lengthlist__44c1_sm_p5_0,
  139508. 1, -529530880, 1611661312, 5, 0,
  139509. _vq_quantlist__44c1_sm_p5_0,
  139510. NULL,
  139511. &_vq_auxt__44c1_sm_p5_0,
  139512. NULL,
  139513. 0
  139514. };
  139515. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139516. 1,
  139517. 0,
  139518. 2,
  139519. };
  139520. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139521. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139522. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139523. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139524. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139525. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139526. 11,
  139527. };
  139528. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139529. -5.5, 5.5,
  139530. };
  139531. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139532. 1, 0, 2,
  139533. };
  139534. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139535. _vq_quantthresh__44c1_sm_p6_0,
  139536. _vq_quantmap__44c1_sm_p6_0,
  139537. 3,
  139538. 3
  139539. };
  139540. static static_codebook _44c1_sm_p6_0 = {
  139541. 4, 81,
  139542. _vq_lengthlist__44c1_sm_p6_0,
  139543. 1, -529137664, 1618345984, 2, 0,
  139544. _vq_quantlist__44c1_sm_p6_0,
  139545. NULL,
  139546. &_vq_auxt__44c1_sm_p6_0,
  139547. NULL,
  139548. 0
  139549. };
  139550. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139551. 5,
  139552. 4,
  139553. 6,
  139554. 3,
  139555. 7,
  139556. 2,
  139557. 8,
  139558. 1,
  139559. 9,
  139560. 0,
  139561. 10,
  139562. };
  139563. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139564. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139565. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139566. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139567. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139568. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139569. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139570. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139571. 10,10,10, 8, 8, 8, 8, 8, 8,
  139572. };
  139573. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139574. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139575. 3.5, 4.5,
  139576. };
  139577. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139578. 9, 7, 5, 3, 1, 0, 2, 4,
  139579. 6, 8, 10,
  139580. };
  139581. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139582. _vq_quantthresh__44c1_sm_p6_1,
  139583. _vq_quantmap__44c1_sm_p6_1,
  139584. 11,
  139585. 11
  139586. };
  139587. static static_codebook _44c1_sm_p6_1 = {
  139588. 2, 121,
  139589. _vq_lengthlist__44c1_sm_p6_1,
  139590. 1, -531365888, 1611661312, 4, 0,
  139591. _vq_quantlist__44c1_sm_p6_1,
  139592. NULL,
  139593. &_vq_auxt__44c1_sm_p6_1,
  139594. NULL,
  139595. 0
  139596. };
  139597. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139598. 6,
  139599. 5,
  139600. 7,
  139601. 4,
  139602. 8,
  139603. 3,
  139604. 9,
  139605. 2,
  139606. 10,
  139607. 1,
  139608. 11,
  139609. 0,
  139610. 12,
  139611. };
  139612. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139613. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139614. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139615. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139616. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139617. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139618. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139619. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139620. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139621. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139622. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139623. 0,12,12,11,11,13,12,14,13,
  139624. };
  139625. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139626. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139627. 12.5, 17.5, 22.5, 27.5,
  139628. };
  139629. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139630. 11, 9, 7, 5, 3, 1, 0, 2,
  139631. 4, 6, 8, 10, 12,
  139632. };
  139633. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139634. _vq_quantthresh__44c1_sm_p7_0,
  139635. _vq_quantmap__44c1_sm_p7_0,
  139636. 13,
  139637. 13
  139638. };
  139639. static static_codebook _44c1_sm_p7_0 = {
  139640. 2, 169,
  139641. _vq_lengthlist__44c1_sm_p7_0,
  139642. 1, -526516224, 1616117760, 4, 0,
  139643. _vq_quantlist__44c1_sm_p7_0,
  139644. NULL,
  139645. &_vq_auxt__44c1_sm_p7_0,
  139646. NULL,
  139647. 0
  139648. };
  139649. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139650. 2,
  139651. 1,
  139652. 3,
  139653. 0,
  139654. 4,
  139655. };
  139656. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139657. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139658. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139659. };
  139660. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139661. -1.5, -0.5, 0.5, 1.5,
  139662. };
  139663. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139664. 3, 1, 0, 2, 4,
  139665. };
  139666. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139667. _vq_quantthresh__44c1_sm_p7_1,
  139668. _vq_quantmap__44c1_sm_p7_1,
  139669. 5,
  139670. 5
  139671. };
  139672. static static_codebook _44c1_sm_p7_1 = {
  139673. 2, 25,
  139674. _vq_lengthlist__44c1_sm_p7_1,
  139675. 1, -533725184, 1611661312, 3, 0,
  139676. _vq_quantlist__44c1_sm_p7_1,
  139677. NULL,
  139678. &_vq_auxt__44c1_sm_p7_1,
  139679. NULL,
  139680. 0
  139681. };
  139682. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139683. 6,
  139684. 5,
  139685. 7,
  139686. 4,
  139687. 8,
  139688. 3,
  139689. 9,
  139690. 2,
  139691. 10,
  139692. 1,
  139693. 11,
  139694. 0,
  139695. 12,
  139696. };
  139697. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139698. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139699. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139700. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139701. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139702. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139703. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139704. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139705. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139706. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139707. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139708. 13,13,13,13,13,13,13,13,13,
  139709. };
  139710. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139711. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139712. 552.5, 773.5, 994.5, 1215.5,
  139713. };
  139714. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139715. 11, 9, 7, 5, 3, 1, 0, 2,
  139716. 4, 6, 8, 10, 12,
  139717. };
  139718. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139719. _vq_quantthresh__44c1_sm_p8_0,
  139720. _vq_quantmap__44c1_sm_p8_0,
  139721. 13,
  139722. 13
  139723. };
  139724. static static_codebook _44c1_sm_p8_0 = {
  139725. 2, 169,
  139726. _vq_lengthlist__44c1_sm_p8_0,
  139727. 1, -514541568, 1627103232, 4, 0,
  139728. _vq_quantlist__44c1_sm_p8_0,
  139729. NULL,
  139730. &_vq_auxt__44c1_sm_p8_0,
  139731. NULL,
  139732. 0
  139733. };
  139734. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139735. 6,
  139736. 5,
  139737. 7,
  139738. 4,
  139739. 8,
  139740. 3,
  139741. 9,
  139742. 2,
  139743. 10,
  139744. 1,
  139745. 11,
  139746. 0,
  139747. 12,
  139748. };
  139749. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139750. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139751. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139752. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139753. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139754. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139755. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139756. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139757. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139758. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139759. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139760. 20,13,12,12,12,14,12,14,13,
  139761. };
  139762. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139763. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139764. 42.5, 59.5, 76.5, 93.5,
  139765. };
  139766. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139767. 11, 9, 7, 5, 3, 1, 0, 2,
  139768. 4, 6, 8, 10, 12,
  139769. };
  139770. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139771. _vq_quantthresh__44c1_sm_p8_1,
  139772. _vq_quantmap__44c1_sm_p8_1,
  139773. 13,
  139774. 13
  139775. };
  139776. static static_codebook _44c1_sm_p8_1 = {
  139777. 2, 169,
  139778. _vq_lengthlist__44c1_sm_p8_1,
  139779. 1, -522616832, 1620115456, 4, 0,
  139780. _vq_quantlist__44c1_sm_p8_1,
  139781. NULL,
  139782. &_vq_auxt__44c1_sm_p8_1,
  139783. NULL,
  139784. 0
  139785. };
  139786. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139787. 8,
  139788. 7,
  139789. 9,
  139790. 6,
  139791. 10,
  139792. 5,
  139793. 11,
  139794. 4,
  139795. 12,
  139796. 3,
  139797. 13,
  139798. 2,
  139799. 14,
  139800. 1,
  139801. 15,
  139802. 0,
  139803. 16,
  139804. };
  139805. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139806. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139807. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139808. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139809. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139810. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139811. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139812. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139813. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139814. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139815. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139816. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139817. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139818. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139819. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139820. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139821. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139822. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139823. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139824. 9,
  139825. };
  139826. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139827. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139828. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139829. };
  139830. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139831. 15, 13, 11, 9, 7, 5, 3, 1,
  139832. 0, 2, 4, 6, 8, 10, 12, 14,
  139833. 16,
  139834. };
  139835. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139836. _vq_quantthresh__44c1_sm_p8_2,
  139837. _vq_quantmap__44c1_sm_p8_2,
  139838. 17,
  139839. 17
  139840. };
  139841. static static_codebook _44c1_sm_p8_2 = {
  139842. 2, 289,
  139843. _vq_lengthlist__44c1_sm_p8_2,
  139844. 1, -529530880, 1611661312, 5, 0,
  139845. _vq_quantlist__44c1_sm_p8_2,
  139846. NULL,
  139847. &_vq_auxt__44c1_sm_p8_2,
  139848. NULL,
  139849. 0
  139850. };
  139851. static long _huff_lengthlist__44c1_sm_short[] = {
  139852. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139853. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139854. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139855. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139856. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139857. 11,
  139858. };
  139859. static static_codebook _huff_book__44c1_sm_short = {
  139860. 2, 81,
  139861. _huff_lengthlist__44c1_sm_short,
  139862. 0, 0, 0, 0, 0,
  139863. NULL,
  139864. NULL,
  139865. NULL,
  139866. NULL,
  139867. 0
  139868. };
  139869. static long _huff_lengthlist__44cn1_s_long[] = {
  139870. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139871. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139872. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139873. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139874. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139875. 20,
  139876. };
  139877. static static_codebook _huff_book__44cn1_s_long = {
  139878. 2, 81,
  139879. _huff_lengthlist__44cn1_s_long,
  139880. 0, 0, 0, 0, 0,
  139881. NULL,
  139882. NULL,
  139883. NULL,
  139884. NULL,
  139885. 0
  139886. };
  139887. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139888. 1,
  139889. 0,
  139890. 2,
  139891. };
  139892. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139893. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139894. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139899. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139904. 0, 0, 0, 0, 8,10, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  139939. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  139944. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  139949. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139985. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139990. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139995. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0,
  140304. };
  140305. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140306. -0.5, 0.5,
  140307. };
  140308. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140309. 1, 0, 2,
  140310. };
  140311. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140312. _vq_quantthresh__44cn1_s_p1_0,
  140313. _vq_quantmap__44cn1_s_p1_0,
  140314. 3,
  140315. 3
  140316. };
  140317. static static_codebook _44cn1_s_p1_0 = {
  140318. 8, 6561,
  140319. _vq_lengthlist__44cn1_s_p1_0,
  140320. 1, -535822336, 1611661312, 2, 0,
  140321. _vq_quantlist__44cn1_s_p1_0,
  140322. NULL,
  140323. &_vq_auxt__44cn1_s_p1_0,
  140324. NULL,
  140325. 0
  140326. };
  140327. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140328. 2,
  140329. 1,
  140330. 3,
  140331. 0,
  140332. 4,
  140333. };
  140334. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140335. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0,
  140375. };
  140376. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140377. -1.5, -0.5, 0.5, 1.5,
  140378. };
  140379. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140380. 3, 1, 0, 2, 4,
  140381. };
  140382. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140383. _vq_quantthresh__44cn1_s_p2_0,
  140384. _vq_quantmap__44cn1_s_p2_0,
  140385. 5,
  140386. 5
  140387. };
  140388. static static_codebook _44cn1_s_p2_0 = {
  140389. 4, 625,
  140390. _vq_lengthlist__44cn1_s_p2_0,
  140391. 1, -533725184, 1611661312, 3, 0,
  140392. _vq_quantlist__44cn1_s_p2_0,
  140393. NULL,
  140394. &_vq_auxt__44cn1_s_p2_0,
  140395. NULL,
  140396. 0
  140397. };
  140398. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140399. 4,
  140400. 3,
  140401. 5,
  140402. 2,
  140403. 6,
  140404. 1,
  140405. 7,
  140406. 0,
  140407. 8,
  140408. };
  140409. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140410. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140411. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140412. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140413. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140414. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0,
  140416. };
  140417. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140418. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140419. };
  140420. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140421. 7, 5, 3, 1, 0, 2, 4, 6,
  140422. 8,
  140423. };
  140424. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140425. _vq_quantthresh__44cn1_s_p3_0,
  140426. _vq_quantmap__44cn1_s_p3_0,
  140427. 9,
  140428. 9
  140429. };
  140430. static static_codebook _44cn1_s_p3_0 = {
  140431. 2, 81,
  140432. _vq_lengthlist__44cn1_s_p3_0,
  140433. 1, -531628032, 1611661312, 4, 0,
  140434. _vq_quantlist__44cn1_s_p3_0,
  140435. NULL,
  140436. &_vq_auxt__44cn1_s_p3_0,
  140437. NULL,
  140438. 0
  140439. };
  140440. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140441. 4,
  140442. 3,
  140443. 5,
  140444. 2,
  140445. 6,
  140446. 1,
  140447. 7,
  140448. 0,
  140449. 8,
  140450. };
  140451. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140452. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140453. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140454. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140455. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140456. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140457. 11,
  140458. };
  140459. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140460. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140461. };
  140462. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140463. 7, 5, 3, 1, 0, 2, 4, 6,
  140464. 8,
  140465. };
  140466. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140467. _vq_quantthresh__44cn1_s_p4_0,
  140468. _vq_quantmap__44cn1_s_p4_0,
  140469. 9,
  140470. 9
  140471. };
  140472. static static_codebook _44cn1_s_p4_0 = {
  140473. 2, 81,
  140474. _vq_lengthlist__44cn1_s_p4_0,
  140475. 1, -531628032, 1611661312, 4, 0,
  140476. _vq_quantlist__44cn1_s_p4_0,
  140477. NULL,
  140478. &_vq_auxt__44cn1_s_p4_0,
  140479. NULL,
  140480. 0
  140481. };
  140482. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140483. 8,
  140484. 7,
  140485. 9,
  140486. 6,
  140487. 10,
  140488. 5,
  140489. 11,
  140490. 4,
  140491. 12,
  140492. 3,
  140493. 13,
  140494. 2,
  140495. 14,
  140496. 1,
  140497. 15,
  140498. 0,
  140499. 16,
  140500. };
  140501. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140502. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140503. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140504. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140505. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140506. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140507. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140508. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140509. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140510. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140511. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140512. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140513. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140514. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140515. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140516. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140517. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140518. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140520. 14,
  140521. };
  140522. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140523. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140524. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140525. };
  140526. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140527. 15, 13, 11, 9, 7, 5, 3, 1,
  140528. 0, 2, 4, 6, 8, 10, 12, 14,
  140529. 16,
  140530. };
  140531. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140532. _vq_quantthresh__44cn1_s_p5_0,
  140533. _vq_quantmap__44cn1_s_p5_0,
  140534. 17,
  140535. 17
  140536. };
  140537. static static_codebook _44cn1_s_p5_0 = {
  140538. 2, 289,
  140539. _vq_lengthlist__44cn1_s_p5_0,
  140540. 1, -529530880, 1611661312, 5, 0,
  140541. _vq_quantlist__44cn1_s_p5_0,
  140542. NULL,
  140543. &_vq_auxt__44cn1_s_p5_0,
  140544. NULL,
  140545. 0
  140546. };
  140547. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140548. 1,
  140549. 0,
  140550. 2,
  140551. };
  140552. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140553. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140554. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140555. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140556. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140557. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140558. 10,
  140559. };
  140560. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140561. -5.5, 5.5,
  140562. };
  140563. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140564. 1, 0, 2,
  140565. };
  140566. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140567. _vq_quantthresh__44cn1_s_p6_0,
  140568. _vq_quantmap__44cn1_s_p6_0,
  140569. 3,
  140570. 3
  140571. };
  140572. static static_codebook _44cn1_s_p6_0 = {
  140573. 4, 81,
  140574. _vq_lengthlist__44cn1_s_p6_0,
  140575. 1, -529137664, 1618345984, 2, 0,
  140576. _vq_quantlist__44cn1_s_p6_0,
  140577. NULL,
  140578. &_vq_auxt__44cn1_s_p6_0,
  140579. NULL,
  140580. 0
  140581. };
  140582. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140583. 5,
  140584. 4,
  140585. 6,
  140586. 3,
  140587. 7,
  140588. 2,
  140589. 8,
  140590. 1,
  140591. 9,
  140592. 0,
  140593. 10,
  140594. };
  140595. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140596. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140597. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140598. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140599. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140600. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140601. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140602. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140603. 10,10,10, 9, 9, 9, 9, 9, 9,
  140604. };
  140605. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140606. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140607. 3.5, 4.5,
  140608. };
  140609. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140610. 9, 7, 5, 3, 1, 0, 2, 4,
  140611. 6, 8, 10,
  140612. };
  140613. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140614. _vq_quantthresh__44cn1_s_p6_1,
  140615. _vq_quantmap__44cn1_s_p6_1,
  140616. 11,
  140617. 11
  140618. };
  140619. static static_codebook _44cn1_s_p6_1 = {
  140620. 2, 121,
  140621. _vq_lengthlist__44cn1_s_p6_1,
  140622. 1, -531365888, 1611661312, 4, 0,
  140623. _vq_quantlist__44cn1_s_p6_1,
  140624. NULL,
  140625. &_vq_auxt__44cn1_s_p6_1,
  140626. NULL,
  140627. 0
  140628. };
  140629. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140630. 6,
  140631. 5,
  140632. 7,
  140633. 4,
  140634. 8,
  140635. 3,
  140636. 9,
  140637. 2,
  140638. 10,
  140639. 1,
  140640. 11,
  140641. 0,
  140642. 12,
  140643. };
  140644. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140645. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140646. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140647. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140648. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140649. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140650. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140651. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140652. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140653. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140654. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140655. 0,13,13,12,12,13,13,13,14,
  140656. };
  140657. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140658. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140659. 12.5, 17.5, 22.5, 27.5,
  140660. };
  140661. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140662. 11, 9, 7, 5, 3, 1, 0, 2,
  140663. 4, 6, 8, 10, 12,
  140664. };
  140665. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140666. _vq_quantthresh__44cn1_s_p7_0,
  140667. _vq_quantmap__44cn1_s_p7_0,
  140668. 13,
  140669. 13
  140670. };
  140671. static static_codebook _44cn1_s_p7_0 = {
  140672. 2, 169,
  140673. _vq_lengthlist__44cn1_s_p7_0,
  140674. 1, -526516224, 1616117760, 4, 0,
  140675. _vq_quantlist__44cn1_s_p7_0,
  140676. NULL,
  140677. &_vq_auxt__44cn1_s_p7_0,
  140678. NULL,
  140679. 0
  140680. };
  140681. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140682. 2,
  140683. 1,
  140684. 3,
  140685. 0,
  140686. 4,
  140687. };
  140688. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140689. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140690. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140691. };
  140692. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140693. -1.5, -0.5, 0.5, 1.5,
  140694. };
  140695. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140696. 3, 1, 0, 2, 4,
  140697. };
  140698. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140699. _vq_quantthresh__44cn1_s_p7_1,
  140700. _vq_quantmap__44cn1_s_p7_1,
  140701. 5,
  140702. 5
  140703. };
  140704. static static_codebook _44cn1_s_p7_1 = {
  140705. 2, 25,
  140706. _vq_lengthlist__44cn1_s_p7_1,
  140707. 1, -533725184, 1611661312, 3, 0,
  140708. _vq_quantlist__44cn1_s_p7_1,
  140709. NULL,
  140710. &_vq_auxt__44cn1_s_p7_1,
  140711. NULL,
  140712. 0
  140713. };
  140714. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140715. 2,
  140716. 1,
  140717. 3,
  140718. 0,
  140719. 4,
  140720. };
  140721. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140722. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140723. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140725. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140729. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140731. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140737. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140745. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140755. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140756. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140757. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140758. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140759. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140760. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140761. 12,
  140762. };
  140763. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140764. -331.5, -110.5, 110.5, 331.5,
  140765. };
  140766. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140767. 3, 1, 0, 2, 4,
  140768. };
  140769. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140770. _vq_quantthresh__44cn1_s_p8_0,
  140771. _vq_quantmap__44cn1_s_p8_0,
  140772. 5,
  140773. 5
  140774. };
  140775. static static_codebook _44cn1_s_p8_0 = {
  140776. 4, 625,
  140777. _vq_lengthlist__44cn1_s_p8_0,
  140778. 1, -518283264, 1627103232, 3, 0,
  140779. _vq_quantlist__44cn1_s_p8_0,
  140780. NULL,
  140781. &_vq_auxt__44cn1_s_p8_0,
  140782. NULL,
  140783. 0
  140784. };
  140785. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140786. 6,
  140787. 5,
  140788. 7,
  140789. 4,
  140790. 8,
  140791. 3,
  140792. 9,
  140793. 2,
  140794. 10,
  140795. 1,
  140796. 11,
  140797. 0,
  140798. 12,
  140799. };
  140800. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140801. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140802. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140803. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140804. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140805. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140806. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140807. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140808. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140809. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140810. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140811. 15,12,12,11,11,14,12,13,14,
  140812. };
  140813. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140814. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140815. 42.5, 59.5, 76.5, 93.5,
  140816. };
  140817. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140818. 11, 9, 7, 5, 3, 1, 0, 2,
  140819. 4, 6, 8, 10, 12,
  140820. };
  140821. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140822. _vq_quantthresh__44cn1_s_p8_1,
  140823. _vq_quantmap__44cn1_s_p8_1,
  140824. 13,
  140825. 13
  140826. };
  140827. static static_codebook _44cn1_s_p8_1 = {
  140828. 2, 169,
  140829. _vq_lengthlist__44cn1_s_p8_1,
  140830. 1, -522616832, 1620115456, 4, 0,
  140831. _vq_quantlist__44cn1_s_p8_1,
  140832. NULL,
  140833. &_vq_auxt__44cn1_s_p8_1,
  140834. NULL,
  140835. 0
  140836. };
  140837. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140838. 8,
  140839. 7,
  140840. 9,
  140841. 6,
  140842. 10,
  140843. 5,
  140844. 11,
  140845. 4,
  140846. 12,
  140847. 3,
  140848. 13,
  140849. 2,
  140850. 14,
  140851. 1,
  140852. 15,
  140853. 0,
  140854. 16,
  140855. };
  140856. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140857. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140858. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140859. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140860. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140861. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140862. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140863. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140864. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140865. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140866. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140867. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140868. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140869. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140870. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140871. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140872. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140873. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140874. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140875. 9,
  140876. };
  140877. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140878. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140879. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140880. };
  140881. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140882. 15, 13, 11, 9, 7, 5, 3, 1,
  140883. 0, 2, 4, 6, 8, 10, 12, 14,
  140884. 16,
  140885. };
  140886. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140887. _vq_quantthresh__44cn1_s_p8_2,
  140888. _vq_quantmap__44cn1_s_p8_2,
  140889. 17,
  140890. 17
  140891. };
  140892. static static_codebook _44cn1_s_p8_2 = {
  140893. 2, 289,
  140894. _vq_lengthlist__44cn1_s_p8_2,
  140895. 1, -529530880, 1611661312, 5, 0,
  140896. _vq_quantlist__44cn1_s_p8_2,
  140897. NULL,
  140898. &_vq_auxt__44cn1_s_p8_2,
  140899. NULL,
  140900. 0
  140901. };
  140902. static long _huff_lengthlist__44cn1_s_short[] = {
  140903. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140904. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140905. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140906. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140907. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140908. 10,
  140909. };
  140910. static static_codebook _huff_book__44cn1_s_short = {
  140911. 2, 81,
  140912. _huff_lengthlist__44cn1_s_short,
  140913. 0, 0, 0, 0, 0,
  140914. NULL,
  140915. NULL,
  140916. NULL,
  140917. NULL,
  140918. 0
  140919. };
  140920. static long _huff_lengthlist__44cn1_sm_long[] = {
  140921. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140922. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140923. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140924. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140925. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140926. 17,
  140927. };
  140928. static static_codebook _huff_book__44cn1_sm_long = {
  140929. 2, 81,
  140930. _huff_lengthlist__44cn1_sm_long,
  140931. 0, 0, 0, 0, 0,
  140932. NULL,
  140933. NULL,
  140934. NULL,
  140935. NULL,
  140936. 0
  140937. };
  140938. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140939. 1,
  140940. 0,
  140941. 2,
  140942. };
  140943. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140944. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140945. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140950. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140955. 0, 0, 0, 0, 8, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  140990. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  140995. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  141000. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141036. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141041. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141046. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0,
  141355. };
  141356. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141357. -0.5, 0.5,
  141358. };
  141359. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141360. 1, 0, 2,
  141361. };
  141362. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141363. _vq_quantthresh__44cn1_sm_p1_0,
  141364. _vq_quantmap__44cn1_sm_p1_0,
  141365. 3,
  141366. 3
  141367. };
  141368. static static_codebook _44cn1_sm_p1_0 = {
  141369. 8, 6561,
  141370. _vq_lengthlist__44cn1_sm_p1_0,
  141371. 1, -535822336, 1611661312, 2, 0,
  141372. _vq_quantlist__44cn1_sm_p1_0,
  141373. NULL,
  141374. &_vq_auxt__44cn1_sm_p1_0,
  141375. NULL,
  141376. 0
  141377. };
  141378. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141379. 2,
  141380. 1,
  141381. 3,
  141382. 0,
  141383. 4,
  141384. };
  141385. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141386. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0,
  141426. };
  141427. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141428. -1.5, -0.5, 0.5, 1.5,
  141429. };
  141430. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141431. 3, 1, 0, 2, 4,
  141432. };
  141433. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141434. _vq_quantthresh__44cn1_sm_p2_0,
  141435. _vq_quantmap__44cn1_sm_p2_0,
  141436. 5,
  141437. 5
  141438. };
  141439. static static_codebook _44cn1_sm_p2_0 = {
  141440. 4, 625,
  141441. _vq_lengthlist__44cn1_sm_p2_0,
  141442. 1, -533725184, 1611661312, 3, 0,
  141443. _vq_quantlist__44cn1_sm_p2_0,
  141444. NULL,
  141445. &_vq_auxt__44cn1_sm_p2_0,
  141446. NULL,
  141447. 0
  141448. };
  141449. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141450. 4,
  141451. 3,
  141452. 5,
  141453. 2,
  141454. 6,
  141455. 1,
  141456. 7,
  141457. 0,
  141458. 8,
  141459. };
  141460. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141461. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141462. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141463. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141464. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141465. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0,
  141467. };
  141468. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141469. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141470. };
  141471. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141472. 7, 5, 3, 1, 0, 2, 4, 6,
  141473. 8,
  141474. };
  141475. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141476. _vq_quantthresh__44cn1_sm_p3_0,
  141477. _vq_quantmap__44cn1_sm_p3_0,
  141478. 9,
  141479. 9
  141480. };
  141481. static static_codebook _44cn1_sm_p3_0 = {
  141482. 2, 81,
  141483. _vq_lengthlist__44cn1_sm_p3_0,
  141484. 1, -531628032, 1611661312, 4, 0,
  141485. _vq_quantlist__44cn1_sm_p3_0,
  141486. NULL,
  141487. &_vq_auxt__44cn1_sm_p3_0,
  141488. NULL,
  141489. 0
  141490. };
  141491. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141492. 4,
  141493. 3,
  141494. 5,
  141495. 2,
  141496. 6,
  141497. 1,
  141498. 7,
  141499. 0,
  141500. 8,
  141501. };
  141502. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141503. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141504. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141505. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141506. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141507. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141508. 11,
  141509. };
  141510. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141511. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141512. };
  141513. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141514. 7, 5, 3, 1, 0, 2, 4, 6,
  141515. 8,
  141516. };
  141517. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141518. _vq_quantthresh__44cn1_sm_p4_0,
  141519. _vq_quantmap__44cn1_sm_p4_0,
  141520. 9,
  141521. 9
  141522. };
  141523. static static_codebook _44cn1_sm_p4_0 = {
  141524. 2, 81,
  141525. _vq_lengthlist__44cn1_sm_p4_0,
  141526. 1, -531628032, 1611661312, 4, 0,
  141527. _vq_quantlist__44cn1_sm_p4_0,
  141528. NULL,
  141529. &_vq_auxt__44cn1_sm_p4_0,
  141530. NULL,
  141531. 0
  141532. };
  141533. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141534. 8,
  141535. 7,
  141536. 9,
  141537. 6,
  141538. 10,
  141539. 5,
  141540. 11,
  141541. 4,
  141542. 12,
  141543. 3,
  141544. 13,
  141545. 2,
  141546. 14,
  141547. 1,
  141548. 15,
  141549. 0,
  141550. 16,
  141551. };
  141552. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141553. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141554. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141555. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141556. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141557. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141558. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141559. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141560. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141561. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141562. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141563. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141564. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141565. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141566. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141567. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141568. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141569. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141570. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141571. 14,
  141572. };
  141573. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141574. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141575. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141576. };
  141577. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141578. 15, 13, 11, 9, 7, 5, 3, 1,
  141579. 0, 2, 4, 6, 8, 10, 12, 14,
  141580. 16,
  141581. };
  141582. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141583. _vq_quantthresh__44cn1_sm_p5_0,
  141584. _vq_quantmap__44cn1_sm_p5_0,
  141585. 17,
  141586. 17
  141587. };
  141588. static static_codebook _44cn1_sm_p5_0 = {
  141589. 2, 289,
  141590. _vq_lengthlist__44cn1_sm_p5_0,
  141591. 1, -529530880, 1611661312, 5, 0,
  141592. _vq_quantlist__44cn1_sm_p5_0,
  141593. NULL,
  141594. &_vq_auxt__44cn1_sm_p5_0,
  141595. NULL,
  141596. 0
  141597. };
  141598. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141599. 1,
  141600. 0,
  141601. 2,
  141602. };
  141603. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141604. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141605. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141606. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141607. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141608. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141609. 10,
  141610. };
  141611. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141612. -5.5, 5.5,
  141613. };
  141614. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141615. 1, 0, 2,
  141616. };
  141617. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141618. _vq_quantthresh__44cn1_sm_p6_0,
  141619. _vq_quantmap__44cn1_sm_p6_0,
  141620. 3,
  141621. 3
  141622. };
  141623. static static_codebook _44cn1_sm_p6_0 = {
  141624. 4, 81,
  141625. _vq_lengthlist__44cn1_sm_p6_0,
  141626. 1, -529137664, 1618345984, 2, 0,
  141627. _vq_quantlist__44cn1_sm_p6_0,
  141628. NULL,
  141629. &_vq_auxt__44cn1_sm_p6_0,
  141630. NULL,
  141631. 0
  141632. };
  141633. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141634. 5,
  141635. 4,
  141636. 6,
  141637. 3,
  141638. 7,
  141639. 2,
  141640. 8,
  141641. 1,
  141642. 9,
  141643. 0,
  141644. 10,
  141645. };
  141646. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141647. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141648. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141649. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141650. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141651. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141652. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141653. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141654. 10,10,10, 8, 9, 8, 8, 9, 8,
  141655. };
  141656. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141657. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141658. 3.5, 4.5,
  141659. };
  141660. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141661. 9, 7, 5, 3, 1, 0, 2, 4,
  141662. 6, 8, 10,
  141663. };
  141664. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141665. _vq_quantthresh__44cn1_sm_p6_1,
  141666. _vq_quantmap__44cn1_sm_p6_1,
  141667. 11,
  141668. 11
  141669. };
  141670. static static_codebook _44cn1_sm_p6_1 = {
  141671. 2, 121,
  141672. _vq_lengthlist__44cn1_sm_p6_1,
  141673. 1, -531365888, 1611661312, 4, 0,
  141674. _vq_quantlist__44cn1_sm_p6_1,
  141675. NULL,
  141676. &_vq_auxt__44cn1_sm_p6_1,
  141677. NULL,
  141678. 0
  141679. };
  141680. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141681. 6,
  141682. 5,
  141683. 7,
  141684. 4,
  141685. 8,
  141686. 3,
  141687. 9,
  141688. 2,
  141689. 10,
  141690. 1,
  141691. 11,
  141692. 0,
  141693. 12,
  141694. };
  141695. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141696. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141697. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141698. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141699. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141700. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141701. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141702. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141703. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141704. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141705. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141706. 0,13,12,12,12,13,13,13,14,
  141707. };
  141708. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141709. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141710. 12.5, 17.5, 22.5, 27.5,
  141711. };
  141712. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141713. 11, 9, 7, 5, 3, 1, 0, 2,
  141714. 4, 6, 8, 10, 12,
  141715. };
  141716. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141717. _vq_quantthresh__44cn1_sm_p7_0,
  141718. _vq_quantmap__44cn1_sm_p7_0,
  141719. 13,
  141720. 13
  141721. };
  141722. static static_codebook _44cn1_sm_p7_0 = {
  141723. 2, 169,
  141724. _vq_lengthlist__44cn1_sm_p7_0,
  141725. 1, -526516224, 1616117760, 4, 0,
  141726. _vq_quantlist__44cn1_sm_p7_0,
  141727. NULL,
  141728. &_vq_auxt__44cn1_sm_p7_0,
  141729. NULL,
  141730. 0
  141731. };
  141732. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141733. 2,
  141734. 1,
  141735. 3,
  141736. 0,
  141737. 4,
  141738. };
  141739. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141740. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141741. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141742. };
  141743. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141744. -1.5, -0.5, 0.5, 1.5,
  141745. };
  141746. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141747. 3, 1, 0, 2, 4,
  141748. };
  141749. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141750. _vq_quantthresh__44cn1_sm_p7_1,
  141751. _vq_quantmap__44cn1_sm_p7_1,
  141752. 5,
  141753. 5
  141754. };
  141755. static static_codebook _44cn1_sm_p7_1 = {
  141756. 2, 25,
  141757. _vq_lengthlist__44cn1_sm_p7_1,
  141758. 1, -533725184, 1611661312, 3, 0,
  141759. _vq_quantlist__44cn1_sm_p7_1,
  141760. NULL,
  141761. &_vq_auxt__44cn1_sm_p7_1,
  141762. NULL,
  141763. 0
  141764. };
  141765. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141766. 4,
  141767. 3,
  141768. 5,
  141769. 2,
  141770. 6,
  141771. 1,
  141772. 7,
  141773. 0,
  141774. 8,
  141775. };
  141776. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141777. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141778. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141779. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141780. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141781. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141782. 14,
  141783. };
  141784. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141785. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141786. };
  141787. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141788. 7, 5, 3, 1, 0, 2, 4, 6,
  141789. 8,
  141790. };
  141791. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141792. _vq_quantthresh__44cn1_sm_p8_0,
  141793. _vq_quantmap__44cn1_sm_p8_0,
  141794. 9,
  141795. 9
  141796. };
  141797. static static_codebook _44cn1_sm_p8_0 = {
  141798. 2, 81,
  141799. _vq_lengthlist__44cn1_sm_p8_0,
  141800. 1, -516186112, 1627103232, 4, 0,
  141801. _vq_quantlist__44cn1_sm_p8_0,
  141802. NULL,
  141803. &_vq_auxt__44cn1_sm_p8_0,
  141804. NULL,
  141805. 0
  141806. };
  141807. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141808. 6,
  141809. 5,
  141810. 7,
  141811. 4,
  141812. 8,
  141813. 3,
  141814. 9,
  141815. 2,
  141816. 10,
  141817. 1,
  141818. 11,
  141819. 0,
  141820. 12,
  141821. };
  141822. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141823. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141824. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141825. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141826. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141827. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141828. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141829. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141830. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141831. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141832. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141833. 17,12,12,11,10,13,11,13,13,
  141834. };
  141835. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141836. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141837. 42.5, 59.5, 76.5, 93.5,
  141838. };
  141839. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141840. 11, 9, 7, 5, 3, 1, 0, 2,
  141841. 4, 6, 8, 10, 12,
  141842. };
  141843. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141844. _vq_quantthresh__44cn1_sm_p8_1,
  141845. _vq_quantmap__44cn1_sm_p8_1,
  141846. 13,
  141847. 13
  141848. };
  141849. static static_codebook _44cn1_sm_p8_1 = {
  141850. 2, 169,
  141851. _vq_lengthlist__44cn1_sm_p8_1,
  141852. 1, -522616832, 1620115456, 4, 0,
  141853. _vq_quantlist__44cn1_sm_p8_1,
  141854. NULL,
  141855. &_vq_auxt__44cn1_sm_p8_1,
  141856. NULL,
  141857. 0
  141858. };
  141859. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141860. 8,
  141861. 7,
  141862. 9,
  141863. 6,
  141864. 10,
  141865. 5,
  141866. 11,
  141867. 4,
  141868. 12,
  141869. 3,
  141870. 13,
  141871. 2,
  141872. 14,
  141873. 1,
  141874. 15,
  141875. 0,
  141876. 16,
  141877. };
  141878. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141879. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141880. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141881. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141882. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141883. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141884. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141885. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141886. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141887. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141888. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141889. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141890. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141891. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141892. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141893. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141894. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141895. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141896. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141897. 9,
  141898. };
  141899. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141900. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141901. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141902. };
  141903. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141904. 15, 13, 11, 9, 7, 5, 3, 1,
  141905. 0, 2, 4, 6, 8, 10, 12, 14,
  141906. 16,
  141907. };
  141908. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141909. _vq_quantthresh__44cn1_sm_p8_2,
  141910. _vq_quantmap__44cn1_sm_p8_2,
  141911. 17,
  141912. 17
  141913. };
  141914. static static_codebook _44cn1_sm_p8_2 = {
  141915. 2, 289,
  141916. _vq_lengthlist__44cn1_sm_p8_2,
  141917. 1, -529530880, 1611661312, 5, 0,
  141918. _vq_quantlist__44cn1_sm_p8_2,
  141919. NULL,
  141920. &_vq_auxt__44cn1_sm_p8_2,
  141921. NULL,
  141922. 0
  141923. };
  141924. static long _huff_lengthlist__44cn1_sm_short[] = {
  141925. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141926. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141927. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141928. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141929. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141930. 9,
  141931. };
  141932. static static_codebook _huff_book__44cn1_sm_short = {
  141933. 2, 81,
  141934. _huff_lengthlist__44cn1_sm_short,
  141935. 0, 0, 0, 0, 0,
  141936. NULL,
  141937. NULL,
  141938. NULL,
  141939. NULL,
  141940. 0
  141941. };
  141942. /*** End of inlined file: res_books_stereo.h ***/
  141943. /***** residue backends *********************************************/
  141944. static vorbis_info_residue0 _residue_44_low={
  141945. 0,-1, -1, 9,-1,
  141946. /* 0 1 2 3 4 5 6 7 */
  141947. {0},
  141948. {-1},
  141949. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141950. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141951. };
  141952. static vorbis_info_residue0 _residue_44_mid={
  141953. 0,-1, -1, 10,-1,
  141954. /* 0 1 2 3 4 5 6 7 8 */
  141955. {0},
  141956. {-1},
  141957. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141958. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141959. };
  141960. static vorbis_info_residue0 _residue_44_high={
  141961. 0,-1, -1, 10,-1,
  141962. /* 0 1 2 3 4 5 6 7 8 */
  141963. {0},
  141964. {-1},
  141965. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141966. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141967. };
  141968. static static_bookblock _resbook_44s_n1={
  141969. {
  141970. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141971. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141972. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141973. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141974. }
  141975. };
  141976. static static_bookblock _resbook_44sm_n1={
  141977. {
  141978. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141979. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141980. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141981. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141982. }
  141983. };
  141984. static static_bookblock _resbook_44s_0={
  141985. {
  141986. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141987. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141988. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141989. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141990. }
  141991. };
  141992. static static_bookblock _resbook_44sm_0={
  141993. {
  141994. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141995. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141996. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141997. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141998. }
  141999. };
  142000. static static_bookblock _resbook_44s_1={
  142001. {
  142002. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142003. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142004. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142005. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142006. }
  142007. };
  142008. static static_bookblock _resbook_44sm_1={
  142009. {
  142010. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142011. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142012. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142013. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142014. }
  142015. };
  142016. static static_bookblock _resbook_44s_2={
  142017. {
  142018. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142019. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142020. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142021. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142022. }
  142023. };
  142024. static static_bookblock _resbook_44s_3={
  142025. {
  142026. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142027. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142028. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142029. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142030. }
  142031. };
  142032. static static_bookblock _resbook_44s_4={
  142033. {
  142034. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142035. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142036. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142037. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142038. }
  142039. };
  142040. static static_bookblock _resbook_44s_5={
  142041. {
  142042. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142043. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142044. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142045. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142046. }
  142047. };
  142048. static static_bookblock _resbook_44s_6={
  142049. {
  142050. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142051. {0,0,&_44c6_s_p4_0},
  142052. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142053. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142054. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142055. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142056. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142057. }
  142058. };
  142059. static static_bookblock _resbook_44s_7={
  142060. {
  142061. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142062. {0,0,&_44c7_s_p4_0},
  142063. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142064. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142065. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142066. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142067. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142068. }
  142069. };
  142070. static static_bookblock _resbook_44s_8={
  142071. {
  142072. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142073. {0,0,&_44c8_s_p4_0},
  142074. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142075. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142076. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142077. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142078. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142079. }
  142080. };
  142081. static static_bookblock _resbook_44s_9={
  142082. {
  142083. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142084. {0,0,&_44c9_s_p4_0},
  142085. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142086. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142087. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142088. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142089. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142090. }
  142091. };
  142092. static vorbis_residue_template _res_44s_n1[]={
  142093. {2,0, &_residue_44_low,
  142094. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142095. &_resbook_44s_n1,&_resbook_44sm_n1},
  142096. {2,0, &_residue_44_low,
  142097. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142098. &_resbook_44s_n1,&_resbook_44sm_n1}
  142099. };
  142100. static vorbis_residue_template _res_44s_0[]={
  142101. {2,0, &_residue_44_low,
  142102. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142103. &_resbook_44s_0,&_resbook_44sm_0},
  142104. {2,0, &_residue_44_low,
  142105. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142106. &_resbook_44s_0,&_resbook_44sm_0}
  142107. };
  142108. static vorbis_residue_template _res_44s_1[]={
  142109. {2,0, &_residue_44_low,
  142110. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142111. &_resbook_44s_1,&_resbook_44sm_1},
  142112. {2,0, &_residue_44_low,
  142113. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142114. &_resbook_44s_1,&_resbook_44sm_1}
  142115. };
  142116. static vorbis_residue_template _res_44s_2[]={
  142117. {2,0, &_residue_44_mid,
  142118. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142119. &_resbook_44s_2,&_resbook_44s_2},
  142120. {2,0, &_residue_44_mid,
  142121. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142122. &_resbook_44s_2,&_resbook_44s_2}
  142123. };
  142124. static vorbis_residue_template _res_44s_3[]={
  142125. {2,0, &_residue_44_mid,
  142126. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142127. &_resbook_44s_3,&_resbook_44s_3},
  142128. {2,0, &_residue_44_mid,
  142129. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142130. &_resbook_44s_3,&_resbook_44s_3}
  142131. };
  142132. static vorbis_residue_template _res_44s_4[]={
  142133. {2,0, &_residue_44_mid,
  142134. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142135. &_resbook_44s_4,&_resbook_44s_4},
  142136. {2,0, &_residue_44_mid,
  142137. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142138. &_resbook_44s_4,&_resbook_44s_4}
  142139. };
  142140. static vorbis_residue_template _res_44s_5[]={
  142141. {2,0, &_residue_44_mid,
  142142. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142143. &_resbook_44s_5,&_resbook_44s_5},
  142144. {2,0, &_residue_44_mid,
  142145. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142146. &_resbook_44s_5,&_resbook_44s_5}
  142147. };
  142148. static vorbis_residue_template _res_44s_6[]={
  142149. {2,0, &_residue_44_high,
  142150. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142151. &_resbook_44s_6,&_resbook_44s_6},
  142152. {2,0, &_residue_44_high,
  142153. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142154. &_resbook_44s_6,&_resbook_44s_6}
  142155. };
  142156. static vorbis_residue_template _res_44s_7[]={
  142157. {2,0, &_residue_44_high,
  142158. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142159. &_resbook_44s_7,&_resbook_44s_7},
  142160. {2,0, &_residue_44_high,
  142161. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142162. &_resbook_44s_7,&_resbook_44s_7}
  142163. };
  142164. static vorbis_residue_template _res_44s_8[]={
  142165. {2,0, &_residue_44_high,
  142166. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142167. &_resbook_44s_8,&_resbook_44s_8},
  142168. {2,0, &_residue_44_high,
  142169. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142170. &_resbook_44s_8,&_resbook_44s_8}
  142171. };
  142172. static vorbis_residue_template _res_44s_9[]={
  142173. {2,0, &_residue_44_high,
  142174. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142175. &_resbook_44s_9,&_resbook_44s_9},
  142176. {2,0, &_residue_44_high,
  142177. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142178. &_resbook_44s_9,&_resbook_44s_9}
  142179. };
  142180. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142181. { _map_nominal, _res_44s_n1 }, /* -1 */
  142182. { _map_nominal, _res_44s_0 }, /* 0 */
  142183. { _map_nominal, _res_44s_1 }, /* 1 */
  142184. { _map_nominal, _res_44s_2 }, /* 2 */
  142185. { _map_nominal, _res_44s_3 }, /* 3 */
  142186. { _map_nominal, _res_44s_4 }, /* 4 */
  142187. { _map_nominal, _res_44s_5 }, /* 5 */
  142188. { _map_nominal, _res_44s_6 }, /* 6 */
  142189. { _map_nominal, _res_44s_7 }, /* 7 */
  142190. { _map_nominal, _res_44s_8 }, /* 8 */
  142191. { _map_nominal, _res_44s_9 }, /* 9 */
  142192. };
  142193. /*** End of inlined file: residue_44.h ***/
  142194. /*** Start of inlined file: psych_44.h ***/
  142195. /* preecho trigger settings *****************************************/
  142196. static vorbis_info_psy_global _psy_global_44[5]={
  142197. {8, /* lines per eighth octave */
  142198. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142199. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142200. -6.f,
  142201. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142202. },
  142203. {8, /* lines per eighth octave */
  142204. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142205. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142206. -6.f,
  142207. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142208. },
  142209. {8, /* lines per eighth octave */
  142210. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142211. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142212. -6.f,
  142213. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142214. },
  142215. {8, /* lines per eighth octave */
  142216. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142217. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142218. -6.f,
  142219. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142220. },
  142221. {8, /* lines per eighth octave */
  142222. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142223. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142224. -6.f,
  142225. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142226. },
  142227. };
  142228. /* noise compander lookups * low, mid, high quality ****************/
  142229. static compandblock _psy_compand_44[6]={
  142230. /* sub-mode Z short */
  142231. {{
  142232. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142233. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142234. 16,17,18,19,20,21,22, 23, /* 23dB */
  142235. 24,25,26,27,28,29,30, 31, /* 31dB */
  142236. 32,33,34,35,36,37,38, 39, /* 39dB */
  142237. }},
  142238. /* mode_Z nominal short */
  142239. {{
  142240. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142241. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142242. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142243. 15,16,17,17,17,18,18, 19, /* 31dB */
  142244. 19,19,20,21,22,23,24, 25, /* 39dB */
  142245. }},
  142246. /* mode A short */
  142247. {{
  142248. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142249. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142250. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142251. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142252. 11,12,13,14,15,16,17, 18, /* 39dB */
  142253. }},
  142254. /* sub-mode Z long */
  142255. {{
  142256. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142257. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142258. 16,17,18,19,20,21,22, 23, /* 23dB */
  142259. 24,25,26,27,28,29,30, 31, /* 31dB */
  142260. 32,33,34,35,36,37,38, 39, /* 39dB */
  142261. }},
  142262. /* mode_Z nominal long */
  142263. {{
  142264. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142265. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142266. 13,14,14,14,15,15,15, 15, /* 23dB */
  142267. 16,16,17,17,17,18,18, 19, /* 31dB */
  142268. 19,19,20,21,22,23,24, 25, /* 39dB */
  142269. }},
  142270. /* mode A long */
  142271. {{
  142272. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142273. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142274. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142275. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142276. 11,12,13,14,15,16,17, 18, /* 39dB */
  142277. }}
  142278. };
  142279. /* tonal masking curve level adjustments *************************/
  142280. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142281. /* 63 125 250 500 1 2 4 8 16 */
  142282. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142283. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142284. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142285. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142286. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142287. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142288. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142289. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142290. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142291. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142292. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142293. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142294. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142295. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142296. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142297. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142298. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142299. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142300. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142301. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142302. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142303. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142304. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142305. };
  142306. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142307. /* 63 125 250 500 1 2 4 8 16 */
  142308. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142309. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142310. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142311. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142312. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142313. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142314. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142315. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142316. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142317. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142318. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142319. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142320. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142321. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142322. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142323. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142324. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142325. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142326. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142327. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142328. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142329. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142330. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142331. };
  142332. /* noise bias (transition block) */
  142333. static noise3 _psy_noisebias_trans[12]={
  142334. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142335. /* -1 */
  142336. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142337. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142338. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142339. /* 0
  142340. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142341. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142342. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142343. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142344. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142345. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142346. /* 1
  142347. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142348. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142349. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142350. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142351. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142352. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142353. /* 2
  142354. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142355. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142356. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142357. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142358. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142359. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142360. /* 3
  142361. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142362. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142363. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142364. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142365. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142366. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142367. /* 4
  142368. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142369. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142370. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142371. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142372. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142373. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142374. /* 5
  142375. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142376. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142377. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142378. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142379. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142380. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142381. /* 6
  142382. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142383. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142384. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142385. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142386. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142387. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142388. /* 7
  142389. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142390. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142391. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142392. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142393. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142394. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142395. /* 8
  142396. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142397. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142398. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142399. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142400. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142401. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142402. /* 9
  142403. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142404. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142405. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142406. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142407. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142408. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142409. /* 10 */
  142410. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142411. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142412. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142413. };
  142414. /* noise bias (long block) */
  142415. static noise3 _psy_noisebias_long[12]={
  142416. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142417. /* -1 */
  142418. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142419. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142420. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142421. /* 0 */
  142422. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142423. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142424. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142425. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142426. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142427. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142428. /* 1 */
  142429. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142430. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142431. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142432. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142433. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142434. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142435. /* 2 */
  142436. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142437. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142438. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142439. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142440. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142441. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142442. /* 3 */
  142443. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142444. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142445. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142446. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142447. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142448. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142449. /* 4 */
  142450. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142451. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142452. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142453. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142454. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142455. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142456. /* 5 */
  142457. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142458. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142459. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142460. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142461. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142462. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142463. /* 6 */
  142464. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142465. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142466. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142467. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142468. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142469. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142470. /* 7 */
  142471. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142472. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142473. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142474. /* 8 */
  142475. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142476. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142477. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142478. /* 9 */
  142479. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142480. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142481. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142482. /* 10 */
  142483. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142484. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142485. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142486. };
  142487. /* noise bias (impulse block) */
  142488. static noise3 _psy_noisebias_impulse[12]={
  142489. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142490. /* -1 */
  142491. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142492. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142493. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142494. /* 0 */
  142495. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142496. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142497. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142498. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142499. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142500. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142501. /* 1 */
  142502. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142503. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142504. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142505. /* 2 */
  142506. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142507. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142508. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142509. /* 3 */
  142510. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142511. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142512. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142513. /* 4 */
  142514. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142515. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142516. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142517. /* 5 */
  142518. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142519. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142520. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142521. /* 6
  142522. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142523. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142524. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142525. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142526. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142527. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142528. /* 7 */
  142529. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142530. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142531. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142532. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142533. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142534. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142535. /* 8 */
  142536. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142537. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142538. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142539. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142540. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142541. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142542. /* 9 */
  142543. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142544. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142545. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142546. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142547. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142548. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142549. /* 10 */
  142550. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142551. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142552. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142553. };
  142554. /* noise bias (padding block) */
  142555. static noise3 _psy_noisebias_padding[12]={
  142556. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142557. /* -1 */
  142558. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142559. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142560. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142561. /* 0 */
  142562. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142563. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142564. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142565. /* 1 */
  142566. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142567. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142568. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142569. /* 2 */
  142570. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142571. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142572. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142573. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142574. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142575. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142576. /* 3 */
  142577. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142578. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142579. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142580. /* 4 */
  142581. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142582. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142583. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142584. /* 5 */
  142585. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142586. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142587. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142588. /* 6 */
  142589. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142590. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142591. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142592. /* 7 */
  142593. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142594. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142595. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142596. /* 8 */
  142597. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142598. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142599. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142600. /* 9 */
  142601. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142602. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142603. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142604. /* 10 */
  142605. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142606. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142607. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142608. };
  142609. static noiseguard _psy_noiseguards_44[4]={
  142610. {3,3,15},
  142611. {3,3,15},
  142612. {10,10,100},
  142613. {10,10,100},
  142614. };
  142615. static int _psy_tone_suppress[12]={
  142616. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142617. };
  142618. static int _psy_tone_0dB[12]={
  142619. 90,90,95,95,95,95,105,105,105,105,105,105,
  142620. };
  142621. static int _psy_noise_suppress[12]={
  142622. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142623. };
  142624. static vorbis_info_psy _psy_info_template={
  142625. /* blockflag */
  142626. -1,
  142627. /* ath_adjatt, ath_maxatt */
  142628. -140.,-140.,
  142629. /* tonemask att boost/decay,suppr,curves */
  142630. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142631. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142632. 1, -0.f, .5f, .5f, 0,0,0,
  142633. /* noiseoffset*3, noisecompand, max_curve_dB */
  142634. {{-1},{-1},{-1}},{-1},105.f,
  142635. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142636. 0,0,-1,-1,0.,
  142637. };
  142638. /* ath ****************/
  142639. static int _psy_ath_floater[12]={
  142640. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142641. };
  142642. static int _psy_ath_abs[12]={
  142643. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142644. };
  142645. /* stereo setup. These don't map directly to quality level, there's
  142646. an additional indirection as several of the below may be used in a
  142647. single bitmanaged stream
  142648. ****************/
  142649. /* various stereo possibilities */
  142650. /* stereo mode by base quality level */
  142651. static adj_stereo _psy_stereo_modes_44[12]={
  142652. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142653. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142654. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142655. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142656. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142657. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142658. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142659. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142660. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142661. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142662. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142663. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142664. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142665. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142666. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142667. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142668. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142669. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142670. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142671. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142672. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142673. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142674. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142675. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142676. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142677. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142678. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142679. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142680. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142681. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142682. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142683. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142684. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142685. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142686. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142687. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142688. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142689. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142690. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142691. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142692. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142693. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142694. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142695. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142696. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142697. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142698. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142699. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142700. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142701. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142702. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142703. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142704. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142705. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142706. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142707. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142708. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142709. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142710. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142711. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142712. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142713. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142714. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142715. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142716. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142717. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142718. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142719. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142720. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142721. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142722. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142723. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142724. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142725. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142726. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142727. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142728. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142729. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142730. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142731. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142732. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142733. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142734. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142735. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142736. };
  142737. /* tone master attenuation by base quality mode and bitrate tweak */
  142738. static att3 _psy_tone_masteratt_44[12]={
  142739. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142740. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142741. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142742. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142743. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142744. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142745. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142746. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142747. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142748. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142749. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142750. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142751. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142752. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142753. };
  142754. /* lowpass by mode **************/
  142755. static double _psy_lowpass_44[12]={
  142756. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142757. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142758. };
  142759. /* noise normalization **********/
  142760. static int _noise_start_short_44[11]={
  142761. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142762. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142763. };
  142764. static int _noise_start_long_44[11]={
  142765. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142766. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142767. };
  142768. static int _noise_part_short_44[11]={
  142769. 8,8,8,8,8,8,8,8,8,8,8
  142770. };
  142771. static int _noise_part_long_44[11]={
  142772. 32,32,32,32,32,32,32,32,32,32,32
  142773. };
  142774. static double _noise_thresh_44[11]={
  142775. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142776. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142777. };
  142778. static double _noise_thresh_5only[2]={
  142779. .5,.5,
  142780. };
  142781. /*** End of inlined file: psych_44.h ***/
  142782. static double rate_mapping_44_stereo[12]={
  142783. 22500.,32000.,40000.,48000.,56000.,64000.,
  142784. 80000.,96000.,112000.,128000.,160000.,250001.
  142785. };
  142786. static double quality_mapping_44[12]={
  142787. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142788. };
  142789. static int blocksize_short_44[11]={
  142790. 512,256,256,256,256,256,256,256,256,256,256
  142791. };
  142792. static int blocksize_long_44[11]={
  142793. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142794. };
  142795. static double _psy_compand_short_mapping[12]={
  142796. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142797. };
  142798. static double _psy_compand_long_mapping[12]={
  142799. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142800. };
  142801. static double _global_mapping_44[12]={
  142802. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142803. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142804. };
  142805. static int _floor_short_mapping_44[11]={
  142806. 1,0,0,2,2,4,5,5,5,5,5
  142807. };
  142808. static int _floor_long_mapping_44[11]={
  142809. 8,7,7,7,7,7,7,7,7,7,7
  142810. };
  142811. ve_setup_data_template ve_setup_44_stereo={
  142812. 11,
  142813. rate_mapping_44_stereo,
  142814. quality_mapping_44,
  142815. 2,
  142816. 40000,
  142817. 50000,
  142818. blocksize_short_44,
  142819. blocksize_long_44,
  142820. _psy_tone_masteratt_44,
  142821. _psy_tone_0dB,
  142822. _psy_tone_suppress,
  142823. _vp_tonemask_adj_otherblock,
  142824. _vp_tonemask_adj_longblock,
  142825. _vp_tonemask_adj_otherblock,
  142826. _psy_noiseguards_44,
  142827. _psy_noisebias_impulse,
  142828. _psy_noisebias_padding,
  142829. _psy_noisebias_trans,
  142830. _psy_noisebias_long,
  142831. _psy_noise_suppress,
  142832. _psy_compand_44,
  142833. _psy_compand_short_mapping,
  142834. _psy_compand_long_mapping,
  142835. {_noise_start_short_44,_noise_start_long_44},
  142836. {_noise_part_short_44,_noise_part_long_44},
  142837. _noise_thresh_44,
  142838. _psy_ath_floater,
  142839. _psy_ath_abs,
  142840. _psy_lowpass_44,
  142841. _psy_global_44,
  142842. _global_mapping_44,
  142843. _psy_stereo_modes_44,
  142844. _floor_books,
  142845. _floor,
  142846. _floor_short_mapping_44,
  142847. _floor_long_mapping_44,
  142848. _mapres_template_44_stereo
  142849. };
  142850. /*** End of inlined file: setup_44.h ***/
  142851. /*** Start of inlined file: setup_44u.h ***/
  142852. /*** Start of inlined file: residue_44u.h ***/
  142853. /*** Start of inlined file: res_books_uncoupled.h ***/
  142854. static long _vq_quantlist__16u0__p1_0[] = {
  142855. 1,
  142856. 0,
  142857. 2,
  142858. };
  142859. static long _vq_lengthlist__16u0__p1_0[] = {
  142860. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142861. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142862. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142863. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142864. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142865. 12,
  142866. };
  142867. static float _vq_quantthresh__16u0__p1_0[] = {
  142868. -0.5, 0.5,
  142869. };
  142870. static long _vq_quantmap__16u0__p1_0[] = {
  142871. 1, 0, 2,
  142872. };
  142873. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142874. _vq_quantthresh__16u0__p1_0,
  142875. _vq_quantmap__16u0__p1_0,
  142876. 3,
  142877. 3
  142878. };
  142879. static static_codebook _16u0__p1_0 = {
  142880. 4, 81,
  142881. _vq_lengthlist__16u0__p1_0,
  142882. 1, -535822336, 1611661312, 2, 0,
  142883. _vq_quantlist__16u0__p1_0,
  142884. NULL,
  142885. &_vq_auxt__16u0__p1_0,
  142886. NULL,
  142887. 0
  142888. };
  142889. static long _vq_quantlist__16u0__p2_0[] = {
  142890. 1,
  142891. 0,
  142892. 2,
  142893. };
  142894. static long _vq_lengthlist__16u0__p2_0[] = {
  142895. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142896. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142897. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142898. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142899. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142900. 8,
  142901. };
  142902. static float _vq_quantthresh__16u0__p2_0[] = {
  142903. -0.5, 0.5,
  142904. };
  142905. static long _vq_quantmap__16u0__p2_0[] = {
  142906. 1, 0, 2,
  142907. };
  142908. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142909. _vq_quantthresh__16u0__p2_0,
  142910. _vq_quantmap__16u0__p2_0,
  142911. 3,
  142912. 3
  142913. };
  142914. static static_codebook _16u0__p2_0 = {
  142915. 4, 81,
  142916. _vq_lengthlist__16u0__p2_0,
  142917. 1, -535822336, 1611661312, 2, 0,
  142918. _vq_quantlist__16u0__p2_0,
  142919. NULL,
  142920. &_vq_auxt__16u0__p2_0,
  142921. NULL,
  142922. 0
  142923. };
  142924. static long _vq_quantlist__16u0__p3_0[] = {
  142925. 2,
  142926. 1,
  142927. 3,
  142928. 0,
  142929. 4,
  142930. };
  142931. static long _vq_lengthlist__16u0__p3_0[] = {
  142932. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142933. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142934. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142935. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142936. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142937. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142938. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142939. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142940. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142941. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142942. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142943. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142944. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142945. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142946. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142947. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142948. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142949. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142950. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142951. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142952. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142953. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142954. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142955. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142956. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142957. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142958. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142959. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142960. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142961. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142962. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142963. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142964. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142965. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142966. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142967. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142968. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142969. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142970. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142971. 18,
  142972. };
  142973. static float _vq_quantthresh__16u0__p3_0[] = {
  142974. -1.5, -0.5, 0.5, 1.5,
  142975. };
  142976. static long _vq_quantmap__16u0__p3_0[] = {
  142977. 3, 1, 0, 2, 4,
  142978. };
  142979. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142980. _vq_quantthresh__16u0__p3_0,
  142981. _vq_quantmap__16u0__p3_0,
  142982. 5,
  142983. 5
  142984. };
  142985. static static_codebook _16u0__p3_0 = {
  142986. 4, 625,
  142987. _vq_lengthlist__16u0__p3_0,
  142988. 1, -533725184, 1611661312, 3, 0,
  142989. _vq_quantlist__16u0__p3_0,
  142990. NULL,
  142991. &_vq_auxt__16u0__p3_0,
  142992. NULL,
  142993. 0
  142994. };
  142995. static long _vq_quantlist__16u0__p4_0[] = {
  142996. 2,
  142997. 1,
  142998. 3,
  142999. 0,
  143000. 4,
  143001. };
  143002. static long _vq_lengthlist__16u0__p4_0[] = {
  143003. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143004. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143005. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143006. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143007. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143008. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143009. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143010. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143011. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143012. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143013. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143014. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143015. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143016. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143017. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143018. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143019. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143020. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143021. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143022. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143023. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143024. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143025. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143026. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143027. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143028. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143029. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143030. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143031. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143032. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143033. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143034. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143035. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143036. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143037. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143038. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143039. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143040. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143041. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143042. 11,
  143043. };
  143044. static float _vq_quantthresh__16u0__p4_0[] = {
  143045. -1.5, -0.5, 0.5, 1.5,
  143046. };
  143047. static long _vq_quantmap__16u0__p4_0[] = {
  143048. 3, 1, 0, 2, 4,
  143049. };
  143050. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143051. _vq_quantthresh__16u0__p4_0,
  143052. _vq_quantmap__16u0__p4_0,
  143053. 5,
  143054. 5
  143055. };
  143056. static static_codebook _16u0__p4_0 = {
  143057. 4, 625,
  143058. _vq_lengthlist__16u0__p4_0,
  143059. 1, -533725184, 1611661312, 3, 0,
  143060. _vq_quantlist__16u0__p4_0,
  143061. NULL,
  143062. &_vq_auxt__16u0__p4_0,
  143063. NULL,
  143064. 0
  143065. };
  143066. static long _vq_quantlist__16u0__p5_0[] = {
  143067. 4,
  143068. 3,
  143069. 5,
  143070. 2,
  143071. 6,
  143072. 1,
  143073. 7,
  143074. 0,
  143075. 8,
  143076. };
  143077. static long _vq_lengthlist__16u0__p5_0[] = {
  143078. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143079. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143080. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143081. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143082. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143083. 12,
  143084. };
  143085. static float _vq_quantthresh__16u0__p5_0[] = {
  143086. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143087. };
  143088. static long _vq_quantmap__16u0__p5_0[] = {
  143089. 7, 5, 3, 1, 0, 2, 4, 6,
  143090. 8,
  143091. };
  143092. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143093. _vq_quantthresh__16u0__p5_0,
  143094. _vq_quantmap__16u0__p5_0,
  143095. 9,
  143096. 9
  143097. };
  143098. static static_codebook _16u0__p5_0 = {
  143099. 2, 81,
  143100. _vq_lengthlist__16u0__p5_0,
  143101. 1, -531628032, 1611661312, 4, 0,
  143102. _vq_quantlist__16u0__p5_0,
  143103. NULL,
  143104. &_vq_auxt__16u0__p5_0,
  143105. NULL,
  143106. 0
  143107. };
  143108. static long _vq_quantlist__16u0__p6_0[] = {
  143109. 6,
  143110. 5,
  143111. 7,
  143112. 4,
  143113. 8,
  143114. 3,
  143115. 9,
  143116. 2,
  143117. 10,
  143118. 1,
  143119. 11,
  143120. 0,
  143121. 12,
  143122. };
  143123. static long _vq_lengthlist__16u0__p6_0[] = {
  143124. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143125. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143126. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143127. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143128. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143129. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143130. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143131. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143132. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143133. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143134. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143135. };
  143136. static float _vq_quantthresh__16u0__p6_0[] = {
  143137. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143138. 12.5, 17.5, 22.5, 27.5,
  143139. };
  143140. static long _vq_quantmap__16u0__p6_0[] = {
  143141. 11, 9, 7, 5, 3, 1, 0, 2,
  143142. 4, 6, 8, 10, 12,
  143143. };
  143144. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143145. _vq_quantthresh__16u0__p6_0,
  143146. _vq_quantmap__16u0__p6_0,
  143147. 13,
  143148. 13
  143149. };
  143150. static static_codebook _16u0__p6_0 = {
  143151. 2, 169,
  143152. _vq_lengthlist__16u0__p6_0,
  143153. 1, -526516224, 1616117760, 4, 0,
  143154. _vq_quantlist__16u0__p6_0,
  143155. NULL,
  143156. &_vq_auxt__16u0__p6_0,
  143157. NULL,
  143158. 0
  143159. };
  143160. static long _vq_quantlist__16u0__p6_1[] = {
  143161. 2,
  143162. 1,
  143163. 3,
  143164. 0,
  143165. 4,
  143166. };
  143167. static long _vq_lengthlist__16u0__p6_1[] = {
  143168. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143169. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143170. };
  143171. static float _vq_quantthresh__16u0__p6_1[] = {
  143172. -1.5, -0.5, 0.5, 1.5,
  143173. };
  143174. static long _vq_quantmap__16u0__p6_1[] = {
  143175. 3, 1, 0, 2, 4,
  143176. };
  143177. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143178. _vq_quantthresh__16u0__p6_1,
  143179. _vq_quantmap__16u0__p6_1,
  143180. 5,
  143181. 5
  143182. };
  143183. static static_codebook _16u0__p6_1 = {
  143184. 2, 25,
  143185. _vq_lengthlist__16u0__p6_1,
  143186. 1, -533725184, 1611661312, 3, 0,
  143187. _vq_quantlist__16u0__p6_1,
  143188. NULL,
  143189. &_vq_auxt__16u0__p6_1,
  143190. NULL,
  143191. 0
  143192. };
  143193. static long _vq_quantlist__16u0__p7_0[] = {
  143194. 1,
  143195. 0,
  143196. 2,
  143197. };
  143198. static long _vq_lengthlist__16u0__p7_0[] = {
  143199. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143200. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143201. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143202. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143203. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143204. 7,
  143205. };
  143206. static float _vq_quantthresh__16u0__p7_0[] = {
  143207. -157.5, 157.5,
  143208. };
  143209. static long _vq_quantmap__16u0__p7_0[] = {
  143210. 1, 0, 2,
  143211. };
  143212. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143213. _vq_quantthresh__16u0__p7_0,
  143214. _vq_quantmap__16u0__p7_0,
  143215. 3,
  143216. 3
  143217. };
  143218. static static_codebook _16u0__p7_0 = {
  143219. 4, 81,
  143220. _vq_lengthlist__16u0__p7_0,
  143221. 1, -518803456, 1628680192, 2, 0,
  143222. _vq_quantlist__16u0__p7_0,
  143223. NULL,
  143224. &_vq_auxt__16u0__p7_0,
  143225. NULL,
  143226. 0
  143227. };
  143228. static long _vq_quantlist__16u0__p7_1[] = {
  143229. 7,
  143230. 6,
  143231. 8,
  143232. 5,
  143233. 9,
  143234. 4,
  143235. 10,
  143236. 3,
  143237. 11,
  143238. 2,
  143239. 12,
  143240. 1,
  143241. 13,
  143242. 0,
  143243. 14,
  143244. };
  143245. static long _vq_lengthlist__16u0__p7_1[] = {
  143246. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143247. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143248. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143249. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143250. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143251. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143252. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143253. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143254. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143255. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143256. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143257. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143258. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143259. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143260. 10,
  143261. };
  143262. static float _vq_quantthresh__16u0__p7_1[] = {
  143263. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143264. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143265. };
  143266. static long _vq_quantmap__16u0__p7_1[] = {
  143267. 13, 11, 9, 7, 5, 3, 1, 0,
  143268. 2, 4, 6, 8, 10, 12, 14,
  143269. };
  143270. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143271. _vq_quantthresh__16u0__p7_1,
  143272. _vq_quantmap__16u0__p7_1,
  143273. 15,
  143274. 15
  143275. };
  143276. static static_codebook _16u0__p7_1 = {
  143277. 2, 225,
  143278. _vq_lengthlist__16u0__p7_1,
  143279. 1, -520986624, 1620377600, 4, 0,
  143280. _vq_quantlist__16u0__p7_1,
  143281. NULL,
  143282. &_vq_auxt__16u0__p7_1,
  143283. NULL,
  143284. 0
  143285. };
  143286. static long _vq_quantlist__16u0__p7_2[] = {
  143287. 10,
  143288. 9,
  143289. 11,
  143290. 8,
  143291. 12,
  143292. 7,
  143293. 13,
  143294. 6,
  143295. 14,
  143296. 5,
  143297. 15,
  143298. 4,
  143299. 16,
  143300. 3,
  143301. 17,
  143302. 2,
  143303. 18,
  143304. 1,
  143305. 19,
  143306. 0,
  143307. 20,
  143308. };
  143309. static long _vq_lengthlist__16u0__p7_2[] = {
  143310. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143311. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143312. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143313. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143314. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143315. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143316. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143317. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143318. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143319. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143320. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143321. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143322. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143323. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143324. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143325. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143326. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143327. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143328. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143329. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143330. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143331. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143332. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143333. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143334. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143335. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143336. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143337. 10,10,12,11,10,11,11,11,10,
  143338. };
  143339. static float _vq_quantthresh__16u0__p7_2[] = {
  143340. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143341. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143342. 6.5, 7.5, 8.5, 9.5,
  143343. };
  143344. static long _vq_quantmap__16u0__p7_2[] = {
  143345. 19, 17, 15, 13, 11, 9, 7, 5,
  143346. 3, 1, 0, 2, 4, 6, 8, 10,
  143347. 12, 14, 16, 18, 20,
  143348. };
  143349. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143350. _vq_quantthresh__16u0__p7_2,
  143351. _vq_quantmap__16u0__p7_2,
  143352. 21,
  143353. 21
  143354. };
  143355. static static_codebook _16u0__p7_2 = {
  143356. 2, 441,
  143357. _vq_lengthlist__16u0__p7_2,
  143358. 1, -529268736, 1611661312, 5, 0,
  143359. _vq_quantlist__16u0__p7_2,
  143360. NULL,
  143361. &_vq_auxt__16u0__p7_2,
  143362. NULL,
  143363. 0
  143364. };
  143365. static long _huff_lengthlist__16u0__single[] = {
  143366. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143367. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143368. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143369. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143370. };
  143371. static static_codebook _huff_book__16u0__single = {
  143372. 2, 64,
  143373. _huff_lengthlist__16u0__single,
  143374. 0, 0, 0, 0, 0,
  143375. NULL,
  143376. NULL,
  143377. NULL,
  143378. NULL,
  143379. 0
  143380. };
  143381. static long _huff_lengthlist__16u1__long[] = {
  143382. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143383. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143384. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143385. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143386. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143387. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143388. 16,13,16,18,
  143389. };
  143390. static static_codebook _huff_book__16u1__long = {
  143391. 2, 100,
  143392. _huff_lengthlist__16u1__long,
  143393. 0, 0, 0, 0, 0,
  143394. NULL,
  143395. NULL,
  143396. NULL,
  143397. NULL,
  143398. 0
  143399. };
  143400. static long _vq_quantlist__16u1__p1_0[] = {
  143401. 1,
  143402. 0,
  143403. 2,
  143404. };
  143405. static long _vq_lengthlist__16u1__p1_0[] = {
  143406. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143407. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143408. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143409. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143410. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143411. 11,
  143412. };
  143413. static float _vq_quantthresh__16u1__p1_0[] = {
  143414. -0.5, 0.5,
  143415. };
  143416. static long _vq_quantmap__16u1__p1_0[] = {
  143417. 1, 0, 2,
  143418. };
  143419. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143420. _vq_quantthresh__16u1__p1_0,
  143421. _vq_quantmap__16u1__p1_0,
  143422. 3,
  143423. 3
  143424. };
  143425. static static_codebook _16u1__p1_0 = {
  143426. 4, 81,
  143427. _vq_lengthlist__16u1__p1_0,
  143428. 1, -535822336, 1611661312, 2, 0,
  143429. _vq_quantlist__16u1__p1_0,
  143430. NULL,
  143431. &_vq_auxt__16u1__p1_0,
  143432. NULL,
  143433. 0
  143434. };
  143435. static long _vq_quantlist__16u1__p2_0[] = {
  143436. 1,
  143437. 0,
  143438. 2,
  143439. };
  143440. static long _vq_lengthlist__16u1__p2_0[] = {
  143441. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143442. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143443. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143444. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143445. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143446. 8,
  143447. };
  143448. static float _vq_quantthresh__16u1__p2_0[] = {
  143449. -0.5, 0.5,
  143450. };
  143451. static long _vq_quantmap__16u1__p2_0[] = {
  143452. 1, 0, 2,
  143453. };
  143454. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143455. _vq_quantthresh__16u1__p2_0,
  143456. _vq_quantmap__16u1__p2_0,
  143457. 3,
  143458. 3
  143459. };
  143460. static static_codebook _16u1__p2_0 = {
  143461. 4, 81,
  143462. _vq_lengthlist__16u1__p2_0,
  143463. 1, -535822336, 1611661312, 2, 0,
  143464. _vq_quantlist__16u1__p2_0,
  143465. NULL,
  143466. &_vq_auxt__16u1__p2_0,
  143467. NULL,
  143468. 0
  143469. };
  143470. static long _vq_quantlist__16u1__p3_0[] = {
  143471. 2,
  143472. 1,
  143473. 3,
  143474. 0,
  143475. 4,
  143476. };
  143477. static long _vq_lengthlist__16u1__p3_0[] = {
  143478. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143479. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143480. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143481. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143482. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143483. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143484. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143485. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143486. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143487. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143488. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143489. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143490. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143491. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143492. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143493. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143494. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143495. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143496. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143497. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143498. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143499. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143500. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143501. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143502. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143503. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143504. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143505. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143506. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143507. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143508. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143509. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143510. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143511. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143512. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143513. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143514. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143515. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143516. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143517. 16,
  143518. };
  143519. static float _vq_quantthresh__16u1__p3_0[] = {
  143520. -1.5, -0.5, 0.5, 1.5,
  143521. };
  143522. static long _vq_quantmap__16u1__p3_0[] = {
  143523. 3, 1, 0, 2, 4,
  143524. };
  143525. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143526. _vq_quantthresh__16u1__p3_0,
  143527. _vq_quantmap__16u1__p3_0,
  143528. 5,
  143529. 5
  143530. };
  143531. static static_codebook _16u1__p3_0 = {
  143532. 4, 625,
  143533. _vq_lengthlist__16u1__p3_0,
  143534. 1, -533725184, 1611661312, 3, 0,
  143535. _vq_quantlist__16u1__p3_0,
  143536. NULL,
  143537. &_vq_auxt__16u1__p3_0,
  143538. NULL,
  143539. 0
  143540. };
  143541. static long _vq_quantlist__16u1__p4_0[] = {
  143542. 2,
  143543. 1,
  143544. 3,
  143545. 0,
  143546. 4,
  143547. };
  143548. static long _vq_lengthlist__16u1__p4_0[] = {
  143549. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143550. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143551. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143552. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143553. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143554. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143555. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143556. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143557. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143558. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143559. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143560. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143561. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143562. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143563. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143564. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143565. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143566. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143567. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143568. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143569. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143570. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143571. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143572. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143573. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143574. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143575. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143576. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143577. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143578. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143579. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143580. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143581. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143582. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143583. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143584. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143585. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143586. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143587. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143588. 11,
  143589. };
  143590. static float _vq_quantthresh__16u1__p4_0[] = {
  143591. -1.5, -0.5, 0.5, 1.5,
  143592. };
  143593. static long _vq_quantmap__16u1__p4_0[] = {
  143594. 3, 1, 0, 2, 4,
  143595. };
  143596. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143597. _vq_quantthresh__16u1__p4_0,
  143598. _vq_quantmap__16u1__p4_0,
  143599. 5,
  143600. 5
  143601. };
  143602. static static_codebook _16u1__p4_0 = {
  143603. 4, 625,
  143604. _vq_lengthlist__16u1__p4_0,
  143605. 1, -533725184, 1611661312, 3, 0,
  143606. _vq_quantlist__16u1__p4_0,
  143607. NULL,
  143608. &_vq_auxt__16u1__p4_0,
  143609. NULL,
  143610. 0
  143611. };
  143612. static long _vq_quantlist__16u1__p5_0[] = {
  143613. 4,
  143614. 3,
  143615. 5,
  143616. 2,
  143617. 6,
  143618. 1,
  143619. 7,
  143620. 0,
  143621. 8,
  143622. };
  143623. static long _vq_lengthlist__16u1__p5_0[] = {
  143624. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143625. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143626. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143627. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143628. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143629. 13,
  143630. };
  143631. static float _vq_quantthresh__16u1__p5_0[] = {
  143632. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143633. };
  143634. static long _vq_quantmap__16u1__p5_0[] = {
  143635. 7, 5, 3, 1, 0, 2, 4, 6,
  143636. 8,
  143637. };
  143638. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143639. _vq_quantthresh__16u1__p5_0,
  143640. _vq_quantmap__16u1__p5_0,
  143641. 9,
  143642. 9
  143643. };
  143644. static static_codebook _16u1__p5_0 = {
  143645. 2, 81,
  143646. _vq_lengthlist__16u1__p5_0,
  143647. 1, -531628032, 1611661312, 4, 0,
  143648. _vq_quantlist__16u1__p5_0,
  143649. NULL,
  143650. &_vq_auxt__16u1__p5_0,
  143651. NULL,
  143652. 0
  143653. };
  143654. static long _vq_quantlist__16u1__p6_0[] = {
  143655. 4,
  143656. 3,
  143657. 5,
  143658. 2,
  143659. 6,
  143660. 1,
  143661. 7,
  143662. 0,
  143663. 8,
  143664. };
  143665. static long _vq_lengthlist__16u1__p6_0[] = {
  143666. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143667. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143668. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143669. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143670. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143671. 11,
  143672. };
  143673. static float _vq_quantthresh__16u1__p6_0[] = {
  143674. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143675. };
  143676. static long _vq_quantmap__16u1__p6_0[] = {
  143677. 7, 5, 3, 1, 0, 2, 4, 6,
  143678. 8,
  143679. };
  143680. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143681. _vq_quantthresh__16u1__p6_0,
  143682. _vq_quantmap__16u1__p6_0,
  143683. 9,
  143684. 9
  143685. };
  143686. static static_codebook _16u1__p6_0 = {
  143687. 2, 81,
  143688. _vq_lengthlist__16u1__p6_0,
  143689. 1, -531628032, 1611661312, 4, 0,
  143690. _vq_quantlist__16u1__p6_0,
  143691. NULL,
  143692. &_vq_auxt__16u1__p6_0,
  143693. NULL,
  143694. 0
  143695. };
  143696. static long _vq_quantlist__16u1__p7_0[] = {
  143697. 1,
  143698. 0,
  143699. 2,
  143700. };
  143701. static long _vq_lengthlist__16u1__p7_0[] = {
  143702. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143703. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143704. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143705. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143706. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143707. 13,
  143708. };
  143709. static float _vq_quantthresh__16u1__p7_0[] = {
  143710. -5.5, 5.5,
  143711. };
  143712. static long _vq_quantmap__16u1__p7_0[] = {
  143713. 1, 0, 2,
  143714. };
  143715. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143716. _vq_quantthresh__16u1__p7_0,
  143717. _vq_quantmap__16u1__p7_0,
  143718. 3,
  143719. 3
  143720. };
  143721. static static_codebook _16u1__p7_0 = {
  143722. 4, 81,
  143723. _vq_lengthlist__16u1__p7_0,
  143724. 1, -529137664, 1618345984, 2, 0,
  143725. _vq_quantlist__16u1__p7_0,
  143726. NULL,
  143727. &_vq_auxt__16u1__p7_0,
  143728. NULL,
  143729. 0
  143730. };
  143731. static long _vq_quantlist__16u1__p7_1[] = {
  143732. 5,
  143733. 4,
  143734. 6,
  143735. 3,
  143736. 7,
  143737. 2,
  143738. 8,
  143739. 1,
  143740. 9,
  143741. 0,
  143742. 10,
  143743. };
  143744. static long _vq_lengthlist__16u1__p7_1[] = {
  143745. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143746. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143747. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143748. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143749. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143750. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143751. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143752. 8, 9, 9,10,10,10,10,10,10,
  143753. };
  143754. static float _vq_quantthresh__16u1__p7_1[] = {
  143755. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143756. 3.5, 4.5,
  143757. };
  143758. static long _vq_quantmap__16u1__p7_1[] = {
  143759. 9, 7, 5, 3, 1, 0, 2, 4,
  143760. 6, 8, 10,
  143761. };
  143762. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143763. _vq_quantthresh__16u1__p7_1,
  143764. _vq_quantmap__16u1__p7_1,
  143765. 11,
  143766. 11
  143767. };
  143768. static static_codebook _16u1__p7_1 = {
  143769. 2, 121,
  143770. _vq_lengthlist__16u1__p7_1,
  143771. 1, -531365888, 1611661312, 4, 0,
  143772. _vq_quantlist__16u1__p7_1,
  143773. NULL,
  143774. &_vq_auxt__16u1__p7_1,
  143775. NULL,
  143776. 0
  143777. };
  143778. static long _vq_quantlist__16u1__p8_0[] = {
  143779. 5,
  143780. 4,
  143781. 6,
  143782. 3,
  143783. 7,
  143784. 2,
  143785. 8,
  143786. 1,
  143787. 9,
  143788. 0,
  143789. 10,
  143790. };
  143791. static long _vq_lengthlist__16u1__p8_0[] = {
  143792. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143793. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143794. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143795. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143796. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143797. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143798. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143799. 13,14,14,15,15,16,16,15,16,
  143800. };
  143801. static float _vq_quantthresh__16u1__p8_0[] = {
  143802. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143803. 38.5, 49.5,
  143804. };
  143805. static long _vq_quantmap__16u1__p8_0[] = {
  143806. 9, 7, 5, 3, 1, 0, 2, 4,
  143807. 6, 8, 10,
  143808. };
  143809. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143810. _vq_quantthresh__16u1__p8_0,
  143811. _vq_quantmap__16u1__p8_0,
  143812. 11,
  143813. 11
  143814. };
  143815. static static_codebook _16u1__p8_0 = {
  143816. 2, 121,
  143817. _vq_lengthlist__16u1__p8_0,
  143818. 1, -524582912, 1618345984, 4, 0,
  143819. _vq_quantlist__16u1__p8_0,
  143820. NULL,
  143821. &_vq_auxt__16u1__p8_0,
  143822. NULL,
  143823. 0
  143824. };
  143825. static long _vq_quantlist__16u1__p8_1[] = {
  143826. 5,
  143827. 4,
  143828. 6,
  143829. 3,
  143830. 7,
  143831. 2,
  143832. 8,
  143833. 1,
  143834. 9,
  143835. 0,
  143836. 10,
  143837. };
  143838. static long _vq_lengthlist__16u1__p8_1[] = {
  143839. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143840. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143841. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143842. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143843. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143844. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143845. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143846. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143847. };
  143848. static float _vq_quantthresh__16u1__p8_1[] = {
  143849. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143850. 3.5, 4.5,
  143851. };
  143852. static long _vq_quantmap__16u1__p8_1[] = {
  143853. 9, 7, 5, 3, 1, 0, 2, 4,
  143854. 6, 8, 10,
  143855. };
  143856. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143857. _vq_quantthresh__16u1__p8_1,
  143858. _vq_quantmap__16u1__p8_1,
  143859. 11,
  143860. 11
  143861. };
  143862. static static_codebook _16u1__p8_1 = {
  143863. 2, 121,
  143864. _vq_lengthlist__16u1__p8_1,
  143865. 1, -531365888, 1611661312, 4, 0,
  143866. _vq_quantlist__16u1__p8_1,
  143867. NULL,
  143868. &_vq_auxt__16u1__p8_1,
  143869. NULL,
  143870. 0
  143871. };
  143872. static long _vq_quantlist__16u1__p9_0[] = {
  143873. 7,
  143874. 6,
  143875. 8,
  143876. 5,
  143877. 9,
  143878. 4,
  143879. 10,
  143880. 3,
  143881. 11,
  143882. 2,
  143883. 12,
  143884. 1,
  143885. 13,
  143886. 0,
  143887. 14,
  143888. };
  143889. static long _vq_lengthlist__16u1__p9_0[] = {
  143890. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143891. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143892. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143893. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143894. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143895. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143896. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143897. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143898. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143899. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143900. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143901. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143902. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143903. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143904. 8,
  143905. };
  143906. static float _vq_quantthresh__16u1__p9_0[] = {
  143907. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143908. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143909. };
  143910. static long _vq_quantmap__16u1__p9_0[] = {
  143911. 13, 11, 9, 7, 5, 3, 1, 0,
  143912. 2, 4, 6, 8, 10, 12, 14,
  143913. };
  143914. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143915. _vq_quantthresh__16u1__p9_0,
  143916. _vq_quantmap__16u1__p9_0,
  143917. 15,
  143918. 15
  143919. };
  143920. static static_codebook _16u1__p9_0 = {
  143921. 2, 225,
  143922. _vq_lengthlist__16u1__p9_0,
  143923. 1, -514071552, 1627381760, 4, 0,
  143924. _vq_quantlist__16u1__p9_0,
  143925. NULL,
  143926. &_vq_auxt__16u1__p9_0,
  143927. NULL,
  143928. 0
  143929. };
  143930. static long _vq_quantlist__16u1__p9_1[] = {
  143931. 7,
  143932. 6,
  143933. 8,
  143934. 5,
  143935. 9,
  143936. 4,
  143937. 10,
  143938. 3,
  143939. 11,
  143940. 2,
  143941. 12,
  143942. 1,
  143943. 13,
  143944. 0,
  143945. 14,
  143946. };
  143947. static long _vq_lengthlist__16u1__p9_1[] = {
  143948. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143949. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143950. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143951. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143952. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143953. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143954. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143955. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143956. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143957. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143958. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143959. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143960. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143961. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143962. 9,
  143963. };
  143964. static float _vq_quantthresh__16u1__p9_1[] = {
  143965. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143966. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143967. };
  143968. static long _vq_quantmap__16u1__p9_1[] = {
  143969. 13, 11, 9, 7, 5, 3, 1, 0,
  143970. 2, 4, 6, 8, 10, 12, 14,
  143971. };
  143972. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143973. _vq_quantthresh__16u1__p9_1,
  143974. _vq_quantmap__16u1__p9_1,
  143975. 15,
  143976. 15
  143977. };
  143978. static static_codebook _16u1__p9_1 = {
  143979. 2, 225,
  143980. _vq_lengthlist__16u1__p9_1,
  143981. 1, -522338304, 1620115456, 4, 0,
  143982. _vq_quantlist__16u1__p9_1,
  143983. NULL,
  143984. &_vq_auxt__16u1__p9_1,
  143985. NULL,
  143986. 0
  143987. };
  143988. static long _vq_quantlist__16u1__p9_2[] = {
  143989. 8,
  143990. 7,
  143991. 9,
  143992. 6,
  143993. 10,
  143994. 5,
  143995. 11,
  143996. 4,
  143997. 12,
  143998. 3,
  143999. 13,
  144000. 2,
  144001. 14,
  144002. 1,
  144003. 15,
  144004. 0,
  144005. 16,
  144006. };
  144007. static long _vq_lengthlist__16u1__p9_2[] = {
  144008. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144009. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144010. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144011. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144012. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144013. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144014. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144015. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144016. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144017. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144018. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144019. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144020. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144021. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144022. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144023. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144024. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144025. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144026. 10,
  144027. };
  144028. static float _vq_quantthresh__16u1__p9_2[] = {
  144029. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144030. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144031. };
  144032. static long _vq_quantmap__16u1__p9_2[] = {
  144033. 15, 13, 11, 9, 7, 5, 3, 1,
  144034. 0, 2, 4, 6, 8, 10, 12, 14,
  144035. 16,
  144036. };
  144037. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144038. _vq_quantthresh__16u1__p9_2,
  144039. _vq_quantmap__16u1__p9_2,
  144040. 17,
  144041. 17
  144042. };
  144043. static static_codebook _16u1__p9_2 = {
  144044. 2, 289,
  144045. _vq_lengthlist__16u1__p9_2,
  144046. 1, -529530880, 1611661312, 5, 0,
  144047. _vq_quantlist__16u1__p9_2,
  144048. NULL,
  144049. &_vq_auxt__16u1__p9_2,
  144050. NULL,
  144051. 0
  144052. };
  144053. static long _huff_lengthlist__16u1__short[] = {
  144054. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144055. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144056. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144057. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144058. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144059. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144060. 16,16,16,16,
  144061. };
  144062. static static_codebook _huff_book__16u1__short = {
  144063. 2, 100,
  144064. _huff_lengthlist__16u1__short,
  144065. 0, 0, 0, 0, 0,
  144066. NULL,
  144067. NULL,
  144068. NULL,
  144069. NULL,
  144070. 0
  144071. };
  144072. static long _huff_lengthlist__16u2__long[] = {
  144073. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144074. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144075. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144076. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144077. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144078. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144079. 13,14,18,18,
  144080. };
  144081. static static_codebook _huff_book__16u2__long = {
  144082. 2, 100,
  144083. _huff_lengthlist__16u2__long,
  144084. 0, 0, 0, 0, 0,
  144085. NULL,
  144086. NULL,
  144087. NULL,
  144088. NULL,
  144089. 0
  144090. };
  144091. static long _huff_lengthlist__16u2__short[] = {
  144092. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144093. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144094. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144095. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144096. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144097. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144098. 16,16,16,16,
  144099. };
  144100. static static_codebook _huff_book__16u2__short = {
  144101. 2, 100,
  144102. _huff_lengthlist__16u2__short,
  144103. 0, 0, 0, 0, 0,
  144104. NULL,
  144105. NULL,
  144106. NULL,
  144107. NULL,
  144108. 0
  144109. };
  144110. static long _vq_quantlist__16u2_p1_0[] = {
  144111. 1,
  144112. 0,
  144113. 2,
  144114. };
  144115. static long _vq_lengthlist__16u2_p1_0[] = {
  144116. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144117. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144118. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144119. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144120. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144121. 10,
  144122. };
  144123. static float _vq_quantthresh__16u2_p1_0[] = {
  144124. -0.5, 0.5,
  144125. };
  144126. static long _vq_quantmap__16u2_p1_0[] = {
  144127. 1, 0, 2,
  144128. };
  144129. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144130. _vq_quantthresh__16u2_p1_0,
  144131. _vq_quantmap__16u2_p1_0,
  144132. 3,
  144133. 3
  144134. };
  144135. static static_codebook _16u2_p1_0 = {
  144136. 4, 81,
  144137. _vq_lengthlist__16u2_p1_0,
  144138. 1, -535822336, 1611661312, 2, 0,
  144139. _vq_quantlist__16u2_p1_0,
  144140. NULL,
  144141. &_vq_auxt__16u2_p1_0,
  144142. NULL,
  144143. 0
  144144. };
  144145. static long _vq_quantlist__16u2_p2_0[] = {
  144146. 2,
  144147. 1,
  144148. 3,
  144149. 0,
  144150. 4,
  144151. };
  144152. static long _vq_lengthlist__16u2_p2_0[] = {
  144153. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144154. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144155. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144156. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144157. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144158. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144159. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144160. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144161. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144162. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144163. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144164. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144165. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144166. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144167. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144168. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144169. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144170. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144171. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144172. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144173. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144174. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144175. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144176. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144177. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144178. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144179. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144180. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144181. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144182. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144183. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144184. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144185. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144186. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144187. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144188. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144189. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144190. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144191. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144192. 13,
  144193. };
  144194. static float _vq_quantthresh__16u2_p2_0[] = {
  144195. -1.5, -0.5, 0.5, 1.5,
  144196. };
  144197. static long _vq_quantmap__16u2_p2_0[] = {
  144198. 3, 1, 0, 2, 4,
  144199. };
  144200. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144201. _vq_quantthresh__16u2_p2_0,
  144202. _vq_quantmap__16u2_p2_0,
  144203. 5,
  144204. 5
  144205. };
  144206. static static_codebook _16u2_p2_0 = {
  144207. 4, 625,
  144208. _vq_lengthlist__16u2_p2_0,
  144209. 1, -533725184, 1611661312, 3, 0,
  144210. _vq_quantlist__16u2_p2_0,
  144211. NULL,
  144212. &_vq_auxt__16u2_p2_0,
  144213. NULL,
  144214. 0
  144215. };
  144216. static long _vq_quantlist__16u2_p3_0[] = {
  144217. 4,
  144218. 3,
  144219. 5,
  144220. 2,
  144221. 6,
  144222. 1,
  144223. 7,
  144224. 0,
  144225. 8,
  144226. };
  144227. static long _vq_lengthlist__16u2_p3_0[] = {
  144228. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144229. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144230. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144231. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144232. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144233. 11,
  144234. };
  144235. static float _vq_quantthresh__16u2_p3_0[] = {
  144236. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144237. };
  144238. static long _vq_quantmap__16u2_p3_0[] = {
  144239. 7, 5, 3, 1, 0, 2, 4, 6,
  144240. 8,
  144241. };
  144242. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144243. _vq_quantthresh__16u2_p3_0,
  144244. _vq_quantmap__16u2_p3_0,
  144245. 9,
  144246. 9
  144247. };
  144248. static static_codebook _16u2_p3_0 = {
  144249. 2, 81,
  144250. _vq_lengthlist__16u2_p3_0,
  144251. 1, -531628032, 1611661312, 4, 0,
  144252. _vq_quantlist__16u2_p3_0,
  144253. NULL,
  144254. &_vq_auxt__16u2_p3_0,
  144255. NULL,
  144256. 0
  144257. };
  144258. static long _vq_quantlist__16u2_p4_0[] = {
  144259. 8,
  144260. 7,
  144261. 9,
  144262. 6,
  144263. 10,
  144264. 5,
  144265. 11,
  144266. 4,
  144267. 12,
  144268. 3,
  144269. 13,
  144270. 2,
  144271. 14,
  144272. 1,
  144273. 15,
  144274. 0,
  144275. 16,
  144276. };
  144277. static long _vq_lengthlist__16u2_p4_0[] = {
  144278. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144279. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144280. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144281. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144282. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144283. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144284. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144285. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144286. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144287. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144288. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144289. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144290. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144291. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144292. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144293. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144294. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144295. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144296. 14,
  144297. };
  144298. static float _vq_quantthresh__16u2_p4_0[] = {
  144299. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144300. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144301. };
  144302. static long _vq_quantmap__16u2_p4_0[] = {
  144303. 15, 13, 11, 9, 7, 5, 3, 1,
  144304. 0, 2, 4, 6, 8, 10, 12, 14,
  144305. 16,
  144306. };
  144307. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144308. _vq_quantthresh__16u2_p4_0,
  144309. _vq_quantmap__16u2_p4_0,
  144310. 17,
  144311. 17
  144312. };
  144313. static static_codebook _16u2_p4_0 = {
  144314. 2, 289,
  144315. _vq_lengthlist__16u2_p4_0,
  144316. 1, -529530880, 1611661312, 5, 0,
  144317. _vq_quantlist__16u2_p4_0,
  144318. NULL,
  144319. &_vq_auxt__16u2_p4_0,
  144320. NULL,
  144321. 0
  144322. };
  144323. static long _vq_quantlist__16u2_p5_0[] = {
  144324. 1,
  144325. 0,
  144326. 2,
  144327. };
  144328. static long _vq_lengthlist__16u2_p5_0[] = {
  144329. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144330. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144331. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144332. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144333. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144334. 10,
  144335. };
  144336. static float _vq_quantthresh__16u2_p5_0[] = {
  144337. -5.5, 5.5,
  144338. };
  144339. static long _vq_quantmap__16u2_p5_0[] = {
  144340. 1, 0, 2,
  144341. };
  144342. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144343. _vq_quantthresh__16u2_p5_0,
  144344. _vq_quantmap__16u2_p5_0,
  144345. 3,
  144346. 3
  144347. };
  144348. static static_codebook _16u2_p5_0 = {
  144349. 4, 81,
  144350. _vq_lengthlist__16u2_p5_0,
  144351. 1, -529137664, 1618345984, 2, 0,
  144352. _vq_quantlist__16u2_p5_0,
  144353. NULL,
  144354. &_vq_auxt__16u2_p5_0,
  144355. NULL,
  144356. 0
  144357. };
  144358. static long _vq_quantlist__16u2_p5_1[] = {
  144359. 5,
  144360. 4,
  144361. 6,
  144362. 3,
  144363. 7,
  144364. 2,
  144365. 8,
  144366. 1,
  144367. 9,
  144368. 0,
  144369. 10,
  144370. };
  144371. static long _vq_lengthlist__16u2_p5_1[] = {
  144372. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144373. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144374. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144375. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144376. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144377. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144378. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144379. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144380. };
  144381. static float _vq_quantthresh__16u2_p5_1[] = {
  144382. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144383. 3.5, 4.5,
  144384. };
  144385. static long _vq_quantmap__16u2_p5_1[] = {
  144386. 9, 7, 5, 3, 1, 0, 2, 4,
  144387. 6, 8, 10,
  144388. };
  144389. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144390. _vq_quantthresh__16u2_p5_1,
  144391. _vq_quantmap__16u2_p5_1,
  144392. 11,
  144393. 11
  144394. };
  144395. static static_codebook _16u2_p5_1 = {
  144396. 2, 121,
  144397. _vq_lengthlist__16u2_p5_1,
  144398. 1, -531365888, 1611661312, 4, 0,
  144399. _vq_quantlist__16u2_p5_1,
  144400. NULL,
  144401. &_vq_auxt__16u2_p5_1,
  144402. NULL,
  144403. 0
  144404. };
  144405. static long _vq_quantlist__16u2_p6_0[] = {
  144406. 6,
  144407. 5,
  144408. 7,
  144409. 4,
  144410. 8,
  144411. 3,
  144412. 9,
  144413. 2,
  144414. 10,
  144415. 1,
  144416. 11,
  144417. 0,
  144418. 12,
  144419. };
  144420. static long _vq_lengthlist__16u2_p6_0[] = {
  144421. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144422. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144423. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144424. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144425. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144426. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144427. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144428. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144429. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144430. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144431. 12,13,13,14,14,14,14,15,15,
  144432. };
  144433. static float _vq_quantthresh__16u2_p6_0[] = {
  144434. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144435. 12.5, 17.5, 22.5, 27.5,
  144436. };
  144437. static long _vq_quantmap__16u2_p6_0[] = {
  144438. 11, 9, 7, 5, 3, 1, 0, 2,
  144439. 4, 6, 8, 10, 12,
  144440. };
  144441. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144442. _vq_quantthresh__16u2_p6_0,
  144443. _vq_quantmap__16u2_p6_0,
  144444. 13,
  144445. 13
  144446. };
  144447. static static_codebook _16u2_p6_0 = {
  144448. 2, 169,
  144449. _vq_lengthlist__16u2_p6_0,
  144450. 1, -526516224, 1616117760, 4, 0,
  144451. _vq_quantlist__16u2_p6_0,
  144452. NULL,
  144453. &_vq_auxt__16u2_p6_0,
  144454. NULL,
  144455. 0
  144456. };
  144457. static long _vq_quantlist__16u2_p6_1[] = {
  144458. 2,
  144459. 1,
  144460. 3,
  144461. 0,
  144462. 4,
  144463. };
  144464. static long _vq_lengthlist__16u2_p6_1[] = {
  144465. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144466. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144467. };
  144468. static float _vq_quantthresh__16u2_p6_1[] = {
  144469. -1.5, -0.5, 0.5, 1.5,
  144470. };
  144471. static long _vq_quantmap__16u2_p6_1[] = {
  144472. 3, 1, 0, 2, 4,
  144473. };
  144474. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144475. _vq_quantthresh__16u2_p6_1,
  144476. _vq_quantmap__16u2_p6_1,
  144477. 5,
  144478. 5
  144479. };
  144480. static static_codebook _16u2_p6_1 = {
  144481. 2, 25,
  144482. _vq_lengthlist__16u2_p6_1,
  144483. 1, -533725184, 1611661312, 3, 0,
  144484. _vq_quantlist__16u2_p6_1,
  144485. NULL,
  144486. &_vq_auxt__16u2_p6_1,
  144487. NULL,
  144488. 0
  144489. };
  144490. static long _vq_quantlist__16u2_p7_0[] = {
  144491. 6,
  144492. 5,
  144493. 7,
  144494. 4,
  144495. 8,
  144496. 3,
  144497. 9,
  144498. 2,
  144499. 10,
  144500. 1,
  144501. 11,
  144502. 0,
  144503. 12,
  144504. };
  144505. static long _vq_lengthlist__16u2_p7_0[] = {
  144506. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144507. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144508. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144509. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144510. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144511. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144512. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144513. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144514. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144515. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144516. 12,13,13,13,14,14,14,15,14,
  144517. };
  144518. static float _vq_quantthresh__16u2_p7_0[] = {
  144519. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144520. 27.5, 38.5, 49.5, 60.5,
  144521. };
  144522. static long _vq_quantmap__16u2_p7_0[] = {
  144523. 11, 9, 7, 5, 3, 1, 0, 2,
  144524. 4, 6, 8, 10, 12,
  144525. };
  144526. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144527. _vq_quantthresh__16u2_p7_0,
  144528. _vq_quantmap__16u2_p7_0,
  144529. 13,
  144530. 13
  144531. };
  144532. static static_codebook _16u2_p7_0 = {
  144533. 2, 169,
  144534. _vq_lengthlist__16u2_p7_0,
  144535. 1, -523206656, 1618345984, 4, 0,
  144536. _vq_quantlist__16u2_p7_0,
  144537. NULL,
  144538. &_vq_auxt__16u2_p7_0,
  144539. NULL,
  144540. 0
  144541. };
  144542. static long _vq_quantlist__16u2_p7_1[] = {
  144543. 5,
  144544. 4,
  144545. 6,
  144546. 3,
  144547. 7,
  144548. 2,
  144549. 8,
  144550. 1,
  144551. 9,
  144552. 0,
  144553. 10,
  144554. };
  144555. static long _vq_lengthlist__16u2_p7_1[] = {
  144556. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144557. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144558. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144559. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144560. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144561. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144562. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144563. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144564. };
  144565. static float _vq_quantthresh__16u2_p7_1[] = {
  144566. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144567. 3.5, 4.5,
  144568. };
  144569. static long _vq_quantmap__16u2_p7_1[] = {
  144570. 9, 7, 5, 3, 1, 0, 2, 4,
  144571. 6, 8, 10,
  144572. };
  144573. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144574. _vq_quantthresh__16u2_p7_1,
  144575. _vq_quantmap__16u2_p7_1,
  144576. 11,
  144577. 11
  144578. };
  144579. static static_codebook _16u2_p7_1 = {
  144580. 2, 121,
  144581. _vq_lengthlist__16u2_p7_1,
  144582. 1, -531365888, 1611661312, 4, 0,
  144583. _vq_quantlist__16u2_p7_1,
  144584. NULL,
  144585. &_vq_auxt__16u2_p7_1,
  144586. NULL,
  144587. 0
  144588. };
  144589. static long _vq_quantlist__16u2_p8_0[] = {
  144590. 7,
  144591. 6,
  144592. 8,
  144593. 5,
  144594. 9,
  144595. 4,
  144596. 10,
  144597. 3,
  144598. 11,
  144599. 2,
  144600. 12,
  144601. 1,
  144602. 13,
  144603. 0,
  144604. 14,
  144605. };
  144606. static long _vq_lengthlist__16u2_p8_0[] = {
  144607. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144608. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144609. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144610. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144611. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144612. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144613. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144614. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144615. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144616. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144617. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144618. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144619. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144620. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144621. 14,
  144622. };
  144623. static float _vq_quantthresh__16u2_p8_0[] = {
  144624. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144625. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144626. };
  144627. static long _vq_quantmap__16u2_p8_0[] = {
  144628. 13, 11, 9, 7, 5, 3, 1, 0,
  144629. 2, 4, 6, 8, 10, 12, 14,
  144630. };
  144631. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144632. _vq_quantthresh__16u2_p8_0,
  144633. _vq_quantmap__16u2_p8_0,
  144634. 15,
  144635. 15
  144636. };
  144637. static static_codebook _16u2_p8_0 = {
  144638. 2, 225,
  144639. _vq_lengthlist__16u2_p8_0,
  144640. 1, -520986624, 1620377600, 4, 0,
  144641. _vq_quantlist__16u2_p8_0,
  144642. NULL,
  144643. &_vq_auxt__16u2_p8_0,
  144644. NULL,
  144645. 0
  144646. };
  144647. static long _vq_quantlist__16u2_p8_1[] = {
  144648. 10,
  144649. 9,
  144650. 11,
  144651. 8,
  144652. 12,
  144653. 7,
  144654. 13,
  144655. 6,
  144656. 14,
  144657. 5,
  144658. 15,
  144659. 4,
  144660. 16,
  144661. 3,
  144662. 17,
  144663. 2,
  144664. 18,
  144665. 1,
  144666. 19,
  144667. 0,
  144668. 20,
  144669. };
  144670. static long _vq_lengthlist__16u2_p8_1[] = {
  144671. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144672. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144673. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144674. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144675. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144676. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144677. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144678. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144679. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144680. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144681. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144682. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144683. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144684. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144685. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144686. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144687. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144688. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144689. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144690. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144691. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144692. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144693. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144694. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144695. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144696. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144697. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144698. 11,11,10,11,11,11,10,11,11,
  144699. };
  144700. static float _vq_quantthresh__16u2_p8_1[] = {
  144701. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144702. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144703. 6.5, 7.5, 8.5, 9.5,
  144704. };
  144705. static long _vq_quantmap__16u2_p8_1[] = {
  144706. 19, 17, 15, 13, 11, 9, 7, 5,
  144707. 3, 1, 0, 2, 4, 6, 8, 10,
  144708. 12, 14, 16, 18, 20,
  144709. };
  144710. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144711. _vq_quantthresh__16u2_p8_1,
  144712. _vq_quantmap__16u2_p8_1,
  144713. 21,
  144714. 21
  144715. };
  144716. static static_codebook _16u2_p8_1 = {
  144717. 2, 441,
  144718. _vq_lengthlist__16u2_p8_1,
  144719. 1, -529268736, 1611661312, 5, 0,
  144720. _vq_quantlist__16u2_p8_1,
  144721. NULL,
  144722. &_vq_auxt__16u2_p8_1,
  144723. NULL,
  144724. 0
  144725. };
  144726. static long _vq_quantlist__16u2_p9_0[] = {
  144727. 5586,
  144728. 4655,
  144729. 6517,
  144730. 3724,
  144731. 7448,
  144732. 2793,
  144733. 8379,
  144734. 1862,
  144735. 9310,
  144736. 931,
  144737. 10241,
  144738. 0,
  144739. 11172,
  144740. 5521,
  144741. 5651,
  144742. };
  144743. static long _vq_lengthlist__16u2_p9_0[] = {
  144744. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144745. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144746. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144749. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144751. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144752. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144753. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144754. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144755. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144756. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144757. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144758. 5,
  144759. };
  144760. static float _vq_quantthresh__16u2_p9_0[] = {
  144761. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144762. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144763. };
  144764. static long _vq_quantmap__16u2_p9_0[] = {
  144765. 11, 9, 7, 5, 3, 1, 13, 0,
  144766. 14, 2, 4, 6, 8, 10, 12,
  144767. };
  144768. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144769. _vq_quantthresh__16u2_p9_0,
  144770. _vq_quantmap__16u2_p9_0,
  144771. 15,
  144772. 15
  144773. };
  144774. static static_codebook _16u2_p9_0 = {
  144775. 2, 225,
  144776. _vq_lengthlist__16u2_p9_0,
  144777. 1, -510275072, 1611661312, 14, 0,
  144778. _vq_quantlist__16u2_p9_0,
  144779. NULL,
  144780. &_vq_auxt__16u2_p9_0,
  144781. NULL,
  144782. 0
  144783. };
  144784. static long _vq_quantlist__16u2_p9_1[] = {
  144785. 392,
  144786. 343,
  144787. 441,
  144788. 294,
  144789. 490,
  144790. 245,
  144791. 539,
  144792. 196,
  144793. 588,
  144794. 147,
  144795. 637,
  144796. 98,
  144797. 686,
  144798. 49,
  144799. 735,
  144800. 0,
  144801. 784,
  144802. 388,
  144803. 396,
  144804. };
  144805. static long _vq_lengthlist__16u2_p9_1[] = {
  144806. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144807. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144808. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144809. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144810. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144811. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144812. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144813. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144814. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144815. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144816. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144817. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144818. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144819. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144820. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144821. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144822. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144823. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144825. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144826. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144827. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144828. 11,11,11,11,11,11,11, 5, 4,
  144829. };
  144830. static float _vq_quantthresh__16u2_p9_1[] = {
  144831. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144832. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144833. 318.5, 367.5,
  144834. };
  144835. static long _vq_quantmap__16u2_p9_1[] = {
  144836. 15, 13, 11, 9, 7, 5, 3, 1,
  144837. 17, 0, 18, 2, 4, 6, 8, 10,
  144838. 12, 14, 16,
  144839. };
  144840. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144841. _vq_quantthresh__16u2_p9_1,
  144842. _vq_quantmap__16u2_p9_1,
  144843. 19,
  144844. 19
  144845. };
  144846. static static_codebook _16u2_p9_1 = {
  144847. 2, 361,
  144848. _vq_lengthlist__16u2_p9_1,
  144849. 1, -518488064, 1611661312, 10, 0,
  144850. _vq_quantlist__16u2_p9_1,
  144851. NULL,
  144852. &_vq_auxt__16u2_p9_1,
  144853. NULL,
  144854. 0
  144855. };
  144856. static long _vq_quantlist__16u2_p9_2[] = {
  144857. 24,
  144858. 23,
  144859. 25,
  144860. 22,
  144861. 26,
  144862. 21,
  144863. 27,
  144864. 20,
  144865. 28,
  144866. 19,
  144867. 29,
  144868. 18,
  144869. 30,
  144870. 17,
  144871. 31,
  144872. 16,
  144873. 32,
  144874. 15,
  144875. 33,
  144876. 14,
  144877. 34,
  144878. 13,
  144879. 35,
  144880. 12,
  144881. 36,
  144882. 11,
  144883. 37,
  144884. 10,
  144885. 38,
  144886. 9,
  144887. 39,
  144888. 8,
  144889. 40,
  144890. 7,
  144891. 41,
  144892. 6,
  144893. 42,
  144894. 5,
  144895. 43,
  144896. 4,
  144897. 44,
  144898. 3,
  144899. 45,
  144900. 2,
  144901. 46,
  144902. 1,
  144903. 47,
  144904. 0,
  144905. 48,
  144906. };
  144907. static long _vq_lengthlist__16u2_p9_2[] = {
  144908. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144909. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144910. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144911. 11,
  144912. };
  144913. static float _vq_quantthresh__16u2_p9_2[] = {
  144914. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144915. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144916. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144917. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144918. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144919. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144920. };
  144921. static long _vq_quantmap__16u2_p9_2[] = {
  144922. 47, 45, 43, 41, 39, 37, 35, 33,
  144923. 31, 29, 27, 25, 23, 21, 19, 17,
  144924. 15, 13, 11, 9, 7, 5, 3, 1,
  144925. 0, 2, 4, 6, 8, 10, 12, 14,
  144926. 16, 18, 20, 22, 24, 26, 28, 30,
  144927. 32, 34, 36, 38, 40, 42, 44, 46,
  144928. 48,
  144929. };
  144930. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144931. _vq_quantthresh__16u2_p9_2,
  144932. _vq_quantmap__16u2_p9_2,
  144933. 49,
  144934. 49
  144935. };
  144936. static static_codebook _16u2_p9_2 = {
  144937. 1, 49,
  144938. _vq_lengthlist__16u2_p9_2,
  144939. 1, -526909440, 1611661312, 6, 0,
  144940. _vq_quantlist__16u2_p9_2,
  144941. NULL,
  144942. &_vq_auxt__16u2_p9_2,
  144943. NULL,
  144944. 0
  144945. };
  144946. static long _vq_quantlist__8u0__p1_0[] = {
  144947. 1,
  144948. 0,
  144949. 2,
  144950. };
  144951. static long _vq_lengthlist__8u0__p1_0[] = {
  144952. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144953. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144954. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144955. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144956. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144957. 11,
  144958. };
  144959. static float _vq_quantthresh__8u0__p1_0[] = {
  144960. -0.5, 0.5,
  144961. };
  144962. static long _vq_quantmap__8u0__p1_0[] = {
  144963. 1, 0, 2,
  144964. };
  144965. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144966. _vq_quantthresh__8u0__p1_0,
  144967. _vq_quantmap__8u0__p1_0,
  144968. 3,
  144969. 3
  144970. };
  144971. static static_codebook _8u0__p1_0 = {
  144972. 4, 81,
  144973. _vq_lengthlist__8u0__p1_0,
  144974. 1, -535822336, 1611661312, 2, 0,
  144975. _vq_quantlist__8u0__p1_0,
  144976. NULL,
  144977. &_vq_auxt__8u0__p1_0,
  144978. NULL,
  144979. 0
  144980. };
  144981. static long _vq_quantlist__8u0__p2_0[] = {
  144982. 1,
  144983. 0,
  144984. 2,
  144985. };
  144986. static long _vq_lengthlist__8u0__p2_0[] = {
  144987. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144988. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144989. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144990. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144991. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144992. 8,
  144993. };
  144994. static float _vq_quantthresh__8u0__p2_0[] = {
  144995. -0.5, 0.5,
  144996. };
  144997. static long _vq_quantmap__8u0__p2_0[] = {
  144998. 1, 0, 2,
  144999. };
  145000. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145001. _vq_quantthresh__8u0__p2_0,
  145002. _vq_quantmap__8u0__p2_0,
  145003. 3,
  145004. 3
  145005. };
  145006. static static_codebook _8u0__p2_0 = {
  145007. 4, 81,
  145008. _vq_lengthlist__8u0__p2_0,
  145009. 1, -535822336, 1611661312, 2, 0,
  145010. _vq_quantlist__8u0__p2_0,
  145011. NULL,
  145012. &_vq_auxt__8u0__p2_0,
  145013. NULL,
  145014. 0
  145015. };
  145016. static long _vq_quantlist__8u0__p3_0[] = {
  145017. 2,
  145018. 1,
  145019. 3,
  145020. 0,
  145021. 4,
  145022. };
  145023. static long _vq_lengthlist__8u0__p3_0[] = {
  145024. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145025. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145026. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145027. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145028. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145029. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145030. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145031. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145032. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145033. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145034. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145035. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145036. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145037. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145038. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145039. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145040. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145041. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145042. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145043. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145044. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145045. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145046. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145047. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145048. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145049. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145050. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145051. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145052. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145053. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145054. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145055. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145056. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145057. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145058. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145059. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145060. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145061. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145062. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145063. 16,
  145064. };
  145065. static float _vq_quantthresh__8u0__p3_0[] = {
  145066. -1.5, -0.5, 0.5, 1.5,
  145067. };
  145068. static long _vq_quantmap__8u0__p3_0[] = {
  145069. 3, 1, 0, 2, 4,
  145070. };
  145071. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145072. _vq_quantthresh__8u0__p3_0,
  145073. _vq_quantmap__8u0__p3_0,
  145074. 5,
  145075. 5
  145076. };
  145077. static static_codebook _8u0__p3_0 = {
  145078. 4, 625,
  145079. _vq_lengthlist__8u0__p3_0,
  145080. 1, -533725184, 1611661312, 3, 0,
  145081. _vq_quantlist__8u0__p3_0,
  145082. NULL,
  145083. &_vq_auxt__8u0__p3_0,
  145084. NULL,
  145085. 0
  145086. };
  145087. static long _vq_quantlist__8u0__p4_0[] = {
  145088. 2,
  145089. 1,
  145090. 3,
  145091. 0,
  145092. 4,
  145093. };
  145094. static long _vq_lengthlist__8u0__p4_0[] = {
  145095. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145096. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145097. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145098. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145099. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145100. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145101. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145102. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145103. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145104. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145105. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145106. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145107. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145108. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145109. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145110. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145111. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145112. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145113. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145114. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145115. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145116. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145117. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145118. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145119. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145120. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145121. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145122. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145123. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145124. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145125. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145126. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145127. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145128. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145129. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145130. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145131. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145132. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145133. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145134. 12,
  145135. };
  145136. static float _vq_quantthresh__8u0__p4_0[] = {
  145137. -1.5, -0.5, 0.5, 1.5,
  145138. };
  145139. static long _vq_quantmap__8u0__p4_0[] = {
  145140. 3, 1, 0, 2, 4,
  145141. };
  145142. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145143. _vq_quantthresh__8u0__p4_0,
  145144. _vq_quantmap__8u0__p4_0,
  145145. 5,
  145146. 5
  145147. };
  145148. static static_codebook _8u0__p4_0 = {
  145149. 4, 625,
  145150. _vq_lengthlist__8u0__p4_0,
  145151. 1, -533725184, 1611661312, 3, 0,
  145152. _vq_quantlist__8u0__p4_0,
  145153. NULL,
  145154. &_vq_auxt__8u0__p4_0,
  145155. NULL,
  145156. 0
  145157. };
  145158. static long _vq_quantlist__8u0__p5_0[] = {
  145159. 4,
  145160. 3,
  145161. 5,
  145162. 2,
  145163. 6,
  145164. 1,
  145165. 7,
  145166. 0,
  145167. 8,
  145168. };
  145169. static long _vq_lengthlist__8u0__p5_0[] = {
  145170. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145171. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145172. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145173. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145174. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145175. 12,
  145176. };
  145177. static float _vq_quantthresh__8u0__p5_0[] = {
  145178. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145179. };
  145180. static long _vq_quantmap__8u0__p5_0[] = {
  145181. 7, 5, 3, 1, 0, 2, 4, 6,
  145182. 8,
  145183. };
  145184. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145185. _vq_quantthresh__8u0__p5_0,
  145186. _vq_quantmap__8u0__p5_0,
  145187. 9,
  145188. 9
  145189. };
  145190. static static_codebook _8u0__p5_0 = {
  145191. 2, 81,
  145192. _vq_lengthlist__8u0__p5_0,
  145193. 1, -531628032, 1611661312, 4, 0,
  145194. _vq_quantlist__8u0__p5_0,
  145195. NULL,
  145196. &_vq_auxt__8u0__p5_0,
  145197. NULL,
  145198. 0
  145199. };
  145200. static long _vq_quantlist__8u0__p6_0[] = {
  145201. 6,
  145202. 5,
  145203. 7,
  145204. 4,
  145205. 8,
  145206. 3,
  145207. 9,
  145208. 2,
  145209. 10,
  145210. 1,
  145211. 11,
  145212. 0,
  145213. 12,
  145214. };
  145215. static long _vq_lengthlist__8u0__p6_0[] = {
  145216. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145217. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145218. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145219. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145220. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145221. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145222. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145223. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145224. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145225. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145226. 16, 0,15, 0,17, 0, 0, 0, 0,
  145227. };
  145228. static float _vq_quantthresh__8u0__p6_0[] = {
  145229. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145230. 12.5, 17.5, 22.5, 27.5,
  145231. };
  145232. static long _vq_quantmap__8u0__p6_0[] = {
  145233. 11, 9, 7, 5, 3, 1, 0, 2,
  145234. 4, 6, 8, 10, 12,
  145235. };
  145236. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145237. _vq_quantthresh__8u0__p6_0,
  145238. _vq_quantmap__8u0__p6_0,
  145239. 13,
  145240. 13
  145241. };
  145242. static static_codebook _8u0__p6_0 = {
  145243. 2, 169,
  145244. _vq_lengthlist__8u0__p6_0,
  145245. 1, -526516224, 1616117760, 4, 0,
  145246. _vq_quantlist__8u0__p6_0,
  145247. NULL,
  145248. &_vq_auxt__8u0__p6_0,
  145249. NULL,
  145250. 0
  145251. };
  145252. static long _vq_quantlist__8u0__p6_1[] = {
  145253. 2,
  145254. 1,
  145255. 3,
  145256. 0,
  145257. 4,
  145258. };
  145259. static long _vq_lengthlist__8u0__p6_1[] = {
  145260. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145261. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145262. };
  145263. static float _vq_quantthresh__8u0__p6_1[] = {
  145264. -1.5, -0.5, 0.5, 1.5,
  145265. };
  145266. static long _vq_quantmap__8u0__p6_1[] = {
  145267. 3, 1, 0, 2, 4,
  145268. };
  145269. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145270. _vq_quantthresh__8u0__p6_1,
  145271. _vq_quantmap__8u0__p6_1,
  145272. 5,
  145273. 5
  145274. };
  145275. static static_codebook _8u0__p6_1 = {
  145276. 2, 25,
  145277. _vq_lengthlist__8u0__p6_1,
  145278. 1, -533725184, 1611661312, 3, 0,
  145279. _vq_quantlist__8u0__p6_1,
  145280. NULL,
  145281. &_vq_auxt__8u0__p6_1,
  145282. NULL,
  145283. 0
  145284. };
  145285. static long _vq_quantlist__8u0__p7_0[] = {
  145286. 1,
  145287. 0,
  145288. 2,
  145289. };
  145290. static long _vq_lengthlist__8u0__p7_0[] = {
  145291. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145292. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145293. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145294. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145295. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145296. 7,
  145297. };
  145298. static float _vq_quantthresh__8u0__p7_0[] = {
  145299. -157.5, 157.5,
  145300. };
  145301. static long _vq_quantmap__8u0__p7_0[] = {
  145302. 1, 0, 2,
  145303. };
  145304. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145305. _vq_quantthresh__8u0__p7_0,
  145306. _vq_quantmap__8u0__p7_0,
  145307. 3,
  145308. 3
  145309. };
  145310. static static_codebook _8u0__p7_0 = {
  145311. 4, 81,
  145312. _vq_lengthlist__8u0__p7_0,
  145313. 1, -518803456, 1628680192, 2, 0,
  145314. _vq_quantlist__8u0__p7_0,
  145315. NULL,
  145316. &_vq_auxt__8u0__p7_0,
  145317. NULL,
  145318. 0
  145319. };
  145320. static long _vq_quantlist__8u0__p7_1[] = {
  145321. 7,
  145322. 6,
  145323. 8,
  145324. 5,
  145325. 9,
  145326. 4,
  145327. 10,
  145328. 3,
  145329. 11,
  145330. 2,
  145331. 12,
  145332. 1,
  145333. 13,
  145334. 0,
  145335. 14,
  145336. };
  145337. static long _vq_lengthlist__8u0__p7_1[] = {
  145338. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145339. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145340. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145341. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145342. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145343. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145345. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145346. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145348. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145350. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145351. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145352. 10,
  145353. };
  145354. static float _vq_quantthresh__8u0__p7_1[] = {
  145355. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145356. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145357. };
  145358. static long _vq_quantmap__8u0__p7_1[] = {
  145359. 13, 11, 9, 7, 5, 3, 1, 0,
  145360. 2, 4, 6, 8, 10, 12, 14,
  145361. };
  145362. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145363. _vq_quantthresh__8u0__p7_1,
  145364. _vq_quantmap__8u0__p7_1,
  145365. 15,
  145366. 15
  145367. };
  145368. static static_codebook _8u0__p7_1 = {
  145369. 2, 225,
  145370. _vq_lengthlist__8u0__p7_1,
  145371. 1, -520986624, 1620377600, 4, 0,
  145372. _vq_quantlist__8u0__p7_1,
  145373. NULL,
  145374. &_vq_auxt__8u0__p7_1,
  145375. NULL,
  145376. 0
  145377. };
  145378. static long _vq_quantlist__8u0__p7_2[] = {
  145379. 10,
  145380. 9,
  145381. 11,
  145382. 8,
  145383. 12,
  145384. 7,
  145385. 13,
  145386. 6,
  145387. 14,
  145388. 5,
  145389. 15,
  145390. 4,
  145391. 16,
  145392. 3,
  145393. 17,
  145394. 2,
  145395. 18,
  145396. 1,
  145397. 19,
  145398. 0,
  145399. 20,
  145400. };
  145401. static long _vq_lengthlist__8u0__p7_2[] = {
  145402. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145403. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145404. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145405. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145406. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145407. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145408. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145409. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145410. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145411. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145412. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145413. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145414. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145415. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145416. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145417. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145418. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145419. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145420. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145421. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145422. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145423. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145424. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145425. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145426. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145427. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145428. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145429. 11,12,11,11,11,10,10,11,11,
  145430. };
  145431. static float _vq_quantthresh__8u0__p7_2[] = {
  145432. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145433. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145434. 6.5, 7.5, 8.5, 9.5,
  145435. };
  145436. static long _vq_quantmap__8u0__p7_2[] = {
  145437. 19, 17, 15, 13, 11, 9, 7, 5,
  145438. 3, 1, 0, 2, 4, 6, 8, 10,
  145439. 12, 14, 16, 18, 20,
  145440. };
  145441. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145442. _vq_quantthresh__8u0__p7_2,
  145443. _vq_quantmap__8u0__p7_2,
  145444. 21,
  145445. 21
  145446. };
  145447. static static_codebook _8u0__p7_2 = {
  145448. 2, 441,
  145449. _vq_lengthlist__8u0__p7_2,
  145450. 1, -529268736, 1611661312, 5, 0,
  145451. _vq_quantlist__8u0__p7_2,
  145452. NULL,
  145453. &_vq_auxt__8u0__p7_2,
  145454. NULL,
  145455. 0
  145456. };
  145457. static long _huff_lengthlist__8u0__single[] = {
  145458. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145459. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145460. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145461. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145462. };
  145463. static static_codebook _huff_book__8u0__single = {
  145464. 2, 64,
  145465. _huff_lengthlist__8u0__single,
  145466. 0, 0, 0, 0, 0,
  145467. NULL,
  145468. NULL,
  145469. NULL,
  145470. NULL,
  145471. 0
  145472. };
  145473. static long _vq_quantlist__8u1__p1_0[] = {
  145474. 1,
  145475. 0,
  145476. 2,
  145477. };
  145478. static long _vq_lengthlist__8u1__p1_0[] = {
  145479. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145480. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145481. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145482. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145483. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145484. 10,
  145485. };
  145486. static float _vq_quantthresh__8u1__p1_0[] = {
  145487. -0.5, 0.5,
  145488. };
  145489. static long _vq_quantmap__8u1__p1_0[] = {
  145490. 1, 0, 2,
  145491. };
  145492. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145493. _vq_quantthresh__8u1__p1_0,
  145494. _vq_quantmap__8u1__p1_0,
  145495. 3,
  145496. 3
  145497. };
  145498. static static_codebook _8u1__p1_0 = {
  145499. 4, 81,
  145500. _vq_lengthlist__8u1__p1_0,
  145501. 1, -535822336, 1611661312, 2, 0,
  145502. _vq_quantlist__8u1__p1_0,
  145503. NULL,
  145504. &_vq_auxt__8u1__p1_0,
  145505. NULL,
  145506. 0
  145507. };
  145508. static long _vq_quantlist__8u1__p2_0[] = {
  145509. 1,
  145510. 0,
  145511. 2,
  145512. };
  145513. static long _vq_lengthlist__8u1__p2_0[] = {
  145514. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145515. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145516. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145517. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145518. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145519. 7,
  145520. };
  145521. static float _vq_quantthresh__8u1__p2_0[] = {
  145522. -0.5, 0.5,
  145523. };
  145524. static long _vq_quantmap__8u1__p2_0[] = {
  145525. 1, 0, 2,
  145526. };
  145527. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145528. _vq_quantthresh__8u1__p2_0,
  145529. _vq_quantmap__8u1__p2_0,
  145530. 3,
  145531. 3
  145532. };
  145533. static static_codebook _8u1__p2_0 = {
  145534. 4, 81,
  145535. _vq_lengthlist__8u1__p2_0,
  145536. 1, -535822336, 1611661312, 2, 0,
  145537. _vq_quantlist__8u1__p2_0,
  145538. NULL,
  145539. &_vq_auxt__8u1__p2_0,
  145540. NULL,
  145541. 0
  145542. };
  145543. static long _vq_quantlist__8u1__p3_0[] = {
  145544. 2,
  145545. 1,
  145546. 3,
  145547. 0,
  145548. 4,
  145549. };
  145550. static long _vq_lengthlist__8u1__p3_0[] = {
  145551. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145552. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145553. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145554. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145555. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145556. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145557. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145558. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145559. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145560. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145561. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145562. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145563. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145564. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145565. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145566. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145567. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145568. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145569. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145570. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145571. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145572. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145573. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145574. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145575. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145576. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145577. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145578. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145579. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145580. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145581. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145582. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145583. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145584. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145585. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145586. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145587. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145588. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145589. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145590. 16,
  145591. };
  145592. static float _vq_quantthresh__8u1__p3_0[] = {
  145593. -1.5, -0.5, 0.5, 1.5,
  145594. };
  145595. static long _vq_quantmap__8u1__p3_0[] = {
  145596. 3, 1, 0, 2, 4,
  145597. };
  145598. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145599. _vq_quantthresh__8u1__p3_0,
  145600. _vq_quantmap__8u1__p3_0,
  145601. 5,
  145602. 5
  145603. };
  145604. static static_codebook _8u1__p3_0 = {
  145605. 4, 625,
  145606. _vq_lengthlist__8u1__p3_0,
  145607. 1, -533725184, 1611661312, 3, 0,
  145608. _vq_quantlist__8u1__p3_0,
  145609. NULL,
  145610. &_vq_auxt__8u1__p3_0,
  145611. NULL,
  145612. 0
  145613. };
  145614. static long _vq_quantlist__8u1__p4_0[] = {
  145615. 2,
  145616. 1,
  145617. 3,
  145618. 0,
  145619. 4,
  145620. };
  145621. static long _vq_lengthlist__8u1__p4_0[] = {
  145622. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145623. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145624. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145625. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145626. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145627. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145628. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145629. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145630. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145631. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145632. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145633. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145634. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145635. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145636. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145637. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145638. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145639. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145640. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145641. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145642. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145643. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145644. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145645. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145646. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145647. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145648. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145649. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145650. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145651. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145652. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145653. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145654. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145655. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145656. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145657. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145658. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145659. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145660. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145661. 10,
  145662. };
  145663. static float _vq_quantthresh__8u1__p4_0[] = {
  145664. -1.5, -0.5, 0.5, 1.5,
  145665. };
  145666. static long _vq_quantmap__8u1__p4_0[] = {
  145667. 3, 1, 0, 2, 4,
  145668. };
  145669. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145670. _vq_quantthresh__8u1__p4_0,
  145671. _vq_quantmap__8u1__p4_0,
  145672. 5,
  145673. 5
  145674. };
  145675. static static_codebook _8u1__p4_0 = {
  145676. 4, 625,
  145677. _vq_lengthlist__8u1__p4_0,
  145678. 1, -533725184, 1611661312, 3, 0,
  145679. _vq_quantlist__8u1__p4_0,
  145680. NULL,
  145681. &_vq_auxt__8u1__p4_0,
  145682. NULL,
  145683. 0
  145684. };
  145685. static long _vq_quantlist__8u1__p5_0[] = {
  145686. 4,
  145687. 3,
  145688. 5,
  145689. 2,
  145690. 6,
  145691. 1,
  145692. 7,
  145693. 0,
  145694. 8,
  145695. };
  145696. static long _vq_lengthlist__8u1__p5_0[] = {
  145697. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145698. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145699. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145700. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145701. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145702. 13,
  145703. };
  145704. static float _vq_quantthresh__8u1__p5_0[] = {
  145705. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145706. };
  145707. static long _vq_quantmap__8u1__p5_0[] = {
  145708. 7, 5, 3, 1, 0, 2, 4, 6,
  145709. 8,
  145710. };
  145711. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145712. _vq_quantthresh__8u1__p5_0,
  145713. _vq_quantmap__8u1__p5_0,
  145714. 9,
  145715. 9
  145716. };
  145717. static static_codebook _8u1__p5_0 = {
  145718. 2, 81,
  145719. _vq_lengthlist__8u1__p5_0,
  145720. 1, -531628032, 1611661312, 4, 0,
  145721. _vq_quantlist__8u1__p5_0,
  145722. NULL,
  145723. &_vq_auxt__8u1__p5_0,
  145724. NULL,
  145725. 0
  145726. };
  145727. static long _vq_quantlist__8u1__p6_0[] = {
  145728. 4,
  145729. 3,
  145730. 5,
  145731. 2,
  145732. 6,
  145733. 1,
  145734. 7,
  145735. 0,
  145736. 8,
  145737. };
  145738. static long _vq_lengthlist__8u1__p6_0[] = {
  145739. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145740. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145741. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145742. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145743. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145744. 10,
  145745. };
  145746. static float _vq_quantthresh__8u1__p6_0[] = {
  145747. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145748. };
  145749. static long _vq_quantmap__8u1__p6_0[] = {
  145750. 7, 5, 3, 1, 0, 2, 4, 6,
  145751. 8,
  145752. };
  145753. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145754. _vq_quantthresh__8u1__p6_0,
  145755. _vq_quantmap__8u1__p6_0,
  145756. 9,
  145757. 9
  145758. };
  145759. static static_codebook _8u1__p6_0 = {
  145760. 2, 81,
  145761. _vq_lengthlist__8u1__p6_0,
  145762. 1, -531628032, 1611661312, 4, 0,
  145763. _vq_quantlist__8u1__p6_0,
  145764. NULL,
  145765. &_vq_auxt__8u1__p6_0,
  145766. NULL,
  145767. 0
  145768. };
  145769. static long _vq_quantlist__8u1__p7_0[] = {
  145770. 1,
  145771. 0,
  145772. 2,
  145773. };
  145774. static long _vq_lengthlist__8u1__p7_0[] = {
  145775. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145776. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145777. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145778. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145779. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145780. 11,
  145781. };
  145782. static float _vq_quantthresh__8u1__p7_0[] = {
  145783. -5.5, 5.5,
  145784. };
  145785. static long _vq_quantmap__8u1__p7_0[] = {
  145786. 1, 0, 2,
  145787. };
  145788. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145789. _vq_quantthresh__8u1__p7_0,
  145790. _vq_quantmap__8u1__p7_0,
  145791. 3,
  145792. 3
  145793. };
  145794. static static_codebook _8u1__p7_0 = {
  145795. 4, 81,
  145796. _vq_lengthlist__8u1__p7_0,
  145797. 1, -529137664, 1618345984, 2, 0,
  145798. _vq_quantlist__8u1__p7_0,
  145799. NULL,
  145800. &_vq_auxt__8u1__p7_0,
  145801. NULL,
  145802. 0
  145803. };
  145804. static long _vq_quantlist__8u1__p7_1[] = {
  145805. 5,
  145806. 4,
  145807. 6,
  145808. 3,
  145809. 7,
  145810. 2,
  145811. 8,
  145812. 1,
  145813. 9,
  145814. 0,
  145815. 10,
  145816. };
  145817. static long _vq_lengthlist__8u1__p7_1[] = {
  145818. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145819. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145820. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145821. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145822. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145823. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145824. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145825. 9, 9, 9, 9, 9,10,10,10,10,
  145826. };
  145827. static float _vq_quantthresh__8u1__p7_1[] = {
  145828. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145829. 3.5, 4.5,
  145830. };
  145831. static long _vq_quantmap__8u1__p7_1[] = {
  145832. 9, 7, 5, 3, 1, 0, 2, 4,
  145833. 6, 8, 10,
  145834. };
  145835. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145836. _vq_quantthresh__8u1__p7_1,
  145837. _vq_quantmap__8u1__p7_1,
  145838. 11,
  145839. 11
  145840. };
  145841. static static_codebook _8u1__p7_1 = {
  145842. 2, 121,
  145843. _vq_lengthlist__8u1__p7_1,
  145844. 1, -531365888, 1611661312, 4, 0,
  145845. _vq_quantlist__8u1__p7_1,
  145846. NULL,
  145847. &_vq_auxt__8u1__p7_1,
  145848. NULL,
  145849. 0
  145850. };
  145851. static long _vq_quantlist__8u1__p8_0[] = {
  145852. 5,
  145853. 4,
  145854. 6,
  145855. 3,
  145856. 7,
  145857. 2,
  145858. 8,
  145859. 1,
  145860. 9,
  145861. 0,
  145862. 10,
  145863. };
  145864. static long _vq_lengthlist__8u1__p8_0[] = {
  145865. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145866. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145867. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145868. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145869. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145870. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145871. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145872. 12,13,13,14,14,15,15,15,15,
  145873. };
  145874. static float _vq_quantthresh__8u1__p8_0[] = {
  145875. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145876. 38.5, 49.5,
  145877. };
  145878. static long _vq_quantmap__8u1__p8_0[] = {
  145879. 9, 7, 5, 3, 1, 0, 2, 4,
  145880. 6, 8, 10,
  145881. };
  145882. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145883. _vq_quantthresh__8u1__p8_0,
  145884. _vq_quantmap__8u1__p8_0,
  145885. 11,
  145886. 11
  145887. };
  145888. static static_codebook _8u1__p8_0 = {
  145889. 2, 121,
  145890. _vq_lengthlist__8u1__p8_0,
  145891. 1, -524582912, 1618345984, 4, 0,
  145892. _vq_quantlist__8u1__p8_0,
  145893. NULL,
  145894. &_vq_auxt__8u1__p8_0,
  145895. NULL,
  145896. 0
  145897. };
  145898. static long _vq_quantlist__8u1__p8_1[] = {
  145899. 5,
  145900. 4,
  145901. 6,
  145902. 3,
  145903. 7,
  145904. 2,
  145905. 8,
  145906. 1,
  145907. 9,
  145908. 0,
  145909. 10,
  145910. };
  145911. static long _vq_lengthlist__8u1__p8_1[] = {
  145912. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145913. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145914. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145915. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145916. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145917. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145918. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145919. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145920. };
  145921. static float _vq_quantthresh__8u1__p8_1[] = {
  145922. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145923. 3.5, 4.5,
  145924. };
  145925. static long _vq_quantmap__8u1__p8_1[] = {
  145926. 9, 7, 5, 3, 1, 0, 2, 4,
  145927. 6, 8, 10,
  145928. };
  145929. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145930. _vq_quantthresh__8u1__p8_1,
  145931. _vq_quantmap__8u1__p8_1,
  145932. 11,
  145933. 11
  145934. };
  145935. static static_codebook _8u1__p8_1 = {
  145936. 2, 121,
  145937. _vq_lengthlist__8u1__p8_1,
  145938. 1, -531365888, 1611661312, 4, 0,
  145939. _vq_quantlist__8u1__p8_1,
  145940. NULL,
  145941. &_vq_auxt__8u1__p8_1,
  145942. NULL,
  145943. 0
  145944. };
  145945. static long _vq_quantlist__8u1__p9_0[] = {
  145946. 7,
  145947. 6,
  145948. 8,
  145949. 5,
  145950. 9,
  145951. 4,
  145952. 10,
  145953. 3,
  145954. 11,
  145955. 2,
  145956. 12,
  145957. 1,
  145958. 13,
  145959. 0,
  145960. 14,
  145961. };
  145962. static long _vq_lengthlist__8u1__p9_0[] = {
  145963. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145964. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145965. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145966. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145967. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145968. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145969. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145970. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145971. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145972. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145973. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145974. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145975. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145976. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145977. 10,
  145978. };
  145979. static float _vq_quantthresh__8u1__p9_0[] = {
  145980. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145981. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145982. };
  145983. static long _vq_quantmap__8u1__p9_0[] = {
  145984. 13, 11, 9, 7, 5, 3, 1, 0,
  145985. 2, 4, 6, 8, 10, 12, 14,
  145986. };
  145987. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145988. _vq_quantthresh__8u1__p9_0,
  145989. _vq_quantmap__8u1__p9_0,
  145990. 15,
  145991. 15
  145992. };
  145993. static static_codebook _8u1__p9_0 = {
  145994. 2, 225,
  145995. _vq_lengthlist__8u1__p9_0,
  145996. 1, -514071552, 1627381760, 4, 0,
  145997. _vq_quantlist__8u1__p9_0,
  145998. NULL,
  145999. &_vq_auxt__8u1__p9_0,
  146000. NULL,
  146001. 0
  146002. };
  146003. static long _vq_quantlist__8u1__p9_1[] = {
  146004. 7,
  146005. 6,
  146006. 8,
  146007. 5,
  146008. 9,
  146009. 4,
  146010. 10,
  146011. 3,
  146012. 11,
  146013. 2,
  146014. 12,
  146015. 1,
  146016. 13,
  146017. 0,
  146018. 14,
  146019. };
  146020. static long _vq_lengthlist__8u1__p9_1[] = {
  146021. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146022. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146023. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146024. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146025. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146026. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146027. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146028. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146029. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146030. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146031. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146032. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146033. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146034. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146035. 13,
  146036. };
  146037. static float _vq_quantthresh__8u1__p9_1[] = {
  146038. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146039. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146040. };
  146041. static long _vq_quantmap__8u1__p9_1[] = {
  146042. 13, 11, 9, 7, 5, 3, 1, 0,
  146043. 2, 4, 6, 8, 10, 12, 14,
  146044. };
  146045. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146046. _vq_quantthresh__8u1__p9_1,
  146047. _vq_quantmap__8u1__p9_1,
  146048. 15,
  146049. 15
  146050. };
  146051. static static_codebook _8u1__p9_1 = {
  146052. 2, 225,
  146053. _vq_lengthlist__8u1__p9_1,
  146054. 1, -522338304, 1620115456, 4, 0,
  146055. _vq_quantlist__8u1__p9_1,
  146056. NULL,
  146057. &_vq_auxt__8u1__p9_1,
  146058. NULL,
  146059. 0
  146060. };
  146061. static long _vq_quantlist__8u1__p9_2[] = {
  146062. 8,
  146063. 7,
  146064. 9,
  146065. 6,
  146066. 10,
  146067. 5,
  146068. 11,
  146069. 4,
  146070. 12,
  146071. 3,
  146072. 13,
  146073. 2,
  146074. 14,
  146075. 1,
  146076. 15,
  146077. 0,
  146078. 16,
  146079. };
  146080. static long _vq_lengthlist__8u1__p9_2[] = {
  146081. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146082. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146083. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146084. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146085. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146086. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146087. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146088. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146089. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146090. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146091. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146092. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146093. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146094. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146095. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146096. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146097. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146098. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146099. 10,
  146100. };
  146101. static float _vq_quantthresh__8u1__p9_2[] = {
  146102. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146103. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146104. };
  146105. static long _vq_quantmap__8u1__p9_2[] = {
  146106. 15, 13, 11, 9, 7, 5, 3, 1,
  146107. 0, 2, 4, 6, 8, 10, 12, 14,
  146108. 16,
  146109. };
  146110. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146111. _vq_quantthresh__8u1__p9_2,
  146112. _vq_quantmap__8u1__p9_2,
  146113. 17,
  146114. 17
  146115. };
  146116. static static_codebook _8u1__p9_2 = {
  146117. 2, 289,
  146118. _vq_lengthlist__8u1__p9_2,
  146119. 1, -529530880, 1611661312, 5, 0,
  146120. _vq_quantlist__8u1__p9_2,
  146121. NULL,
  146122. &_vq_auxt__8u1__p9_2,
  146123. NULL,
  146124. 0
  146125. };
  146126. static long _huff_lengthlist__8u1__single[] = {
  146127. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146128. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146129. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146130. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146131. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146132. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146133. 13, 8, 8,15,
  146134. };
  146135. static static_codebook _huff_book__8u1__single = {
  146136. 2, 100,
  146137. _huff_lengthlist__8u1__single,
  146138. 0, 0, 0, 0, 0,
  146139. NULL,
  146140. NULL,
  146141. NULL,
  146142. NULL,
  146143. 0
  146144. };
  146145. static long _huff_lengthlist__44u0__long[] = {
  146146. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146147. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146148. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146149. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146150. };
  146151. static static_codebook _huff_book__44u0__long = {
  146152. 2, 64,
  146153. _huff_lengthlist__44u0__long,
  146154. 0, 0, 0, 0, 0,
  146155. NULL,
  146156. NULL,
  146157. NULL,
  146158. NULL,
  146159. 0
  146160. };
  146161. static long _vq_quantlist__44u0__p1_0[] = {
  146162. 1,
  146163. 0,
  146164. 2,
  146165. };
  146166. static long _vq_lengthlist__44u0__p1_0[] = {
  146167. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146168. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146169. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146170. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146171. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146172. 13,
  146173. };
  146174. static float _vq_quantthresh__44u0__p1_0[] = {
  146175. -0.5, 0.5,
  146176. };
  146177. static long _vq_quantmap__44u0__p1_0[] = {
  146178. 1, 0, 2,
  146179. };
  146180. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146181. _vq_quantthresh__44u0__p1_0,
  146182. _vq_quantmap__44u0__p1_0,
  146183. 3,
  146184. 3
  146185. };
  146186. static static_codebook _44u0__p1_0 = {
  146187. 4, 81,
  146188. _vq_lengthlist__44u0__p1_0,
  146189. 1, -535822336, 1611661312, 2, 0,
  146190. _vq_quantlist__44u0__p1_0,
  146191. NULL,
  146192. &_vq_auxt__44u0__p1_0,
  146193. NULL,
  146194. 0
  146195. };
  146196. static long _vq_quantlist__44u0__p2_0[] = {
  146197. 1,
  146198. 0,
  146199. 2,
  146200. };
  146201. static long _vq_lengthlist__44u0__p2_0[] = {
  146202. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146203. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146204. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146205. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146206. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146207. 9,
  146208. };
  146209. static float _vq_quantthresh__44u0__p2_0[] = {
  146210. -0.5, 0.5,
  146211. };
  146212. static long _vq_quantmap__44u0__p2_0[] = {
  146213. 1, 0, 2,
  146214. };
  146215. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146216. _vq_quantthresh__44u0__p2_0,
  146217. _vq_quantmap__44u0__p2_0,
  146218. 3,
  146219. 3
  146220. };
  146221. static static_codebook _44u0__p2_0 = {
  146222. 4, 81,
  146223. _vq_lengthlist__44u0__p2_0,
  146224. 1, -535822336, 1611661312, 2, 0,
  146225. _vq_quantlist__44u0__p2_0,
  146226. NULL,
  146227. &_vq_auxt__44u0__p2_0,
  146228. NULL,
  146229. 0
  146230. };
  146231. static long _vq_quantlist__44u0__p3_0[] = {
  146232. 2,
  146233. 1,
  146234. 3,
  146235. 0,
  146236. 4,
  146237. };
  146238. static long _vq_lengthlist__44u0__p3_0[] = {
  146239. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146240. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146241. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146242. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146243. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146244. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146245. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146246. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146247. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146248. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146249. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146250. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146251. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146252. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146253. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146254. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146255. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146256. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146257. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146258. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146259. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146260. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146261. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146262. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146263. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146264. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146265. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146266. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146267. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146268. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146269. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146270. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146271. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146272. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146273. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146274. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146275. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146276. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146277. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146278. 19,
  146279. };
  146280. static float _vq_quantthresh__44u0__p3_0[] = {
  146281. -1.5, -0.5, 0.5, 1.5,
  146282. };
  146283. static long _vq_quantmap__44u0__p3_0[] = {
  146284. 3, 1, 0, 2, 4,
  146285. };
  146286. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146287. _vq_quantthresh__44u0__p3_0,
  146288. _vq_quantmap__44u0__p3_0,
  146289. 5,
  146290. 5
  146291. };
  146292. static static_codebook _44u0__p3_0 = {
  146293. 4, 625,
  146294. _vq_lengthlist__44u0__p3_0,
  146295. 1, -533725184, 1611661312, 3, 0,
  146296. _vq_quantlist__44u0__p3_0,
  146297. NULL,
  146298. &_vq_auxt__44u0__p3_0,
  146299. NULL,
  146300. 0
  146301. };
  146302. static long _vq_quantlist__44u0__p4_0[] = {
  146303. 2,
  146304. 1,
  146305. 3,
  146306. 0,
  146307. 4,
  146308. };
  146309. static long _vq_lengthlist__44u0__p4_0[] = {
  146310. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146311. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146312. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146313. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146314. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146315. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146316. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146317. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146318. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146319. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146320. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146321. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146322. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146323. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146324. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146325. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146326. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146327. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146328. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146329. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146330. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146331. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146332. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146333. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146334. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146335. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146336. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146337. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146338. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146339. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146340. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146341. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146342. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146343. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146344. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146345. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146346. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146347. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146348. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146349. 12,
  146350. };
  146351. static float _vq_quantthresh__44u0__p4_0[] = {
  146352. -1.5, -0.5, 0.5, 1.5,
  146353. };
  146354. static long _vq_quantmap__44u0__p4_0[] = {
  146355. 3, 1, 0, 2, 4,
  146356. };
  146357. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146358. _vq_quantthresh__44u0__p4_0,
  146359. _vq_quantmap__44u0__p4_0,
  146360. 5,
  146361. 5
  146362. };
  146363. static static_codebook _44u0__p4_0 = {
  146364. 4, 625,
  146365. _vq_lengthlist__44u0__p4_0,
  146366. 1, -533725184, 1611661312, 3, 0,
  146367. _vq_quantlist__44u0__p4_0,
  146368. NULL,
  146369. &_vq_auxt__44u0__p4_0,
  146370. NULL,
  146371. 0
  146372. };
  146373. static long _vq_quantlist__44u0__p5_0[] = {
  146374. 4,
  146375. 3,
  146376. 5,
  146377. 2,
  146378. 6,
  146379. 1,
  146380. 7,
  146381. 0,
  146382. 8,
  146383. };
  146384. static long _vq_lengthlist__44u0__p5_0[] = {
  146385. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146386. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146387. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146388. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146389. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146390. 12,
  146391. };
  146392. static float _vq_quantthresh__44u0__p5_0[] = {
  146393. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146394. };
  146395. static long _vq_quantmap__44u0__p5_0[] = {
  146396. 7, 5, 3, 1, 0, 2, 4, 6,
  146397. 8,
  146398. };
  146399. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146400. _vq_quantthresh__44u0__p5_0,
  146401. _vq_quantmap__44u0__p5_0,
  146402. 9,
  146403. 9
  146404. };
  146405. static static_codebook _44u0__p5_0 = {
  146406. 2, 81,
  146407. _vq_lengthlist__44u0__p5_0,
  146408. 1, -531628032, 1611661312, 4, 0,
  146409. _vq_quantlist__44u0__p5_0,
  146410. NULL,
  146411. &_vq_auxt__44u0__p5_0,
  146412. NULL,
  146413. 0
  146414. };
  146415. static long _vq_quantlist__44u0__p6_0[] = {
  146416. 6,
  146417. 5,
  146418. 7,
  146419. 4,
  146420. 8,
  146421. 3,
  146422. 9,
  146423. 2,
  146424. 10,
  146425. 1,
  146426. 11,
  146427. 0,
  146428. 12,
  146429. };
  146430. static long _vq_lengthlist__44u0__p6_0[] = {
  146431. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146432. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146433. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146434. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146435. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146436. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146437. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146438. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146439. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146440. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146441. 15,17,16,17,18,17,17,18, 0,
  146442. };
  146443. static float _vq_quantthresh__44u0__p6_0[] = {
  146444. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146445. 12.5, 17.5, 22.5, 27.5,
  146446. };
  146447. static long _vq_quantmap__44u0__p6_0[] = {
  146448. 11, 9, 7, 5, 3, 1, 0, 2,
  146449. 4, 6, 8, 10, 12,
  146450. };
  146451. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146452. _vq_quantthresh__44u0__p6_0,
  146453. _vq_quantmap__44u0__p6_0,
  146454. 13,
  146455. 13
  146456. };
  146457. static static_codebook _44u0__p6_0 = {
  146458. 2, 169,
  146459. _vq_lengthlist__44u0__p6_0,
  146460. 1, -526516224, 1616117760, 4, 0,
  146461. _vq_quantlist__44u0__p6_0,
  146462. NULL,
  146463. &_vq_auxt__44u0__p6_0,
  146464. NULL,
  146465. 0
  146466. };
  146467. static long _vq_quantlist__44u0__p6_1[] = {
  146468. 2,
  146469. 1,
  146470. 3,
  146471. 0,
  146472. 4,
  146473. };
  146474. static long _vq_lengthlist__44u0__p6_1[] = {
  146475. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146476. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146477. };
  146478. static float _vq_quantthresh__44u0__p6_1[] = {
  146479. -1.5, -0.5, 0.5, 1.5,
  146480. };
  146481. static long _vq_quantmap__44u0__p6_1[] = {
  146482. 3, 1, 0, 2, 4,
  146483. };
  146484. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146485. _vq_quantthresh__44u0__p6_1,
  146486. _vq_quantmap__44u0__p6_1,
  146487. 5,
  146488. 5
  146489. };
  146490. static static_codebook _44u0__p6_1 = {
  146491. 2, 25,
  146492. _vq_lengthlist__44u0__p6_1,
  146493. 1, -533725184, 1611661312, 3, 0,
  146494. _vq_quantlist__44u0__p6_1,
  146495. NULL,
  146496. &_vq_auxt__44u0__p6_1,
  146497. NULL,
  146498. 0
  146499. };
  146500. static long _vq_quantlist__44u0__p7_0[] = {
  146501. 2,
  146502. 1,
  146503. 3,
  146504. 0,
  146505. 4,
  146506. };
  146507. static long _vq_lengthlist__44u0__p7_0[] = {
  146508. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146511. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146514. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146515. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146516. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146517. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146519. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146520. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146521. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146522. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146523. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146524. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146525. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146526. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146527. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146528. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146534. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146538. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146539. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146540. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146541. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146542. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146543. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146544. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146545. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146546. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146547. 10,
  146548. };
  146549. static float _vq_quantthresh__44u0__p7_0[] = {
  146550. -253.5, -84.5, 84.5, 253.5,
  146551. };
  146552. static long _vq_quantmap__44u0__p7_0[] = {
  146553. 3, 1, 0, 2, 4,
  146554. };
  146555. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146556. _vq_quantthresh__44u0__p7_0,
  146557. _vq_quantmap__44u0__p7_0,
  146558. 5,
  146559. 5
  146560. };
  146561. static static_codebook _44u0__p7_0 = {
  146562. 4, 625,
  146563. _vq_lengthlist__44u0__p7_0,
  146564. 1, -518709248, 1626677248, 3, 0,
  146565. _vq_quantlist__44u0__p7_0,
  146566. NULL,
  146567. &_vq_auxt__44u0__p7_0,
  146568. NULL,
  146569. 0
  146570. };
  146571. static long _vq_quantlist__44u0__p7_1[] = {
  146572. 6,
  146573. 5,
  146574. 7,
  146575. 4,
  146576. 8,
  146577. 3,
  146578. 9,
  146579. 2,
  146580. 10,
  146581. 1,
  146582. 11,
  146583. 0,
  146584. 12,
  146585. };
  146586. static long _vq_lengthlist__44u0__p7_1[] = {
  146587. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146588. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146589. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146590. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146591. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146592. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146593. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146594. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146595. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146596. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146597. 15,15,15,15,15,15,15,15,15,
  146598. };
  146599. static float _vq_quantthresh__44u0__p7_1[] = {
  146600. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146601. 32.5, 45.5, 58.5, 71.5,
  146602. };
  146603. static long _vq_quantmap__44u0__p7_1[] = {
  146604. 11, 9, 7, 5, 3, 1, 0, 2,
  146605. 4, 6, 8, 10, 12,
  146606. };
  146607. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146608. _vq_quantthresh__44u0__p7_1,
  146609. _vq_quantmap__44u0__p7_1,
  146610. 13,
  146611. 13
  146612. };
  146613. static static_codebook _44u0__p7_1 = {
  146614. 2, 169,
  146615. _vq_lengthlist__44u0__p7_1,
  146616. 1, -523010048, 1618608128, 4, 0,
  146617. _vq_quantlist__44u0__p7_1,
  146618. NULL,
  146619. &_vq_auxt__44u0__p7_1,
  146620. NULL,
  146621. 0
  146622. };
  146623. static long _vq_quantlist__44u0__p7_2[] = {
  146624. 6,
  146625. 5,
  146626. 7,
  146627. 4,
  146628. 8,
  146629. 3,
  146630. 9,
  146631. 2,
  146632. 10,
  146633. 1,
  146634. 11,
  146635. 0,
  146636. 12,
  146637. };
  146638. static long _vq_lengthlist__44u0__p7_2[] = {
  146639. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146640. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146641. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146642. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146643. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146644. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146645. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146646. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146647. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146648. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146649. 9, 9, 9,10, 9, 9,10,10, 9,
  146650. };
  146651. static float _vq_quantthresh__44u0__p7_2[] = {
  146652. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146653. 2.5, 3.5, 4.5, 5.5,
  146654. };
  146655. static long _vq_quantmap__44u0__p7_2[] = {
  146656. 11, 9, 7, 5, 3, 1, 0, 2,
  146657. 4, 6, 8, 10, 12,
  146658. };
  146659. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146660. _vq_quantthresh__44u0__p7_2,
  146661. _vq_quantmap__44u0__p7_2,
  146662. 13,
  146663. 13
  146664. };
  146665. static static_codebook _44u0__p7_2 = {
  146666. 2, 169,
  146667. _vq_lengthlist__44u0__p7_2,
  146668. 1, -531103744, 1611661312, 4, 0,
  146669. _vq_quantlist__44u0__p7_2,
  146670. NULL,
  146671. &_vq_auxt__44u0__p7_2,
  146672. NULL,
  146673. 0
  146674. };
  146675. static long _huff_lengthlist__44u0__short[] = {
  146676. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146677. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146678. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146679. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146680. };
  146681. static static_codebook _huff_book__44u0__short = {
  146682. 2, 64,
  146683. _huff_lengthlist__44u0__short,
  146684. 0, 0, 0, 0, 0,
  146685. NULL,
  146686. NULL,
  146687. NULL,
  146688. NULL,
  146689. 0
  146690. };
  146691. static long _huff_lengthlist__44u1__long[] = {
  146692. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146693. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146694. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146695. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146696. };
  146697. static static_codebook _huff_book__44u1__long = {
  146698. 2, 64,
  146699. _huff_lengthlist__44u1__long,
  146700. 0, 0, 0, 0, 0,
  146701. NULL,
  146702. NULL,
  146703. NULL,
  146704. NULL,
  146705. 0
  146706. };
  146707. static long _vq_quantlist__44u1__p1_0[] = {
  146708. 1,
  146709. 0,
  146710. 2,
  146711. };
  146712. static long _vq_lengthlist__44u1__p1_0[] = {
  146713. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146714. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146715. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146716. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146717. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146718. 13,
  146719. };
  146720. static float _vq_quantthresh__44u1__p1_0[] = {
  146721. -0.5, 0.5,
  146722. };
  146723. static long _vq_quantmap__44u1__p1_0[] = {
  146724. 1, 0, 2,
  146725. };
  146726. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146727. _vq_quantthresh__44u1__p1_0,
  146728. _vq_quantmap__44u1__p1_0,
  146729. 3,
  146730. 3
  146731. };
  146732. static static_codebook _44u1__p1_0 = {
  146733. 4, 81,
  146734. _vq_lengthlist__44u1__p1_0,
  146735. 1, -535822336, 1611661312, 2, 0,
  146736. _vq_quantlist__44u1__p1_0,
  146737. NULL,
  146738. &_vq_auxt__44u1__p1_0,
  146739. NULL,
  146740. 0
  146741. };
  146742. static long _vq_quantlist__44u1__p2_0[] = {
  146743. 1,
  146744. 0,
  146745. 2,
  146746. };
  146747. static long _vq_lengthlist__44u1__p2_0[] = {
  146748. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146749. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146750. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146751. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146752. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146753. 9,
  146754. };
  146755. static float _vq_quantthresh__44u1__p2_0[] = {
  146756. -0.5, 0.5,
  146757. };
  146758. static long _vq_quantmap__44u1__p2_0[] = {
  146759. 1, 0, 2,
  146760. };
  146761. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146762. _vq_quantthresh__44u1__p2_0,
  146763. _vq_quantmap__44u1__p2_0,
  146764. 3,
  146765. 3
  146766. };
  146767. static static_codebook _44u1__p2_0 = {
  146768. 4, 81,
  146769. _vq_lengthlist__44u1__p2_0,
  146770. 1, -535822336, 1611661312, 2, 0,
  146771. _vq_quantlist__44u1__p2_0,
  146772. NULL,
  146773. &_vq_auxt__44u1__p2_0,
  146774. NULL,
  146775. 0
  146776. };
  146777. static long _vq_quantlist__44u1__p3_0[] = {
  146778. 2,
  146779. 1,
  146780. 3,
  146781. 0,
  146782. 4,
  146783. };
  146784. static long _vq_lengthlist__44u1__p3_0[] = {
  146785. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146786. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146787. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146788. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146789. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146790. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146791. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146792. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146793. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146794. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146795. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146796. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146797. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146798. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146799. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146800. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146801. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146802. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146803. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146804. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146805. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146806. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146807. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146808. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146809. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146810. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146811. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146812. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146813. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146814. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146815. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146816. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146817. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146818. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146819. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146820. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146821. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146822. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146823. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146824. 19,
  146825. };
  146826. static float _vq_quantthresh__44u1__p3_0[] = {
  146827. -1.5, -0.5, 0.5, 1.5,
  146828. };
  146829. static long _vq_quantmap__44u1__p3_0[] = {
  146830. 3, 1, 0, 2, 4,
  146831. };
  146832. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146833. _vq_quantthresh__44u1__p3_0,
  146834. _vq_quantmap__44u1__p3_0,
  146835. 5,
  146836. 5
  146837. };
  146838. static static_codebook _44u1__p3_0 = {
  146839. 4, 625,
  146840. _vq_lengthlist__44u1__p3_0,
  146841. 1, -533725184, 1611661312, 3, 0,
  146842. _vq_quantlist__44u1__p3_0,
  146843. NULL,
  146844. &_vq_auxt__44u1__p3_0,
  146845. NULL,
  146846. 0
  146847. };
  146848. static long _vq_quantlist__44u1__p4_0[] = {
  146849. 2,
  146850. 1,
  146851. 3,
  146852. 0,
  146853. 4,
  146854. };
  146855. static long _vq_lengthlist__44u1__p4_0[] = {
  146856. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146857. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146858. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146859. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146860. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146861. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146862. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146863. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146864. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146865. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146866. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146867. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146868. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146869. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146870. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146871. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146872. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146873. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146874. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146875. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146876. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146877. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146878. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146879. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146880. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146881. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146882. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146883. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146884. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146885. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146886. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146887. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146888. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146889. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146890. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146891. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146892. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146893. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146894. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146895. 12,
  146896. };
  146897. static float _vq_quantthresh__44u1__p4_0[] = {
  146898. -1.5, -0.5, 0.5, 1.5,
  146899. };
  146900. static long _vq_quantmap__44u1__p4_0[] = {
  146901. 3, 1, 0, 2, 4,
  146902. };
  146903. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146904. _vq_quantthresh__44u1__p4_0,
  146905. _vq_quantmap__44u1__p4_0,
  146906. 5,
  146907. 5
  146908. };
  146909. static static_codebook _44u1__p4_0 = {
  146910. 4, 625,
  146911. _vq_lengthlist__44u1__p4_0,
  146912. 1, -533725184, 1611661312, 3, 0,
  146913. _vq_quantlist__44u1__p4_0,
  146914. NULL,
  146915. &_vq_auxt__44u1__p4_0,
  146916. NULL,
  146917. 0
  146918. };
  146919. static long _vq_quantlist__44u1__p5_0[] = {
  146920. 4,
  146921. 3,
  146922. 5,
  146923. 2,
  146924. 6,
  146925. 1,
  146926. 7,
  146927. 0,
  146928. 8,
  146929. };
  146930. static long _vq_lengthlist__44u1__p5_0[] = {
  146931. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146932. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146933. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146934. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146935. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146936. 12,
  146937. };
  146938. static float _vq_quantthresh__44u1__p5_0[] = {
  146939. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146940. };
  146941. static long _vq_quantmap__44u1__p5_0[] = {
  146942. 7, 5, 3, 1, 0, 2, 4, 6,
  146943. 8,
  146944. };
  146945. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146946. _vq_quantthresh__44u1__p5_0,
  146947. _vq_quantmap__44u1__p5_0,
  146948. 9,
  146949. 9
  146950. };
  146951. static static_codebook _44u1__p5_0 = {
  146952. 2, 81,
  146953. _vq_lengthlist__44u1__p5_0,
  146954. 1, -531628032, 1611661312, 4, 0,
  146955. _vq_quantlist__44u1__p5_0,
  146956. NULL,
  146957. &_vq_auxt__44u1__p5_0,
  146958. NULL,
  146959. 0
  146960. };
  146961. static long _vq_quantlist__44u1__p6_0[] = {
  146962. 6,
  146963. 5,
  146964. 7,
  146965. 4,
  146966. 8,
  146967. 3,
  146968. 9,
  146969. 2,
  146970. 10,
  146971. 1,
  146972. 11,
  146973. 0,
  146974. 12,
  146975. };
  146976. static long _vq_lengthlist__44u1__p6_0[] = {
  146977. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146978. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146979. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146980. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146981. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146982. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146983. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146984. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146985. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146986. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146987. 15,17,16,17,18,17,17,18, 0,
  146988. };
  146989. static float _vq_quantthresh__44u1__p6_0[] = {
  146990. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146991. 12.5, 17.5, 22.5, 27.5,
  146992. };
  146993. static long _vq_quantmap__44u1__p6_0[] = {
  146994. 11, 9, 7, 5, 3, 1, 0, 2,
  146995. 4, 6, 8, 10, 12,
  146996. };
  146997. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146998. _vq_quantthresh__44u1__p6_0,
  146999. _vq_quantmap__44u1__p6_0,
  147000. 13,
  147001. 13
  147002. };
  147003. static static_codebook _44u1__p6_0 = {
  147004. 2, 169,
  147005. _vq_lengthlist__44u1__p6_0,
  147006. 1, -526516224, 1616117760, 4, 0,
  147007. _vq_quantlist__44u1__p6_0,
  147008. NULL,
  147009. &_vq_auxt__44u1__p6_0,
  147010. NULL,
  147011. 0
  147012. };
  147013. static long _vq_quantlist__44u1__p6_1[] = {
  147014. 2,
  147015. 1,
  147016. 3,
  147017. 0,
  147018. 4,
  147019. };
  147020. static long _vq_lengthlist__44u1__p6_1[] = {
  147021. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147022. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147023. };
  147024. static float _vq_quantthresh__44u1__p6_1[] = {
  147025. -1.5, -0.5, 0.5, 1.5,
  147026. };
  147027. static long _vq_quantmap__44u1__p6_1[] = {
  147028. 3, 1, 0, 2, 4,
  147029. };
  147030. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147031. _vq_quantthresh__44u1__p6_1,
  147032. _vq_quantmap__44u1__p6_1,
  147033. 5,
  147034. 5
  147035. };
  147036. static static_codebook _44u1__p6_1 = {
  147037. 2, 25,
  147038. _vq_lengthlist__44u1__p6_1,
  147039. 1, -533725184, 1611661312, 3, 0,
  147040. _vq_quantlist__44u1__p6_1,
  147041. NULL,
  147042. &_vq_auxt__44u1__p6_1,
  147043. NULL,
  147044. 0
  147045. };
  147046. static long _vq_quantlist__44u1__p7_0[] = {
  147047. 3,
  147048. 2,
  147049. 4,
  147050. 1,
  147051. 5,
  147052. 0,
  147053. 6,
  147054. };
  147055. static long _vq_lengthlist__44u1__p7_0[] = {
  147056. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147057. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147058. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147059. 8,
  147060. };
  147061. static float _vq_quantthresh__44u1__p7_0[] = {
  147062. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147063. };
  147064. static long _vq_quantmap__44u1__p7_0[] = {
  147065. 5, 3, 1, 0, 2, 4, 6,
  147066. };
  147067. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147068. _vq_quantthresh__44u1__p7_0,
  147069. _vq_quantmap__44u1__p7_0,
  147070. 7,
  147071. 7
  147072. };
  147073. static static_codebook _44u1__p7_0 = {
  147074. 2, 49,
  147075. _vq_lengthlist__44u1__p7_0,
  147076. 1, -518017024, 1626677248, 3, 0,
  147077. _vq_quantlist__44u1__p7_0,
  147078. NULL,
  147079. &_vq_auxt__44u1__p7_0,
  147080. NULL,
  147081. 0
  147082. };
  147083. static long _vq_quantlist__44u1__p7_1[] = {
  147084. 6,
  147085. 5,
  147086. 7,
  147087. 4,
  147088. 8,
  147089. 3,
  147090. 9,
  147091. 2,
  147092. 10,
  147093. 1,
  147094. 11,
  147095. 0,
  147096. 12,
  147097. };
  147098. static long _vq_lengthlist__44u1__p7_1[] = {
  147099. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147100. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147101. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147102. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147103. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147104. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147105. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147106. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147107. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147108. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147109. 15,15,15,15,15,15,15,15,15,
  147110. };
  147111. static float _vq_quantthresh__44u1__p7_1[] = {
  147112. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147113. 32.5, 45.5, 58.5, 71.5,
  147114. };
  147115. static long _vq_quantmap__44u1__p7_1[] = {
  147116. 11, 9, 7, 5, 3, 1, 0, 2,
  147117. 4, 6, 8, 10, 12,
  147118. };
  147119. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147120. _vq_quantthresh__44u1__p7_1,
  147121. _vq_quantmap__44u1__p7_1,
  147122. 13,
  147123. 13
  147124. };
  147125. static static_codebook _44u1__p7_1 = {
  147126. 2, 169,
  147127. _vq_lengthlist__44u1__p7_1,
  147128. 1, -523010048, 1618608128, 4, 0,
  147129. _vq_quantlist__44u1__p7_1,
  147130. NULL,
  147131. &_vq_auxt__44u1__p7_1,
  147132. NULL,
  147133. 0
  147134. };
  147135. static long _vq_quantlist__44u1__p7_2[] = {
  147136. 6,
  147137. 5,
  147138. 7,
  147139. 4,
  147140. 8,
  147141. 3,
  147142. 9,
  147143. 2,
  147144. 10,
  147145. 1,
  147146. 11,
  147147. 0,
  147148. 12,
  147149. };
  147150. static long _vq_lengthlist__44u1__p7_2[] = {
  147151. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147152. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147153. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147154. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147155. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147156. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147157. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147158. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147159. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147160. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147161. 9, 9, 9,10, 9, 9,10,10, 9,
  147162. };
  147163. static float _vq_quantthresh__44u1__p7_2[] = {
  147164. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147165. 2.5, 3.5, 4.5, 5.5,
  147166. };
  147167. static long _vq_quantmap__44u1__p7_2[] = {
  147168. 11, 9, 7, 5, 3, 1, 0, 2,
  147169. 4, 6, 8, 10, 12,
  147170. };
  147171. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147172. _vq_quantthresh__44u1__p7_2,
  147173. _vq_quantmap__44u1__p7_2,
  147174. 13,
  147175. 13
  147176. };
  147177. static static_codebook _44u1__p7_2 = {
  147178. 2, 169,
  147179. _vq_lengthlist__44u1__p7_2,
  147180. 1, -531103744, 1611661312, 4, 0,
  147181. _vq_quantlist__44u1__p7_2,
  147182. NULL,
  147183. &_vq_auxt__44u1__p7_2,
  147184. NULL,
  147185. 0
  147186. };
  147187. static long _huff_lengthlist__44u1__short[] = {
  147188. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147189. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147190. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147191. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147192. };
  147193. static static_codebook _huff_book__44u1__short = {
  147194. 2, 64,
  147195. _huff_lengthlist__44u1__short,
  147196. 0, 0, 0, 0, 0,
  147197. NULL,
  147198. NULL,
  147199. NULL,
  147200. NULL,
  147201. 0
  147202. };
  147203. static long _huff_lengthlist__44u2__long[] = {
  147204. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147205. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147206. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147207. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147208. };
  147209. static static_codebook _huff_book__44u2__long = {
  147210. 2, 64,
  147211. _huff_lengthlist__44u2__long,
  147212. 0, 0, 0, 0, 0,
  147213. NULL,
  147214. NULL,
  147215. NULL,
  147216. NULL,
  147217. 0
  147218. };
  147219. static long _vq_quantlist__44u2__p1_0[] = {
  147220. 1,
  147221. 0,
  147222. 2,
  147223. };
  147224. static long _vq_lengthlist__44u2__p1_0[] = {
  147225. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147226. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147227. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147228. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147229. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147230. 13,
  147231. };
  147232. static float _vq_quantthresh__44u2__p1_0[] = {
  147233. -0.5, 0.5,
  147234. };
  147235. static long _vq_quantmap__44u2__p1_0[] = {
  147236. 1, 0, 2,
  147237. };
  147238. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147239. _vq_quantthresh__44u2__p1_0,
  147240. _vq_quantmap__44u2__p1_0,
  147241. 3,
  147242. 3
  147243. };
  147244. static static_codebook _44u2__p1_0 = {
  147245. 4, 81,
  147246. _vq_lengthlist__44u2__p1_0,
  147247. 1, -535822336, 1611661312, 2, 0,
  147248. _vq_quantlist__44u2__p1_0,
  147249. NULL,
  147250. &_vq_auxt__44u2__p1_0,
  147251. NULL,
  147252. 0
  147253. };
  147254. static long _vq_quantlist__44u2__p2_0[] = {
  147255. 1,
  147256. 0,
  147257. 2,
  147258. };
  147259. static long _vq_lengthlist__44u2__p2_0[] = {
  147260. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147261. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147262. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147263. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147264. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147265. 9,
  147266. };
  147267. static float _vq_quantthresh__44u2__p2_0[] = {
  147268. -0.5, 0.5,
  147269. };
  147270. static long _vq_quantmap__44u2__p2_0[] = {
  147271. 1, 0, 2,
  147272. };
  147273. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147274. _vq_quantthresh__44u2__p2_0,
  147275. _vq_quantmap__44u2__p2_0,
  147276. 3,
  147277. 3
  147278. };
  147279. static static_codebook _44u2__p2_0 = {
  147280. 4, 81,
  147281. _vq_lengthlist__44u2__p2_0,
  147282. 1, -535822336, 1611661312, 2, 0,
  147283. _vq_quantlist__44u2__p2_0,
  147284. NULL,
  147285. &_vq_auxt__44u2__p2_0,
  147286. NULL,
  147287. 0
  147288. };
  147289. static long _vq_quantlist__44u2__p3_0[] = {
  147290. 2,
  147291. 1,
  147292. 3,
  147293. 0,
  147294. 4,
  147295. };
  147296. static long _vq_lengthlist__44u2__p3_0[] = {
  147297. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147298. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147299. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147300. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147301. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147302. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147303. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147304. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147305. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147306. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147307. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147308. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147309. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147310. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147311. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147312. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147313. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147314. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147315. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147316. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147317. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147318. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147319. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147320. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147321. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147322. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147323. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147324. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147325. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147326. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147327. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147328. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147329. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147330. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147331. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147332. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147333. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147334. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147335. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147336. 0,
  147337. };
  147338. static float _vq_quantthresh__44u2__p3_0[] = {
  147339. -1.5, -0.5, 0.5, 1.5,
  147340. };
  147341. static long _vq_quantmap__44u2__p3_0[] = {
  147342. 3, 1, 0, 2, 4,
  147343. };
  147344. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147345. _vq_quantthresh__44u2__p3_0,
  147346. _vq_quantmap__44u2__p3_0,
  147347. 5,
  147348. 5
  147349. };
  147350. static static_codebook _44u2__p3_0 = {
  147351. 4, 625,
  147352. _vq_lengthlist__44u2__p3_0,
  147353. 1, -533725184, 1611661312, 3, 0,
  147354. _vq_quantlist__44u2__p3_0,
  147355. NULL,
  147356. &_vq_auxt__44u2__p3_0,
  147357. NULL,
  147358. 0
  147359. };
  147360. static long _vq_quantlist__44u2__p4_0[] = {
  147361. 2,
  147362. 1,
  147363. 3,
  147364. 0,
  147365. 4,
  147366. };
  147367. static long _vq_lengthlist__44u2__p4_0[] = {
  147368. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147369. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147370. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147371. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147372. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147373. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147374. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147375. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147376. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147377. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147378. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147379. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147380. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147381. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147382. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147383. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147384. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147385. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147386. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147387. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147388. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147389. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147390. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147391. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147392. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147393. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147394. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147395. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147396. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147397. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147398. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147399. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147400. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147401. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147402. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147403. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147404. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147405. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147406. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147407. 13,
  147408. };
  147409. static float _vq_quantthresh__44u2__p4_0[] = {
  147410. -1.5, -0.5, 0.5, 1.5,
  147411. };
  147412. static long _vq_quantmap__44u2__p4_0[] = {
  147413. 3, 1, 0, 2, 4,
  147414. };
  147415. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147416. _vq_quantthresh__44u2__p4_0,
  147417. _vq_quantmap__44u2__p4_0,
  147418. 5,
  147419. 5
  147420. };
  147421. static static_codebook _44u2__p4_0 = {
  147422. 4, 625,
  147423. _vq_lengthlist__44u2__p4_0,
  147424. 1, -533725184, 1611661312, 3, 0,
  147425. _vq_quantlist__44u2__p4_0,
  147426. NULL,
  147427. &_vq_auxt__44u2__p4_0,
  147428. NULL,
  147429. 0
  147430. };
  147431. static long _vq_quantlist__44u2__p5_0[] = {
  147432. 4,
  147433. 3,
  147434. 5,
  147435. 2,
  147436. 6,
  147437. 1,
  147438. 7,
  147439. 0,
  147440. 8,
  147441. };
  147442. static long _vq_lengthlist__44u2__p5_0[] = {
  147443. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147444. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147445. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147446. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147447. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147448. 13,
  147449. };
  147450. static float _vq_quantthresh__44u2__p5_0[] = {
  147451. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147452. };
  147453. static long _vq_quantmap__44u2__p5_0[] = {
  147454. 7, 5, 3, 1, 0, 2, 4, 6,
  147455. 8,
  147456. };
  147457. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147458. _vq_quantthresh__44u2__p5_0,
  147459. _vq_quantmap__44u2__p5_0,
  147460. 9,
  147461. 9
  147462. };
  147463. static static_codebook _44u2__p5_0 = {
  147464. 2, 81,
  147465. _vq_lengthlist__44u2__p5_0,
  147466. 1, -531628032, 1611661312, 4, 0,
  147467. _vq_quantlist__44u2__p5_0,
  147468. NULL,
  147469. &_vq_auxt__44u2__p5_0,
  147470. NULL,
  147471. 0
  147472. };
  147473. static long _vq_quantlist__44u2__p6_0[] = {
  147474. 6,
  147475. 5,
  147476. 7,
  147477. 4,
  147478. 8,
  147479. 3,
  147480. 9,
  147481. 2,
  147482. 10,
  147483. 1,
  147484. 11,
  147485. 0,
  147486. 12,
  147487. };
  147488. static long _vq_lengthlist__44u2__p6_0[] = {
  147489. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147490. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147491. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147492. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147493. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147494. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147495. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147496. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147497. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147498. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147499. 15,17,17,16,18,17,18, 0, 0,
  147500. };
  147501. static float _vq_quantthresh__44u2__p6_0[] = {
  147502. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147503. 12.5, 17.5, 22.5, 27.5,
  147504. };
  147505. static long _vq_quantmap__44u2__p6_0[] = {
  147506. 11, 9, 7, 5, 3, 1, 0, 2,
  147507. 4, 6, 8, 10, 12,
  147508. };
  147509. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147510. _vq_quantthresh__44u2__p6_0,
  147511. _vq_quantmap__44u2__p6_0,
  147512. 13,
  147513. 13
  147514. };
  147515. static static_codebook _44u2__p6_0 = {
  147516. 2, 169,
  147517. _vq_lengthlist__44u2__p6_0,
  147518. 1, -526516224, 1616117760, 4, 0,
  147519. _vq_quantlist__44u2__p6_0,
  147520. NULL,
  147521. &_vq_auxt__44u2__p6_0,
  147522. NULL,
  147523. 0
  147524. };
  147525. static long _vq_quantlist__44u2__p6_1[] = {
  147526. 2,
  147527. 1,
  147528. 3,
  147529. 0,
  147530. 4,
  147531. };
  147532. static long _vq_lengthlist__44u2__p6_1[] = {
  147533. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147534. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147535. };
  147536. static float _vq_quantthresh__44u2__p6_1[] = {
  147537. -1.5, -0.5, 0.5, 1.5,
  147538. };
  147539. static long _vq_quantmap__44u2__p6_1[] = {
  147540. 3, 1, 0, 2, 4,
  147541. };
  147542. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147543. _vq_quantthresh__44u2__p6_1,
  147544. _vq_quantmap__44u2__p6_1,
  147545. 5,
  147546. 5
  147547. };
  147548. static static_codebook _44u2__p6_1 = {
  147549. 2, 25,
  147550. _vq_lengthlist__44u2__p6_1,
  147551. 1, -533725184, 1611661312, 3, 0,
  147552. _vq_quantlist__44u2__p6_1,
  147553. NULL,
  147554. &_vq_auxt__44u2__p6_1,
  147555. NULL,
  147556. 0
  147557. };
  147558. static long _vq_quantlist__44u2__p7_0[] = {
  147559. 4,
  147560. 3,
  147561. 5,
  147562. 2,
  147563. 6,
  147564. 1,
  147565. 7,
  147566. 0,
  147567. 8,
  147568. };
  147569. static long _vq_lengthlist__44u2__p7_0[] = {
  147570. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147571. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147572. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147573. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147575. 11,
  147576. };
  147577. static float _vq_quantthresh__44u2__p7_0[] = {
  147578. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147579. };
  147580. static long _vq_quantmap__44u2__p7_0[] = {
  147581. 7, 5, 3, 1, 0, 2, 4, 6,
  147582. 8,
  147583. };
  147584. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147585. _vq_quantthresh__44u2__p7_0,
  147586. _vq_quantmap__44u2__p7_0,
  147587. 9,
  147588. 9
  147589. };
  147590. static static_codebook _44u2__p7_0 = {
  147591. 2, 81,
  147592. _vq_lengthlist__44u2__p7_0,
  147593. 1, -516612096, 1626677248, 4, 0,
  147594. _vq_quantlist__44u2__p7_0,
  147595. NULL,
  147596. &_vq_auxt__44u2__p7_0,
  147597. NULL,
  147598. 0
  147599. };
  147600. static long _vq_quantlist__44u2__p7_1[] = {
  147601. 6,
  147602. 5,
  147603. 7,
  147604. 4,
  147605. 8,
  147606. 3,
  147607. 9,
  147608. 2,
  147609. 10,
  147610. 1,
  147611. 11,
  147612. 0,
  147613. 12,
  147614. };
  147615. static long _vq_lengthlist__44u2__p7_1[] = {
  147616. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147617. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147618. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147619. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147620. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147621. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147622. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147623. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147624. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147625. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147626. 14,14,14,17,15,17,17,17,17,
  147627. };
  147628. static float _vq_quantthresh__44u2__p7_1[] = {
  147629. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147630. 32.5, 45.5, 58.5, 71.5,
  147631. };
  147632. static long _vq_quantmap__44u2__p7_1[] = {
  147633. 11, 9, 7, 5, 3, 1, 0, 2,
  147634. 4, 6, 8, 10, 12,
  147635. };
  147636. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147637. _vq_quantthresh__44u2__p7_1,
  147638. _vq_quantmap__44u2__p7_1,
  147639. 13,
  147640. 13
  147641. };
  147642. static static_codebook _44u2__p7_1 = {
  147643. 2, 169,
  147644. _vq_lengthlist__44u2__p7_1,
  147645. 1, -523010048, 1618608128, 4, 0,
  147646. _vq_quantlist__44u2__p7_1,
  147647. NULL,
  147648. &_vq_auxt__44u2__p7_1,
  147649. NULL,
  147650. 0
  147651. };
  147652. static long _vq_quantlist__44u2__p7_2[] = {
  147653. 6,
  147654. 5,
  147655. 7,
  147656. 4,
  147657. 8,
  147658. 3,
  147659. 9,
  147660. 2,
  147661. 10,
  147662. 1,
  147663. 11,
  147664. 0,
  147665. 12,
  147666. };
  147667. static long _vq_lengthlist__44u2__p7_2[] = {
  147668. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147669. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147670. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147671. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147672. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147673. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147674. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147675. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147676. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147677. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147678. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147679. };
  147680. static float _vq_quantthresh__44u2__p7_2[] = {
  147681. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147682. 2.5, 3.5, 4.5, 5.5,
  147683. };
  147684. static long _vq_quantmap__44u2__p7_2[] = {
  147685. 11, 9, 7, 5, 3, 1, 0, 2,
  147686. 4, 6, 8, 10, 12,
  147687. };
  147688. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147689. _vq_quantthresh__44u2__p7_2,
  147690. _vq_quantmap__44u2__p7_2,
  147691. 13,
  147692. 13
  147693. };
  147694. static static_codebook _44u2__p7_2 = {
  147695. 2, 169,
  147696. _vq_lengthlist__44u2__p7_2,
  147697. 1, -531103744, 1611661312, 4, 0,
  147698. _vq_quantlist__44u2__p7_2,
  147699. NULL,
  147700. &_vq_auxt__44u2__p7_2,
  147701. NULL,
  147702. 0
  147703. };
  147704. static long _huff_lengthlist__44u2__short[] = {
  147705. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147706. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147707. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147708. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147709. };
  147710. static static_codebook _huff_book__44u2__short = {
  147711. 2, 64,
  147712. _huff_lengthlist__44u2__short,
  147713. 0, 0, 0, 0, 0,
  147714. NULL,
  147715. NULL,
  147716. NULL,
  147717. NULL,
  147718. 0
  147719. };
  147720. static long _huff_lengthlist__44u3__long[] = {
  147721. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147722. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147723. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147724. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147725. };
  147726. static static_codebook _huff_book__44u3__long = {
  147727. 2, 64,
  147728. _huff_lengthlist__44u3__long,
  147729. 0, 0, 0, 0, 0,
  147730. NULL,
  147731. NULL,
  147732. NULL,
  147733. NULL,
  147734. 0
  147735. };
  147736. static long _vq_quantlist__44u3__p1_0[] = {
  147737. 1,
  147738. 0,
  147739. 2,
  147740. };
  147741. static long _vq_lengthlist__44u3__p1_0[] = {
  147742. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147743. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147744. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147745. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147746. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147747. 13,
  147748. };
  147749. static float _vq_quantthresh__44u3__p1_0[] = {
  147750. -0.5, 0.5,
  147751. };
  147752. static long _vq_quantmap__44u3__p1_0[] = {
  147753. 1, 0, 2,
  147754. };
  147755. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147756. _vq_quantthresh__44u3__p1_0,
  147757. _vq_quantmap__44u3__p1_0,
  147758. 3,
  147759. 3
  147760. };
  147761. static static_codebook _44u3__p1_0 = {
  147762. 4, 81,
  147763. _vq_lengthlist__44u3__p1_0,
  147764. 1, -535822336, 1611661312, 2, 0,
  147765. _vq_quantlist__44u3__p1_0,
  147766. NULL,
  147767. &_vq_auxt__44u3__p1_0,
  147768. NULL,
  147769. 0
  147770. };
  147771. static long _vq_quantlist__44u3__p2_0[] = {
  147772. 1,
  147773. 0,
  147774. 2,
  147775. };
  147776. static long _vq_lengthlist__44u3__p2_0[] = {
  147777. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147778. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147779. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147780. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147781. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147782. 9,
  147783. };
  147784. static float _vq_quantthresh__44u3__p2_0[] = {
  147785. -0.5, 0.5,
  147786. };
  147787. static long _vq_quantmap__44u3__p2_0[] = {
  147788. 1, 0, 2,
  147789. };
  147790. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147791. _vq_quantthresh__44u3__p2_0,
  147792. _vq_quantmap__44u3__p2_0,
  147793. 3,
  147794. 3
  147795. };
  147796. static static_codebook _44u3__p2_0 = {
  147797. 4, 81,
  147798. _vq_lengthlist__44u3__p2_0,
  147799. 1, -535822336, 1611661312, 2, 0,
  147800. _vq_quantlist__44u3__p2_0,
  147801. NULL,
  147802. &_vq_auxt__44u3__p2_0,
  147803. NULL,
  147804. 0
  147805. };
  147806. static long _vq_quantlist__44u3__p3_0[] = {
  147807. 2,
  147808. 1,
  147809. 3,
  147810. 0,
  147811. 4,
  147812. };
  147813. static long _vq_lengthlist__44u3__p3_0[] = {
  147814. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147815. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147816. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147817. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147818. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147819. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147820. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147821. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147822. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147823. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147824. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147825. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147826. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147827. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147828. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147829. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147830. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147831. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147832. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147833. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147834. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147835. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147836. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147837. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147838. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147839. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147840. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147841. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147842. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147843. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147844. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147845. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147846. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147847. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147848. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147849. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147850. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147851. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147852. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147853. 0,
  147854. };
  147855. static float _vq_quantthresh__44u3__p3_0[] = {
  147856. -1.5, -0.5, 0.5, 1.5,
  147857. };
  147858. static long _vq_quantmap__44u3__p3_0[] = {
  147859. 3, 1, 0, 2, 4,
  147860. };
  147861. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147862. _vq_quantthresh__44u3__p3_0,
  147863. _vq_quantmap__44u3__p3_0,
  147864. 5,
  147865. 5
  147866. };
  147867. static static_codebook _44u3__p3_0 = {
  147868. 4, 625,
  147869. _vq_lengthlist__44u3__p3_0,
  147870. 1, -533725184, 1611661312, 3, 0,
  147871. _vq_quantlist__44u3__p3_0,
  147872. NULL,
  147873. &_vq_auxt__44u3__p3_0,
  147874. NULL,
  147875. 0
  147876. };
  147877. static long _vq_quantlist__44u3__p4_0[] = {
  147878. 2,
  147879. 1,
  147880. 3,
  147881. 0,
  147882. 4,
  147883. };
  147884. static long _vq_lengthlist__44u3__p4_0[] = {
  147885. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147886. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147887. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147888. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147889. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147890. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147891. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147892. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147893. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147894. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147895. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147896. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147897. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147898. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147899. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147900. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147901. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147902. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147903. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147904. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147905. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147906. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147907. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147908. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147909. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147910. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147911. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147912. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147913. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147914. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147915. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147916. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147917. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147918. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147919. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147920. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147921. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147922. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147923. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147924. 13,
  147925. };
  147926. static float _vq_quantthresh__44u3__p4_0[] = {
  147927. -1.5, -0.5, 0.5, 1.5,
  147928. };
  147929. static long _vq_quantmap__44u3__p4_0[] = {
  147930. 3, 1, 0, 2, 4,
  147931. };
  147932. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147933. _vq_quantthresh__44u3__p4_0,
  147934. _vq_quantmap__44u3__p4_0,
  147935. 5,
  147936. 5
  147937. };
  147938. static static_codebook _44u3__p4_0 = {
  147939. 4, 625,
  147940. _vq_lengthlist__44u3__p4_0,
  147941. 1, -533725184, 1611661312, 3, 0,
  147942. _vq_quantlist__44u3__p4_0,
  147943. NULL,
  147944. &_vq_auxt__44u3__p4_0,
  147945. NULL,
  147946. 0
  147947. };
  147948. static long _vq_quantlist__44u3__p5_0[] = {
  147949. 4,
  147950. 3,
  147951. 5,
  147952. 2,
  147953. 6,
  147954. 1,
  147955. 7,
  147956. 0,
  147957. 8,
  147958. };
  147959. static long _vq_lengthlist__44u3__p5_0[] = {
  147960. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147961. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147962. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147963. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147964. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147965. 12,
  147966. };
  147967. static float _vq_quantthresh__44u3__p5_0[] = {
  147968. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147969. };
  147970. static long _vq_quantmap__44u3__p5_0[] = {
  147971. 7, 5, 3, 1, 0, 2, 4, 6,
  147972. 8,
  147973. };
  147974. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147975. _vq_quantthresh__44u3__p5_0,
  147976. _vq_quantmap__44u3__p5_0,
  147977. 9,
  147978. 9
  147979. };
  147980. static static_codebook _44u3__p5_0 = {
  147981. 2, 81,
  147982. _vq_lengthlist__44u3__p5_0,
  147983. 1, -531628032, 1611661312, 4, 0,
  147984. _vq_quantlist__44u3__p5_0,
  147985. NULL,
  147986. &_vq_auxt__44u3__p5_0,
  147987. NULL,
  147988. 0
  147989. };
  147990. static long _vq_quantlist__44u3__p6_0[] = {
  147991. 6,
  147992. 5,
  147993. 7,
  147994. 4,
  147995. 8,
  147996. 3,
  147997. 9,
  147998. 2,
  147999. 10,
  148000. 1,
  148001. 11,
  148002. 0,
  148003. 12,
  148004. };
  148005. static long _vq_lengthlist__44u3__p6_0[] = {
  148006. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148007. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148008. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148009. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148010. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148011. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148012. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148013. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148014. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148015. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148016. 15,16,16,16,17,18,16,20,18,
  148017. };
  148018. static float _vq_quantthresh__44u3__p6_0[] = {
  148019. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148020. 12.5, 17.5, 22.5, 27.5,
  148021. };
  148022. static long _vq_quantmap__44u3__p6_0[] = {
  148023. 11, 9, 7, 5, 3, 1, 0, 2,
  148024. 4, 6, 8, 10, 12,
  148025. };
  148026. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148027. _vq_quantthresh__44u3__p6_0,
  148028. _vq_quantmap__44u3__p6_0,
  148029. 13,
  148030. 13
  148031. };
  148032. static static_codebook _44u3__p6_0 = {
  148033. 2, 169,
  148034. _vq_lengthlist__44u3__p6_0,
  148035. 1, -526516224, 1616117760, 4, 0,
  148036. _vq_quantlist__44u3__p6_0,
  148037. NULL,
  148038. &_vq_auxt__44u3__p6_0,
  148039. NULL,
  148040. 0
  148041. };
  148042. static long _vq_quantlist__44u3__p6_1[] = {
  148043. 2,
  148044. 1,
  148045. 3,
  148046. 0,
  148047. 4,
  148048. };
  148049. static long _vq_lengthlist__44u3__p6_1[] = {
  148050. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148051. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148052. };
  148053. static float _vq_quantthresh__44u3__p6_1[] = {
  148054. -1.5, -0.5, 0.5, 1.5,
  148055. };
  148056. static long _vq_quantmap__44u3__p6_1[] = {
  148057. 3, 1, 0, 2, 4,
  148058. };
  148059. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148060. _vq_quantthresh__44u3__p6_1,
  148061. _vq_quantmap__44u3__p6_1,
  148062. 5,
  148063. 5
  148064. };
  148065. static static_codebook _44u3__p6_1 = {
  148066. 2, 25,
  148067. _vq_lengthlist__44u3__p6_1,
  148068. 1, -533725184, 1611661312, 3, 0,
  148069. _vq_quantlist__44u3__p6_1,
  148070. NULL,
  148071. &_vq_auxt__44u3__p6_1,
  148072. NULL,
  148073. 0
  148074. };
  148075. static long _vq_quantlist__44u3__p7_0[] = {
  148076. 4,
  148077. 3,
  148078. 5,
  148079. 2,
  148080. 6,
  148081. 1,
  148082. 7,
  148083. 0,
  148084. 8,
  148085. };
  148086. static long _vq_lengthlist__44u3__p7_0[] = {
  148087. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148088. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148089. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148090. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148091. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148092. 9,
  148093. };
  148094. static float _vq_quantthresh__44u3__p7_0[] = {
  148095. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148096. };
  148097. static long _vq_quantmap__44u3__p7_0[] = {
  148098. 7, 5, 3, 1, 0, 2, 4, 6,
  148099. 8,
  148100. };
  148101. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148102. _vq_quantthresh__44u3__p7_0,
  148103. _vq_quantmap__44u3__p7_0,
  148104. 9,
  148105. 9
  148106. };
  148107. static static_codebook _44u3__p7_0 = {
  148108. 2, 81,
  148109. _vq_lengthlist__44u3__p7_0,
  148110. 1, -515907584, 1627381760, 4, 0,
  148111. _vq_quantlist__44u3__p7_0,
  148112. NULL,
  148113. &_vq_auxt__44u3__p7_0,
  148114. NULL,
  148115. 0
  148116. };
  148117. static long _vq_quantlist__44u3__p7_1[] = {
  148118. 7,
  148119. 6,
  148120. 8,
  148121. 5,
  148122. 9,
  148123. 4,
  148124. 10,
  148125. 3,
  148126. 11,
  148127. 2,
  148128. 12,
  148129. 1,
  148130. 13,
  148131. 0,
  148132. 14,
  148133. };
  148134. static long _vq_lengthlist__44u3__p7_1[] = {
  148135. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148136. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148137. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148138. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148139. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148140. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148141. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148142. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148143. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148144. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148145. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148146. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148147. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148148. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148149. 17,
  148150. };
  148151. static float _vq_quantthresh__44u3__p7_1[] = {
  148152. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148153. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148154. };
  148155. static long _vq_quantmap__44u3__p7_1[] = {
  148156. 13, 11, 9, 7, 5, 3, 1, 0,
  148157. 2, 4, 6, 8, 10, 12, 14,
  148158. };
  148159. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148160. _vq_quantthresh__44u3__p7_1,
  148161. _vq_quantmap__44u3__p7_1,
  148162. 15,
  148163. 15
  148164. };
  148165. static static_codebook _44u3__p7_1 = {
  148166. 2, 225,
  148167. _vq_lengthlist__44u3__p7_1,
  148168. 1, -522338304, 1620115456, 4, 0,
  148169. _vq_quantlist__44u3__p7_1,
  148170. NULL,
  148171. &_vq_auxt__44u3__p7_1,
  148172. NULL,
  148173. 0
  148174. };
  148175. static long _vq_quantlist__44u3__p7_2[] = {
  148176. 8,
  148177. 7,
  148178. 9,
  148179. 6,
  148180. 10,
  148181. 5,
  148182. 11,
  148183. 4,
  148184. 12,
  148185. 3,
  148186. 13,
  148187. 2,
  148188. 14,
  148189. 1,
  148190. 15,
  148191. 0,
  148192. 16,
  148193. };
  148194. static long _vq_lengthlist__44u3__p7_2[] = {
  148195. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148196. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148197. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148198. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148199. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148200. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148201. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148202. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148203. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148204. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148205. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148206. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148207. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148208. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148209. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148210. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148211. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148212. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148213. 11,
  148214. };
  148215. static float _vq_quantthresh__44u3__p7_2[] = {
  148216. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148217. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148218. };
  148219. static long _vq_quantmap__44u3__p7_2[] = {
  148220. 15, 13, 11, 9, 7, 5, 3, 1,
  148221. 0, 2, 4, 6, 8, 10, 12, 14,
  148222. 16,
  148223. };
  148224. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148225. _vq_quantthresh__44u3__p7_2,
  148226. _vq_quantmap__44u3__p7_2,
  148227. 17,
  148228. 17
  148229. };
  148230. static static_codebook _44u3__p7_2 = {
  148231. 2, 289,
  148232. _vq_lengthlist__44u3__p7_2,
  148233. 1, -529530880, 1611661312, 5, 0,
  148234. _vq_quantlist__44u3__p7_2,
  148235. NULL,
  148236. &_vq_auxt__44u3__p7_2,
  148237. NULL,
  148238. 0
  148239. };
  148240. static long _huff_lengthlist__44u3__short[] = {
  148241. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148242. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148243. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148244. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148245. };
  148246. static static_codebook _huff_book__44u3__short = {
  148247. 2, 64,
  148248. _huff_lengthlist__44u3__short,
  148249. 0, 0, 0, 0, 0,
  148250. NULL,
  148251. NULL,
  148252. NULL,
  148253. NULL,
  148254. 0
  148255. };
  148256. static long _huff_lengthlist__44u4__long[] = {
  148257. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148258. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148259. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148260. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148261. };
  148262. static static_codebook _huff_book__44u4__long = {
  148263. 2, 64,
  148264. _huff_lengthlist__44u4__long,
  148265. 0, 0, 0, 0, 0,
  148266. NULL,
  148267. NULL,
  148268. NULL,
  148269. NULL,
  148270. 0
  148271. };
  148272. static long _vq_quantlist__44u4__p1_0[] = {
  148273. 1,
  148274. 0,
  148275. 2,
  148276. };
  148277. static long _vq_lengthlist__44u4__p1_0[] = {
  148278. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148279. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148280. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148281. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148282. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148283. 13,
  148284. };
  148285. static float _vq_quantthresh__44u4__p1_0[] = {
  148286. -0.5, 0.5,
  148287. };
  148288. static long _vq_quantmap__44u4__p1_0[] = {
  148289. 1, 0, 2,
  148290. };
  148291. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148292. _vq_quantthresh__44u4__p1_0,
  148293. _vq_quantmap__44u4__p1_0,
  148294. 3,
  148295. 3
  148296. };
  148297. static static_codebook _44u4__p1_0 = {
  148298. 4, 81,
  148299. _vq_lengthlist__44u4__p1_0,
  148300. 1, -535822336, 1611661312, 2, 0,
  148301. _vq_quantlist__44u4__p1_0,
  148302. NULL,
  148303. &_vq_auxt__44u4__p1_0,
  148304. NULL,
  148305. 0
  148306. };
  148307. static long _vq_quantlist__44u4__p2_0[] = {
  148308. 1,
  148309. 0,
  148310. 2,
  148311. };
  148312. static long _vq_lengthlist__44u4__p2_0[] = {
  148313. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148314. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148315. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148316. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148317. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148318. 9,
  148319. };
  148320. static float _vq_quantthresh__44u4__p2_0[] = {
  148321. -0.5, 0.5,
  148322. };
  148323. static long _vq_quantmap__44u4__p2_0[] = {
  148324. 1, 0, 2,
  148325. };
  148326. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148327. _vq_quantthresh__44u4__p2_0,
  148328. _vq_quantmap__44u4__p2_0,
  148329. 3,
  148330. 3
  148331. };
  148332. static static_codebook _44u4__p2_0 = {
  148333. 4, 81,
  148334. _vq_lengthlist__44u4__p2_0,
  148335. 1, -535822336, 1611661312, 2, 0,
  148336. _vq_quantlist__44u4__p2_0,
  148337. NULL,
  148338. &_vq_auxt__44u4__p2_0,
  148339. NULL,
  148340. 0
  148341. };
  148342. static long _vq_quantlist__44u4__p3_0[] = {
  148343. 2,
  148344. 1,
  148345. 3,
  148346. 0,
  148347. 4,
  148348. };
  148349. static long _vq_lengthlist__44u4__p3_0[] = {
  148350. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148351. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148352. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148353. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148354. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148355. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148356. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148357. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148358. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148359. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148360. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148361. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148362. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148363. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148364. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148365. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148366. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148367. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148368. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148369. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148370. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148371. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148372. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148373. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148374. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148375. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148376. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148377. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148378. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148379. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148380. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148381. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148382. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148383. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148384. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148385. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148386. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148387. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148388. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148389. 0,
  148390. };
  148391. static float _vq_quantthresh__44u4__p3_0[] = {
  148392. -1.5, -0.5, 0.5, 1.5,
  148393. };
  148394. static long _vq_quantmap__44u4__p3_0[] = {
  148395. 3, 1, 0, 2, 4,
  148396. };
  148397. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148398. _vq_quantthresh__44u4__p3_0,
  148399. _vq_quantmap__44u4__p3_0,
  148400. 5,
  148401. 5
  148402. };
  148403. static static_codebook _44u4__p3_0 = {
  148404. 4, 625,
  148405. _vq_lengthlist__44u4__p3_0,
  148406. 1, -533725184, 1611661312, 3, 0,
  148407. _vq_quantlist__44u4__p3_0,
  148408. NULL,
  148409. &_vq_auxt__44u4__p3_0,
  148410. NULL,
  148411. 0
  148412. };
  148413. static long _vq_quantlist__44u4__p4_0[] = {
  148414. 2,
  148415. 1,
  148416. 3,
  148417. 0,
  148418. 4,
  148419. };
  148420. static long _vq_lengthlist__44u4__p4_0[] = {
  148421. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148422. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148423. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148424. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148425. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148426. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148427. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148428. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148429. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148430. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148431. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148432. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148433. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148434. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148435. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148436. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148437. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148438. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148439. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148440. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148441. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148442. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148443. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148444. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148445. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148446. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148447. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148448. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148449. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148450. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148451. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148452. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148453. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148454. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148455. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148456. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148457. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148458. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148459. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148460. 13,
  148461. };
  148462. static float _vq_quantthresh__44u4__p4_0[] = {
  148463. -1.5, -0.5, 0.5, 1.5,
  148464. };
  148465. static long _vq_quantmap__44u4__p4_0[] = {
  148466. 3, 1, 0, 2, 4,
  148467. };
  148468. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148469. _vq_quantthresh__44u4__p4_0,
  148470. _vq_quantmap__44u4__p4_0,
  148471. 5,
  148472. 5
  148473. };
  148474. static static_codebook _44u4__p4_0 = {
  148475. 4, 625,
  148476. _vq_lengthlist__44u4__p4_0,
  148477. 1, -533725184, 1611661312, 3, 0,
  148478. _vq_quantlist__44u4__p4_0,
  148479. NULL,
  148480. &_vq_auxt__44u4__p4_0,
  148481. NULL,
  148482. 0
  148483. };
  148484. static long _vq_quantlist__44u4__p5_0[] = {
  148485. 4,
  148486. 3,
  148487. 5,
  148488. 2,
  148489. 6,
  148490. 1,
  148491. 7,
  148492. 0,
  148493. 8,
  148494. };
  148495. static long _vq_lengthlist__44u4__p5_0[] = {
  148496. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148497. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148498. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148499. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148500. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148501. 12,
  148502. };
  148503. static float _vq_quantthresh__44u4__p5_0[] = {
  148504. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148505. };
  148506. static long _vq_quantmap__44u4__p5_0[] = {
  148507. 7, 5, 3, 1, 0, 2, 4, 6,
  148508. 8,
  148509. };
  148510. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148511. _vq_quantthresh__44u4__p5_0,
  148512. _vq_quantmap__44u4__p5_0,
  148513. 9,
  148514. 9
  148515. };
  148516. static static_codebook _44u4__p5_0 = {
  148517. 2, 81,
  148518. _vq_lengthlist__44u4__p5_0,
  148519. 1, -531628032, 1611661312, 4, 0,
  148520. _vq_quantlist__44u4__p5_0,
  148521. NULL,
  148522. &_vq_auxt__44u4__p5_0,
  148523. NULL,
  148524. 0
  148525. };
  148526. static long _vq_quantlist__44u4__p6_0[] = {
  148527. 6,
  148528. 5,
  148529. 7,
  148530. 4,
  148531. 8,
  148532. 3,
  148533. 9,
  148534. 2,
  148535. 10,
  148536. 1,
  148537. 11,
  148538. 0,
  148539. 12,
  148540. };
  148541. static long _vq_lengthlist__44u4__p6_0[] = {
  148542. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148543. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148544. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148545. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148546. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148547. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148548. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148549. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148550. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148551. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148552. 16,16,16,17,17,18,17,20,21,
  148553. };
  148554. static float _vq_quantthresh__44u4__p6_0[] = {
  148555. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148556. 12.5, 17.5, 22.5, 27.5,
  148557. };
  148558. static long _vq_quantmap__44u4__p6_0[] = {
  148559. 11, 9, 7, 5, 3, 1, 0, 2,
  148560. 4, 6, 8, 10, 12,
  148561. };
  148562. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148563. _vq_quantthresh__44u4__p6_0,
  148564. _vq_quantmap__44u4__p6_0,
  148565. 13,
  148566. 13
  148567. };
  148568. static static_codebook _44u4__p6_0 = {
  148569. 2, 169,
  148570. _vq_lengthlist__44u4__p6_0,
  148571. 1, -526516224, 1616117760, 4, 0,
  148572. _vq_quantlist__44u4__p6_0,
  148573. NULL,
  148574. &_vq_auxt__44u4__p6_0,
  148575. NULL,
  148576. 0
  148577. };
  148578. static long _vq_quantlist__44u4__p6_1[] = {
  148579. 2,
  148580. 1,
  148581. 3,
  148582. 0,
  148583. 4,
  148584. };
  148585. static long _vq_lengthlist__44u4__p6_1[] = {
  148586. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148587. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148588. };
  148589. static float _vq_quantthresh__44u4__p6_1[] = {
  148590. -1.5, -0.5, 0.5, 1.5,
  148591. };
  148592. static long _vq_quantmap__44u4__p6_1[] = {
  148593. 3, 1, 0, 2, 4,
  148594. };
  148595. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148596. _vq_quantthresh__44u4__p6_1,
  148597. _vq_quantmap__44u4__p6_1,
  148598. 5,
  148599. 5
  148600. };
  148601. static static_codebook _44u4__p6_1 = {
  148602. 2, 25,
  148603. _vq_lengthlist__44u4__p6_1,
  148604. 1, -533725184, 1611661312, 3, 0,
  148605. _vq_quantlist__44u4__p6_1,
  148606. NULL,
  148607. &_vq_auxt__44u4__p6_1,
  148608. NULL,
  148609. 0
  148610. };
  148611. static long _vq_quantlist__44u4__p7_0[] = {
  148612. 6,
  148613. 5,
  148614. 7,
  148615. 4,
  148616. 8,
  148617. 3,
  148618. 9,
  148619. 2,
  148620. 10,
  148621. 1,
  148622. 11,
  148623. 0,
  148624. 12,
  148625. };
  148626. static long _vq_lengthlist__44u4__p7_0[] = {
  148627. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148628. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148629. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148630. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148631. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148632. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148637. 11,11,11,11,11,11,11,11,11,
  148638. };
  148639. static float _vq_quantthresh__44u4__p7_0[] = {
  148640. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148641. 637.5, 892.5, 1147.5, 1402.5,
  148642. };
  148643. static long _vq_quantmap__44u4__p7_0[] = {
  148644. 11, 9, 7, 5, 3, 1, 0, 2,
  148645. 4, 6, 8, 10, 12,
  148646. };
  148647. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148648. _vq_quantthresh__44u4__p7_0,
  148649. _vq_quantmap__44u4__p7_0,
  148650. 13,
  148651. 13
  148652. };
  148653. static static_codebook _44u4__p7_0 = {
  148654. 2, 169,
  148655. _vq_lengthlist__44u4__p7_0,
  148656. 1, -514332672, 1627381760, 4, 0,
  148657. _vq_quantlist__44u4__p7_0,
  148658. NULL,
  148659. &_vq_auxt__44u4__p7_0,
  148660. NULL,
  148661. 0
  148662. };
  148663. static long _vq_quantlist__44u4__p7_1[] = {
  148664. 7,
  148665. 6,
  148666. 8,
  148667. 5,
  148668. 9,
  148669. 4,
  148670. 10,
  148671. 3,
  148672. 11,
  148673. 2,
  148674. 12,
  148675. 1,
  148676. 13,
  148677. 0,
  148678. 14,
  148679. };
  148680. static long _vq_lengthlist__44u4__p7_1[] = {
  148681. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148682. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148683. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148684. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148685. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148686. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148687. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148688. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148689. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148690. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148691. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148692. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148693. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148694. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148695. 16,
  148696. };
  148697. static float _vq_quantthresh__44u4__p7_1[] = {
  148698. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148699. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148700. };
  148701. static long _vq_quantmap__44u4__p7_1[] = {
  148702. 13, 11, 9, 7, 5, 3, 1, 0,
  148703. 2, 4, 6, 8, 10, 12, 14,
  148704. };
  148705. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148706. _vq_quantthresh__44u4__p7_1,
  148707. _vq_quantmap__44u4__p7_1,
  148708. 15,
  148709. 15
  148710. };
  148711. static static_codebook _44u4__p7_1 = {
  148712. 2, 225,
  148713. _vq_lengthlist__44u4__p7_1,
  148714. 1, -522338304, 1620115456, 4, 0,
  148715. _vq_quantlist__44u4__p7_1,
  148716. NULL,
  148717. &_vq_auxt__44u4__p7_1,
  148718. NULL,
  148719. 0
  148720. };
  148721. static long _vq_quantlist__44u4__p7_2[] = {
  148722. 8,
  148723. 7,
  148724. 9,
  148725. 6,
  148726. 10,
  148727. 5,
  148728. 11,
  148729. 4,
  148730. 12,
  148731. 3,
  148732. 13,
  148733. 2,
  148734. 14,
  148735. 1,
  148736. 15,
  148737. 0,
  148738. 16,
  148739. };
  148740. static long _vq_lengthlist__44u4__p7_2[] = {
  148741. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148742. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148743. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148744. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148745. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148746. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148747. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148748. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148749. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148750. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148751. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148752. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148753. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148754. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148755. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148756. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148757. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148758. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148759. 10,
  148760. };
  148761. static float _vq_quantthresh__44u4__p7_2[] = {
  148762. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148763. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148764. };
  148765. static long _vq_quantmap__44u4__p7_2[] = {
  148766. 15, 13, 11, 9, 7, 5, 3, 1,
  148767. 0, 2, 4, 6, 8, 10, 12, 14,
  148768. 16,
  148769. };
  148770. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148771. _vq_quantthresh__44u4__p7_2,
  148772. _vq_quantmap__44u4__p7_2,
  148773. 17,
  148774. 17
  148775. };
  148776. static static_codebook _44u4__p7_2 = {
  148777. 2, 289,
  148778. _vq_lengthlist__44u4__p7_2,
  148779. 1, -529530880, 1611661312, 5, 0,
  148780. _vq_quantlist__44u4__p7_2,
  148781. NULL,
  148782. &_vq_auxt__44u4__p7_2,
  148783. NULL,
  148784. 0
  148785. };
  148786. static long _huff_lengthlist__44u4__short[] = {
  148787. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148788. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148789. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148790. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148791. };
  148792. static static_codebook _huff_book__44u4__short = {
  148793. 2, 64,
  148794. _huff_lengthlist__44u4__short,
  148795. 0, 0, 0, 0, 0,
  148796. NULL,
  148797. NULL,
  148798. NULL,
  148799. NULL,
  148800. 0
  148801. };
  148802. static long _huff_lengthlist__44u5__long[] = {
  148803. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148804. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148805. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148806. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148807. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148808. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148809. 14, 8, 7, 8,
  148810. };
  148811. static static_codebook _huff_book__44u5__long = {
  148812. 2, 100,
  148813. _huff_lengthlist__44u5__long,
  148814. 0, 0, 0, 0, 0,
  148815. NULL,
  148816. NULL,
  148817. NULL,
  148818. NULL,
  148819. 0
  148820. };
  148821. static long _vq_quantlist__44u5__p1_0[] = {
  148822. 1,
  148823. 0,
  148824. 2,
  148825. };
  148826. static long _vq_lengthlist__44u5__p1_0[] = {
  148827. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148828. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148829. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148830. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148831. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148832. 12,
  148833. };
  148834. static float _vq_quantthresh__44u5__p1_0[] = {
  148835. -0.5, 0.5,
  148836. };
  148837. static long _vq_quantmap__44u5__p1_0[] = {
  148838. 1, 0, 2,
  148839. };
  148840. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148841. _vq_quantthresh__44u5__p1_0,
  148842. _vq_quantmap__44u5__p1_0,
  148843. 3,
  148844. 3
  148845. };
  148846. static static_codebook _44u5__p1_0 = {
  148847. 4, 81,
  148848. _vq_lengthlist__44u5__p1_0,
  148849. 1, -535822336, 1611661312, 2, 0,
  148850. _vq_quantlist__44u5__p1_0,
  148851. NULL,
  148852. &_vq_auxt__44u5__p1_0,
  148853. NULL,
  148854. 0
  148855. };
  148856. static long _vq_quantlist__44u5__p2_0[] = {
  148857. 1,
  148858. 0,
  148859. 2,
  148860. };
  148861. static long _vq_lengthlist__44u5__p2_0[] = {
  148862. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148863. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148864. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148865. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148866. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148867. 9,
  148868. };
  148869. static float _vq_quantthresh__44u5__p2_0[] = {
  148870. -0.5, 0.5,
  148871. };
  148872. static long _vq_quantmap__44u5__p2_0[] = {
  148873. 1, 0, 2,
  148874. };
  148875. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148876. _vq_quantthresh__44u5__p2_0,
  148877. _vq_quantmap__44u5__p2_0,
  148878. 3,
  148879. 3
  148880. };
  148881. static static_codebook _44u5__p2_0 = {
  148882. 4, 81,
  148883. _vq_lengthlist__44u5__p2_0,
  148884. 1, -535822336, 1611661312, 2, 0,
  148885. _vq_quantlist__44u5__p2_0,
  148886. NULL,
  148887. &_vq_auxt__44u5__p2_0,
  148888. NULL,
  148889. 0
  148890. };
  148891. static long _vq_quantlist__44u5__p3_0[] = {
  148892. 2,
  148893. 1,
  148894. 3,
  148895. 0,
  148896. 4,
  148897. };
  148898. static long _vq_lengthlist__44u5__p3_0[] = {
  148899. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148900. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148901. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148902. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148903. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148904. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148905. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148906. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148907. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148908. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148909. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148910. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148911. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148912. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148913. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148914. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148915. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148916. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148917. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148918. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148919. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148920. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148921. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148922. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148923. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148924. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148925. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148926. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148927. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148928. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148929. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148930. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148931. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148932. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148933. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148934. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148935. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148936. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148937. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148938. 0,
  148939. };
  148940. static float _vq_quantthresh__44u5__p3_0[] = {
  148941. -1.5, -0.5, 0.5, 1.5,
  148942. };
  148943. static long _vq_quantmap__44u5__p3_0[] = {
  148944. 3, 1, 0, 2, 4,
  148945. };
  148946. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148947. _vq_quantthresh__44u5__p3_0,
  148948. _vq_quantmap__44u5__p3_0,
  148949. 5,
  148950. 5
  148951. };
  148952. static static_codebook _44u5__p3_0 = {
  148953. 4, 625,
  148954. _vq_lengthlist__44u5__p3_0,
  148955. 1, -533725184, 1611661312, 3, 0,
  148956. _vq_quantlist__44u5__p3_0,
  148957. NULL,
  148958. &_vq_auxt__44u5__p3_0,
  148959. NULL,
  148960. 0
  148961. };
  148962. static long _vq_quantlist__44u5__p4_0[] = {
  148963. 2,
  148964. 1,
  148965. 3,
  148966. 0,
  148967. 4,
  148968. };
  148969. static long _vq_lengthlist__44u5__p4_0[] = {
  148970. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148971. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148972. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148973. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148974. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148975. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148976. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148977. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148978. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148979. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148980. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148981. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148982. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148983. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148984. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148985. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148986. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148987. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148988. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148989. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148990. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148991. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148992. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148993. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148994. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148995. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148996. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148997. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148998. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148999. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149000. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149001. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149002. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149003. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149004. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149005. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149006. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149007. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149008. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149009. 12,
  149010. };
  149011. static float _vq_quantthresh__44u5__p4_0[] = {
  149012. -1.5, -0.5, 0.5, 1.5,
  149013. };
  149014. static long _vq_quantmap__44u5__p4_0[] = {
  149015. 3, 1, 0, 2, 4,
  149016. };
  149017. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149018. _vq_quantthresh__44u5__p4_0,
  149019. _vq_quantmap__44u5__p4_0,
  149020. 5,
  149021. 5
  149022. };
  149023. static static_codebook _44u5__p4_0 = {
  149024. 4, 625,
  149025. _vq_lengthlist__44u5__p4_0,
  149026. 1, -533725184, 1611661312, 3, 0,
  149027. _vq_quantlist__44u5__p4_0,
  149028. NULL,
  149029. &_vq_auxt__44u5__p4_0,
  149030. NULL,
  149031. 0
  149032. };
  149033. static long _vq_quantlist__44u5__p5_0[] = {
  149034. 4,
  149035. 3,
  149036. 5,
  149037. 2,
  149038. 6,
  149039. 1,
  149040. 7,
  149041. 0,
  149042. 8,
  149043. };
  149044. static long _vq_lengthlist__44u5__p5_0[] = {
  149045. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149046. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149047. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149048. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149049. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149050. 14,
  149051. };
  149052. static float _vq_quantthresh__44u5__p5_0[] = {
  149053. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149054. };
  149055. static long _vq_quantmap__44u5__p5_0[] = {
  149056. 7, 5, 3, 1, 0, 2, 4, 6,
  149057. 8,
  149058. };
  149059. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149060. _vq_quantthresh__44u5__p5_0,
  149061. _vq_quantmap__44u5__p5_0,
  149062. 9,
  149063. 9
  149064. };
  149065. static static_codebook _44u5__p5_0 = {
  149066. 2, 81,
  149067. _vq_lengthlist__44u5__p5_0,
  149068. 1, -531628032, 1611661312, 4, 0,
  149069. _vq_quantlist__44u5__p5_0,
  149070. NULL,
  149071. &_vq_auxt__44u5__p5_0,
  149072. NULL,
  149073. 0
  149074. };
  149075. static long _vq_quantlist__44u5__p6_0[] = {
  149076. 4,
  149077. 3,
  149078. 5,
  149079. 2,
  149080. 6,
  149081. 1,
  149082. 7,
  149083. 0,
  149084. 8,
  149085. };
  149086. static long _vq_lengthlist__44u5__p6_0[] = {
  149087. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149088. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149089. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149090. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149091. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149092. 11,
  149093. };
  149094. static float _vq_quantthresh__44u5__p6_0[] = {
  149095. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149096. };
  149097. static long _vq_quantmap__44u5__p6_0[] = {
  149098. 7, 5, 3, 1, 0, 2, 4, 6,
  149099. 8,
  149100. };
  149101. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149102. _vq_quantthresh__44u5__p6_0,
  149103. _vq_quantmap__44u5__p6_0,
  149104. 9,
  149105. 9
  149106. };
  149107. static static_codebook _44u5__p6_0 = {
  149108. 2, 81,
  149109. _vq_lengthlist__44u5__p6_0,
  149110. 1, -531628032, 1611661312, 4, 0,
  149111. _vq_quantlist__44u5__p6_0,
  149112. NULL,
  149113. &_vq_auxt__44u5__p6_0,
  149114. NULL,
  149115. 0
  149116. };
  149117. static long _vq_quantlist__44u5__p7_0[] = {
  149118. 1,
  149119. 0,
  149120. 2,
  149121. };
  149122. static long _vq_lengthlist__44u5__p7_0[] = {
  149123. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149124. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149125. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149126. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149127. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149128. 12,
  149129. };
  149130. static float _vq_quantthresh__44u5__p7_0[] = {
  149131. -5.5, 5.5,
  149132. };
  149133. static long _vq_quantmap__44u5__p7_0[] = {
  149134. 1, 0, 2,
  149135. };
  149136. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149137. _vq_quantthresh__44u5__p7_0,
  149138. _vq_quantmap__44u5__p7_0,
  149139. 3,
  149140. 3
  149141. };
  149142. static static_codebook _44u5__p7_0 = {
  149143. 4, 81,
  149144. _vq_lengthlist__44u5__p7_0,
  149145. 1, -529137664, 1618345984, 2, 0,
  149146. _vq_quantlist__44u5__p7_0,
  149147. NULL,
  149148. &_vq_auxt__44u5__p7_0,
  149149. NULL,
  149150. 0
  149151. };
  149152. static long _vq_quantlist__44u5__p7_1[] = {
  149153. 5,
  149154. 4,
  149155. 6,
  149156. 3,
  149157. 7,
  149158. 2,
  149159. 8,
  149160. 1,
  149161. 9,
  149162. 0,
  149163. 10,
  149164. };
  149165. static long _vq_lengthlist__44u5__p7_1[] = {
  149166. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149167. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149168. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149169. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149170. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149171. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149172. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149173. 9, 9, 9, 9, 9,10,10,10,10,
  149174. };
  149175. static float _vq_quantthresh__44u5__p7_1[] = {
  149176. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149177. 3.5, 4.5,
  149178. };
  149179. static long _vq_quantmap__44u5__p7_1[] = {
  149180. 9, 7, 5, 3, 1, 0, 2, 4,
  149181. 6, 8, 10,
  149182. };
  149183. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149184. _vq_quantthresh__44u5__p7_1,
  149185. _vq_quantmap__44u5__p7_1,
  149186. 11,
  149187. 11
  149188. };
  149189. static static_codebook _44u5__p7_1 = {
  149190. 2, 121,
  149191. _vq_lengthlist__44u5__p7_1,
  149192. 1, -531365888, 1611661312, 4, 0,
  149193. _vq_quantlist__44u5__p7_1,
  149194. NULL,
  149195. &_vq_auxt__44u5__p7_1,
  149196. NULL,
  149197. 0
  149198. };
  149199. static long _vq_quantlist__44u5__p8_0[] = {
  149200. 5,
  149201. 4,
  149202. 6,
  149203. 3,
  149204. 7,
  149205. 2,
  149206. 8,
  149207. 1,
  149208. 9,
  149209. 0,
  149210. 10,
  149211. };
  149212. static long _vq_lengthlist__44u5__p8_0[] = {
  149213. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149214. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149215. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149216. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149217. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149218. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149219. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149220. 12,13,13,14,14,14,14,15,15,
  149221. };
  149222. static float _vq_quantthresh__44u5__p8_0[] = {
  149223. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149224. 38.5, 49.5,
  149225. };
  149226. static long _vq_quantmap__44u5__p8_0[] = {
  149227. 9, 7, 5, 3, 1, 0, 2, 4,
  149228. 6, 8, 10,
  149229. };
  149230. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149231. _vq_quantthresh__44u5__p8_0,
  149232. _vq_quantmap__44u5__p8_0,
  149233. 11,
  149234. 11
  149235. };
  149236. static static_codebook _44u5__p8_0 = {
  149237. 2, 121,
  149238. _vq_lengthlist__44u5__p8_0,
  149239. 1, -524582912, 1618345984, 4, 0,
  149240. _vq_quantlist__44u5__p8_0,
  149241. NULL,
  149242. &_vq_auxt__44u5__p8_0,
  149243. NULL,
  149244. 0
  149245. };
  149246. static long _vq_quantlist__44u5__p8_1[] = {
  149247. 5,
  149248. 4,
  149249. 6,
  149250. 3,
  149251. 7,
  149252. 2,
  149253. 8,
  149254. 1,
  149255. 9,
  149256. 0,
  149257. 10,
  149258. };
  149259. static long _vq_lengthlist__44u5__p8_1[] = {
  149260. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149261. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149262. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149263. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149264. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149265. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149266. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149267. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149268. };
  149269. static float _vq_quantthresh__44u5__p8_1[] = {
  149270. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149271. 3.5, 4.5,
  149272. };
  149273. static long _vq_quantmap__44u5__p8_1[] = {
  149274. 9, 7, 5, 3, 1, 0, 2, 4,
  149275. 6, 8, 10,
  149276. };
  149277. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149278. _vq_quantthresh__44u5__p8_1,
  149279. _vq_quantmap__44u5__p8_1,
  149280. 11,
  149281. 11
  149282. };
  149283. static static_codebook _44u5__p8_1 = {
  149284. 2, 121,
  149285. _vq_lengthlist__44u5__p8_1,
  149286. 1, -531365888, 1611661312, 4, 0,
  149287. _vq_quantlist__44u5__p8_1,
  149288. NULL,
  149289. &_vq_auxt__44u5__p8_1,
  149290. NULL,
  149291. 0
  149292. };
  149293. static long _vq_quantlist__44u5__p9_0[] = {
  149294. 6,
  149295. 5,
  149296. 7,
  149297. 4,
  149298. 8,
  149299. 3,
  149300. 9,
  149301. 2,
  149302. 10,
  149303. 1,
  149304. 11,
  149305. 0,
  149306. 12,
  149307. };
  149308. static long _vq_lengthlist__44u5__p9_0[] = {
  149309. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149310. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149311. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149312. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149313. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149314. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149315. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149316. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149317. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149318. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149319. 12,12,12,12,12,12,12,12,12,
  149320. };
  149321. static float _vq_quantthresh__44u5__p9_0[] = {
  149322. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149323. 637.5, 892.5, 1147.5, 1402.5,
  149324. };
  149325. static long _vq_quantmap__44u5__p9_0[] = {
  149326. 11, 9, 7, 5, 3, 1, 0, 2,
  149327. 4, 6, 8, 10, 12,
  149328. };
  149329. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149330. _vq_quantthresh__44u5__p9_0,
  149331. _vq_quantmap__44u5__p9_0,
  149332. 13,
  149333. 13
  149334. };
  149335. static static_codebook _44u5__p9_0 = {
  149336. 2, 169,
  149337. _vq_lengthlist__44u5__p9_0,
  149338. 1, -514332672, 1627381760, 4, 0,
  149339. _vq_quantlist__44u5__p9_0,
  149340. NULL,
  149341. &_vq_auxt__44u5__p9_0,
  149342. NULL,
  149343. 0
  149344. };
  149345. static long _vq_quantlist__44u5__p9_1[] = {
  149346. 7,
  149347. 6,
  149348. 8,
  149349. 5,
  149350. 9,
  149351. 4,
  149352. 10,
  149353. 3,
  149354. 11,
  149355. 2,
  149356. 12,
  149357. 1,
  149358. 13,
  149359. 0,
  149360. 14,
  149361. };
  149362. static long _vq_lengthlist__44u5__p9_1[] = {
  149363. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149364. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149365. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149366. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149367. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149368. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149369. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149370. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149371. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149372. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149373. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149374. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149375. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149376. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149377. 14,
  149378. };
  149379. static float _vq_quantthresh__44u5__p9_1[] = {
  149380. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149381. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149382. };
  149383. static long _vq_quantmap__44u5__p9_1[] = {
  149384. 13, 11, 9, 7, 5, 3, 1, 0,
  149385. 2, 4, 6, 8, 10, 12, 14,
  149386. };
  149387. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149388. _vq_quantthresh__44u5__p9_1,
  149389. _vq_quantmap__44u5__p9_1,
  149390. 15,
  149391. 15
  149392. };
  149393. static static_codebook _44u5__p9_1 = {
  149394. 2, 225,
  149395. _vq_lengthlist__44u5__p9_1,
  149396. 1, -522338304, 1620115456, 4, 0,
  149397. _vq_quantlist__44u5__p9_1,
  149398. NULL,
  149399. &_vq_auxt__44u5__p9_1,
  149400. NULL,
  149401. 0
  149402. };
  149403. static long _vq_quantlist__44u5__p9_2[] = {
  149404. 8,
  149405. 7,
  149406. 9,
  149407. 6,
  149408. 10,
  149409. 5,
  149410. 11,
  149411. 4,
  149412. 12,
  149413. 3,
  149414. 13,
  149415. 2,
  149416. 14,
  149417. 1,
  149418. 15,
  149419. 0,
  149420. 16,
  149421. };
  149422. static long _vq_lengthlist__44u5__p9_2[] = {
  149423. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149424. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149425. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149426. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149427. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149428. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149429. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149430. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149431. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149432. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149433. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149434. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149435. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149436. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149437. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149438. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149439. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149440. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149441. 10,
  149442. };
  149443. static float _vq_quantthresh__44u5__p9_2[] = {
  149444. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149445. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149446. };
  149447. static long _vq_quantmap__44u5__p9_2[] = {
  149448. 15, 13, 11, 9, 7, 5, 3, 1,
  149449. 0, 2, 4, 6, 8, 10, 12, 14,
  149450. 16,
  149451. };
  149452. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149453. _vq_quantthresh__44u5__p9_2,
  149454. _vq_quantmap__44u5__p9_2,
  149455. 17,
  149456. 17
  149457. };
  149458. static static_codebook _44u5__p9_2 = {
  149459. 2, 289,
  149460. _vq_lengthlist__44u5__p9_2,
  149461. 1, -529530880, 1611661312, 5, 0,
  149462. _vq_quantlist__44u5__p9_2,
  149463. NULL,
  149464. &_vq_auxt__44u5__p9_2,
  149465. NULL,
  149466. 0
  149467. };
  149468. static long _huff_lengthlist__44u5__short[] = {
  149469. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149470. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149471. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149472. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149473. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149474. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149475. 6, 8,15,17,
  149476. };
  149477. static static_codebook _huff_book__44u5__short = {
  149478. 2, 100,
  149479. _huff_lengthlist__44u5__short,
  149480. 0, 0, 0, 0, 0,
  149481. NULL,
  149482. NULL,
  149483. NULL,
  149484. NULL,
  149485. 0
  149486. };
  149487. static long _huff_lengthlist__44u6__long[] = {
  149488. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149489. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149490. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149491. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149492. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149493. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149494. 13, 8, 7, 7,
  149495. };
  149496. static static_codebook _huff_book__44u6__long = {
  149497. 2, 100,
  149498. _huff_lengthlist__44u6__long,
  149499. 0, 0, 0, 0, 0,
  149500. NULL,
  149501. NULL,
  149502. NULL,
  149503. NULL,
  149504. 0
  149505. };
  149506. static long _vq_quantlist__44u6__p1_0[] = {
  149507. 1,
  149508. 0,
  149509. 2,
  149510. };
  149511. static long _vq_lengthlist__44u6__p1_0[] = {
  149512. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149513. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149514. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149515. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149516. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149517. 12,
  149518. };
  149519. static float _vq_quantthresh__44u6__p1_0[] = {
  149520. -0.5, 0.5,
  149521. };
  149522. static long _vq_quantmap__44u6__p1_0[] = {
  149523. 1, 0, 2,
  149524. };
  149525. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149526. _vq_quantthresh__44u6__p1_0,
  149527. _vq_quantmap__44u6__p1_0,
  149528. 3,
  149529. 3
  149530. };
  149531. static static_codebook _44u6__p1_0 = {
  149532. 4, 81,
  149533. _vq_lengthlist__44u6__p1_0,
  149534. 1, -535822336, 1611661312, 2, 0,
  149535. _vq_quantlist__44u6__p1_0,
  149536. NULL,
  149537. &_vq_auxt__44u6__p1_0,
  149538. NULL,
  149539. 0
  149540. };
  149541. static long _vq_quantlist__44u6__p2_0[] = {
  149542. 1,
  149543. 0,
  149544. 2,
  149545. };
  149546. static long _vq_lengthlist__44u6__p2_0[] = {
  149547. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149548. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149549. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149550. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149551. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149552. 9,
  149553. };
  149554. static float _vq_quantthresh__44u6__p2_0[] = {
  149555. -0.5, 0.5,
  149556. };
  149557. static long _vq_quantmap__44u6__p2_0[] = {
  149558. 1, 0, 2,
  149559. };
  149560. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149561. _vq_quantthresh__44u6__p2_0,
  149562. _vq_quantmap__44u6__p2_0,
  149563. 3,
  149564. 3
  149565. };
  149566. static static_codebook _44u6__p2_0 = {
  149567. 4, 81,
  149568. _vq_lengthlist__44u6__p2_0,
  149569. 1, -535822336, 1611661312, 2, 0,
  149570. _vq_quantlist__44u6__p2_0,
  149571. NULL,
  149572. &_vq_auxt__44u6__p2_0,
  149573. NULL,
  149574. 0
  149575. };
  149576. static long _vq_quantlist__44u6__p3_0[] = {
  149577. 2,
  149578. 1,
  149579. 3,
  149580. 0,
  149581. 4,
  149582. };
  149583. static long _vq_lengthlist__44u6__p3_0[] = {
  149584. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149585. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149586. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149587. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149588. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149589. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149590. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149591. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149592. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149593. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149594. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149595. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149596. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149597. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149598. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149599. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149600. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149601. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149602. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149603. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149604. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149605. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149606. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149607. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149608. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149609. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149610. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149611. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149612. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149613. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149614. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149615. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149616. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149617. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149618. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149619. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149620. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149621. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149622. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149623. 19,
  149624. };
  149625. static float _vq_quantthresh__44u6__p3_0[] = {
  149626. -1.5, -0.5, 0.5, 1.5,
  149627. };
  149628. static long _vq_quantmap__44u6__p3_0[] = {
  149629. 3, 1, 0, 2, 4,
  149630. };
  149631. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149632. _vq_quantthresh__44u6__p3_0,
  149633. _vq_quantmap__44u6__p3_0,
  149634. 5,
  149635. 5
  149636. };
  149637. static static_codebook _44u6__p3_0 = {
  149638. 4, 625,
  149639. _vq_lengthlist__44u6__p3_0,
  149640. 1, -533725184, 1611661312, 3, 0,
  149641. _vq_quantlist__44u6__p3_0,
  149642. NULL,
  149643. &_vq_auxt__44u6__p3_0,
  149644. NULL,
  149645. 0
  149646. };
  149647. static long _vq_quantlist__44u6__p4_0[] = {
  149648. 2,
  149649. 1,
  149650. 3,
  149651. 0,
  149652. 4,
  149653. };
  149654. static long _vq_lengthlist__44u6__p4_0[] = {
  149655. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149656. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149657. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149658. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149659. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149660. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149661. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149662. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149663. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149664. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149665. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149666. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149667. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149668. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149669. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149670. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149671. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149672. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149673. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149674. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149675. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149676. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149677. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149678. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149679. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149680. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149681. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149682. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149683. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149684. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149685. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149686. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149687. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149688. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149689. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149690. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149691. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149692. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149693. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149694. 13,
  149695. };
  149696. static float _vq_quantthresh__44u6__p4_0[] = {
  149697. -1.5, -0.5, 0.5, 1.5,
  149698. };
  149699. static long _vq_quantmap__44u6__p4_0[] = {
  149700. 3, 1, 0, 2, 4,
  149701. };
  149702. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149703. _vq_quantthresh__44u6__p4_0,
  149704. _vq_quantmap__44u6__p4_0,
  149705. 5,
  149706. 5
  149707. };
  149708. static static_codebook _44u6__p4_0 = {
  149709. 4, 625,
  149710. _vq_lengthlist__44u6__p4_0,
  149711. 1, -533725184, 1611661312, 3, 0,
  149712. _vq_quantlist__44u6__p4_0,
  149713. NULL,
  149714. &_vq_auxt__44u6__p4_0,
  149715. NULL,
  149716. 0
  149717. };
  149718. static long _vq_quantlist__44u6__p5_0[] = {
  149719. 4,
  149720. 3,
  149721. 5,
  149722. 2,
  149723. 6,
  149724. 1,
  149725. 7,
  149726. 0,
  149727. 8,
  149728. };
  149729. static long _vq_lengthlist__44u6__p5_0[] = {
  149730. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149731. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149732. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149733. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149734. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149735. 14,
  149736. };
  149737. static float _vq_quantthresh__44u6__p5_0[] = {
  149738. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149739. };
  149740. static long _vq_quantmap__44u6__p5_0[] = {
  149741. 7, 5, 3, 1, 0, 2, 4, 6,
  149742. 8,
  149743. };
  149744. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149745. _vq_quantthresh__44u6__p5_0,
  149746. _vq_quantmap__44u6__p5_0,
  149747. 9,
  149748. 9
  149749. };
  149750. static static_codebook _44u6__p5_0 = {
  149751. 2, 81,
  149752. _vq_lengthlist__44u6__p5_0,
  149753. 1, -531628032, 1611661312, 4, 0,
  149754. _vq_quantlist__44u6__p5_0,
  149755. NULL,
  149756. &_vq_auxt__44u6__p5_0,
  149757. NULL,
  149758. 0
  149759. };
  149760. static long _vq_quantlist__44u6__p6_0[] = {
  149761. 4,
  149762. 3,
  149763. 5,
  149764. 2,
  149765. 6,
  149766. 1,
  149767. 7,
  149768. 0,
  149769. 8,
  149770. };
  149771. static long _vq_lengthlist__44u6__p6_0[] = {
  149772. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149773. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149774. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149775. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149776. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149777. 12,
  149778. };
  149779. static float _vq_quantthresh__44u6__p6_0[] = {
  149780. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149781. };
  149782. static long _vq_quantmap__44u6__p6_0[] = {
  149783. 7, 5, 3, 1, 0, 2, 4, 6,
  149784. 8,
  149785. };
  149786. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149787. _vq_quantthresh__44u6__p6_0,
  149788. _vq_quantmap__44u6__p6_0,
  149789. 9,
  149790. 9
  149791. };
  149792. static static_codebook _44u6__p6_0 = {
  149793. 2, 81,
  149794. _vq_lengthlist__44u6__p6_0,
  149795. 1, -531628032, 1611661312, 4, 0,
  149796. _vq_quantlist__44u6__p6_0,
  149797. NULL,
  149798. &_vq_auxt__44u6__p6_0,
  149799. NULL,
  149800. 0
  149801. };
  149802. static long _vq_quantlist__44u6__p7_0[] = {
  149803. 1,
  149804. 0,
  149805. 2,
  149806. };
  149807. static long _vq_lengthlist__44u6__p7_0[] = {
  149808. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149809. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149810. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149811. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149812. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149813. 10,
  149814. };
  149815. static float _vq_quantthresh__44u6__p7_0[] = {
  149816. -5.5, 5.5,
  149817. };
  149818. static long _vq_quantmap__44u6__p7_0[] = {
  149819. 1, 0, 2,
  149820. };
  149821. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149822. _vq_quantthresh__44u6__p7_0,
  149823. _vq_quantmap__44u6__p7_0,
  149824. 3,
  149825. 3
  149826. };
  149827. static static_codebook _44u6__p7_0 = {
  149828. 4, 81,
  149829. _vq_lengthlist__44u6__p7_0,
  149830. 1, -529137664, 1618345984, 2, 0,
  149831. _vq_quantlist__44u6__p7_0,
  149832. NULL,
  149833. &_vq_auxt__44u6__p7_0,
  149834. NULL,
  149835. 0
  149836. };
  149837. static long _vq_quantlist__44u6__p7_1[] = {
  149838. 5,
  149839. 4,
  149840. 6,
  149841. 3,
  149842. 7,
  149843. 2,
  149844. 8,
  149845. 1,
  149846. 9,
  149847. 0,
  149848. 10,
  149849. };
  149850. static long _vq_lengthlist__44u6__p7_1[] = {
  149851. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149852. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149853. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149854. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149855. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149856. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149857. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149858. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149859. };
  149860. static float _vq_quantthresh__44u6__p7_1[] = {
  149861. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149862. 3.5, 4.5,
  149863. };
  149864. static long _vq_quantmap__44u6__p7_1[] = {
  149865. 9, 7, 5, 3, 1, 0, 2, 4,
  149866. 6, 8, 10,
  149867. };
  149868. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149869. _vq_quantthresh__44u6__p7_1,
  149870. _vq_quantmap__44u6__p7_1,
  149871. 11,
  149872. 11
  149873. };
  149874. static static_codebook _44u6__p7_1 = {
  149875. 2, 121,
  149876. _vq_lengthlist__44u6__p7_1,
  149877. 1, -531365888, 1611661312, 4, 0,
  149878. _vq_quantlist__44u6__p7_1,
  149879. NULL,
  149880. &_vq_auxt__44u6__p7_1,
  149881. NULL,
  149882. 0
  149883. };
  149884. static long _vq_quantlist__44u6__p8_0[] = {
  149885. 5,
  149886. 4,
  149887. 6,
  149888. 3,
  149889. 7,
  149890. 2,
  149891. 8,
  149892. 1,
  149893. 9,
  149894. 0,
  149895. 10,
  149896. };
  149897. static long _vq_lengthlist__44u6__p8_0[] = {
  149898. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149899. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149900. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149901. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149902. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149903. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149904. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149905. 12,13,13,14,14,14,15,15,15,
  149906. };
  149907. static float _vq_quantthresh__44u6__p8_0[] = {
  149908. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149909. 38.5, 49.5,
  149910. };
  149911. static long _vq_quantmap__44u6__p8_0[] = {
  149912. 9, 7, 5, 3, 1, 0, 2, 4,
  149913. 6, 8, 10,
  149914. };
  149915. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149916. _vq_quantthresh__44u6__p8_0,
  149917. _vq_quantmap__44u6__p8_0,
  149918. 11,
  149919. 11
  149920. };
  149921. static static_codebook _44u6__p8_0 = {
  149922. 2, 121,
  149923. _vq_lengthlist__44u6__p8_0,
  149924. 1, -524582912, 1618345984, 4, 0,
  149925. _vq_quantlist__44u6__p8_0,
  149926. NULL,
  149927. &_vq_auxt__44u6__p8_0,
  149928. NULL,
  149929. 0
  149930. };
  149931. static long _vq_quantlist__44u6__p8_1[] = {
  149932. 5,
  149933. 4,
  149934. 6,
  149935. 3,
  149936. 7,
  149937. 2,
  149938. 8,
  149939. 1,
  149940. 9,
  149941. 0,
  149942. 10,
  149943. };
  149944. static long _vq_lengthlist__44u6__p8_1[] = {
  149945. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149946. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149947. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149948. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149949. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149950. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149951. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149952. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149953. };
  149954. static float _vq_quantthresh__44u6__p8_1[] = {
  149955. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149956. 3.5, 4.5,
  149957. };
  149958. static long _vq_quantmap__44u6__p8_1[] = {
  149959. 9, 7, 5, 3, 1, 0, 2, 4,
  149960. 6, 8, 10,
  149961. };
  149962. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149963. _vq_quantthresh__44u6__p8_1,
  149964. _vq_quantmap__44u6__p8_1,
  149965. 11,
  149966. 11
  149967. };
  149968. static static_codebook _44u6__p8_1 = {
  149969. 2, 121,
  149970. _vq_lengthlist__44u6__p8_1,
  149971. 1, -531365888, 1611661312, 4, 0,
  149972. _vq_quantlist__44u6__p8_1,
  149973. NULL,
  149974. &_vq_auxt__44u6__p8_1,
  149975. NULL,
  149976. 0
  149977. };
  149978. static long _vq_quantlist__44u6__p9_0[] = {
  149979. 7,
  149980. 6,
  149981. 8,
  149982. 5,
  149983. 9,
  149984. 4,
  149985. 10,
  149986. 3,
  149987. 11,
  149988. 2,
  149989. 12,
  149990. 1,
  149991. 13,
  149992. 0,
  149993. 14,
  149994. };
  149995. static long _vq_lengthlist__44u6__p9_0[] = {
  149996. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149997. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149998. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149999. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150000. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150001. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150002. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150003. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150004. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150005. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150006. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150007. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150008. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150009. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150010. 14,
  150011. };
  150012. static float _vq_quantthresh__44u6__p9_0[] = {
  150013. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150014. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150015. };
  150016. static long _vq_quantmap__44u6__p9_0[] = {
  150017. 13, 11, 9, 7, 5, 3, 1, 0,
  150018. 2, 4, 6, 8, 10, 12, 14,
  150019. };
  150020. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150021. _vq_quantthresh__44u6__p9_0,
  150022. _vq_quantmap__44u6__p9_0,
  150023. 15,
  150024. 15
  150025. };
  150026. static static_codebook _44u6__p9_0 = {
  150027. 2, 225,
  150028. _vq_lengthlist__44u6__p9_0,
  150029. 1, -514071552, 1627381760, 4, 0,
  150030. _vq_quantlist__44u6__p9_0,
  150031. NULL,
  150032. &_vq_auxt__44u6__p9_0,
  150033. NULL,
  150034. 0
  150035. };
  150036. static long _vq_quantlist__44u6__p9_1[] = {
  150037. 7,
  150038. 6,
  150039. 8,
  150040. 5,
  150041. 9,
  150042. 4,
  150043. 10,
  150044. 3,
  150045. 11,
  150046. 2,
  150047. 12,
  150048. 1,
  150049. 13,
  150050. 0,
  150051. 14,
  150052. };
  150053. static long _vq_lengthlist__44u6__p9_1[] = {
  150054. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150055. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150056. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150057. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150058. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150059. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150060. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150061. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150062. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150063. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150064. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150065. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150066. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150067. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150068. 13,
  150069. };
  150070. static float _vq_quantthresh__44u6__p9_1[] = {
  150071. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150072. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150073. };
  150074. static long _vq_quantmap__44u6__p9_1[] = {
  150075. 13, 11, 9, 7, 5, 3, 1, 0,
  150076. 2, 4, 6, 8, 10, 12, 14,
  150077. };
  150078. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150079. _vq_quantthresh__44u6__p9_1,
  150080. _vq_quantmap__44u6__p9_1,
  150081. 15,
  150082. 15
  150083. };
  150084. static static_codebook _44u6__p9_1 = {
  150085. 2, 225,
  150086. _vq_lengthlist__44u6__p9_1,
  150087. 1, -522338304, 1620115456, 4, 0,
  150088. _vq_quantlist__44u6__p9_1,
  150089. NULL,
  150090. &_vq_auxt__44u6__p9_1,
  150091. NULL,
  150092. 0
  150093. };
  150094. static long _vq_quantlist__44u6__p9_2[] = {
  150095. 8,
  150096. 7,
  150097. 9,
  150098. 6,
  150099. 10,
  150100. 5,
  150101. 11,
  150102. 4,
  150103. 12,
  150104. 3,
  150105. 13,
  150106. 2,
  150107. 14,
  150108. 1,
  150109. 15,
  150110. 0,
  150111. 16,
  150112. };
  150113. static long _vq_lengthlist__44u6__p9_2[] = {
  150114. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150115. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150116. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150117. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150118. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150119. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150120. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150121. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150122. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150123. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150124. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150125. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150126. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150127. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150128. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150129. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150130. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150131. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150132. 10,
  150133. };
  150134. static float _vq_quantthresh__44u6__p9_2[] = {
  150135. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150136. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150137. };
  150138. static long _vq_quantmap__44u6__p9_2[] = {
  150139. 15, 13, 11, 9, 7, 5, 3, 1,
  150140. 0, 2, 4, 6, 8, 10, 12, 14,
  150141. 16,
  150142. };
  150143. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150144. _vq_quantthresh__44u6__p9_2,
  150145. _vq_quantmap__44u6__p9_2,
  150146. 17,
  150147. 17
  150148. };
  150149. static static_codebook _44u6__p9_2 = {
  150150. 2, 289,
  150151. _vq_lengthlist__44u6__p9_2,
  150152. 1, -529530880, 1611661312, 5, 0,
  150153. _vq_quantlist__44u6__p9_2,
  150154. NULL,
  150155. &_vq_auxt__44u6__p9_2,
  150156. NULL,
  150157. 0
  150158. };
  150159. static long _huff_lengthlist__44u6__short[] = {
  150160. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150161. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150162. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150163. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150164. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150165. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150166. 7, 6, 9,16,
  150167. };
  150168. static static_codebook _huff_book__44u6__short = {
  150169. 2, 100,
  150170. _huff_lengthlist__44u6__short,
  150171. 0, 0, 0, 0, 0,
  150172. NULL,
  150173. NULL,
  150174. NULL,
  150175. NULL,
  150176. 0
  150177. };
  150178. static long _huff_lengthlist__44u7__long[] = {
  150179. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150180. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150181. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150182. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150183. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150184. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150185. 12, 8, 6, 7,
  150186. };
  150187. static static_codebook _huff_book__44u7__long = {
  150188. 2, 100,
  150189. _huff_lengthlist__44u7__long,
  150190. 0, 0, 0, 0, 0,
  150191. NULL,
  150192. NULL,
  150193. NULL,
  150194. NULL,
  150195. 0
  150196. };
  150197. static long _vq_quantlist__44u7__p1_0[] = {
  150198. 1,
  150199. 0,
  150200. 2,
  150201. };
  150202. static long _vq_lengthlist__44u7__p1_0[] = {
  150203. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150204. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150205. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150206. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150207. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150208. 12,
  150209. };
  150210. static float _vq_quantthresh__44u7__p1_0[] = {
  150211. -0.5, 0.5,
  150212. };
  150213. static long _vq_quantmap__44u7__p1_0[] = {
  150214. 1, 0, 2,
  150215. };
  150216. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150217. _vq_quantthresh__44u7__p1_0,
  150218. _vq_quantmap__44u7__p1_0,
  150219. 3,
  150220. 3
  150221. };
  150222. static static_codebook _44u7__p1_0 = {
  150223. 4, 81,
  150224. _vq_lengthlist__44u7__p1_0,
  150225. 1, -535822336, 1611661312, 2, 0,
  150226. _vq_quantlist__44u7__p1_0,
  150227. NULL,
  150228. &_vq_auxt__44u7__p1_0,
  150229. NULL,
  150230. 0
  150231. };
  150232. static long _vq_quantlist__44u7__p2_0[] = {
  150233. 1,
  150234. 0,
  150235. 2,
  150236. };
  150237. static long _vq_lengthlist__44u7__p2_0[] = {
  150238. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150239. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150240. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150241. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150242. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150243. 9,
  150244. };
  150245. static float _vq_quantthresh__44u7__p2_0[] = {
  150246. -0.5, 0.5,
  150247. };
  150248. static long _vq_quantmap__44u7__p2_0[] = {
  150249. 1, 0, 2,
  150250. };
  150251. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150252. _vq_quantthresh__44u7__p2_0,
  150253. _vq_quantmap__44u7__p2_0,
  150254. 3,
  150255. 3
  150256. };
  150257. static static_codebook _44u7__p2_0 = {
  150258. 4, 81,
  150259. _vq_lengthlist__44u7__p2_0,
  150260. 1, -535822336, 1611661312, 2, 0,
  150261. _vq_quantlist__44u7__p2_0,
  150262. NULL,
  150263. &_vq_auxt__44u7__p2_0,
  150264. NULL,
  150265. 0
  150266. };
  150267. static long _vq_quantlist__44u7__p3_0[] = {
  150268. 2,
  150269. 1,
  150270. 3,
  150271. 0,
  150272. 4,
  150273. };
  150274. static long _vq_lengthlist__44u7__p3_0[] = {
  150275. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150276. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150277. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150278. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150279. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150280. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150281. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150282. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150283. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150284. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150285. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150286. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150287. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150288. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150289. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150290. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150291. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150292. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150293. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150294. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150295. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150296. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150297. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150298. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150299. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150300. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150301. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150302. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150303. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150304. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150305. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150306. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150307. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150308. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150309. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150310. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150311. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150312. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150313. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150314. 0,
  150315. };
  150316. static float _vq_quantthresh__44u7__p3_0[] = {
  150317. -1.5, -0.5, 0.5, 1.5,
  150318. };
  150319. static long _vq_quantmap__44u7__p3_0[] = {
  150320. 3, 1, 0, 2, 4,
  150321. };
  150322. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150323. _vq_quantthresh__44u7__p3_0,
  150324. _vq_quantmap__44u7__p3_0,
  150325. 5,
  150326. 5
  150327. };
  150328. static static_codebook _44u7__p3_0 = {
  150329. 4, 625,
  150330. _vq_lengthlist__44u7__p3_0,
  150331. 1, -533725184, 1611661312, 3, 0,
  150332. _vq_quantlist__44u7__p3_0,
  150333. NULL,
  150334. &_vq_auxt__44u7__p3_0,
  150335. NULL,
  150336. 0
  150337. };
  150338. static long _vq_quantlist__44u7__p4_0[] = {
  150339. 2,
  150340. 1,
  150341. 3,
  150342. 0,
  150343. 4,
  150344. };
  150345. static long _vq_lengthlist__44u7__p4_0[] = {
  150346. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150347. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150348. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150349. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150350. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150351. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150352. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150353. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150354. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150355. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150356. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150357. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150358. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150359. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150360. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150361. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150362. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150363. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150364. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150365. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150366. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150367. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150368. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150369. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150370. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150371. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150372. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150373. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150374. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150375. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150376. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150377. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150378. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150379. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150380. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150381. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150382. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150383. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150384. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150385. 14,
  150386. };
  150387. static float _vq_quantthresh__44u7__p4_0[] = {
  150388. -1.5, -0.5, 0.5, 1.5,
  150389. };
  150390. static long _vq_quantmap__44u7__p4_0[] = {
  150391. 3, 1, 0, 2, 4,
  150392. };
  150393. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150394. _vq_quantthresh__44u7__p4_0,
  150395. _vq_quantmap__44u7__p4_0,
  150396. 5,
  150397. 5
  150398. };
  150399. static static_codebook _44u7__p4_0 = {
  150400. 4, 625,
  150401. _vq_lengthlist__44u7__p4_0,
  150402. 1, -533725184, 1611661312, 3, 0,
  150403. _vq_quantlist__44u7__p4_0,
  150404. NULL,
  150405. &_vq_auxt__44u7__p4_0,
  150406. NULL,
  150407. 0
  150408. };
  150409. static long _vq_quantlist__44u7__p5_0[] = {
  150410. 4,
  150411. 3,
  150412. 5,
  150413. 2,
  150414. 6,
  150415. 1,
  150416. 7,
  150417. 0,
  150418. 8,
  150419. };
  150420. static long _vq_lengthlist__44u7__p5_0[] = {
  150421. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150422. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150423. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150424. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150425. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150426. 14,
  150427. };
  150428. static float _vq_quantthresh__44u7__p5_0[] = {
  150429. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150430. };
  150431. static long _vq_quantmap__44u7__p5_0[] = {
  150432. 7, 5, 3, 1, 0, 2, 4, 6,
  150433. 8,
  150434. };
  150435. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150436. _vq_quantthresh__44u7__p5_0,
  150437. _vq_quantmap__44u7__p5_0,
  150438. 9,
  150439. 9
  150440. };
  150441. static static_codebook _44u7__p5_0 = {
  150442. 2, 81,
  150443. _vq_lengthlist__44u7__p5_0,
  150444. 1, -531628032, 1611661312, 4, 0,
  150445. _vq_quantlist__44u7__p5_0,
  150446. NULL,
  150447. &_vq_auxt__44u7__p5_0,
  150448. NULL,
  150449. 0
  150450. };
  150451. static long _vq_quantlist__44u7__p6_0[] = {
  150452. 4,
  150453. 3,
  150454. 5,
  150455. 2,
  150456. 6,
  150457. 1,
  150458. 7,
  150459. 0,
  150460. 8,
  150461. };
  150462. static long _vq_lengthlist__44u7__p6_0[] = {
  150463. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150464. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150465. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150466. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150467. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150468. 12,
  150469. };
  150470. static float _vq_quantthresh__44u7__p6_0[] = {
  150471. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150472. };
  150473. static long _vq_quantmap__44u7__p6_0[] = {
  150474. 7, 5, 3, 1, 0, 2, 4, 6,
  150475. 8,
  150476. };
  150477. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150478. _vq_quantthresh__44u7__p6_0,
  150479. _vq_quantmap__44u7__p6_0,
  150480. 9,
  150481. 9
  150482. };
  150483. static static_codebook _44u7__p6_0 = {
  150484. 2, 81,
  150485. _vq_lengthlist__44u7__p6_0,
  150486. 1, -531628032, 1611661312, 4, 0,
  150487. _vq_quantlist__44u7__p6_0,
  150488. NULL,
  150489. &_vq_auxt__44u7__p6_0,
  150490. NULL,
  150491. 0
  150492. };
  150493. static long _vq_quantlist__44u7__p7_0[] = {
  150494. 1,
  150495. 0,
  150496. 2,
  150497. };
  150498. static long _vq_lengthlist__44u7__p7_0[] = {
  150499. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150500. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150501. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150502. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150503. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150504. 10,
  150505. };
  150506. static float _vq_quantthresh__44u7__p7_0[] = {
  150507. -5.5, 5.5,
  150508. };
  150509. static long _vq_quantmap__44u7__p7_0[] = {
  150510. 1, 0, 2,
  150511. };
  150512. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150513. _vq_quantthresh__44u7__p7_0,
  150514. _vq_quantmap__44u7__p7_0,
  150515. 3,
  150516. 3
  150517. };
  150518. static static_codebook _44u7__p7_0 = {
  150519. 4, 81,
  150520. _vq_lengthlist__44u7__p7_0,
  150521. 1, -529137664, 1618345984, 2, 0,
  150522. _vq_quantlist__44u7__p7_0,
  150523. NULL,
  150524. &_vq_auxt__44u7__p7_0,
  150525. NULL,
  150526. 0
  150527. };
  150528. static long _vq_quantlist__44u7__p7_1[] = {
  150529. 5,
  150530. 4,
  150531. 6,
  150532. 3,
  150533. 7,
  150534. 2,
  150535. 8,
  150536. 1,
  150537. 9,
  150538. 0,
  150539. 10,
  150540. };
  150541. static long _vq_lengthlist__44u7__p7_1[] = {
  150542. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150543. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150544. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150545. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150546. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150547. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150548. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150549. 8, 9, 9, 9, 9, 9,10,10,10,
  150550. };
  150551. static float _vq_quantthresh__44u7__p7_1[] = {
  150552. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150553. 3.5, 4.5,
  150554. };
  150555. static long _vq_quantmap__44u7__p7_1[] = {
  150556. 9, 7, 5, 3, 1, 0, 2, 4,
  150557. 6, 8, 10,
  150558. };
  150559. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150560. _vq_quantthresh__44u7__p7_1,
  150561. _vq_quantmap__44u7__p7_1,
  150562. 11,
  150563. 11
  150564. };
  150565. static static_codebook _44u7__p7_1 = {
  150566. 2, 121,
  150567. _vq_lengthlist__44u7__p7_1,
  150568. 1, -531365888, 1611661312, 4, 0,
  150569. _vq_quantlist__44u7__p7_1,
  150570. NULL,
  150571. &_vq_auxt__44u7__p7_1,
  150572. NULL,
  150573. 0
  150574. };
  150575. static long _vq_quantlist__44u7__p8_0[] = {
  150576. 5,
  150577. 4,
  150578. 6,
  150579. 3,
  150580. 7,
  150581. 2,
  150582. 8,
  150583. 1,
  150584. 9,
  150585. 0,
  150586. 10,
  150587. };
  150588. static long _vq_lengthlist__44u7__p8_0[] = {
  150589. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150590. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150591. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150592. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150593. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150594. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150595. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150596. 12,13,13,14,14,15,15,15,16,
  150597. };
  150598. static float _vq_quantthresh__44u7__p8_0[] = {
  150599. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150600. 38.5, 49.5,
  150601. };
  150602. static long _vq_quantmap__44u7__p8_0[] = {
  150603. 9, 7, 5, 3, 1, 0, 2, 4,
  150604. 6, 8, 10,
  150605. };
  150606. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150607. _vq_quantthresh__44u7__p8_0,
  150608. _vq_quantmap__44u7__p8_0,
  150609. 11,
  150610. 11
  150611. };
  150612. static static_codebook _44u7__p8_0 = {
  150613. 2, 121,
  150614. _vq_lengthlist__44u7__p8_0,
  150615. 1, -524582912, 1618345984, 4, 0,
  150616. _vq_quantlist__44u7__p8_0,
  150617. NULL,
  150618. &_vq_auxt__44u7__p8_0,
  150619. NULL,
  150620. 0
  150621. };
  150622. static long _vq_quantlist__44u7__p8_1[] = {
  150623. 5,
  150624. 4,
  150625. 6,
  150626. 3,
  150627. 7,
  150628. 2,
  150629. 8,
  150630. 1,
  150631. 9,
  150632. 0,
  150633. 10,
  150634. };
  150635. static long _vq_lengthlist__44u7__p8_1[] = {
  150636. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150637. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150638. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150639. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150640. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150641. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150642. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150643. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150644. };
  150645. static float _vq_quantthresh__44u7__p8_1[] = {
  150646. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150647. 3.5, 4.5,
  150648. };
  150649. static long _vq_quantmap__44u7__p8_1[] = {
  150650. 9, 7, 5, 3, 1, 0, 2, 4,
  150651. 6, 8, 10,
  150652. };
  150653. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150654. _vq_quantthresh__44u7__p8_1,
  150655. _vq_quantmap__44u7__p8_1,
  150656. 11,
  150657. 11
  150658. };
  150659. static static_codebook _44u7__p8_1 = {
  150660. 2, 121,
  150661. _vq_lengthlist__44u7__p8_1,
  150662. 1, -531365888, 1611661312, 4, 0,
  150663. _vq_quantlist__44u7__p8_1,
  150664. NULL,
  150665. &_vq_auxt__44u7__p8_1,
  150666. NULL,
  150667. 0
  150668. };
  150669. static long _vq_quantlist__44u7__p9_0[] = {
  150670. 5,
  150671. 4,
  150672. 6,
  150673. 3,
  150674. 7,
  150675. 2,
  150676. 8,
  150677. 1,
  150678. 9,
  150679. 0,
  150680. 10,
  150681. };
  150682. static long _vq_lengthlist__44u7__p9_0[] = {
  150683. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150684. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150685. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150686. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150687. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150688. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150689. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150690. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150691. };
  150692. static float _vq_quantthresh__44u7__p9_0[] = {
  150693. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150694. 2229.5, 2866.5,
  150695. };
  150696. static long _vq_quantmap__44u7__p9_0[] = {
  150697. 9, 7, 5, 3, 1, 0, 2, 4,
  150698. 6, 8, 10,
  150699. };
  150700. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150701. _vq_quantthresh__44u7__p9_0,
  150702. _vq_quantmap__44u7__p9_0,
  150703. 11,
  150704. 11
  150705. };
  150706. static static_codebook _44u7__p9_0 = {
  150707. 2, 121,
  150708. _vq_lengthlist__44u7__p9_0,
  150709. 1, -512171520, 1630791680, 4, 0,
  150710. _vq_quantlist__44u7__p9_0,
  150711. NULL,
  150712. &_vq_auxt__44u7__p9_0,
  150713. NULL,
  150714. 0
  150715. };
  150716. static long _vq_quantlist__44u7__p9_1[] = {
  150717. 6,
  150718. 5,
  150719. 7,
  150720. 4,
  150721. 8,
  150722. 3,
  150723. 9,
  150724. 2,
  150725. 10,
  150726. 1,
  150727. 11,
  150728. 0,
  150729. 12,
  150730. };
  150731. static long _vq_lengthlist__44u7__p9_1[] = {
  150732. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150733. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150734. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150735. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150736. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150737. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150738. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150739. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150740. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150741. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150742. 15,15,15,15,17,17,16,17,16,
  150743. };
  150744. static float _vq_quantthresh__44u7__p9_1[] = {
  150745. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150746. 122.5, 171.5, 220.5, 269.5,
  150747. };
  150748. static long _vq_quantmap__44u7__p9_1[] = {
  150749. 11, 9, 7, 5, 3, 1, 0, 2,
  150750. 4, 6, 8, 10, 12,
  150751. };
  150752. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150753. _vq_quantthresh__44u7__p9_1,
  150754. _vq_quantmap__44u7__p9_1,
  150755. 13,
  150756. 13
  150757. };
  150758. static static_codebook _44u7__p9_1 = {
  150759. 2, 169,
  150760. _vq_lengthlist__44u7__p9_1,
  150761. 1, -518889472, 1622704128, 4, 0,
  150762. _vq_quantlist__44u7__p9_1,
  150763. NULL,
  150764. &_vq_auxt__44u7__p9_1,
  150765. NULL,
  150766. 0
  150767. };
  150768. static long _vq_quantlist__44u7__p9_2[] = {
  150769. 24,
  150770. 23,
  150771. 25,
  150772. 22,
  150773. 26,
  150774. 21,
  150775. 27,
  150776. 20,
  150777. 28,
  150778. 19,
  150779. 29,
  150780. 18,
  150781. 30,
  150782. 17,
  150783. 31,
  150784. 16,
  150785. 32,
  150786. 15,
  150787. 33,
  150788. 14,
  150789. 34,
  150790. 13,
  150791. 35,
  150792. 12,
  150793. 36,
  150794. 11,
  150795. 37,
  150796. 10,
  150797. 38,
  150798. 9,
  150799. 39,
  150800. 8,
  150801. 40,
  150802. 7,
  150803. 41,
  150804. 6,
  150805. 42,
  150806. 5,
  150807. 43,
  150808. 4,
  150809. 44,
  150810. 3,
  150811. 45,
  150812. 2,
  150813. 46,
  150814. 1,
  150815. 47,
  150816. 0,
  150817. 48,
  150818. };
  150819. static long _vq_lengthlist__44u7__p9_2[] = {
  150820. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150821. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150822. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150823. 8,
  150824. };
  150825. static float _vq_quantthresh__44u7__p9_2[] = {
  150826. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150827. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150828. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150829. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150830. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150831. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150832. };
  150833. static long _vq_quantmap__44u7__p9_2[] = {
  150834. 47, 45, 43, 41, 39, 37, 35, 33,
  150835. 31, 29, 27, 25, 23, 21, 19, 17,
  150836. 15, 13, 11, 9, 7, 5, 3, 1,
  150837. 0, 2, 4, 6, 8, 10, 12, 14,
  150838. 16, 18, 20, 22, 24, 26, 28, 30,
  150839. 32, 34, 36, 38, 40, 42, 44, 46,
  150840. 48,
  150841. };
  150842. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150843. _vq_quantthresh__44u7__p9_2,
  150844. _vq_quantmap__44u7__p9_2,
  150845. 49,
  150846. 49
  150847. };
  150848. static static_codebook _44u7__p9_2 = {
  150849. 1, 49,
  150850. _vq_lengthlist__44u7__p9_2,
  150851. 1, -526909440, 1611661312, 6, 0,
  150852. _vq_quantlist__44u7__p9_2,
  150853. NULL,
  150854. &_vq_auxt__44u7__p9_2,
  150855. NULL,
  150856. 0
  150857. };
  150858. static long _huff_lengthlist__44u7__short[] = {
  150859. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150860. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150861. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150862. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150863. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150864. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150865. 6, 8, 5, 9,
  150866. };
  150867. static static_codebook _huff_book__44u7__short = {
  150868. 2, 100,
  150869. _huff_lengthlist__44u7__short,
  150870. 0, 0, 0, 0, 0,
  150871. NULL,
  150872. NULL,
  150873. NULL,
  150874. NULL,
  150875. 0
  150876. };
  150877. static long _huff_lengthlist__44u8__long[] = {
  150878. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150879. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150880. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150881. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150882. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150883. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150884. 10, 8, 8, 9,
  150885. };
  150886. static static_codebook _huff_book__44u8__long = {
  150887. 2, 100,
  150888. _huff_lengthlist__44u8__long,
  150889. 0, 0, 0, 0, 0,
  150890. NULL,
  150891. NULL,
  150892. NULL,
  150893. NULL,
  150894. 0
  150895. };
  150896. static long _huff_lengthlist__44u8__short[] = {
  150897. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150898. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150899. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150900. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150901. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150902. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150903. 10,10,15,17,
  150904. };
  150905. static static_codebook _huff_book__44u8__short = {
  150906. 2, 100,
  150907. _huff_lengthlist__44u8__short,
  150908. 0, 0, 0, 0, 0,
  150909. NULL,
  150910. NULL,
  150911. NULL,
  150912. NULL,
  150913. 0
  150914. };
  150915. static long _vq_quantlist__44u8_p1_0[] = {
  150916. 1,
  150917. 0,
  150918. 2,
  150919. };
  150920. static long _vq_lengthlist__44u8_p1_0[] = {
  150921. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150922. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150923. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150924. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150925. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150926. 10,
  150927. };
  150928. static float _vq_quantthresh__44u8_p1_0[] = {
  150929. -0.5, 0.5,
  150930. };
  150931. static long _vq_quantmap__44u8_p1_0[] = {
  150932. 1, 0, 2,
  150933. };
  150934. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150935. _vq_quantthresh__44u8_p1_0,
  150936. _vq_quantmap__44u8_p1_0,
  150937. 3,
  150938. 3
  150939. };
  150940. static static_codebook _44u8_p1_0 = {
  150941. 4, 81,
  150942. _vq_lengthlist__44u8_p1_0,
  150943. 1, -535822336, 1611661312, 2, 0,
  150944. _vq_quantlist__44u8_p1_0,
  150945. NULL,
  150946. &_vq_auxt__44u8_p1_0,
  150947. NULL,
  150948. 0
  150949. };
  150950. static long _vq_quantlist__44u8_p2_0[] = {
  150951. 2,
  150952. 1,
  150953. 3,
  150954. 0,
  150955. 4,
  150956. };
  150957. static long _vq_lengthlist__44u8_p2_0[] = {
  150958. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150959. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150960. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150961. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150962. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150963. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150964. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150965. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150966. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150967. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150968. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150969. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150970. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150971. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150972. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150973. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150974. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150975. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150976. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150977. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150978. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150979. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150980. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150981. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150982. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150983. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150984. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150985. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150986. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150987. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150988. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150989. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150990. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150991. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150992. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150993. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150994. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150995. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150996. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150997. 14,
  150998. };
  150999. static float _vq_quantthresh__44u8_p2_0[] = {
  151000. -1.5, -0.5, 0.5, 1.5,
  151001. };
  151002. static long _vq_quantmap__44u8_p2_0[] = {
  151003. 3, 1, 0, 2, 4,
  151004. };
  151005. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151006. _vq_quantthresh__44u8_p2_0,
  151007. _vq_quantmap__44u8_p2_0,
  151008. 5,
  151009. 5
  151010. };
  151011. static static_codebook _44u8_p2_0 = {
  151012. 4, 625,
  151013. _vq_lengthlist__44u8_p2_0,
  151014. 1, -533725184, 1611661312, 3, 0,
  151015. _vq_quantlist__44u8_p2_0,
  151016. NULL,
  151017. &_vq_auxt__44u8_p2_0,
  151018. NULL,
  151019. 0
  151020. };
  151021. static long _vq_quantlist__44u8_p3_0[] = {
  151022. 4,
  151023. 3,
  151024. 5,
  151025. 2,
  151026. 6,
  151027. 1,
  151028. 7,
  151029. 0,
  151030. 8,
  151031. };
  151032. static long _vq_lengthlist__44u8_p3_0[] = {
  151033. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151034. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151035. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151036. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151037. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151038. 12,
  151039. };
  151040. static float _vq_quantthresh__44u8_p3_0[] = {
  151041. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151042. };
  151043. static long _vq_quantmap__44u8_p3_0[] = {
  151044. 7, 5, 3, 1, 0, 2, 4, 6,
  151045. 8,
  151046. };
  151047. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151048. _vq_quantthresh__44u8_p3_0,
  151049. _vq_quantmap__44u8_p3_0,
  151050. 9,
  151051. 9
  151052. };
  151053. static static_codebook _44u8_p3_0 = {
  151054. 2, 81,
  151055. _vq_lengthlist__44u8_p3_0,
  151056. 1, -531628032, 1611661312, 4, 0,
  151057. _vq_quantlist__44u8_p3_0,
  151058. NULL,
  151059. &_vq_auxt__44u8_p3_0,
  151060. NULL,
  151061. 0
  151062. };
  151063. static long _vq_quantlist__44u8_p4_0[] = {
  151064. 8,
  151065. 7,
  151066. 9,
  151067. 6,
  151068. 10,
  151069. 5,
  151070. 11,
  151071. 4,
  151072. 12,
  151073. 3,
  151074. 13,
  151075. 2,
  151076. 14,
  151077. 1,
  151078. 15,
  151079. 0,
  151080. 16,
  151081. };
  151082. static long _vq_lengthlist__44u8_p4_0[] = {
  151083. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151084. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151085. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151086. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151087. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151088. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151089. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151090. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151091. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151092. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151093. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151094. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151095. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151096. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151097. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151098. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151099. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151100. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151101. 14,
  151102. };
  151103. static float _vq_quantthresh__44u8_p4_0[] = {
  151104. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151105. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151106. };
  151107. static long _vq_quantmap__44u8_p4_0[] = {
  151108. 15, 13, 11, 9, 7, 5, 3, 1,
  151109. 0, 2, 4, 6, 8, 10, 12, 14,
  151110. 16,
  151111. };
  151112. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151113. _vq_quantthresh__44u8_p4_0,
  151114. _vq_quantmap__44u8_p4_0,
  151115. 17,
  151116. 17
  151117. };
  151118. static static_codebook _44u8_p4_0 = {
  151119. 2, 289,
  151120. _vq_lengthlist__44u8_p4_0,
  151121. 1, -529530880, 1611661312, 5, 0,
  151122. _vq_quantlist__44u8_p4_0,
  151123. NULL,
  151124. &_vq_auxt__44u8_p4_0,
  151125. NULL,
  151126. 0
  151127. };
  151128. static long _vq_quantlist__44u8_p5_0[] = {
  151129. 1,
  151130. 0,
  151131. 2,
  151132. };
  151133. static long _vq_lengthlist__44u8_p5_0[] = {
  151134. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151135. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151136. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151137. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151138. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151139. 10,
  151140. };
  151141. static float _vq_quantthresh__44u8_p5_0[] = {
  151142. -5.5, 5.5,
  151143. };
  151144. static long _vq_quantmap__44u8_p5_0[] = {
  151145. 1, 0, 2,
  151146. };
  151147. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151148. _vq_quantthresh__44u8_p5_0,
  151149. _vq_quantmap__44u8_p5_0,
  151150. 3,
  151151. 3
  151152. };
  151153. static static_codebook _44u8_p5_0 = {
  151154. 4, 81,
  151155. _vq_lengthlist__44u8_p5_0,
  151156. 1, -529137664, 1618345984, 2, 0,
  151157. _vq_quantlist__44u8_p5_0,
  151158. NULL,
  151159. &_vq_auxt__44u8_p5_0,
  151160. NULL,
  151161. 0
  151162. };
  151163. static long _vq_quantlist__44u8_p5_1[] = {
  151164. 5,
  151165. 4,
  151166. 6,
  151167. 3,
  151168. 7,
  151169. 2,
  151170. 8,
  151171. 1,
  151172. 9,
  151173. 0,
  151174. 10,
  151175. };
  151176. static long _vq_lengthlist__44u8_p5_1[] = {
  151177. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151178. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151179. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151180. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151181. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151182. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151183. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151184. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151185. };
  151186. static float _vq_quantthresh__44u8_p5_1[] = {
  151187. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151188. 3.5, 4.5,
  151189. };
  151190. static long _vq_quantmap__44u8_p5_1[] = {
  151191. 9, 7, 5, 3, 1, 0, 2, 4,
  151192. 6, 8, 10,
  151193. };
  151194. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151195. _vq_quantthresh__44u8_p5_1,
  151196. _vq_quantmap__44u8_p5_1,
  151197. 11,
  151198. 11
  151199. };
  151200. static static_codebook _44u8_p5_1 = {
  151201. 2, 121,
  151202. _vq_lengthlist__44u8_p5_1,
  151203. 1, -531365888, 1611661312, 4, 0,
  151204. _vq_quantlist__44u8_p5_1,
  151205. NULL,
  151206. &_vq_auxt__44u8_p5_1,
  151207. NULL,
  151208. 0
  151209. };
  151210. static long _vq_quantlist__44u8_p6_0[] = {
  151211. 6,
  151212. 5,
  151213. 7,
  151214. 4,
  151215. 8,
  151216. 3,
  151217. 9,
  151218. 2,
  151219. 10,
  151220. 1,
  151221. 11,
  151222. 0,
  151223. 12,
  151224. };
  151225. static long _vq_lengthlist__44u8_p6_0[] = {
  151226. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151227. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151228. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151229. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151230. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151231. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151232. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151233. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151234. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151235. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151236. 11,11,11,11,11,12,11,12,12,
  151237. };
  151238. static float _vq_quantthresh__44u8_p6_0[] = {
  151239. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151240. 12.5, 17.5, 22.5, 27.5,
  151241. };
  151242. static long _vq_quantmap__44u8_p6_0[] = {
  151243. 11, 9, 7, 5, 3, 1, 0, 2,
  151244. 4, 6, 8, 10, 12,
  151245. };
  151246. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151247. _vq_quantthresh__44u8_p6_0,
  151248. _vq_quantmap__44u8_p6_0,
  151249. 13,
  151250. 13
  151251. };
  151252. static static_codebook _44u8_p6_0 = {
  151253. 2, 169,
  151254. _vq_lengthlist__44u8_p6_0,
  151255. 1, -526516224, 1616117760, 4, 0,
  151256. _vq_quantlist__44u8_p6_0,
  151257. NULL,
  151258. &_vq_auxt__44u8_p6_0,
  151259. NULL,
  151260. 0
  151261. };
  151262. static long _vq_quantlist__44u8_p6_1[] = {
  151263. 2,
  151264. 1,
  151265. 3,
  151266. 0,
  151267. 4,
  151268. };
  151269. static long _vq_lengthlist__44u8_p6_1[] = {
  151270. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151271. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151272. };
  151273. static float _vq_quantthresh__44u8_p6_1[] = {
  151274. -1.5, -0.5, 0.5, 1.5,
  151275. };
  151276. static long _vq_quantmap__44u8_p6_1[] = {
  151277. 3, 1, 0, 2, 4,
  151278. };
  151279. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151280. _vq_quantthresh__44u8_p6_1,
  151281. _vq_quantmap__44u8_p6_1,
  151282. 5,
  151283. 5
  151284. };
  151285. static static_codebook _44u8_p6_1 = {
  151286. 2, 25,
  151287. _vq_lengthlist__44u8_p6_1,
  151288. 1, -533725184, 1611661312, 3, 0,
  151289. _vq_quantlist__44u8_p6_1,
  151290. NULL,
  151291. &_vq_auxt__44u8_p6_1,
  151292. NULL,
  151293. 0
  151294. };
  151295. static long _vq_quantlist__44u8_p7_0[] = {
  151296. 6,
  151297. 5,
  151298. 7,
  151299. 4,
  151300. 8,
  151301. 3,
  151302. 9,
  151303. 2,
  151304. 10,
  151305. 1,
  151306. 11,
  151307. 0,
  151308. 12,
  151309. };
  151310. static long _vq_lengthlist__44u8_p7_0[] = {
  151311. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151312. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151313. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151314. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151315. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151316. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151317. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151318. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151319. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151320. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151321. 13,13,14,14,14,15,15,15,16,
  151322. };
  151323. static float _vq_quantthresh__44u8_p7_0[] = {
  151324. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151325. 27.5, 38.5, 49.5, 60.5,
  151326. };
  151327. static long _vq_quantmap__44u8_p7_0[] = {
  151328. 11, 9, 7, 5, 3, 1, 0, 2,
  151329. 4, 6, 8, 10, 12,
  151330. };
  151331. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151332. _vq_quantthresh__44u8_p7_0,
  151333. _vq_quantmap__44u8_p7_0,
  151334. 13,
  151335. 13
  151336. };
  151337. static static_codebook _44u8_p7_0 = {
  151338. 2, 169,
  151339. _vq_lengthlist__44u8_p7_0,
  151340. 1, -523206656, 1618345984, 4, 0,
  151341. _vq_quantlist__44u8_p7_0,
  151342. NULL,
  151343. &_vq_auxt__44u8_p7_0,
  151344. NULL,
  151345. 0
  151346. };
  151347. static long _vq_quantlist__44u8_p7_1[] = {
  151348. 5,
  151349. 4,
  151350. 6,
  151351. 3,
  151352. 7,
  151353. 2,
  151354. 8,
  151355. 1,
  151356. 9,
  151357. 0,
  151358. 10,
  151359. };
  151360. static long _vq_lengthlist__44u8_p7_1[] = {
  151361. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151362. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151363. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151364. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151365. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151366. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151367. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151368. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151369. };
  151370. static float _vq_quantthresh__44u8_p7_1[] = {
  151371. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151372. 3.5, 4.5,
  151373. };
  151374. static long _vq_quantmap__44u8_p7_1[] = {
  151375. 9, 7, 5, 3, 1, 0, 2, 4,
  151376. 6, 8, 10,
  151377. };
  151378. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151379. _vq_quantthresh__44u8_p7_1,
  151380. _vq_quantmap__44u8_p7_1,
  151381. 11,
  151382. 11
  151383. };
  151384. static static_codebook _44u8_p7_1 = {
  151385. 2, 121,
  151386. _vq_lengthlist__44u8_p7_1,
  151387. 1, -531365888, 1611661312, 4, 0,
  151388. _vq_quantlist__44u8_p7_1,
  151389. NULL,
  151390. &_vq_auxt__44u8_p7_1,
  151391. NULL,
  151392. 0
  151393. };
  151394. static long _vq_quantlist__44u8_p8_0[] = {
  151395. 7,
  151396. 6,
  151397. 8,
  151398. 5,
  151399. 9,
  151400. 4,
  151401. 10,
  151402. 3,
  151403. 11,
  151404. 2,
  151405. 12,
  151406. 1,
  151407. 13,
  151408. 0,
  151409. 14,
  151410. };
  151411. static long _vq_lengthlist__44u8_p8_0[] = {
  151412. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151413. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151414. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151415. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151416. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151417. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151418. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151419. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151420. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151421. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151422. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151423. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151424. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151425. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151426. 17,
  151427. };
  151428. static float _vq_quantthresh__44u8_p8_0[] = {
  151429. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151430. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151431. };
  151432. static long _vq_quantmap__44u8_p8_0[] = {
  151433. 13, 11, 9, 7, 5, 3, 1, 0,
  151434. 2, 4, 6, 8, 10, 12, 14,
  151435. };
  151436. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151437. _vq_quantthresh__44u8_p8_0,
  151438. _vq_quantmap__44u8_p8_0,
  151439. 15,
  151440. 15
  151441. };
  151442. static static_codebook _44u8_p8_0 = {
  151443. 2, 225,
  151444. _vq_lengthlist__44u8_p8_0,
  151445. 1, -520986624, 1620377600, 4, 0,
  151446. _vq_quantlist__44u8_p8_0,
  151447. NULL,
  151448. &_vq_auxt__44u8_p8_0,
  151449. NULL,
  151450. 0
  151451. };
  151452. static long _vq_quantlist__44u8_p8_1[] = {
  151453. 10,
  151454. 9,
  151455. 11,
  151456. 8,
  151457. 12,
  151458. 7,
  151459. 13,
  151460. 6,
  151461. 14,
  151462. 5,
  151463. 15,
  151464. 4,
  151465. 16,
  151466. 3,
  151467. 17,
  151468. 2,
  151469. 18,
  151470. 1,
  151471. 19,
  151472. 0,
  151473. 20,
  151474. };
  151475. static long _vq_lengthlist__44u8_p8_1[] = {
  151476. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151477. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151478. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151479. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151480. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151481. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151482. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151483. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151484. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151485. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151486. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151487. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151488. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151489. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151490. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151491. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151492. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151493. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151494. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151495. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151496. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151497. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151498. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151499. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151500. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151501. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151502. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151503. 10,10,10,10,10,10,10,10,10,
  151504. };
  151505. static float _vq_quantthresh__44u8_p8_1[] = {
  151506. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151507. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151508. 6.5, 7.5, 8.5, 9.5,
  151509. };
  151510. static long _vq_quantmap__44u8_p8_1[] = {
  151511. 19, 17, 15, 13, 11, 9, 7, 5,
  151512. 3, 1, 0, 2, 4, 6, 8, 10,
  151513. 12, 14, 16, 18, 20,
  151514. };
  151515. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151516. _vq_quantthresh__44u8_p8_1,
  151517. _vq_quantmap__44u8_p8_1,
  151518. 21,
  151519. 21
  151520. };
  151521. static static_codebook _44u8_p8_1 = {
  151522. 2, 441,
  151523. _vq_lengthlist__44u8_p8_1,
  151524. 1, -529268736, 1611661312, 5, 0,
  151525. _vq_quantlist__44u8_p8_1,
  151526. NULL,
  151527. &_vq_auxt__44u8_p8_1,
  151528. NULL,
  151529. 0
  151530. };
  151531. static long _vq_quantlist__44u8_p9_0[] = {
  151532. 4,
  151533. 3,
  151534. 5,
  151535. 2,
  151536. 6,
  151537. 1,
  151538. 7,
  151539. 0,
  151540. 8,
  151541. };
  151542. static long _vq_lengthlist__44u8_p9_0[] = {
  151543. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151544. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151545. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151546. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151547. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151548. 8,
  151549. };
  151550. static float _vq_quantthresh__44u8_p9_0[] = {
  151551. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151552. };
  151553. static long _vq_quantmap__44u8_p9_0[] = {
  151554. 7, 5, 3, 1, 0, 2, 4, 6,
  151555. 8,
  151556. };
  151557. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151558. _vq_quantthresh__44u8_p9_0,
  151559. _vq_quantmap__44u8_p9_0,
  151560. 9,
  151561. 9
  151562. };
  151563. static static_codebook _44u8_p9_0 = {
  151564. 2, 81,
  151565. _vq_lengthlist__44u8_p9_0,
  151566. 1, -511895552, 1631393792, 4, 0,
  151567. _vq_quantlist__44u8_p9_0,
  151568. NULL,
  151569. &_vq_auxt__44u8_p9_0,
  151570. NULL,
  151571. 0
  151572. };
  151573. static long _vq_quantlist__44u8_p9_1[] = {
  151574. 9,
  151575. 8,
  151576. 10,
  151577. 7,
  151578. 11,
  151579. 6,
  151580. 12,
  151581. 5,
  151582. 13,
  151583. 4,
  151584. 14,
  151585. 3,
  151586. 15,
  151587. 2,
  151588. 16,
  151589. 1,
  151590. 17,
  151591. 0,
  151592. 18,
  151593. };
  151594. static long _vq_lengthlist__44u8_p9_1[] = {
  151595. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151596. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151597. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151598. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151599. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151600. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151601. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151602. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151603. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151604. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151605. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151606. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151607. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151608. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151609. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151610. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151611. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151612. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151613. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151614. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151615. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151616. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151617. 16,15,16,16,16,16,16,16,16,
  151618. };
  151619. static float _vq_quantthresh__44u8_p9_1[] = {
  151620. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151621. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151622. 367.5, 416.5,
  151623. };
  151624. static long _vq_quantmap__44u8_p9_1[] = {
  151625. 17, 15, 13, 11, 9, 7, 5, 3,
  151626. 1, 0, 2, 4, 6, 8, 10, 12,
  151627. 14, 16, 18,
  151628. };
  151629. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151630. _vq_quantthresh__44u8_p9_1,
  151631. _vq_quantmap__44u8_p9_1,
  151632. 19,
  151633. 19
  151634. };
  151635. static static_codebook _44u8_p9_1 = {
  151636. 2, 361,
  151637. _vq_lengthlist__44u8_p9_1,
  151638. 1, -518287360, 1622704128, 5, 0,
  151639. _vq_quantlist__44u8_p9_1,
  151640. NULL,
  151641. &_vq_auxt__44u8_p9_1,
  151642. NULL,
  151643. 0
  151644. };
  151645. static long _vq_quantlist__44u8_p9_2[] = {
  151646. 24,
  151647. 23,
  151648. 25,
  151649. 22,
  151650. 26,
  151651. 21,
  151652. 27,
  151653. 20,
  151654. 28,
  151655. 19,
  151656. 29,
  151657. 18,
  151658. 30,
  151659. 17,
  151660. 31,
  151661. 16,
  151662. 32,
  151663. 15,
  151664. 33,
  151665. 14,
  151666. 34,
  151667. 13,
  151668. 35,
  151669. 12,
  151670. 36,
  151671. 11,
  151672. 37,
  151673. 10,
  151674. 38,
  151675. 9,
  151676. 39,
  151677. 8,
  151678. 40,
  151679. 7,
  151680. 41,
  151681. 6,
  151682. 42,
  151683. 5,
  151684. 43,
  151685. 4,
  151686. 44,
  151687. 3,
  151688. 45,
  151689. 2,
  151690. 46,
  151691. 1,
  151692. 47,
  151693. 0,
  151694. 48,
  151695. };
  151696. static long _vq_lengthlist__44u8_p9_2[] = {
  151697. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151698. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151699. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151700. 7,
  151701. };
  151702. static float _vq_quantthresh__44u8_p9_2[] = {
  151703. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151704. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151705. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151706. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151707. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151708. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151709. };
  151710. static long _vq_quantmap__44u8_p9_2[] = {
  151711. 47, 45, 43, 41, 39, 37, 35, 33,
  151712. 31, 29, 27, 25, 23, 21, 19, 17,
  151713. 15, 13, 11, 9, 7, 5, 3, 1,
  151714. 0, 2, 4, 6, 8, 10, 12, 14,
  151715. 16, 18, 20, 22, 24, 26, 28, 30,
  151716. 32, 34, 36, 38, 40, 42, 44, 46,
  151717. 48,
  151718. };
  151719. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151720. _vq_quantthresh__44u8_p9_2,
  151721. _vq_quantmap__44u8_p9_2,
  151722. 49,
  151723. 49
  151724. };
  151725. static static_codebook _44u8_p9_2 = {
  151726. 1, 49,
  151727. _vq_lengthlist__44u8_p9_2,
  151728. 1, -526909440, 1611661312, 6, 0,
  151729. _vq_quantlist__44u8_p9_2,
  151730. NULL,
  151731. &_vq_auxt__44u8_p9_2,
  151732. NULL,
  151733. 0
  151734. };
  151735. static long _huff_lengthlist__44u9__long[] = {
  151736. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151737. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151738. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151739. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151740. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151741. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151742. 10, 8, 8, 9,
  151743. };
  151744. static static_codebook _huff_book__44u9__long = {
  151745. 2, 100,
  151746. _huff_lengthlist__44u9__long,
  151747. 0, 0, 0, 0, 0,
  151748. NULL,
  151749. NULL,
  151750. NULL,
  151751. NULL,
  151752. 0
  151753. };
  151754. static long _huff_lengthlist__44u9__short[] = {
  151755. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151756. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151757. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151758. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151759. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151760. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151761. 9, 9,12,15,
  151762. };
  151763. static static_codebook _huff_book__44u9__short = {
  151764. 2, 100,
  151765. _huff_lengthlist__44u9__short,
  151766. 0, 0, 0, 0, 0,
  151767. NULL,
  151768. NULL,
  151769. NULL,
  151770. NULL,
  151771. 0
  151772. };
  151773. static long _vq_quantlist__44u9_p1_0[] = {
  151774. 1,
  151775. 0,
  151776. 2,
  151777. };
  151778. static long _vq_lengthlist__44u9_p1_0[] = {
  151779. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151780. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151781. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151782. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151783. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151784. 10,
  151785. };
  151786. static float _vq_quantthresh__44u9_p1_0[] = {
  151787. -0.5, 0.5,
  151788. };
  151789. static long _vq_quantmap__44u9_p1_0[] = {
  151790. 1, 0, 2,
  151791. };
  151792. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151793. _vq_quantthresh__44u9_p1_0,
  151794. _vq_quantmap__44u9_p1_0,
  151795. 3,
  151796. 3
  151797. };
  151798. static static_codebook _44u9_p1_0 = {
  151799. 4, 81,
  151800. _vq_lengthlist__44u9_p1_0,
  151801. 1, -535822336, 1611661312, 2, 0,
  151802. _vq_quantlist__44u9_p1_0,
  151803. NULL,
  151804. &_vq_auxt__44u9_p1_0,
  151805. NULL,
  151806. 0
  151807. };
  151808. static long _vq_quantlist__44u9_p2_0[] = {
  151809. 2,
  151810. 1,
  151811. 3,
  151812. 0,
  151813. 4,
  151814. };
  151815. static long _vq_lengthlist__44u9_p2_0[] = {
  151816. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151817. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151818. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151819. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151820. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151821. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151822. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151823. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151824. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151825. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151826. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151827. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151828. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151829. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151830. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151831. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151832. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151833. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151834. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151835. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151836. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151837. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151838. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151839. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151840. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151841. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151842. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151843. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151844. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151845. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151846. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151847. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151848. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151849. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151850. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151851. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151852. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151853. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151854. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151855. 14,
  151856. };
  151857. static float _vq_quantthresh__44u9_p2_0[] = {
  151858. -1.5, -0.5, 0.5, 1.5,
  151859. };
  151860. static long _vq_quantmap__44u9_p2_0[] = {
  151861. 3, 1, 0, 2, 4,
  151862. };
  151863. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151864. _vq_quantthresh__44u9_p2_0,
  151865. _vq_quantmap__44u9_p2_0,
  151866. 5,
  151867. 5
  151868. };
  151869. static static_codebook _44u9_p2_0 = {
  151870. 4, 625,
  151871. _vq_lengthlist__44u9_p2_0,
  151872. 1, -533725184, 1611661312, 3, 0,
  151873. _vq_quantlist__44u9_p2_0,
  151874. NULL,
  151875. &_vq_auxt__44u9_p2_0,
  151876. NULL,
  151877. 0
  151878. };
  151879. static long _vq_quantlist__44u9_p3_0[] = {
  151880. 4,
  151881. 3,
  151882. 5,
  151883. 2,
  151884. 6,
  151885. 1,
  151886. 7,
  151887. 0,
  151888. 8,
  151889. };
  151890. static long _vq_lengthlist__44u9_p3_0[] = {
  151891. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151892. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151893. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151894. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151895. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151896. 11,
  151897. };
  151898. static float _vq_quantthresh__44u9_p3_0[] = {
  151899. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151900. };
  151901. static long _vq_quantmap__44u9_p3_0[] = {
  151902. 7, 5, 3, 1, 0, 2, 4, 6,
  151903. 8,
  151904. };
  151905. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151906. _vq_quantthresh__44u9_p3_0,
  151907. _vq_quantmap__44u9_p3_0,
  151908. 9,
  151909. 9
  151910. };
  151911. static static_codebook _44u9_p3_0 = {
  151912. 2, 81,
  151913. _vq_lengthlist__44u9_p3_0,
  151914. 1, -531628032, 1611661312, 4, 0,
  151915. _vq_quantlist__44u9_p3_0,
  151916. NULL,
  151917. &_vq_auxt__44u9_p3_0,
  151918. NULL,
  151919. 0
  151920. };
  151921. static long _vq_quantlist__44u9_p4_0[] = {
  151922. 8,
  151923. 7,
  151924. 9,
  151925. 6,
  151926. 10,
  151927. 5,
  151928. 11,
  151929. 4,
  151930. 12,
  151931. 3,
  151932. 13,
  151933. 2,
  151934. 14,
  151935. 1,
  151936. 15,
  151937. 0,
  151938. 16,
  151939. };
  151940. static long _vq_lengthlist__44u9_p4_0[] = {
  151941. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151942. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151943. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151944. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151945. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151946. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151947. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151948. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151949. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151950. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151951. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151952. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151953. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151954. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151955. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151956. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151957. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151958. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151959. 14,
  151960. };
  151961. static float _vq_quantthresh__44u9_p4_0[] = {
  151962. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151963. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151964. };
  151965. static long _vq_quantmap__44u9_p4_0[] = {
  151966. 15, 13, 11, 9, 7, 5, 3, 1,
  151967. 0, 2, 4, 6, 8, 10, 12, 14,
  151968. 16,
  151969. };
  151970. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151971. _vq_quantthresh__44u9_p4_0,
  151972. _vq_quantmap__44u9_p4_0,
  151973. 17,
  151974. 17
  151975. };
  151976. static static_codebook _44u9_p4_0 = {
  151977. 2, 289,
  151978. _vq_lengthlist__44u9_p4_0,
  151979. 1, -529530880, 1611661312, 5, 0,
  151980. _vq_quantlist__44u9_p4_0,
  151981. NULL,
  151982. &_vq_auxt__44u9_p4_0,
  151983. NULL,
  151984. 0
  151985. };
  151986. static long _vq_quantlist__44u9_p5_0[] = {
  151987. 1,
  151988. 0,
  151989. 2,
  151990. };
  151991. static long _vq_lengthlist__44u9_p5_0[] = {
  151992. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151993. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151994. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151995. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151996. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151997. 10,
  151998. };
  151999. static float _vq_quantthresh__44u9_p5_0[] = {
  152000. -5.5, 5.5,
  152001. };
  152002. static long _vq_quantmap__44u9_p5_0[] = {
  152003. 1, 0, 2,
  152004. };
  152005. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152006. _vq_quantthresh__44u9_p5_0,
  152007. _vq_quantmap__44u9_p5_0,
  152008. 3,
  152009. 3
  152010. };
  152011. static static_codebook _44u9_p5_0 = {
  152012. 4, 81,
  152013. _vq_lengthlist__44u9_p5_0,
  152014. 1, -529137664, 1618345984, 2, 0,
  152015. _vq_quantlist__44u9_p5_0,
  152016. NULL,
  152017. &_vq_auxt__44u9_p5_0,
  152018. NULL,
  152019. 0
  152020. };
  152021. static long _vq_quantlist__44u9_p5_1[] = {
  152022. 5,
  152023. 4,
  152024. 6,
  152025. 3,
  152026. 7,
  152027. 2,
  152028. 8,
  152029. 1,
  152030. 9,
  152031. 0,
  152032. 10,
  152033. };
  152034. static long _vq_lengthlist__44u9_p5_1[] = {
  152035. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152036. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152037. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152038. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152039. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152040. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152041. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152042. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152043. };
  152044. static float _vq_quantthresh__44u9_p5_1[] = {
  152045. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152046. 3.5, 4.5,
  152047. };
  152048. static long _vq_quantmap__44u9_p5_1[] = {
  152049. 9, 7, 5, 3, 1, 0, 2, 4,
  152050. 6, 8, 10,
  152051. };
  152052. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152053. _vq_quantthresh__44u9_p5_1,
  152054. _vq_quantmap__44u9_p5_1,
  152055. 11,
  152056. 11
  152057. };
  152058. static static_codebook _44u9_p5_1 = {
  152059. 2, 121,
  152060. _vq_lengthlist__44u9_p5_1,
  152061. 1, -531365888, 1611661312, 4, 0,
  152062. _vq_quantlist__44u9_p5_1,
  152063. NULL,
  152064. &_vq_auxt__44u9_p5_1,
  152065. NULL,
  152066. 0
  152067. };
  152068. static long _vq_quantlist__44u9_p6_0[] = {
  152069. 6,
  152070. 5,
  152071. 7,
  152072. 4,
  152073. 8,
  152074. 3,
  152075. 9,
  152076. 2,
  152077. 10,
  152078. 1,
  152079. 11,
  152080. 0,
  152081. 12,
  152082. };
  152083. static long _vq_lengthlist__44u9_p6_0[] = {
  152084. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152085. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152086. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152087. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152088. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152089. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152090. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152091. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152092. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152093. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152094. 10,11,11,11,11,12,11,12,12,
  152095. };
  152096. static float _vq_quantthresh__44u9_p6_0[] = {
  152097. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152098. 12.5, 17.5, 22.5, 27.5,
  152099. };
  152100. static long _vq_quantmap__44u9_p6_0[] = {
  152101. 11, 9, 7, 5, 3, 1, 0, 2,
  152102. 4, 6, 8, 10, 12,
  152103. };
  152104. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152105. _vq_quantthresh__44u9_p6_0,
  152106. _vq_quantmap__44u9_p6_0,
  152107. 13,
  152108. 13
  152109. };
  152110. static static_codebook _44u9_p6_0 = {
  152111. 2, 169,
  152112. _vq_lengthlist__44u9_p6_0,
  152113. 1, -526516224, 1616117760, 4, 0,
  152114. _vq_quantlist__44u9_p6_0,
  152115. NULL,
  152116. &_vq_auxt__44u9_p6_0,
  152117. NULL,
  152118. 0
  152119. };
  152120. static long _vq_quantlist__44u9_p6_1[] = {
  152121. 2,
  152122. 1,
  152123. 3,
  152124. 0,
  152125. 4,
  152126. };
  152127. static long _vq_lengthlist__44u9_p6_1[] = {
  152128. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152129. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152130. };
  152131. static float _vq_quantthresh__44u9_p6_1[] = {
  152132. -1.5, -0.5, 0.5, 1.5,
  152133. };
  152134. static long _vq_quantmap__44u9_p6_1[] = {
  152135. 3, 1, 0, 2, 4,
  152136. };
  152137. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152138. _vq_quantthresh__44u9_p6_1,
  152139. _vq_quantmap__44u9_p6_1,
  152140. 5,
  152141. 5
  152142. };
  152143. static static_codebook _44u9_p6_1 = {
  152144. 2, 25,
  152145. _vq_lengthlist__44u9_p6_1,
  152146. 1, -533725184, 1611661312, 3, 0,
  152147. _vq_quantlist__44u9_p6_1,
  152148. NULL,
  152149. &_vq_auxt__44u9_p6_1,
  152150. NULL,
  152151. 0
  152152. };
  152153. static long _vq_quantlist__44u9_p7_0[] = {
  152154. 6,
  152155. 5,
  152156. 7,
  152157. 4,
  152158. 8,
  152159. 3,
  152160. 9,
  152161. 2,
  152162. 10,
  152163. 1,
  152164. 11,
  152165. 0,
  152166. 12,
  152167. };
  152168. static long _vq_lengthlist__44u9_p7_0[] = {
  152169. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152170. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152171. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152172. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152173. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152174. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152175. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152176. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152177. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152178. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152179. 12,13,13,14,14,14,15,15,15,
  152180. };
  152181. static float _vq_quantthresh__44u9_p7_0[] = {
  152182. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152183. 27.5, 38.5, 49.5, 60.5,
  152184. };
  152185. static long _vq_quantmap__44u9_p7_0[] = {
  152186. 11, 9, 7, 5, 3, 1, 0, 2,
  152187. 4, 6, 8, 10, 12,
  152188. };
  152189. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152190. _vq_quantthresh__44u9_p7_0,
  152191. _vq_quantmap__44u9_p7_0,
  152192. 13,
  152193. 13
  152194. };
  152195. static static_codebook _44u9_p7_0 = {
  152196. 2, 169,
  152197. _vq_lengthlist__44u9_p7_0,
  152198. 1, -523206656, 1618345984, 4, 0,
  152199. _vq_quantlist__44u9_p7_0,
  152200. NULL,
  152201. &_vq_auxt__44u9_p7_0,
  152202. NULL,
  152203. 0
  152204. };
  152205. static long _vq_quantlist__44u9_p7_1[] = {
  152206. 5,
  152207. 4,
  152208. 6,
  152209. 3,
  152210. 7,
  152211. 2,
  152212. 8,
  152213. 1,
  152214. 9,
  152215. 0,
  152216. 10,
  152217. };
  152218. static long _vq_lengthlist__44u9_p7_1[] = {
  152219. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152220. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152221. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152222. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152223. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152224. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152225. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152226. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152227. };
  152228. static float _vq_quantthresh__44u9_p7_1[] = {
  152229. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152230. 3.5, 4.5,
  152231. };
  152232. static long _vq_quantmap__44u9_p7_1[] = {
  152233. 9, 7, 5, 3, 1, 0, 2, 4,
  152234. 6, 8, 10,
  152235. };
  152236. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152237. _vq_quantthresh__44u9_p7_1,
  152238. _vq_quantmap__44u9_p7_1,
  152239. 11,
  152240. 11
  152241. };
  152242. static static_codebook _44u9_p7_1 = {
  152243. 2, 121,
  152244. _vq_lengthlist__44u9_p7_1,
  152245. 1, -531365888, 1611661312, 4, 0,
  152246. _vq_quantlist__44u9_p7_1,
  152247. NULL,
  152248. &_vq_auxt__44u9_p7_1,
  152249. NULL,
  152250. 0
  152251. };
  152252. static long _vq_quantlist__44u9_p8_0[] = {
  152253. 7,
  152254. 6,
  152255. 8,
  152256. 5,
  152257. 9,
  152258. 4,
  152259. 10,
  152260. 3,
  152261. 11,
  152262. 2,
  152263. 12,
  152264. 1,
  152265. 13,
  152266. 0,
  152267. 14,
  152268. };
  152269. static long _vq_lengthlist__44u9_p8_0[] = {
  152270. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152271. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152272. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152273. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152274. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152275. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152276. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152277. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152278. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152279. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152280. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152281. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152282. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152283. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152284. 15,
  152285. };
  152286. static float _vq_quantthresh__44u9_p8_0[] = {
  152287. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152288. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152289. };
  152290. static long _vq_quantmap__44u9_p8_0[] = {
  152291. 13, 11, 9, 7, 5, 3, 1, 0,
  152292. 2, 4, 6, 8, 10, 12, 14,
  152293. };
  152294. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152295. _vq_quantthresh__44u9_p8_0,
  152296. _vq_quantmap__44u9_p8_0,
  152297. 15,
  152298. 15
  152299. };
  152300. static static_codebook _44u9_p8_0 = {
  152301. 2, 225,
  152302. _vq_lengthlist__44u9_p8_0,
  152303. 1, -520986624, 1620377600, 4, 0,
  152304. _vq_quantlist__44u9_p8_0,
  152305. NULL,
  152306. &_vq_auxt__44u9_p8_0,
  152307. NULL,
  152308. 0
  152309. };
  152310. static long _vq_quantlist__44u9_p8_1[] = {
  152311. 10,
  152312. 9,
  152313. 11,
  152314. 8,
  152315. 12,
  152316. 7,
  152317. 13,
  152318. 6,
  152319. 14,
  152320. 5,
  152321. 15,
  152322. 4,
  152323. 16,
  152324. 3,
  152325. 17,
  152326. 2,
  152327. 18,
  152328. 1,
  152329. 19,
  152330. 0,
  152331. 20,
  152332. };
  152333. static long _vq_lengthlist__44u9_p8_1[] = {
  152334. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152335. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152336. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152337. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152338. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152339. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152340. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152341. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152342. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152343. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152344. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152345. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152346. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152347. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152348. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152349. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152350. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152351. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152352. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152353. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152354. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152355. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152356. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152357. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152358. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152359. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152360. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152361. 10,10,10,10,10,10,10,10,10,
  152362. };
  152363. static float _vq_quantthresh__44u9_p8_1[] = {
  152364. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152365. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152366. 6.5, 7.5, 8.5, 9.5,
  152367. };
  152368. static long _vq_quantmap__44u9_p8_1[] = {
  152369. 19, 17, 15, 13, 11, 9, 7, 5,
  152370. 3, 1, 0, 2, 4, 6, 8, 10,
  152371. 12, 14, 16, 18, 20,
  152372. };
  152373. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152374. _vq_quantthresh__44u9_p8_1,
  152375. _vq_quantmap__44u9_p8_1,
  152376. 21,
  152377. 21
  152378. };
  152379. static static_codebook _44u9_p8_1 = {
  152380. 2, 441,
  152381. _vq_lengthlist__44u9_p8_1,
  152382. 1, -529268736, 1611661312, 5, 0,
  152383. _vq_quantlist__44u9_p8_1,
  152384. NULL,
  152385. &_vq_auxt__44u9_p8_1,
  152386. NULL,
  152387. 0
  152388. };
  152389. static long _vq_quantlist__44u9_p9_0[] = {
  152390. 7,
  152391. 6,
  152392. 8,
  152393. 5,
  152394. 9,
  152395. 4,
  152396. 10,
  152397. 3,
  152398. 11,
  152399. 2,
  152400. 12,
  152401. 1,
  152402. 13,
  152403. 0,
  152404. 14,
  152405. };
  152406. static long _vq_lengthlist__44u9_p9_0[] = {
  152407. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152408. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152409. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152410. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152411. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152412. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152413. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152414. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152415. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152416. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152417. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152418. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152419. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152420. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152421. 10,
  152422. };
  152423. static float _vq_quantthresh__44u9_p9_0[] = {
  152424. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152425. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152426. };
  152427. static long _vq_quantmap__44u9_p9_0[] = {
  152428. 13, 11, 9, 7, 5, 3, 1, 0,
  152429. 2, 4, 6, 8, 10, 12, 14,
  152430. };
  152431. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152432. _vq_quantthresh__44u9_p9_0,
  152433. _vq_quantmap__44u9_p9_0,
  152434. 15,
  152435. 15
  152436. };
  152437. static static_codebook _44u9_p9_0 = {
  152438. 2, 225,
  152439. _vq_lengthlist__44u9_p9_0,
  152440. 1, -510036736, 1631393792, 4, 0,
  152441. _vq_quantlist__44u9_p9_0,
  152442. NULL,
  152443. &_vq_auxt__44u9_p9_0,
  152444. NULL,
  152445. 0
  152446. };
  152447. static long _vq_quantlist__44u9_p9_1[] = {
  152448. 9,
  152449. 8,
  152450. 10,
  152451. 7,
  152452. 11,
  152453. 6,
  152454. 12,
  152455. 5,
  152456. 13,
  152457. 4,
  152458. 14,
  152459. 3,
  152460. 15,
  152461. 2,
  152462. 16,
  152463. 1,
  152464. 17,
  152465. 0,
  152466. 18,
  152467. };
  152468. static long _vq_lengthlist__44u9_p9_1[] = {
  152469. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152470. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152471. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152472. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152473. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152474. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152475. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152476. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152477. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152478. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152479. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152480. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152481. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152482. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152483. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152484. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152485. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152486. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152487. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152488. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152489. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152490. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152491. 17,17,15,17,15,17,16,16,17,
  152492. };
  152493. static float _vq_quantthresh__44u9_p9_1[] = {
  152494. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152495. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152496. 367.5, 416.5,
  152497. };
  152498. static long _vq_quantmap__44u9_p9_1[] = {
  152499. 17, 15, 13, 11, 9, 7, 5, 3,
  152500. 1, 0, 2, 4, 6, 8, 10, 12,
  152501. 14, 16, 18,
  152502. };
  152503. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152504. _vq_quantthresh__44u9_p9_1,
  152505. _vq_quantmap__44u9_p9_1,
  152506. 19,
  152507. 19
  152508. };
  152509. static static_codebook _44u9_p9_1 = {
  152510. 2, 361,
  152511. _vq_lengthlist__44u9_p9_1,
  152512. 1, -518287360, 1622704128, 5, 0,
  152513. _vq_quantlist__44u9_p9_1,
  152514. NULL,
  152515. &_vq_auxt__44u9_p9_1,
  152516. NULL,
  152517. 0
  152518. };
  152519. static long _vq_quantlist__44u9_p9_2[] = {
  152520. 24,
  152521. 23,
  152522. 25,
  152523. 22,
  152524. 26,
  152525. 21,
  152526. 27,
  152527. 20,
  152528. 28,
  152529. 19,
  152530. 29,
  152531. 18,
  152532. 30,
  152533. 17,
  152534. 31,
  152535. 16,
  152536. 32,
  152537. 15,
  152538. 33,
  152539. 14,
  152540. 34,
  152541. 13,
  152542. 35,
  152543. 12,
  152544. 36,
  152545. 11,
  152546. 37,
  152547. 10,
  152548. 38,
  152549. 9,
  152550. 39,
  152551. 8,
  152552. 40,
  152553. 7,
  152554. 41,
  152555. 6,
  152556. 42,
  152557. 5,
  152558. 43,
  152559. 4,
  152560. 44,
  152561. 3,
  152562. 45,
  152563. 2,
  152564. 46,
  152565. 1,
  152566. 47,
  152567. 0,
  152568. 48,
  152569. };
  152570. static long _vq_lengthlist__44u9_p9_2[] = {
  152571. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152572. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152573. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152574. 7,
  152575. };
  152576. static float _vq_quantthresh__44u9_p9_2[] = {
  152577. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152578. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152579. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152580. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152581. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152582. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152583. };
  152584. static long _vq_quantmap__44u9_p9_2[] = {
  152585. 47, 45, 43, 41, 39, 37, 35, 33,
  152586. 31, 29, 27, 25, 23, 21, 19, 17,
  152587. 15, 13, 11, 9, 7, 5, 3, 1,
  152588. 0, 2, 4, 6, 8, 10, 12, 14,
  152589. 16, 18, 20, 22, 24, 26, 28, 30,
  152590. 32, 34, 36, 38, 40, 42, 44, 46,
  152591. 48,
  152592. };
  152593. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152594. _vq_quantthresh__44u9_p9_2,
  152595. _vq_quantmap__44u9_p9_2,
  152596. 49,
  152597. 49
  152598. };
  152599. static static_codebook _44u9_p9_2 = {
  152600. 1, 49,
  152601. _vq_lengthlist__44u9_p9_2,
  152602. 1, -526909440, 1611661312, 6, 0,
  152603. _vq_quantlist__44u9_p9_2,
  152604. NULL,
  152605. &_vq_auxt__44u9_p9_2,
  152606. NULL,
  152607. 0
  152608. };
  152609. static long _huff_lengthlist__44un1__long[] = {
  152610. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152611. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152612. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152613. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152614. };
  152615. static static_codebook _huff_book__44un1__long = {
  152616. 2, 64,
  152617. _huff_lengthlist__44un1__long,
  152618. 0, 0, 0, 0, 0,
  152619. NULL,
  152620. NULL,
  152621. NULL,
  152622. NULL,
  152623. 0
  152624. };
  152625. static long _vq_quantlist__44un1__p1_0[] = {
  152626. 1,
  152627. 0,
  152628. 2,
  152629. };
  152630. static long _vq_lengthlist__44un1__p1_0[] = {
  152631. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152632. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152633. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152634. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152635. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152636. 12,
  152637. };
  152638. static float _vq_quantthresh__44un1__p1_0[] = {
  152639. -0.5, 0.5,
  152640. };
  152641. static long _vq_quantmap__44un1__p1_0[] = {
  152642. 1, 0, 2,
  152643. };
  152644. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152645. _vq_quantthresh__44un1__p1_0,
  152646. _vq_quantmap__44un1__p1_0,
  152647. 3,
  152648. 3
  152649. };
  152650. static static_codebook _44un1__p1_0 = {
  152651. 4, 81,
  152652. _vq_lengthlist__44un1__p1_0,
  152653. 1, -535822336, 1611661312, 2, 0,
  152654. _vq_quantlist__44un1__p1_0,
  152655. NULL,
  152656. &_vq_auxt__44un1__p1_0,
  152657. NULL,
  152658. 0
  152659. };
  152660. static long _vq_quantlist__44un1__p2_0[] = {
  152661. 1,
  152662. 0,
  152663. 2,
  152664. };
  152665. static long _vq_lengthlist__44un1__p2_0[] = {
  152666. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152667. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152668. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152669. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152670. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152671. 8,
  152672. };
  152673. static float _vq_quantthresh__44un1__p2_0[] = {
  152674. -0.5, 0.5,
  152675. };
  152676. static long _vq_quantmap__44un1__p2_0[] = {
  152677. 1, 0, 2,
  152678. };
  152679. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152680. _vq_quantthresh__44un1__p2_0,
  152681. _vq_quantmap__44un1__p2_0,
  152682. 3,
  152683. 3
  152684. };
  152685. static static_codebook _44un1__p2_0 = {
  152686. 4, 81,
  152687. _vq_lengthlist__44un1__p2_0,
  152688. 1, -535822336, 1611661312, 2, 0,
  152689. _vq_quantlist__44un1__p2_0,
  152690. NULL,
  152691. &_vq_auxt__44un1__p2_0,
  152692. NULL,
  152693. 0
  152694. };
  152695. static long _vq_quantlist__44un1__p3_0[] = {
  152696. 2,
  152697. 1,
  152698. 3,
  152699. 0,
  152700. 4,
  152701. };
  152702. static long _vq_lengthlist__44un1__p3_0[] = {
  152703. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152704. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152705. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152706. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152707. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152708. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152709. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152710. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152711. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152712. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152713. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152714. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152715. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152716. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152717. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152718. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152719. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152720. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152721. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152722. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152723. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152724. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152725. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152726. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152727. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152728. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152729. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152730. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152731. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152732. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152733. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152734. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152735. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152736. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152737. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152738. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152739. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152740. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152741. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152742. 17,
  152743. };
  152744. static float _vq_quantthresh__44un1__p3_0[] = {
  152745. -1.5, -0.5, 0.5, 1.5,
  152746. };
  152747. static long _vq_quantmap__44un1__p3_0[] = {
  152748. 3, 1, 0, 2, 4,
  152749. };
  152750. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152751. _vq_quantthresh__44un1__p3_0,
  152752. _vq_quantmap__44un1__p3_0,
  152753. 5,
  152754. 5
  152755. };
  152756. static static_codebook _44un1__p3_0 = {
  152757. 4, 625,
  152758. _vq_lengthlist__44un1__p3_0,
  152759. 1, -533725184, 1611661312, 3, 0,
  152760. _vq_quantlist__44un1__p3_0,
  152761. NULL,
  152762. &_vq_auxt__44un1__p3_0,
  152763. NULL,
  152764. 0
  152765. };
  152766. static long _vq_quantlist__44un1__p4_0[] = {
  152767. 2,
  152768. 1,
  152769. 3,
  152770. 0,
  152771. 4,
  152772. };
  152773. static long _vq_lengthlist__44un1__p4_0[] = {
  152774. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152775. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152776. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152777. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152778. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152779. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152780. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152781. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152782. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152783. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152784. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152785. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152786. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152787. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152788. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152789. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152790. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152791. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152792. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152793. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152794. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152795. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152796. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152797. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152798. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152799. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152800. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152801. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152802. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152803. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152804. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152805. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152806. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152807. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152808. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152809. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152810. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152811. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152812. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152813. 12,
  152814. };
  152815. static float _vq_quantthresh__44un1__p4_0[] = {
  152816. -1.5, -0.5, 0.5, 1.5,
  152817. };
  152818. static long _vq_quantmap__44un1__p4_0[] = {
  152819. 3, 1, 0, 2, 4,
  152820. };
  152821. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152822. _vq_quantthresh__44un1__p4_0,
  152823. _vq_quantmap__44un1__p4_0,
  152824. 5,
  152825. 5
  152826. };
  152827. static static_codebook _44un1__p4_0 = {
  152828. 4, 625,
  152829. _vq_lengthlist__44un1__p4_0,
  152830. 1, -533725184, 1611661312, 3, 0,
  152831. _vq_quantlist__44un1__p4_0,
  152832. NULL,
  152833. &_vq_auxt__44un1__p4_0,
  152834. NULL,
  152835. 0
  152836. };
  152837. static long _vq_quantlist__44un1__p5_0[] = {
  152838. 4,
  152839. 3,
  152840. 5,
  152841. 2,
  152842. 6,
  152843. 1,
  152844. 7,
  152845. 0,
  152846. 8,
  152847. };
  152848. static long _vq_lengthlist__44un1__p5_0[] = {
  152849. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152850. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152851. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152852. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152853. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152854. 12,
  152855. };
  152856. static float _vq_quantthresh__44un1__p5_0[] = {
  152857. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152858. };
  152859. static long _vq_quantmap__44un1__p5_0[] = {
  152860. 7, 5, 3, 1, 0, 2, 4, 6,
  152861. 8,
  152862. };
  152863. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152864. _vq_quantthresh__44un1__p5_0,
  152865. _vq_quantmap__44un1__p5_0,
  152866. 9,
  152867. 9
  152868. };
  152869. static static_codebook _44un1__p5_0 = {
  152870. 2, 81,
  152871. _vq_lengthlist__44un1__p5_0,
  152872. 1, -531628032, 1611661312, 4, 0,
  152873. _vq_quantlist__44un1__p5_0,
  152874. NULL,
  152875. &_vq_auxt__44un1__p5_0,
  152876. NULL,
  152877. 0
  152878. };
  152879. static long _vq_quantlist__44un1__p6_0[] = {
  152880. 6,
  152881. 5,
  152882. 7,
  152883. 4,
  152884. 8,
  152885. 3,
  152886. 9,
  152887. 2,
  152888. 10,
  152889. 1,
  152890. 11,
  152891. 0,
  152892. 12,
  152893. };
  152894. static long _vq_lengthlist__44un1__p6_0[] = {
  152895. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152896. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152897. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152898. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152899. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152900. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152901. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152902. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152903. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152904. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152905. 16, 0,15,18,18, 0,16, 0, 0,
  152906. };
  152907. static float _vq_quantthresh__44un1__p6_0[] = {
  152908. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152909. 12.5, 17.5, 22.5, 27.5,
  152910. };
  152911. static long _vq_quantmap__44un1__p6_0[] = {
  152912. 11, 9, 7, 5, 3, 1, 0, 2,
  152913. 4, 6, 8, 10, 12,
  152914. };
  152915. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152916. _vq_quantthresh__44un1__p6_0,
  152917. _vq_quantmap__44un1__p6_0,
  152918. 13,
  152919. 13
  152920. };
  152921. static static_codebook _44un1__p6_0 = {
  152922. 2, 169,
  152923. _vq_lengthlist__44un1__p6_0,
  152924. 1, -526516224, 1616117760, 4, 0,
  152925. _vq_quantlist__44un1__p6_0,
  152926. NULL,
  152927. &_vq_auxt__44un1__p6_0,
  152928. NULL,
  152929. 0
  152930. };
  152931. static long _vq_quantlist__44un1__p6_1[] = {
  152932. 2,
  152933. 1,
  152934. 3,
  152935. 0,
  152936. 4,
  152937. };
  152938. static long _vq_lengthlist__44un1__p6_1[] = {
  152939. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152940. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152941. };
  152942. static float _vq_quantthresh__44un1__p6_1[] = {
  152943. -1.5, -0.5, 0.5, 1.5,
  152944. };
  152945. static long _vq_quantmap__44un1__p6_1[] = {
  152946. 3, 1, 0, 2, 4,
  152947. };
  152948. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152949. _vq_quantthresh__44un1__p6_1,
  152950. _vq_quantmap__44un1__p6_1,
  152951. 5,
  152952. 5
  152953. };
  152954. static static_codebook _44un1__p6_1 = {
  152955. 2, 25,
  152956. _vq_lengthlist__44un1__p6_1,
  152957. 1, -533725184, 1611661312, 3, 0,
  152958. _vq_quantlist__44un1__p6_1,
  152959. NULL,
  152960. &_vq_auxt__44un1__p6_1,
  152961. NULL,
  152962. 0
  152963. };
  152964. static long _vq_quantlist__44un1__p7_0[] = {
  152965. 2,
  152966. 1,
  152967. 3,
  152968. 0,
  152969. 4,
  152970. };
  152971. static long _vq_lengthlist__44un1__p7_0[] = {
  152972. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152973. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152974. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152975. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152976. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152977. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152978. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152979. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152980. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152981. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152982. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152983. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152984. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152985. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152986. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152987. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152988. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152989. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152990. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152991. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152992. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152993. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152994. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152995. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152996. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153000. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153002. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153003. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153008. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153009. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153010. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153011. 10,
  153012. };
  153013. static float _vq_quantthresh__44un1__p7_0[] = {
  153014. -253.5, -84.5, 84.5, 253.5,
  153015. };
  153016. static long _vq_quantmap__44un1__p7_0[] = {
  153017. 3, 1, 0, 2, 4,
  153018. };
  153019. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153020. _vq_quantthresh__44un1__p7_0,
  153021. _vq_quantmap__44un1__p7_0,
  153022. 5,
  153023. 5
  153024. };
  153025. static static_codebook _44un1__p7_0 = {
  153026. 4, 625,
  153027. _vq_lengthlist__44un1__p7_0,
  153028. 1, -518709248, 1626677248, 3, 0,
  153029. _vq_quantlist__44un1__p7_0,
  153030. NULL,
  153031. &_vq_auxt__44un1__p7_0,
  153032. NULL,
  153033. 0
  153034. };
  153035. static long _vq_quantlist__44un1__p7_1[] = {
  153036. 6,
  153037. 5,
  153038. 7,
  153039. 4,
  153040. 8,
  153041. 3,
  153042. 9,
  153043. 2,
  153044. 10,
  153045. 1,
  153046. 11,
  153047. 0,
  153048. 12,
  153049. };
  153050. static long _vq_lengthlist__44un1__p7_1[] = {
  153051. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153052. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153053. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153054. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153055. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153056. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153057. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153058. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153059. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153060. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153061. 12,13,13,12,13,13,14,14,14,
  153062. };
  153063. static float _vq_quantthresh__44un1__p7_1[] = {
  153064. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153065. 32.5, 45.5, 58.5, 71.5,
  153066. };
  153067. static long _vq_quantmap__44un1__p7_1[] = {
  153068. 11, 9, 7, 5, 3, 1, 0, 2,
  153069. 4, 6, 8, 10, 12,
  153070. };
  153071. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153072. _vq_quantthresh__44un1__p7_1,
  153073. _vq_quantmap__44un1__p7_1,
  153074. 13,
  153075. 13
  153076. };
  153077. static static_codebook _44un1__p7_1 = {
  153078. 2, 169,
  153079. _vq_lengthlist__44un1__p7_1,
  153080. 1, -523010048, 1618608128, 4, 0,
  153081. _vq_quantlist__44un1__p7_1,
  153082. NULL,
  153083. &_vq_auxt__44un1__p7_1,
  153084. NULL,
  153085. 0
  153086. };
  153087. static long _vq_quantlist__44un1__p7_2[] = {
  153088. 6,
  153089. 5,
  153090. 7,
  153091. 4,
  153092. 8,
  153093. 3,
  153094. 9,
  153095. 2,
  153096. 10,
  153097. 1,
  153098. 11,
  153099. 0,
  153100. 12,
  153101. };
  153102. static long _vq_lengthlist__44un1__p7_2[] = {
  153103. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153104. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153105. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153106. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153107. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153108. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153109. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153110. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153111. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153112. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153113. 9, 9, 9,10,10,10,10,10,10,
  153114. };
  153115. static float _vq_quantthresh__44un1__p7_2[] = {
  153116. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153117. 2.5, 3.5, 4.5, 5.5,
  153118. };
  153119. static long _vq_quantmap__44un1__p7_2[] = {
  153120. 11, 9, 7, 5, 3, 1, 0, 2,
  153121. 4, 6, 8, 10, 12,
  153122. };
  153123. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153124. _vq_quantthresh__44un1__p7_2,
  153125. _vq_quantmap__44un1__p7_2,
  153126. 13,
  153127. 13
  153128. };
  153129. static static_codebook _44un1__p7_2 = {
  153130. 2, 169,
  153131. _vq_lengthlist__44un1__p7_2,
  153132. 1, -531103744, 1611661312, 4, 0,
  153133. _vq_quantlist__44un1__p7_2,
  153134. NULL,
  153135. &_vq_auxt__44un1__p7_2,
  153136. NULL,
  153137. 0
  153138. };
  153139. static long _huff_lengthlist__44un1__short[] = {
  153140. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153141. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153142. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153143. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153144. };
  153145. static static_codebook _huff_book__44un1__short = {
  153146. 2, 64,
  153147. _huff_lengthlist__44un1__short,
  153148. 0, 0, 0, 0, 0,
  153149. NULL,
  153150. NULL,
  153151. NULL,
  153152. NULL,
  153153. 0
  153154. };
  153155. /*** End of inlined file: res_books_uncoupled.h ***/
  153156. /***** residue backends *********************************************/
  153157. static vorbis_info_residue0 _residue_44_low_un={
  153158. 0,-1, -1, 8,-1,
  153159. {0},
  153160. {-1},
  153161. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153162. { -1, 25, -1, 45, -1, -1, -1}
  153163. };
  153164. static vorbis_info_residue0 _residue_44_mid_un={
  153165. 0,-1, -1, 10,-1,
  153166. /* 0 1 2 3 4 5 6 7 8 9 */
  153167. {0},
  153168. {-1},
  153169. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153170. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153171. };
  153172. static vorbis_info_residue0 _residue_44_hi_un={
  153173. 0,-1, -1, 10,-1,
  153174. /* 0 1 2 3 4 5 6 7 8 9 */
  153175. {0},
  153176. {-1},
  153177. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153178. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153179. };
  153180. /* mapping conventions:
  153181. only one submap (this would change for efficient 5.1 support for example)*/
  153182. /* Four psychoacoustic profiles are used, one for each blocktype */
  153183. static vorbis_info_mapping0 _map_nominal_u[2]={
  153184. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153185. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153186. };
  153187. static static_bookblock _resbook_44u_n1={
  153188. {
  153189. {0},
  153190. {0,0,&_44un1__p1_0},
  153191. {0,0,&_44un1__p2_0},
  153192. {0,0,&_44un1__p3_0},
  153193. {0,0,&_44un1__p4_0},
  153194. {0,0,&_44un1__p5_0},
  153195. {&_44un1__p6_0,&_44un1__p6_1},
  153196. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153197. }
  153198. };
  153199. static static_bookblock _resbook_44u_0={
  153200. {
  153201. {0},
  153202. {0,0,&_44u0__p1_0},
  153203. {0,0,&_44u0__p2_0},
  153204. {0,0,&_44u0__p3_0},
  153205. {0,0,&_44u0__p4_0},
  153206. {0,0,&_44u0__p5_0},
  153207. {&_44u0__p6_0,&_44u0__p6_1},
  153208. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153209. }
  153210. };
  153211. static static_bookblock _resbook_44u_1={
  153212. {
  153213. {0},
  153214. {0,0,&_44u1__p1_0},
  153215. {0,0,&_44u1__p2_0},
  153216. {0,0,&_44u1__p3_0},
  153217. {0,0,&_44u1__p4_0},
  153218. {0,0,&_44u1__p5_0},
  153219. {&_44u1__p6_0,&_44u1__p6_1},
  153220. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153221. }
  153222. };
  153223. static static_bookblock _resbook_44u_2={
  153224. {
  153225. {0},
  153226. {0,0,&_44u2__p1_0},
  153227. {0,0,&_44u2__p2_0},
  153228. {0,0,&_44u2__p3_0},
  153229. {0,0,&_44u2__p4_0},
  153230. {0,0,&_44u2__p5_0},
  153231. {&_44u2__p6_0,&_44u2__p6_1},
  153232. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153233. }
  153234. };
  153235. static static_bookblock _resbook_44u_3={
  153236. {
  153237. {0},
  153238. {0,0,&_44u3__p1_0},
  153239. {0,0,&_44u3__p2_0},
  153240. {0,0,&_44u3__p3_0},
  153241. {0,0,&_44u3__p4_0},
  153242. {0,0,&_44u3__p5_0},
  153243. {&_44u3__p6_0,&_44u3__p6_1},
  153244. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153245. }
  153246. };
  153247. static static_bookblock _resbook_44u_4={
  153248. {
  153249. {0},
  153250. {0,0,&_44u4__p1_0},
  153251. {0,0,&_44u4__p2_0},
  153252. {0,0,&_44u4__p3_0},
  153253. {0,0,&_44u4__p4_0},
  153254. {0,0,&_44u4__p5_0},
  153255. {&_44u4__p6_0,&_44u4__p6_1},
  153256. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153257. }
  153258. };
  153259. static static_bookblock _resbook_44u_5={
  153260. {
  153261. {0},
  153262. {0,0,&_44u5__p1_0},
  153263. {0,0,&_44u5__p2_0},
  153264. {0,0,&_44u5__p3_0},
  153265. {0,0,&_44u5__p4_0},
  153266. {0,0,&_44u5__p5_0},
  153267. {0,0,&_44u5__p6_0},
  153268. {&_44u5__p7_0,&_44u5__p7_1},
  153269. {&_44u5__p8_0,&_44u5__p8_1},
  153270. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153271. }
  153272. };
  153273. static static_bookblock _resbook_44u_6={
  153274. {
  153275. {0},
  153276. {0,0,&_44u6__p1_0},
  153277. {0,0,&_44u6__p2_0},
  153278. {0,0,&_44u6__p3_0},
  153279. {0,0,&_44u6__p4_0},
  153280. {0,0,&_44u6__p5_0},
  153281. {0,0,&_44u6__p6_0},
  153282. {&_44u6__p7_0,&_44u6__p7_1},
  153283. {&_44u6__p8_0,&_44u6__p8_1},
  153284. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153285. }
  153286. };
  153287. static static_bookblock _resbook_44u_7={
  153288. {
  153289. {0},
  153290. {0,0,&_44u7__p1_0},
  153291. {0,0,&_44u7__p2_0},
  153292. {0,0,&_44u7__p3_0},
  153293. {0,0,&_44u7__p4_0},
  153294. {0,0,&_44u7__p5_0},
  153295. {0,0,&_44u7__p6_0},
  153296. {&_44u7__p7_0,&_44u7__p7_1},
  153297. {&_44u7__p8_0,&_44u7__p8_1},
  153298. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153299. }
  153300. };
  153301. static static_bookblock _resbook_44u_8={
  153302. {
  153303. {0},
  153304. {0,0,&_44u8_p1_0},
  153305. {0,0,&_44u8_p2_0},
  153306. {0,0,&_44u8_p3_0},
  153307. {0,0,&_44u8_p4_0},
  153308. {&_44u8_p5_0,&_44u8_p5_1},
  153309. {&_44u8_p6_0,&_44u8_p6_1},
  153310. {&_44u8_p7_0,&_44u8_p7_1},
  153311. {&_44u8_p8_0,&_44u8_p8_1},
  153312. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153313. }
  153314. };
  153315. static static_bookblock _resbook_44u_9={
  153316. {
  153317. {0},
  153318. {0,0,&_44u9_p1_0},
  153319. {0,0,&_44u9_p2_0},
  153320. {0,0,&_44u9_p3_0},
  153321. {0,0,&_44u9_p4_0},
  153322. {&_44u9_p5_0,&_44u9_p5_1},
  153323. {&_44u9_p6_0,&_44u9_p6_1},
  153324. {&_44u9_p7_0,&_44u9_p7_1},
  153325. {&_44u9_p8_0,&_44u9_p8_1},
  153326. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153327. }
  153328. };
  153329. static vorbis_residue_template _res_44u_n1[]={
  153330. {1,0, &_residue_44_low_un,
  153331. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153332. &_resbook_44u_n1,&_resbook_44u_n1},
  153333. {1,0, &_residue_44_low_un,
  153334. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153335. &_resbook_44u_n1,&_resbook_44u_n1}
  153336. };
  153337. static vorbis_residue_template _res_44u_0[]={
  153338. {1,0, &_residue_44_low_un,
  153339. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153340. &_resbook_44u_0,&_resbook_44u_0},
  153341. {1,0, &_residue_44_low_un,
  153342. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153343. &_resbook_44u_0,&_resbook_44u_0}
  153344. };
  153345. static vorbis_residue_template _res_44u_1[]={
  153346. {1,0, &_residue_44_low_un,
  153347. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153348. &_resbook_44u_1,&_resbook_44u_1},
  153349. {1,0, &_residue_44_low_un,
  153350. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153351. &_resbook_44u_1,&_resbook_44u_1}
  153352. };
  153353. static vorbis_residue_template _res_44u_2[]={
  153354. {1,0, &_residue_44_low_un,
  153355. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153356. &_resbook_44u_2,&_resbook_44u_2},
  153357. {1,0, &_residue_44_low_un,
  153358. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153359. &_resbook_44u_2,&_resbook_44u_2}
  153360. };
  153361. static vorbis_residue_template _res_44u_3[]={
  153362. {1,0, &_residue_44_low_un,
  153363. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153364. &_resbook_44u_3,&_resbook_44u_3},
  153365. {1,0, &_residue_44_low_un,
  153366. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153367. &_resbook_44u_3,&_resbook_44u_3}
  153368. };
  153369. static vorbis_residue_template _res_44u_4[]={
  153370. {1,0, &_residue_44_low_un,
  153371. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153372. &_resbook_44u_4,&_resbook_44u_4},
  153373. {1,0, &_residue_44_low_un,
  153374. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153375. &_resbook_44u_4,&_resbook_44u_4}
  153376. };
  153377. static vorbis_residue_template _res_44u_5[]={
  153378. {1,0, &_residue_44_mid_un,
  153379. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153380. &_resbook_44u_5,&_resbook_44u_5},
  153381. {1,0, &_residue_44_mid_un,
  153382. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153383. &_resbook_44u_5,&_resbook_44u_5}
  153384. };
  153385. static vorbis_residue_template _res_44u_6[]={
  153386. {1,0, &_residue_44_mid_un,
  153387. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153388. &_resbook_44u_6,&_resbook_44u_6},
  153389. {1,0, &_residue_44_mid_un,
  153390. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153391. &_resbook_44u_6,&_resbook_44u_6}
  153392. };
  153393. static vorbis_residue_template _res_44u_7[]={
  153394. {1,0, &_residue_44_mid_un,
  153395. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153396. &_resbook_44u_7,&_resbook_44u_7},
  153397. {1,0, &_residue_44_mid_un,
  153398. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153399. &_resbook_44u_7,&_resbook_44u_7}
  153400. };
  153401. static vorbis_residue_template _res_44u_8[]={
  153402. {1,0, &_residue_44_hi_un,
  153403. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153404. &_resbook_44u_8,&_resbook_44u_8},
  153405. {1,0, &_residue_44_hi_un,
  153406. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153407. &_resbook_44u_8,&_resbook_44u_8}
  153408. };
  153409. static vorbis_residue_template _res_44u_9[]={
  153410. {1,0, &_residue_44_hi_un,
  153411. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153412. &_resbook_44u_9,&_resbook_44u_9},
  153413. {1,0, &_residue_44_hi_un,
  153414. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153415. &_resbook_44u_9,&_resbook_44u_9}
  153416. };
  153417. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153418. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153419. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153420. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153421. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153422. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153423. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153424. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153425. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153426. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153427. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153428. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153429. };
  153430. /*** End of inlined file: residue_44u.h ***/
  153431. static double rate_mapping_44_un[12]={
  153432. 32000.,48000.,60000.,70000.,80000.,86000.,
  153433. 96000.,110000.,120000.,140000.,160000.,240001.
  153434. };
  153435. ve_setup_data_template ve_setup_44_uncoupled={
  153436. 11,
  153437. rate_mapping_44_un,
  153438. quality_mapping_44,
  153439. -1,
  153440. 40000,
  153441. 50000,
  153442. blocksize_short_44,
  153443. blocksize_long_44,
  153444. _psy_tone_masteratt_44,
  153445. _psy_tone_0dB,
  153446. _psy_tone_suppress,
  153447. _vp_tonemask_adj_otherblock,
  153448. _vp_tonemask_adj_longblock,
  153449. _vp_tonemask_adj_otherblock,
  153450. _psy_noiseguards_44,
  153451. _psy_noisebias_impulse,
  153452. _psy_noisebias_padding,
  153453. _psy_noisebias_trans,
  153454. _psy_noisebias_long,
  153455. _psy_noise_suppress,
  153456. _psy_compand_44,
  153457. _psy_compand_short_mapping,
  153458. _psy_compand_long_mapping,
  153459. {_noise_start_short_44,_noise_start_long_44},
  153460. {_noise_part_short_44,_noise_part_long_44},
  153461. _noise_thresh_44,
  153462. _psy_ath_floater,
  153463. _psy_ath_abs,
  153464. _psy_lowpass_44,
  153465. _psy_global_44,
  153466. _global_mapping_44,
  153467. NULL,
  153468. _floor_books,
  153469. _floor,
  153470. _floor_short_mapping_44,
  153471. _floor_long_mapping_44,
  153472. _mapres_template_44_uncoupled
  153473. };
  153474. /*** End of inlined file: setup_44u.h ***/
  153475. /*** Start of inlined file: setup_32.h ***/
  153476. static double rate_mapping_32[12]={
  153477. 18000.,28000.,35000.,45000.,56000.,60000.,
  153478. 75000.,90000.,100000.,115000.,150000.,190000.,
  153479. };
  153480. static double rate_mapping_32_un[12]={
  153481. 30000.,42000.,52000.,64000.,72000.,78000.,
  153482. 86000.,92000.,110000.,120000.,140000.,190000.,
  153483. };
  153484. static double _psy_lowpass_32[12]={
  153485. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153486. };
  153487. ve_setup_data_template ve_setup_32_stereo={
  153488. 11,
  153489. rate_mapping_32,
  153490. quality_mapping_44,
  153491. 2,
  153492. 26000,
  153493. 40000,
  153494. blocksize_short_44,
  153495. blocksize_long_44,
  153496. _psy_tone_masteratt_44,
  153497. _psy_tone_0dB,
  153498. _psy_tone_suppress,
  153499. _vp_tonemask_adj_otherblock,
  153500. _vp_tonemask_adj_longblock,
  153501. _vp_tonemask_adj_otherblock,
  153502. _psy_noiseguards_44,
  153503. _psy_noisebias_impulse,
  153504. _psy_noisebias_padding,
  153505. _psy_noisebias_trans,
  153506. _psy_noisebias_long,
  153507. _psy_noise_suppress,
  153508. _psy_compand_44,
  153509. _psy_compand_short_mapping,
  153510. _psy_compand_long_mapping,
  153511. {_noise_start_short_44,_noise_start_long_44},
  153512. {_noise_part_short_44,_noise_part_long_44},
  153513. _noise_thresh_44,
  153514. _psy_ath_floater,
  153515. _psy_ath_abs,
  153516. _psy_lowpass_32,
  153517. _psy_global_44,
  153518. _global_mapping_44,
  153519. _psy_stereo_modes_44,
  153520. _floor_books,
  153521. _floor,
  153522. _floor_short_mapping_44,
  153523. _floor_long_mapping_44,
  153524. _mapres_template_44_stereo
  153525. };
  153526. ve_setup_data_template ve_setup_32_uncoupled={
  153527. 11,
  153528. rate_mapping_32_un,
  153529. quality_mapping_44,
  153530. -1,
  153531. 26000,
  153532. 40000,
  153533. blocksize_short_44,
  153534. blocksize_long_44,
  153535. _psy_tone_masteratt_44,
  153536. _psy_tone_0dB,
  153537. _psy_tone_suppress,
  153538. _vp_tonemask_adj_otherblock,
  153539. _vp_tonemask_adj_longblock,
  153540. _vp_tonemask_adj_otherblock,
  153541. _psy_noiseguards_44,
  153542. _psy_noisebias_impulse,
  153543. _psy_noisebias_padding,
  153544. _psy_noisebias_trans,
  153545. _psy_noisebias_long,
  153546. _psy_noise_suppress,
  153547. _psy_compand_44,
  153548. _psy_compand_short_mapping,
  153549. _psy_compand_long_mapping,
  153550. {_noise_start_short_44,_noise_start_long_44},
  153551. {_noise_part_short_44,_noise_part_long_44},
  153552. _noise_thresh_44,
  153553. _psy_ath_floater,
  153554. _psy_ath_abs,
  153555. _psy_lowpass_32,
  153556. _psy_global_44,
  153557. _global_mapping_44,
  153558. NULL,
  153559. _floor_books,
  153560. _floor,
  153561. _floor_short_mapping_44,
  153562. _floor_long_mapping_44,
  153563. _mapres_template_44_uncoupled
  153564. };
  153565. /*** End of inlined file: setup_32.h ***/
  153566. /*** Start of inlined file: setup_8.h ***/
  153567. /*** Start of inlined file: psych_8.h ***/
  153568. static att3 _psy_tone_masteratt_8[3]={
  153569. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153570. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153571. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153572. };
  153573. static vp_adjblock _vp_tonemask_adj_8[3]={
  153574. /* adjust for mode zero */
  153575. /* 63 125 250 500 1 2 4 8 16 */
  153576. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153577. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153578. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153579. };
  153580. static noise3 _psy_noisebias_8[3]={
  153581. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153582. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153583. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153584. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153585. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153586. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153587. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153588. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153589. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153590. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153591. };
  153592. /* stereo mode by base quality level */
  153593. static adj_stereo _psy_stereo_modes_8[3]={
  153594. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153595. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153596. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153597. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153598. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153599. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153600. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153601. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153602. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153603. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153604. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153605. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153606. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153607. };
  153608. static noiseguard _psy_noiseguards_8[2]={
  153609. {10,10,-1},
  153610. {10,10,-1},
  153611. };
  153612. static compandblock _psy_compand_8[2]={
  153613. {{
  153614. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153615. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153616. 12,12,13,13,14,14,15, 15, /* 23dB */
  153617. 16,16,17,17,17,18,18, 19, /* 31dB */
  153618. 19,19,20,21,22,23,24, 25, /* 39dB */
  153619. }},
  153620. {{
  153621. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153622. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153623. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153624. 9,10,11,12,13,14,15, 16, /* 31dB */
  153625. 17,18,19,20,21,22,23, 24, /* 39dB */
  153626. }},
  153627. };
  153628. static double _psy_lowpass_8[3]={3.,4.,4.};
  153629. static int _noise_start_8[2]={
  153630. 64,64,
  153631. };
  153632. static int _noise_part_8[2]={
  153633. 8,8,
  153634. };
  153635. static int _psy_ath_floater_8[3]={
  153636. -100,-100,-105,
  153637. };
  153638. static int _psy_ath_abs_8[3]={
  153639. -130,-130,-140,
  153640. };
  153641. /*** End of inlined file: psych_8.h ***/
  153642. /*** Start of inlined file: residue_8.h ***/
  153643. /***** residue backends *********************************************/
  153644. static static_bookblock _resbook_8s_0={
  153645. {
  153646. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153647. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153648. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153649. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153650. }
  153651. };
  153652. static static_bookblock _resbook_8s_1={
  153653. {
  153654. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153655. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153656. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153657. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153658. }
  153659. };
  153660. static vorbis_residue_template _res_8s_0[]={
  153661. {2,0, &_residue_44_mid,
  153662. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153663. &_resbook_8s_0,&_resbook_8s_0},
  153664. };
  153665. static vorbis_residue_template _res_8s_1[]={
  153666. {2,0, &_residue_44_mid,
  153667. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153668. &_resbook_8s_1,&_resbook_8s_1},
  153669. };
  153670. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153671. { _map_nominal, _res_8s_0 }, /* 0 */
  153672. { _map_nominal, _res_8s_1 }, /* 1 */
  153673. };
  153674. static static_bookblock _resbook_8u_0={
  153675. {
  153676. {0},
  153677. {0,0,&_8u0__p1_0},
  153678. {0,0,&_8u0__p2_0},
  153679. {0,0,&_8u0__p3_0},
  153680. {0,0,&_8u0__p4_0},
  153681. {0,0,&_8u0__p5_0},
  153682. {&_8u0__p6_0,&_8u0__p6_1},
  153683. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153684. }
  153685. };
  153686. static static_bookblock _resbook_8u_1={
  153687. {
  153688. {0},
  153689. {0,0,&_8u1__p1_0},
  153690. {0,0,&_8u1__p2_0},
  153691. {0,0,&_8u1__p3_0},
  153692. {0,0,&_8u1__p4_0},
  153693. {0,0,&_8u1__p5_0},
  153694. {0,0,&_8u1__p6_0},
  153695. {&_8u1__p7_0,&_8u1__p7_1},
  153696. {&_8u1__p8_0,&_8u1__p8_1},
  153697. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153698. }
  153699. };
  153700. static vorbis_residue_template _res_8u_0[]={
  153701. {1,0, &_residue_44_low_un,
  153702. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153703. &_resbook_8u_0,&_resbook_8u_0},
  153704. };
  153705. static vorbis_residue_template _res_8u_1[]={
  153706. {1,0, &_residue_44_mid_un,
  153707. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153708. &_resbook_8u_1,&_resbook_8u_1},
  153709. };
  153710. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153711. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153712. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153713. };
  153714. /*** End of inlined file: residue_8.h ***/
  153715. static int blocksize_8[2]={
  153716. 512,512
  153717. };
  153718. static int _floor_mapping_8[2]={
  153719. 6,6,
  153720. };
  153721. static double rate_mapping_8[3]={
  153722. 6000.,9000.,32000.,
  153723. };
  153724. static double rate_mapping_8_uncoupled[3]={
  153725. 8000.,14000.,42000.,
  153726. };
  153727. static double quality_mapping_8[3]={
  153728. -.1,.0,1.
  153729. };
  153730. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153731. static double _global_mapping_8[3]={ 1., 2., 3. };
  153732. ve_setup_data_template ve_setup_8_stereo={
  153733. 2,
  153734. rate_mapping_8,
  153735. quality_mapping_8,
  153736. 2,
  153737. 8000,
  153738. 9000,
  153739. blocksize_8,
  153740. blocksize_8,
  153741. _psy_tone_masteratt_8,
  153742. _psy_tone_0dB,
  153743. _psy_tone_suppress,
  153744. _vp_tonemask_adj_8,
  153745. NULL,
  153746. _vp_tonemask_adj_8,
  153747. _psy_noiseguards_8,
  153748. _psy_noisebias_8,
  153749. _psy_noisebias_8,
  153750. NULL,
  153751. NULL,
  153752. _psy_noise_suppress,
  153753. _psy_compand_8,
  153754. _psy_compand_8_mapping,
  153755. NULL,
  153756. {_noise_start_8,_noise_start_8},
  153757. {_noise_part_8,_noise_part_8},
  153758. _noise_thresh_5only,
  153759. _psy_ath_floater_8,
  153760. _psy_ath_abs_8,
  153761. _psy_lowpass_8,
  153762. _psy_global_44,
  153763. _global_mapping_8,
  153764. _psy_stereo_modes_8,
  153765. _floor_books,
  153766. _floor,
  153767. _floor_mapping_8,
  153768. NULL,
  153769. _mapres_template_8_stereo
  153770. };
  153771. ve_setup_data_template ve_setup_8_uncoupled={
  153772. 2,
  153773. rate_mapping_8_uncoupled,
  153774. quality_mapping_8,
  153775. -1,
  153776. 8000,
  153777. 9000,
  153778. blocksize_8,
  153779. blocksize_8,
  153780. _psy_tone_masteratt_8,
  153781. _psy_tone_0dB,
  153782. _psy_tone_suppress,
  153783. _vp_tonemask_adj_8,
  153784. NULL,
  153785. _vp_tonemask_adj_8,
  153786. _psy_noiseguards_8,
  153787. _psy_noisebias_8,
  153788. _psy_noisebias_8,
  153789. NULL,
  153790. NULL,
  153791. _psy_noise_suppress,
  153792. _psy_compand_8,
  153793. _psy_compand_8_mapping,
  153794. NULL,
  153795. {_noise_start_8,_noise_start_8},
  153796. {_noise_part_8,_noise_part_8},
  153797. _noise_thresh_5only,
  153798. _psy_ath_floater_8,
  153799. _psy_ath_abs_8,
  153800. _psy_lowpass_8,
  153801. _psy_global_44,
  153802. _global_mapping_8,
  153803. _psy_stereo_modes_8,
  153804. _floor_books,
  153805. _floor,
  153806. _floor_mapping_8,
  153807. NULL,
  153808. _mapres_template_8_uncoupled
  153809. };
  153810. /*** End of inlined file: setup_8.h ***/
  153811. /*** Start of inlined file: setup_11.h ***/
  153812. /*** Start of inlined file: psych_11.h ***/
  153813. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153814. static att3 _psy_tone_masteratt_11[3]={
  153815. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153816. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153817. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153818. };
  153819. static vp_adjblock _vp_tonemask_adj_11[3]={
  153820. /* adjust for mode zero */
  153821. /* 63 125 250 500 1 2 4 8 16 */
  153822. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153823. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153824. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153825. };
  153826. static noise3 _psy_noisebias_11[3]={
  153827. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153828. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153829. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153830. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153831. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153832. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153833. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153834. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153835. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153836. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153837. };
  153838. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153839. /*** End of inlined file: psych_11.h ***/
  153840. static int blocksize_11[2]={
  153841. 512,512
  153842. };
  153843. static int _floor_mapping_11[2]={
  153844. 6,6,
  153845. };
  153846. static double rate_mapping_11[3]={
  153847. 8000.,13000.,44000.,
  153848. };
  153849. static double rate_mapping_11_uncoupled[3]={
  153850. 12000.,20000.,50000.,
  153851. };
  153852. static double quality_mapping_11[3]={
  153853. -.1,.0,1.
  153854. };
  153855. ve_setup_data_template ve_setup_11_stereo={
  153856. 2,
  153857. rate_mapping_11,
  153858. quality_mapping_11,
  153859. 2,
  153860. 9000,
  153861. 15000,
  153862. blocksize_11,
  153863. blocksize_11,
  153864. _psy_tone_masteratt_11,
  153865. _psy_tone_0dB,
  153866. _psy_tone_suppress,
  153867. _vp_tonemask_adj_11,
  153868. NULL,
  153869. _vp_tonemask_adj_11,
  153870. _psy_noiseguards_8,
  153871. _psy_noisebias_11,
  153872. _psy_noisebias_11,
  153873. NULL,
  153874. NULL,
  153875. _psy_noise_suppress,
  153876. _psy_compand_8,
  153877. _psy_compand_8_mapping,
  153878. NULL,
  153879. {_noise_start_8,_noise_start_8},
  153880. {_noise_part_8,_noise_part_8},
  153881. _noise_thresh_11,
  153882. _psy_ath_floater_8,
  153883. _psy_ath_abs_8,
  153884. _psy_lowpass_11,
  153885. _psy_global_44,
  153886. _global_mapping_8,
  153887. _psy_stereo_modes_8,
  153888. _floor_books,
  153889. _floor,
  153890. _floor_mapping_11,
  153891. NULL,
  153892. _mapres_template_8_stereo
  153893. };
  153894. ve_setup_data_template ve_setup_11_uncoupled={
  153895. 2,
  153896. rate_mapping_11_uncoupled,
  153897. quality_mapping_11,
  153898. -1,
  153899. 9000,
  153900. 15000,
  153901. blocksize_11,
  153902. blocksize_11,
  153903. _psy_tone_masteratt_11,
  153904. _psy_tone_0dB,
  153905. _psy_tone_suppress,
  153906. _vp_tonemask_adj_11,
  153907. NULL,
  153908. _vp_tonemask_adj_11,
  153909. _psy_noiseguards_8,
  153910. _psy_noisebias_11,
  153911. _psy_noisebias_11,
  153912. NULL,
  153913. NULL,
  153914. _psy_noise_suppress,
  153915. _psy_compand_8,
  153916. _psy_compand_8_mapping,
  153917. NULL,
  153918. {_noise_start_8,_noise_start_8},
  153919. {_noise_part_8,_noise_part_8},
  153920. _noise_thresh_11,
  153921. _psy_ath_floater_8,
  153922. _psy_ath_abs_8,
  153923. _psy_lowpass_11,
  153924. _psy_global_44,
  153925. _global_mapping_8,
  153926. _psy_stereo_modes_8,
  153927. _floor_books,
  153928. _floor,
  153929. _floor_mapping_11,
  153930. NULL,
  153931. _mapres_template_8_uncoupled
  153932. };
  153933. /*** End of inlined file: setup_11.h ***/
  153934. /*** Start of inlined file: setup_16.h ***/
  153935. /*** Start of inlined file: psych_16.h ***/
  153936. /* stereo mode by base quality level */
  153937. static adj_stereo _psy_stereo_modes_16[4]={
  153938. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153939. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153940. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153941. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153942. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153943. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153944. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153945. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153946. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153947. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153948. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153949. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153950. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153951. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153952. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153953. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153954. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153955. };
  153956. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153957. static att3 _psy_tone_masteratt_16[4]={
  153958. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153959. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153960. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153961. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153962. };
  153963. static vp_adjblock _vp_tonemask_adj_16[4]={
  153964. /* adjust for mode zero */
  153965. /* 63 125 250 500 1 2 4 8 16 */
  153966. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153967. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153968. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153969. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153970. };
  153971. static noise3 _psy_noisebias_16_short[4]={
  153972. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153973. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153974. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153975. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153976. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153977. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153978. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153979. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153980. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153981. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153982. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153983. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153984. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153985. };
  153986. static noise3 _psy_noisebias_16_impulse[4]={
  153987. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153988. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153989. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153990. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153991. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153992. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153993. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153994. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153995. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153996. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153997. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153998. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153999. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154000. };
  154001. static noise3 _psy_noisebias_16[4]={
  154002. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154003. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154004. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154005. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154006. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154007. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154008. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154009. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154010. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154011. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154012. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154013. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154014. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154015. };
  154016. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154017. static int _noise_start_16[3]={ 256,256,9999 };
  154018. static int _noise_part_16[4]={ 8,8,8,8 };
  154019. static int _psy_ath_floater_16[4]={
  154020. -100,-100,-100,-105,
  154021. };
  154022. static int _psy_ath_abs_16[4]={
  154023. -130,-130,-130,-140,
  154024. };
  154025. /*** End of inlined file: psych_16.h ***/
  154026. /*** Start of inlined file: residue_16.h ***/
  154027. /***** residue backends *********************************************/
  154028. static static_bookblock _resbook_16s_0={
  154029. {
  154030. {0},
  154031. {0,0,&_16c0_s_p1_0},
  154032. {0,0,&_16c0_s_p2_0},
  154033. {0,0,&_16c0_s_p3_0},
  154034. {0,0,&_16c0_s_p4_0},
  154035. {0,0,&_16c0_s_p5_0},
  154036. {0,0,&_16c0_s_p6_0},
  154037. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154038. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154039. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154040. }
  154041. };
  154042. static static_bookblock _resbook_16s_1={
  154043. {
  154044. {0},
  154045. {0,0,&_16c1_s_p1_0},
  154046. {0,0,&_16c1_s_p2_0},
  154047. {0,0,&_16c1_s_p3_0},
  154048. {0,0,&_16c1_s_p4_0},
  154049. {0,0,&_16c1_s_p5_0},
  154050. {0,0,&_16c1_s_p6_0},
  154051. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154052. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154053. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154054. }
  154055. };
  154056. static static_bookblock _resbook_16s_2={
  154057. {
  154058. {0},
  154059. {0,0,&_16c2_s_p1_0},
  154060. {0,0,&_16c2_s_p2_0},
  154061. {0,0,&_16c2_s_p3_0},
  154062. {0,0,&_16c2_s_p4_0},
  154063. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154064. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154065. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154066. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154067. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154068. }
  154069. };
  154070. static vorbis_residue_template _res_16s_0[]={
  154071. {2,0, &_residue_44_mid,
  154072. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154073. &_resbook_16s_0,&_resbook_16s_0},
  154074. };
  154075. static vorbis_residue_template _res_16s_1[]={
  154076. {2,0, &_residue_44_mid,
  154077. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154078. &_resbook_16s_1,&_resbook_16s_1},
  154079. {2,0, &_residue_44_mid,
  154080. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154081. &_resbook_16s_1,&_resbook_16s_1}
  154082. };
  154083. static vorbis_residue_template _res_16s_2[]={
  154084. {2,0, &_residue_44_high,
  154085. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154086. &_resbook_16s_2,&_resbook_16s_2},
  154087. {2,0, &_residue_44_high,
  154088. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154089. &_resbook_16s_2,&_resbook_16s_2}
  154090. };
  154091. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154092. { _map_nominal, _res_16s_0 }, /* 0 */
  154093. { _map_nominal, _res_16s_1 }, /* 1 */
  154094. { _map_nominal, _res_16s_2 }, /* 2 */
  154095. };
  154096. static static_bookblock _resbook_16u_0={
  154097. {
  154098. {0},
  154099. {0,0,&_16u0__p1_0},
  154100. {0,0,&_16u0__p2_0},
  154101. {0,0,&_16u0__p3_0},
  154102. {0,0,&_16u0__p4_0},
  154103. {0,0,&_16u0__p5_0},
  154104. {&_16u0__p6_0,&_16u0__p6_1},
  154105. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154106. }
  154107. };
  154108. static static_bookblock _resbook_16u_1={
  154109. {
  154110. {0},
  154111. {0,0,&_16u1__p1_0},
  154112. {0,0,&_16u1__p2_0},
  154113. {0,0,&_16u1__p3_0},
  154114. {0,0,&_16u1__p4_0},
  154115. {0,0,&_16u1__p5_0},
  154116. {0,0,&_16u1__p6_0},
  154117. {&_16u1__p7_0,&_16u1__p7_1},
  154118. {&_16u1__p8_0,&_16u1__p8_1},
  154119. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154120. }
  154121. };
  154122. static static_bookblock _resbook_16u_2={
  154123. {
  154124. {0},
  154125. {0,0,&_16u2_p1_0},
  154126. {0,0,&_16u2_p2_0},
  154127. {0,0,&_16u2_p3_0},
  154128. {0,0,&_16u2_p4_0},
  154129. {&_16u2_p5_0,&_16u2_p5_1},
  154130. {&_16u2_p6_0,&_16u2_p6_1},
  154131. {&_16u2_p7_0,&_16u2_p7_1},
  154132. {&_16u2_p8_0,&_16u2_p8_1},
  154133. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154134. }
  154135. };
  154136. static vorbis_residue_template _res_16u_0[]={
  154137. {1,0, &_residue_44_low_un,
  154138. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154139. &_resbook_16u_0,&_resbook_16u_0},
  154140. };
  154141. static vorbis_residue_template _res_16u_1[]={
  154142. {1,0, &_residue_44_mid_un,
  154143. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154144. &_resbook_16u_1,&_resbook_16u_1},
  154145. {1,0, &_residue_44_mid_un,
  154146. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154147. &_resbook_16u_1,&_resbook_16u_1}
  154148. };
  154149. static vorbis_residue_template _res_16u_2[]={
  154150. {1,0, &_residue_44_hi_un,
  154151. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154152. &_resbook_16u_2,&_resbook_16u_2},
  154153. {1,0, &_residue_44_hi_un,
  154154. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154155. &_resbook_16u_2,&_resbook_16u_2}
  154156. };
  154157. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154158. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154159. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154160. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154161. };
  154162. /*** End of inlined file: residue_16.h ***/
  154163. static int blocksize_16_short[3]={
  154164. 1024,512,512
  154165. };
  154166. static int blocksize_16_long[3]={
  154167. 1024,1024,1024
  154168. };
  154169. static int _floor_mapping_16_short[3]={
  154170. 9,3,3
  154171. };
  154172. static int _floor_mapping_16[3]={
  154173. 9,9,9
  154174. };
  154175. static double rate_mapping_16[4]={
  154176. 12000.,20000.,44000.,86000.
  154177. };
  154178. static double rate_mapping_16_uncoupled[4]={
  154179. 16000.,28000.,64000.,100000.
  154180. };
  154181. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154182. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154183. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154184. ve_setup_data_template ve_setup_16_stereo={
  154185. 3,
  154186. rate_mapping_16,
  154187. quality_mapping_16,
  154188. 2,
  154189. 15000,
  154190. 19000,
  154191. blocksize_16_short,
  154192. blocksize_16_long,
  154193. _psy_tone_masteratt_16,
  154194. _psy_tone_0dB,
  154195. _psy_tone_suppress,
  154196. _vp_tonemask_adj_16,
  154197. _vp_tonemask_adj_16,
  154198. _vp_tonemask_adj_16,
  154199. _psy_noiseguards_8,
  154200. _psy_noisebias_16_impulse,
  154201. _psy_noisebias_16_short,
  154202. _psy_noisebias_16_short,
  154203. _psy_noisebias_16,
  154204. _psy_noise_suppress,
  154205. _psy_compand_8,
  154206. _psy_compand_16_mapping,
  154207. _psy_compand_16_mapping,
  154208. {_noise_start_16,_noise_start_16},
  154209. { _noise_part_16, _noise_part_16},
  154210. _noise_thresh_16,
  154211. _psy_ath_floater_16,
  154212. _psy_ath_abs_16,
  154213. _psy_lowpass_16,
  154214. _psy_global_44,
  154215. _global_mapping_16,
  154216. _psy_stereo_modes_16,
  154217. _floor_books,
  154218. _floor,
  154219. _floor_mapping_16_short,
  154220. _floor_mapping_16,
  154221. _mapres_template_16_stereo
  154222. };
  154223. ve_setup_data_template ve_setup_16_uncoupled={
  154224. 3,
  154225. rate_mapping_16_uncoupled,
  154226. quality_mapping_16,
  154227. -1,
  154228. 15000,
  154229. 19000,
  154230. blocksize_16_short,
  154231. blocksize_16_long,
  154232. _psy_tone_masteratt_16,
  154233. _psy_tone_0dB,
  154234. _psy_tone_suppress,
  154235. _vp_tonemask_adj_16,
  154236. _vp_tonemask_adj_16,
  154237. _vp_tonemask_adj_16,
  154238. _psy_noiseguards_8,
  154239. _psy_noisebias_16_impulse,
  154240. _psy_noisebias_16_short,
  154241. _psy_noisebias_16_short,
  154242. _psy_noisebias_16,
  154243. _psy_noise_suppress,
  154244. _psy_compand_8,
  154245. _psy_compand_16_mapping,
  154246. _psy_compand_16_mapping,
  154247. {_noise_start_16,_noise_start_16},
  154248. { _noise_part_16, _noise_part_16},
  154249. _noise_thresh_16,
  154250. _psy_ath_floater_16,
  154251. _psy_ath_abs_16,
  154252. _psy_lowpass_16,
  154253. _psy_global_44,
  154254. _global_mapping_16,
  154255. _psy_stereo_modes_16,
  154256. _floor_books,
  154257. _floor,
  154258. _floor_mapping_16_short,
  154259. _floor_mapping_16,
  154260. _mapres_template_16_uncoupled
  154261. };
  154262. /*** End of inlined file: setup_16.h ***/
  154263. /*** Start of inlined file: setup_22.h ***/
  154264. static double rate_mapping_22[4]={
  154265. 15000.,20000.,44000.,86000.
  154266. };
  154267. static double rate_mapping_22_uncoupled[4]={
  154268. 16000.,28000.,50000.,90000.
  154269. };
  154270. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154271. ve_setup_data_template ve_setup_22_stereo={
  154272. 3,
  154273. rate_mapping_22,
  154274. quality_mapping_16,
  154275. 2,
  154276. 19000,
  154277. 26000,
  154278. blocksize_16_short,
  154279. blocksize_16_long,
  154280. _psy_tone_masteratt_16,
  154281. _psy_tone_0dB,
  154282. _psy_tone_suppress,
  154283. _vp_tonemask_adj_16,
  154284. _vp_tonemask_adj_16,
  154285. _vp_tonemask_adj_16,
  154286. _psy_noiseguards_8,
  154287. _psy_noisebias_16_impulse,
  154288. _psy_noisebias_16_short,
  154289. _psy_noisebias_16_short,
  154290. _psy_noisebias_16,
  154291. _psy_noise_suppress,
  154292. _psy_compand_8,
  154293. _psy_compand_8_mapping,
  154294. _psy_compand_8_mapping,
  154295. {_noise_start_16,_noise_start_16},
  154296. { _noise_part_16, _noise_part_16},
  154297. _noise_thresh_16,
  154298. _psy_ath_floater_16,
  154299. _psy_ath_abs_16,
  154300. _psy_lowpass_22,
  154301. _psy_global_44,
  154302. _global_mapping_16,
  154303. _psy_stereo_modes_16,
  154304. _floor_books,
  154305. _floor,
  154306. _floor_mapping_16_short,
  154307. _floor_mapping_16,
  154308. _mapres_template_16_stereo
  154309. };
  154310. ve_setup_data_template ve_setup_22_uncoupled={
  154311. 3,
  154312. rate_mapping_22_uncoupled,
  154313. quality_mapping_16,
  154314. -1,
  154315. 19000,
  154316. 26000,
  154317. blocksize_16_short,
  154318. blocksize_16_long,
  154319. _psy_tone_masteratt_16,
  154320. _psy_tone_0dB,
  154321. _psy_tone_suppress,
  154322. _vp_tonemask_adj_16,
  154323. _vp_tonemask_adj_16,
  154324. _vp_tonemask_adj_16,
  154325. _psy_noiseguards_8,
  154326. _psy_noisebias_16_impulse,
  154327. _psy_noisebias_16_short,
  154328. _psy_noisebias_16_short,
  154329. _psy_noisebias_16,
  154330. _psy_noise_suppress,
  154331. _psy_compand_8,
  154332. _psy_compand_8_mapping,
  154333. _psy_compand_8_mapping,
  154334. {_noise_start_16,_noise_start_16},
  154335. { _noise_part_16, _noise_part_16},
  154336. _noise_thresh_16,
  154337. _psy_ath_floater_16,
  154338. _psy_ath_abs_16,
  154339. _psy_lowpass_22,
  154340. _psy_global_44,
  154341. _global_mapping_16,
  154342. _psy_stereo_modes_16,
  154343. _floor_books,
  154344. _floor,
  154345. _floor_mapping_16_short,
  154346. _floor_mapping_16,
  154347. _mapres_template_16_uncoupled
  154348. };
  154349. /*** End of inlined file: setup_22.h ***/
  154350. /*** Start of inlined file: setup_X.h ***/
  154351. static double rate_mapping_X[12]={
  154352. -1.,-1.,-1.,-1.,-1.,-1.,
  154353. -1.,-1.,-1.,-1.,-1.,-1.
  154354. };
  154355. ve_setup_data_template ve_setup_X_stereo={
  154356. 11,
  154357. rate_mapping_X,
  154358. quality_mapping_44,
  154359. 2,
  154360. 50000,
  154361. 200000,
  154362. blocksize_short_44,
  154363. blocksize_long_44,
  154364. _psy_tone_masteratt_44,
  154365. _psy_tone_0dB,
  154366. _psy_tone_suppress,
  154367. _vp_tonemask_adj_otherblock,
  154368. _vp_tonemask_adj_longblock,
  154369. _vp_tonemask_adj_otherblock,
  154370. _psy_noiseguards_44,
  154371. _psy_noisebias_impulse,
  154372. _psy_noisebias_padding,
  154373. _psy_noisebias_trans,
  154374. _psy_noisebias_long,
  154375. _psy_noise_suppress,
  154376. _psy_compand_44,
  154377. _psy_compand_short_mapping,
  154378. _psy_compand_long_mapping,
  154379. {_noise_start_short_44,_noise_start_long_44},
  154380. {_noise_part_short_44,_noise_part_long_44},
  154381. _noise_thresh_44,
  154382. _psy_ath_floater,
  154383. _psy_ath_abs,
  154384. _psy_lowpass_44,
  154385. _psy_global_44,
  154386. _global_mapping_44,
  154387. _psy_stereo_modes_44,
  154388. _floor_books,
  154389. _floor,
  154390. _floor_short_mapping_44,
  154391. _floor_long_mapping_44,
  154392. _mapres_template_44_stereo
  154393. };
  154394. ve_setup_data_template ve_setup_X_uncoupled={
  154395. 11,
  154396. rate_mapping_X,
  154397. quality_mapping_44,
  154398. -1,
  154399. 50000,
  154400. 200000,
  154401. blocksize_short_44,
  154402. blocksize_long_44,
  154403. _psy_tone_masteratt_44,
  154404. _psy_tone_0dB,
  154405. _psy_tone_suppress,
  154406. _vp_tonemask_adj_otherblock,
  154407. _vp_tonemask_adj_longblock,
  154408. _vp_tonemask_adj_otherblock,
  154409. _psy_noiseguards_44,
  154410. _psy_noisebias_impulse,
  154411. _psy_noisebias_padding,
  154412. _psy_noisebias_trans,
  154413. _psy_noisebias_long,
  154414. _psy_noise_suppress,
  154415. _psy_compand_44,
  154416. _psy_compand_short_mapping,
  154417. _psy_compand_long_mapping,
  154418. {_noise_start_short_44,_noise_start_long_44},
  154419. {_noise_part_short_44,_noise_part_long_44},
  154420. _noise_thresh_44,
  154421. _psy_ath_floater,
  154422. _psy_ath_abs,
  154423. _psy_lowpass_44,
  154424. _psy_global_44,
  154425. _global_mapping_44,
  154426. NULL,
  154427. _floor_books,
  154428. _floor,
  154429. _floor_short_mapping_44,
  154430. _floor_long_mapping_44,
  154431. _mapres_template_44_uncoupled
  154432. };
  154433. ve_setup_data_template ve_setup_XX_stereo={
  154434. 2,
  154435. rate_mapping_X,
  154436. quality_mapping_8,
  154437. 2,
  154438. 0,
  154439. 8000,
  154440. blocksize_8,
  154441. blocksize_8,
  154442. _psy_tone_masteratt_8,
  154443. _psy_tone_0dB,
  154444. _psy_tone_suppress,
  154445. _vp_tonemask_adj_8,
  154446. NULL,
  154447. _vp_tonemask_adj_8,
  154448. _psy_noiseguards_8,
  154449. _psy_noisebias_8,
  154450. _psy_noisebias_8,
  154451. NULL,
  154452. NULL,
  154453. _psy_noise_suppress,
  154454. _psy_compand_8,
  154455. _psy_compand_8_mapping,
  154456. NULL,
  154457. {_noise_start_8,_noise_start_8},
  154458. {_noise_part_8,_noise_part_8},
  154459. _noise_thresh_5only,
  154460. _psy_ath_floater_8,
  154461. _psy_ath_abs_8,
  154462. _psy_lowpass_8,
  154463. _psy_global_44,
  154464. _global_mapping_8,
  154465. _psy_stereo_modes_8,
  154466. _floor_books,
  154467. _floor,
  154468. _floor_mapping_8,
  154469. NULL,
  154470. _mapres_template_8_stereo
  154471. };
  154472. ve_setup_data_template ve_setup_XX_uncoupled={
  154473. 2,
  154474. rate_mapping_X,
  154475. quality_mapping_8,
  154476. -1,
  154477. 0,
  154478. 8000,
  154479. blocksize_8,
  154480. blocksize_8,
  154481. _psy_tone_masteratt_8,
  154482. _psy_tone_0dB,
  154483. _psy_tone_suppress,
  154484. _vp_tonemask_adj_8,
  154485. NULL,
  154486. _vp_tonemask_adj_8,
  154487. _psy_noiseguards_8,
  154488. _psy_noisebias_8,
  154489. _psy_noisebias_8,
  154490. NULL,
  154491. NULL,
  154492. _psy_noise_suppress,
  154493. _psy_compand_8,
  154494. _psy_compand_8_mapping,
  154495. NULL,
  154496. {_noise_start_8,_noise_start_8},
  154497. {_noise_part_8,_noise_part_8},
  154498. _noise_thresh_5only,
  154499. _psy_ath_floater_8,
  154500. _psy_ath_abs_8,
  154501. _psy_lowpass_8,
  154502. _psy_global_44,
  154503. _global_mapping_8,
  154504. _psy_stereo_modes_8,
  154505. _floor_books,
  154506. _floor,
  154507. _floor_mapping_8,
  154508. NULL,
  154509. _mapres_template_8_uncoupled
  154510. };
  154511. /*** End of inlined file: setup_X.h ***/
  154512. static ve_setup_data_template *setup_list[]={
  154513. &ve_setup_44_stereo,
  154514. &ve_setup_44_uncoupled,
  154515. &ve_setup_32_stereo,
  154516. &ve_setup_32_uncoupled,
  154517. &ve_setup_22_stereo,
  154518. &ve_setup_22_uncoupled,
  154519. &ve_setup_16_stereo,
  154520. &ve_setup_16_uncoupled,
  154521. &ve_setup_11_stereo,
  154522. &ve_setup_11_uncoupled,
  154523. &ve_setup_8_stereo,
  154524. &ve_setup_8_uncoupled,
  154525. &ve_setup_X_stereo,
  154526. &ve_setup_X_uncoupled,
  154527. &ve_setup_XX_stereo,
  154528. &ve_setup_XX_uncoupled,
  154529. 0
  154530. };
  154531. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154532. if(vi && vi->codec_setup){
  154533. vi->version=0;
  154534. vi->channels=ch;
  154535. vi->rate=rate;
  154536. return(0);
  154537. }
  154538. return(OV_EINVAL);
  154539. }
  154540. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154541. static_codebook ***books,
  154542. vorbis_info_floor1 *in,
  154543. int *x){
  154544. int i,k,is=s;
  154545. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154546. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154547. memcpy(f,in+x[is],sizeof(*f));
  154548. /* fill in the lowpass field, even if it's temporary */
  154549. f->n=ci->blocksizes[block]>>1;
  154550. /* books */
  154551. {
  154552. int partitions=f->partitions;
  154553. int maxclass=-1;
  154554. int maxbook=-1;
  154555. for(i=0;i<partitions;i++)
  154556. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154557. for(i=0;i<=maxclass;i++){
  154558. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154559. f->class_book[i]+=ci->books;
  154560. for(k=0;k<(1<<f->class_subs[i]);k++){
  154561. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154562. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154563. }
  154564. }
  154565. for(i=0;i<=maxbook;i++)
  154566. ci->book_param[ci->books++]=books[x[is]][i];
  154567. }
  154568. /* for now, we're only using floor 1 */
  154569. ci->floor_type[ci->floors]=1;
  154570. ci->floor_param[ci->floors]=f;
  154571. ci->floors++;
  154572. return;
  154573. }
  154574. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154575. vorbis_info_psy_global *in,
  154576. double *x){
  154577. int i,is=s;
  154578. double ds=s-is;
  154579. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154580. vorbis_info_psy_global *g=&ci->psy_g_param;
  154581. memcpy(g,in+(int)x[is],sizeof(*g));
  154582. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154583. is=(int)ds;
  154584. ds-=is;
  154585. if(ds==0 && is>0){
  154586. is--;
  154587. ds=1.;
  154588. }
  154589. /* interpolate the trigger threshholds */
  154590. for(i=0;i<4;i++){
  154591. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154592. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154593. }
  154594. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154595. return;
  154596. }
  154597. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154598. highlevel_encode_setup *hi,
  154599. adj_stereo *p){
  154600. float s=hi->stereo_point_setting;
  154601. int i,is=s;
  154602. double ds=s-is;
  154603. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154604. vorbis_info_psy_global *g=&ci->psy_g_param;
  154605. if(p){
  154606. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154607. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154608. if(hi->managed){
  154609. /* interpolate the kHz threshholds */
  154610. for(i=0;i<PACKETBLOBS;i++){
  154611. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154612. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154613. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154614. g->coupling_pkHz[i]=kHz;
  154615. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154616. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154617. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154618. }
  154619. }else{
  154620. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154621. for(i=0;i<PACKETBLOBS;i++){
  154622. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154623. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154624. g->coupling_pkHz[i]=kHz;
  154625. }
  154626. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154627. for(i=0;i<PACKETBLOBS;i++){
  154628. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154629. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154630. }
  154631. }
  154632. }else{
  154633. for(i=0;i<PACKETBLOBS;i++){
  154634. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154635. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154636. }
  154637. }
  154638. return;
  154639. }
  154640. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154641. int *nn_start,
  154642. int *nn_partition,
  154643. double *nn_thresh,
  154644. int block){
  154645. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154646. vorbis_info_psy *p=ci->psy_param[block];
  154647. highlevel_encode_setup *hi=&ci->hi;
  154648. int is=s;
  154649. if(block>=ci->psys)
  154650. ci->psys=block+1;
  154651. if(!p){
  154652. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154653. ci->psy_param[block]=p;
  154654. }
  154655. memcpy(p,&_psy_info_template,sizeof(*p));
  154656. p->blockflag=block>>1;
  154657. if(hi->noise_normalize_p){
  154658. p->normal_channel_p=1;
  154659. p->normal_point_p=1;
  154660. p->normal_start=nn_start[is];
  154661. p->normal_partition=nn_partition[is];
  154662. p->normal_thresh=nn_thresh[is];
  154663. }
  154664. return;
  154665. }
  154666. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154667. att3 *att,
  154668. int *max,
  154669. vp_adjblock *in){
  154670. int i,is=s;
  154671. double ds=s-is;
  154672. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154673. vorbis_info_psy *p=ci->psy_param[block];
  154674. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154675. filling the values in here */
  154676. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154677. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154678. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154679. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154680. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154681. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154682. for(i=0;i<P_BANDS;i++)
  154683. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154684. return;
  154685. }
  154686. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154687. compandblock *in, double *x){
  154688. int i,is=s;
  154689. double ds=s-is;
  154690. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154691. vorbis_info_psy *p=ci->psy_param[block];
  154692. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154693. is=(int)ds;
  154694. ds-=is;
  154695. if(ds==0 && is>0){
  154696. is--;
  154697. ds=1.;
  154698. }
  154699. /* interpolate the compander settings */
  154700. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154701. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154702. return;
  154703. }
  154704. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154705. int *suppress){
  154706. int is=s;
  154707. double ds=s-is;
  154708. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154709. vorbis_info_psy *p=ci->psy_param[block];
  154710. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154711. return;
  154712. }
  154713. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154714. int *suppress,
  154715. noise3 *in,
  154716. noiseguard *guard,
  154717. double userbias){
  154718. int i,is=s,j;
  154719. double ds=s-is;
  154720. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154721. vorbis_info_psy *p=ci->psy_param[block];
  154722. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154723. p->noisewindowlomin=guard[block].lo;
  154724. p->noisewindowhimin=guard[block].hi;
  154725. p->noisewindowfixed=guard[block].fixed;
  154726. for(j=0;j<P_NOISECURVES;j++)
  154727. for(i=0;i<P_BANDS;i++)
  154728. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154729. /* impulse blocks may take a user specified bias to boost the
  154730. nominal/high noise encoding depth */
  154731. for(j=0;j<P_NOISECURVES;j++){
  154732. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154733. for(i=0;i<P_BANDS;i++){
  154734. p->noiseoff[j][i]+=userbias;
  154735. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154736. }
  154737. }
  154738. return;
  154739. }
  154740. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154741. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154742. vorbis_info_psy *p=ci->psy_param[block];
  154743. p->ath_adjatt=ci->hi.ath_floating_dB;
  154744. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154745. return;
  154746. }
  154747. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154748. int i;
  154749. for(i=0;i<ci->books;i++)
  154750. if(ci->book_param[i]==book)return(i);
  154751. return(ci->books++);
  154752. }
  154753. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154754. int *shortb,int *longb){
  154755. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154756. int is=s;
  154757. int blockshort=shortb[is];
  154758. int blocklong=longb[is];
  154759. ci->blocksizes[0]=blockshort;
  154760. ci->blocksizes[1]=blocklong;
  154761. }
  154762. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154763. int number, int block,
  154764. vorbis_residue_template *res){
  154765. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154766. int i,n;
  154767. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154768. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154769. memcpy(r,res->res,sizeof(*r));
  154770. if(ci->residues<=number)ci->residues=number+1;
  154771. switch(ci->blocksizes[block]){
  154772. case 64:case 128:case 256:
  154773. r->grouping=16;
  154774. break;
  154775. default:
  154776. r->grouping=32;
  154777. break;
  154778. }
  154779. ci->residue_type[number]=res->res_type;
  154780. /* to be adjusted by lowpass/pointlimit later */
  154781. n=r->end=ci->blocksizes[block]>>1;
  154782. if(res->res_type==2)
  154783. n=r->end*=vi->channels;
  154784. /* fill in all the books */
  154785. {
  154786. int booklist=0,k;
  154787. if(ci->hi.managed){
  154788. for(i=0;i<r->partitions;i++)
  154789. for(k=0;k<3;k++)
  154790. if(res->books_base_managed->books[i][k])
  154791. r->secondstages[i]|=(1<<k);
  154792. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154793. ci->book_param[r->groupbook]=res->book_aux_managed;
  154794. for(i=0;i<r->partitions;i++){
  154795. for(k=0;k<3;k++){
  154796. if(res->books_base_managed->books[i][k]){
  154797. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154798. r->booklist[booklist++]=bookid;
  154799. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154800. }
  154801. }
  154802. }
  154803. }else{
  154804. for(i=0;i<r->partitions;i++)
  154805. for(k=0;k<3;k++)
  154806. if(res->books_base->books[i][k])
  154807. r->secondstages[i]|=(1<<k);
  154808. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154809. ci->book_param[r->groupbook]=res->book_aux;
  154810. for(i=0;i<r->partitions;i++){
  154811. for(k=0;k<3;k++){
  154812. if(res->books_base->books[i][k]){
  154813. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154814. r->booklist[booklist++]=bookid;
  154815. ci->book_param[bookid]=res->books_base->books[i][k];
  154816. }
  154817. }
  154818. }
  154819. }
  154820. }
  154821. /* lowpass setup/pointlimit */
  154822. {
  154823. double freq=ci->hi.lowpass_kHz*1000.;
  154824. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154825. double nyq=vi->rate/2.;
  154826. long blocksize=ci->blocksizes[block]>>1;
  154827. /* lowpass needs to be set in the floor and the residue. */
  154828. if(freq>nyq)freq=nyq;
  154829. /* in the floor, the granularity can be very fine; it doesn't alter
  154830. the encoding structure, only the samples used to fit the floor
  154831. approximation */
  154832. f->n=freq/nyq*blocksize;
  154833. /* this res may by limited by the maximum pointlimit of the mode,
  154834. not the lowpass. the floor is always lowpass limited. */
  154835. if(res->limit_type){
  154836. if(ci->hi.managed)
  154837. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154838. else
  154839. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154840. if(freq>nyq)freq=nyq;
  154841. }
  154842. /* in the residue, we're constrained, physically, by partition
  154843. boundaries. We still lowpass 'wherever', but we have to round up
  154844. here to next boundary, or the vorbis spec will round it *down* to
  154845. previous boundary in encode/decode */
  154846. if(ci->residue_type[block]==2)
  154847. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154848. r->grouping;
  154849. else
  154850. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154851. r->grouping;
  154852. }
  154853. }
  154854. /* we assume two maps in this encoder */
  154855. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154856. vorbis_mapping_template *maps){
  154857. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154858. int i,j,is=s,modes=2;
  154859. vorbis_info_mapping0 *map=maps[is].map;
  154860. vorbis_info_mode *mode=_mode_template;
  154861. vorbis_residue_template *res=maps[is].res;
  154862. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154863. for(i=0;i<modes;i++){
  154864. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154865. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154866. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154867. if(i>=ci->modes)ci->modes=i+1;
  154868. ci->map_type[i]=0;
  154869. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154870. if(i>=ci->maps)ci->maps=i+1;
  154871. for(j=0;j<map[i].submaps;j++)
  154872. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154873. ,res+map[i].residuesubmap[j]);
  154874. }
  154875. }
  154876. static double setting_to_approx_bitrate(vorbis_info *vi){
  154877. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154878. highlevel_encode_setup *hi=&ci->hi;
  154879. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154880. int is=hi->base_setting;
  154881. double ds=hi->base_setting-is;
  154882. int ch=vi->channels;
  154883. double *r=setup->rate_mapping;
  154884. if(r==NULL)
  154885. return(-1);
  154886. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154887. }
  154888. static void get_setup_template(vorbis_info *vi,
  154889. long ch,long srate,
  154890. double req,int q_or_bitrate){
  154891. int i=0,j;
  154892. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154893. highlevel_encode_setup *hi=&ci->hi;
  154894. if(q_or_bitrate)req/=ch;
  154895. while(setup_list[i]){
  154896. if(setup_list[i]->coupling_restriction==-1 ||
  154897. setup_list[i]->coupling_restriction==ch){
  154898. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154899. srate<=setup_list[i]->samplerate_max_restriction){
  154900. int mappings=setup_list[i]->mappings;
  154901. double *map=(q_or_bitrate?
  154902. setup_list[i]->rate_mapping:
  154903. setup_list[i]->quality_mapping);
  154904. /* the template matches. Does the requested quality mode
  154905. fall within this template's modes? */
  154906. if(req<map[0]){++i;continue;}
  154907. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154908. for(j=0;j<mappings;j++)
  154909. if(req>=map[j] && req<map[j+1])break;
  154910. /* an all-points match */
  154911. hi->setup=setup_list[i];
  154912. if(j==mappings)
  154913. hi->base_setting=j-.001;
  154914. else{
  154915. float low=map[j];
  154916. float high=map[j+1];
  154917. float del=(req-low)/(high-low);
  154918. hi->base_setting=j+del;
  154919. }
  154920. return;
  154921. }
  154922. }
  154923. i++;
  154924. }
  154925. hi->setup=NULL;
  154926. }
  154927. /* encoders will need to use vorbis_info_init beforehand and call
  154928. vorbis_info clear when all done */
  154929. /* two interfaces; this, more detailed one, and later a convenience
  154930. layer on top */
  154931. /* the final setup call */
  154932. int vorbis_encode_setup_init(vorbis_info *vi){
  154933. int i0=0,singleblock=0;
  154934. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154935. ve_setup_data_template *setup=NULL;
  154936. highlevel_encode_setup *hi=&ci->hi;
  154937. if(ci==NULL)return(OV_EINVAL);
  154938. if(!hi->impulse_block_p)i0=1;
  154939. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154940. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154941. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154942. /* again, bound this to avoid the app shooting itself int he foot
  154943. too badly */
  154944. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154945. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154946. /* get the appropriate setup template; matches the fetch in previous
  154947. stages */
  154948. setup=(ve_setup_data_template *)hi->setup;
  154949. if(setup==NULL)return(OV_EINVAL);
  154950. hi->set_in_stone=1;
  154951. /* choose block sizes from configured sizes as well as paying
  154952. attention to long_block_p and short_block_p. If the configured
  154953. short and long blocks are the same length, we set long_block_p
  154954. and unset short_block_p */
  154955. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154956. setup->blocksize_short,
  154957. setup->blocksize_long);
  154958. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154959. /* floor setup; choose proper floor params. Allocated on the floor
  154960. stack in order; if we alloc only long floor, it's 0 */
  154961. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154962. setup->floor_books,
  154963. setup->floor_params,
  154964. setup->floor_short_mapping);
  154965. if(!singleblock)
  154966. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154967. setup->floor_books,
  154968. setup->floor_params,
  154969. setup->floor_long_mapping);
  154970. /* setup of [mostly] short block detection and stereo*/
  154971. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154972. setup->global_params,
  154973. setup->global_mapping);
  154974. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154975. /* basic psych setup and noise normalization */
  154976. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154977. setup->psy_noise_normal_start[0],
  154978. setup->psy_noise_normal_partition[0],
  154979. setup->psy_noise_normal_thresh,
  154980. 0);
  154981. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154982. setup->psy_noise_normal_start[0],
  154983. setup->psy_noise_normal_partition[0],
  154984. setup->psy_noise_normal_thresh,
  154985. 1);
  154986. if(!singleblock){
  154987. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154988. setup->psy_noise_normal_start[1],
  154989. setup->psy_noise_normal_partition[1],
  154990. setup->psy_noise_normal_thresh,
  154991. 2);
  154992. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154993. setup->psy_noise_normal_start[1],
  154994. setup->psy_noise_normal_partition[1],
  154995. setup->psy_noise_normal_thresh,
  154996. 3);
  154997. }
  154998. /* tone masking setup */
  154999. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155000. setup->psy_tone_masteratt,
  155001. setup->psy_tone_0dB,
  155002. setup->psy_tone_adj_impulse);
  155003. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155004. setup->psy_tone_masteratt,
  155005. setup->psy_tone_0dB,
  155006. setup->psy_tone_adj_other);
  155007. if(!singleblock){
  155008. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155009. setup->psy_tone_masteratt,
  155010. setup->psy_tone_0dB,
  155011. setup->psy_tone_adj_other);
  155012. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155013. setup->psy_tone_masteratt,
  155014. setup->psy_tone_0dB,
  155015. setup->psy_tone_adj_long);
  155016. }
  155017. /* noise companding setup */
  155018. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155019. setup->psy_noise_compand,
  155020. setup->psy_noise_compand_short_mapping);
  155021. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155022. setup->psy_noise_compand,
  155023. setup->psy_noise_compand_short_mapping);
  155024. if(!singleblock){
  155025. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155026. setup->psy_noise_compand,
  155027. setup->psy_noise_compand_long_mapping);
  155028. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155029. setup->psy_noise_compand,
  155030. setup->psy_noise_compand_long_mapping);
  155031. }
  155032. /* peak guarding setup */
  155033. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155034. setup->psy_tone_dBsuppress);
  155035. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155036. setup->psy_tone_dBsuppress);
  155037. if(!singleblock){
  155038. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155039. setup->psy_tone_dBsuppress);
  155040. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155041. setup->psy_tone_dBsuppress);
  155042. }
  155043. /* noise bias setup */
  155044. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155045. setup->psy_noise_dBsuppress,
  155046. setup->psy_noise_bias_impulse,
  155047. setup->psy_noiseguards,
  155048. (i0==0?hi->impulse_noisetune:0.));
  155049. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155050. setup->psy_noise_dBsuppress,
  155051. setup->psy_noise_bias_padding,
  155052. setup->psy_noiseguards,0.);
  155053. if(!singleblock){
  155054. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155055. setup->psy_noise_dBsuppress,
  155056. setup->psy_noise_bias_trans,
  155057. setup->psy_noiseguards,0.);
  155058. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155059. setup->psy_noise_dBsuppress,
  155060. setup->psy_noise_bias_long,
  155061. setup->psy_noiseguards,0.);
  155062. }
  155063. vorbis_encode_ath_setup(vi,0);
  155064. vorbis_encode_ath_setup(vi,1);
  155065. if(!singleblock){
  155066. vorbis_encode_ath_setup(vi,2);
  155067. vorbis_encode_ath_setup(vi,3);
  155068. }
  155069. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155070. /* set bitrate readonlies and management */
  155071. if(hi->bitrate_av>0)
  155072. vi->bitrate_nominal=hi->bitrate_av;
  155073. else{
  155074. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155075. }
  155076. vi->bitrate_lower=hi->bitrate_min;
  155077. vi->bitrate_upper=hi->bitrate_max;
  155078. if(hi->bitrate_av)
  155079. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155080. else
  155081. vi->bitrate_window=0.;
  155082. if(hi->managed){
  155083. ci->bi.avg_rate=hi->bitrate_av;
  155084. ci->bi.min_rate=hi->bitrate_min;
  155085. ci->bi.max_rate=hi->bitrate_max;
  155086. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155087. ci->bi.reservoir_bias=
  155088. hi->bitrate_reservoir_bias;
  155089. ci->bi.slew_damp=hi->bitrate_av_damp;
  155090. }
  155091. return(0);
  155092. }
  155093. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155094. long channels,
  155095. long rate){
  155096. int ret=0,i,is;
  155097. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155098. highlevel_encode_setup *hi=&ci->hi;
  155099. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155100. double ds;
  155101. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155102. if(ret)return(ret);
  155103. is=hi->base_setting;
  155104. ds=hi->base_setting-is;
  155105. hi->short_setting=hi->base_setting;
  155106. hi->long_setting=hi->base_setting;
  155107. hi->managed=0;
  155108. hi->impulse_block_p=1;
  155109. hi->noise_normalize_p=1;
  155110. hi->stereo_point_setting=hi->base_setting;
  155111. hi->lowpass_kHz=
  155112. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155113. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155114. setup->psy_ath_float[is+1]*ds;
  155115. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155116. setup->psy_ath_abs[is+1]*ds;
  155117. hi->amplitude_track_dBpersec=-6.;
  155118. hi->trigger_setting=hi->base_setting;
  155119. for(i=0;i<4;i++){
  155120. hi->block[i].tone_mask_setting=hi->base_setting;
  155121. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155122. hi->block[i].noise_bias_setting=hi->base_setting;
  155123. hi->block[i].noise_compand_setting=hi->base_setting;
  155124. }
  155125. return(ret);
  155126. }
  155127. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155128. long channels,
  155129. long rate,
  155130. float quality){
  155131. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155132. highlevel_encode_setup *hi=&ci->hi;
  155133. quality+=.0000001;
  155134. if(quality>=1.)quality=.9999;
  155135. get_setup_template(vi,channels,rate,quality,0);
  155136. if(!hi->setup)return OV_EIMPL;
  155137. return vorbis_encode_setup_setting(vi,channels,rate);
  155138. }
  155139. int vorbis_encode_init_vbr(vorbis_info *vi,
  155140. long channels,
  155141. long rate,
  155142. float base_quality /* 0. to 1. */
  155143. ){
  155144. int ret=0;
  155145. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155146. if(ret){
  155147. vorbis_info_clear(vi);
  155148. return ret;
  155149. }
  155150. ret=vorbis_encode_setup_init(vi);
  155151. if(ret)
  155152. vorbis_info_clear(vi);
  155153. return(ret);
  155154. }
  155155. int vorbis_encode_setup_managed(vorbis_info *vi,
  155156. long channels,
  155157. long rate,
  155158. long max_bitrate,
  155159. long nominal_bitrate,
  155160. long min_bitrate){
  155161. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155162. highlevel_encode_setup *hi=&ci->hi;
  155163. double tnominal=nominal_bitrate;
  155164. int ret=0;
  155165. if(nominal_bitrate<=0.){
  155166. if(max_bitrate>0.){
  155167. if(min_bitrate>0.)
  155168. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155169. else
  155170. nominal_bitrate=max_bitrate*.875;
  155171. }else{
  155172. if(min_bitrate>0.){
  155173. nominal_bitrate=min_bitrate;
  155174. }else{
  155175. return(OV_EINVAL);
  155176. }
  155177. }
  155178. }
  155179. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155180. if(!hi->setup)return OV_EIMPL;
  155181. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155182. if(ret){
  155183. vorbis_info_clear(vi);
  155184. return ret;
  155185. }
  155186. /* initialize management with sane defaults */
  155187. hi->managed=1;
  155188. hi->bitrate_min=min_bitrate;
  155189. hi->bitrate_max=max_bitrate;
  155190. hi->bitrate_av=tnominal;
  155191. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155192. hi->bitrate_reservoir=nominal_bitrate*2;
  155193. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155194. return(ret);
  155195. }
  155196. int vorbis_encode_init(vorbis_info *vi,
  155197. long channels,
  155198. long rate,
  155199. long max_bitrate,
  155200. long nominal_bitrate,
  155201. long min_bitrate){
  155202. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155203. max_bitrate,
  155204. nominal_bitrate,
  155205. min_bitrate);
  155206. if(ret){
  155207. vorbis_info_clear(vi);
  155208. return(ret);
  155209. }
  155210. ret=vorbis_encode_setup_init(vi);
  155211. if(ret)
  155212. vorbis_info_clear(vi);
  155213. return(ret);
  155214. }
  155215. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155216. if(vi){
  155217. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155218. highlevel_encode_setup *hi=&ci->hi;
  155219. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155220. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155221. switch(number){
  155222. /* now deprecated *****************/
  155223. case OV_ECTL_RATEMANAGE_GET:
  155224. {
  155225. struct ovectl_ratemanage_arg *ai=
  155226. (struct ovectl_ratemanage_arg *)arg;
  155227. ai->management_active=hi->managed;
  155228. ai->bitrate_hard_window=ai->bitrate_av_window=
  155229. (double)hi->bitrate_reservoir/vi->rate;
  155230. ai->bitrate_av_window_center=1.;
  155231. ai->bitrate_hard_min=hi->bitrate_min;
  155232. ai->bitrate_hard_max=hi->bitrate_max;
  155233. ai->bitrate_av_lo=hi->bitrate_av;
  155234. ai->bitrate_av_hi=hi->bitrate_av;
  155235. }
  155236. return(0);
  155237. /* now deprecated *****************/
  155238. case OV_ECTL_RATEMANAGE_SET:
  155239. {
  155240. struct ovectl_ratemanage_arg *ai=
  155241. (struct ovectl_ratemanage_arg *)arg;
  155242. if(ai==NULL){
  155243. hi->managed=0;
  155244. }else{
  155245. hi->managed=ai->management_active;
  155246. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155247. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155248. }
  155249. }
  155250. return 0;
  155251. /* now deprecated *****************/
  155252. case OV_ECTL_RATEMANAGE_AVG:
  155253. {
  155254. struct ovectl_ratemanage_arg *ai=
  155255. (struct ovectl_ratemanage_arg *)arg;
  155256. if(ai==NULL){
  155257. hi->bitrate_av=0;
  155258. }else{
  155259. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155260. }
  155261. }
  155262. return(0);
  155263. /* now deprecated *****************/
  155264. case OV_ECTL_RATEMANAGE_HARD:
  155265. {
  155266. struct ovectl_ratemanage_arg *ai=
  155267. (struct ovectl_ratemanage_arg *)arg;
  155268. if(ai==NULL){
  155269. hi->bitrate_min=0;
  155270. hi->bitrate_max=0;
  155271. }else{
  155272. hi->bitrate_min=ai->bitrate_hard_min;
  155273. hi->bitrate_max=ai->bitrate_hard_max;
  155274. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155275. (hi->bitrate_max+hi->bitrate_min)*.5;
  155276. }
  155277. if(hi->bitrate_reservoir<128.)
  155278. hi->bitrate_reservoir=128.;
  155279. }
  155280. return(0);
  155281. /* replacement ratemanage interface */
  155282. case OV_ECTL_RATEMANAGE2_GET:
  155283. {
  155284. struct ovectl_ratemanage2_arg *ai=
  155285. (struct ovectl_ratemanage2_arg *)arg;
  155286. if(ai==NULL)return OV_EINVAL;
  155287. ai->management_active=hi->managed;
  155288. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155289. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155290. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155291. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155292. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155293. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155294. }
  155295. return (0);
  155296. case OV_ECTL_RATEMANAGE2_SET:
  155297. {
  155298. struct ovectl_ratemanage2_arg *ai=
  155299. (struct ovectl_ratemanage2_arg *)arg;
  155300. if(ai==NULL){
  155301. hi->managed=0;
  155302. }else{
  155303. /* sanity check; only catch invariant violations */
  155304. if(ai->bitrate_limit_min_kbps>0 &&
  155305. ai->bitrate_average_kbps>0 &&
  155306. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155307. return OV_EINVAL;
  155308. if(ai->bitrate_limit_max_kbps>0 &&
  155309. ai->bitrate_average_kbps>0 &&
  155310. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155311. return OV_EINVAL;
  155312. if(ai->bitrate_limit_min_kbps>0 &&
  155313. ai->bitrate_limit_max_kbps>0 &&
  155314. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155315. return OV_EINVAL;
  155316. if(ai->bitrate_average_damping <= 0.)
  155317. return OV_EINVAL;
  155318. if(ai->bitrate_limit_reservoir_bits < 0)
  155319. return OV_EINVAL;
  155320. if(ai->bitrate_limit_reservoir_bias < 0.)
  155321. return OV_EINVAL;
  155322. if(ai->bitrate_limit_reservoir_bias > 1.)
  155323. return OV_EINVAL;
  155324. hi->managed=ai->management_active;
  155325. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155326. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155327. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155328. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155329. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155330. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155331. }
  155332. }
  155333. return 0;
  155334. case OV_ECTL_LOWPASS_GET:
  155335. {
  155336. double *farg=(double *)arg;
  155337. *farg=hi->lowpass_kHz;
  155338. }
  155339. return(0);
  155340. case OV_ECTL_LOWPASS_SET:
  155341. {
  155342. double *farg=(double *)arg;
  155343. hi->lowpass_kHz=*farg;
  155344. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155345. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155346. }
  155347. return(0);
  155348. case OV_ECTL_IBLOCK_GET:
  155349. {
  155350. double *farg=(double *)arg;
  155351. *farg=hi->impulse_noisetune;
  155352. }
  155353. return(0);
  155354. case OV_ECTL_IBLOCK_SET:
  155355. {
  155356. double *farg=(double *)arg;
  155357. hi->impulse_noisetune=*farg;
  155358. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155359. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155360. }
  155361. return(0);
  155362. }
  155363. return(OV_EIMPL);
  155364. }
  155365. return(OV_EINVAL);
  155366. }
  155367. #endif
  155368. /*** End of inlined file: vorbisenc.c ***/
  155369. /*** Start of inlined file: vorbisfile.c ***/
  155370. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155371. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155372. // tasks..
  155373. #if JUCE_MSVC
  155374. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155375. #endif
  155376. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155377. #if JUCE_USE_OGGVORBIS
  155378. #include <stdlib.h>
  155379. #include <stdio.h>
  155380. #include <errno.h>
  155381. #include <string.h>
  155382. #include <math.h>
  155383. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155384. one logical bitstream arranged end to end (the only form of Ogg
  155385. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155386. multiplexing] is not allowed in Vorbis) */
  155387. /* A Vorbis file can be played beginning to end (streamed) without
  155388. worrying ahead of time about chaining (see decoder_example.c). If
  155389. we have the whole file, however, and want random access
  155390. (seeking/scrubbing) or desire to know the total length/time of a
  155391. file, we need to account for the possibility of chaining. */
  155392. /* We can handle things a number of ways; we can determine the entire
  155393. bitstream structure right off the bat, or find pieces on demand.
  155394. This example determines and caches structure for the entire
  155395. bitstream, but builds a virtual decoder on the fly when moving
  155396. between links in the chain. */
  155397. /* There are also different ways to implement seeking. Enough
  155398. information exists in an Ogg bitstream to seek to
  155399. sample-granularity positions in the output. Or, one can seek by
  155400. picking some portion of the stream roughly in the desired area if
  155401. we only want coarse navigation through the stream. */
  155402. /*************************************************************************
  155403. * Many, many internal helpers. The intention is not to be confusing;
  155404. * rampant duplication and monolithic function implementation would be
  155405. * harder to understand anyway. The high level functions are last. Begin
  155406. * grokking near the end of the file */
  155407. /* read a little more data from the file/pipe into the ogg_sync framer
  155408. */
  155409. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155410. over 8k gets what they deserve */
  155411. static long _get_data(OggVorbis_File *vf){
  155412. errno=0;
  155413. if(vf->datasource){
  155414. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155415. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155416. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155417. if(bytes==0 && errno)return(-1);
  155418. return(bytes);
  155419. }else
  155420. return(0);
  155421. }
  155422. /* save a tiny smidge of verbosity to make the code more readable */
  155423. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155424. if(vf->datasource){
  155425. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155426. vf->offset=offset;
  155427. ogg_sync_reset(&vf->oy);
  155428. }else{
  155429. /* shouldn't happen unless someone writes a broken callback */
  155430. return;
  155431. }
  155432. }
  155433. /* The read/seek functions track absolute position within the stream */
  155434. /* from the head of the stream, get the next page. boundary specifies
  155435. if the function is allowed to fetch more data from the stream (and
  155436. how much) or only use internally buffered data.
  155437. boundary: -1) unbounded search
  155438. 0) read no additional data; use cached only
  155439. n) search for a new page beginning for n bytes
  155440. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155441. n) found a page at absolute offset n */
  155442. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155443. ogg_int64_t boundary){
  155444. if(boundary>0)boundary+=vf->offset;
  155445. while(1){
  155446. long more;
  155447. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155448. more=ogg_sync_pageseek(&vf->oy,og);
  155449. if(more<0){
  155450. /* skipped n bytes */
  155451. vf->offset-=more;
  155452. }else{
  155453. if(more==0){
  155454. /* send more paramedics */
  155455. if(!boundary)return(OV_FALSE);
  155456. {
  155457. long ret=_get_data(vf);
  155458. if(ret==0)return(OV_EOF);
  155459. if(ret<0)return(OV_EREAD);
  155460. }
  155461. }else{
  155462. /* got a page. Return the offset at the page beginning,
  155463. advance the internal offset past the page end */
  155464. ogg_int64_t ret=vf->offset;
  155465. vf->offset+=more;
  155466. return(ret);
  155467. }
  155468. }
  155469. }
  155470. }
  155471. /* find the latest page beginning before the current stream cursor
  155472. position. Much dirtier than the above as Ogg doesn't have any
  155473. backward search linkage. no 'readp' as it will certainly have to
  155474. read. */
  155475. /* returns offset or OV_EREAD, OV_FAULT */
  155476. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155477. ogg_int64_t begin=vf->offset;
  155478. ogg_int64_t end=begin;
  155479. ogg_int64_t ret;
  155480. ogg_int64_t offset=-1;
  155481. while(offset==-1){
  155482. begin-=CHUNKSIZE;
  155483. if(begin<0)
  155484. begin=0;
  155485. _seek_helper(vf,begin);
  155486. while(vf->offset<end){
  155487. ret=_get_next_page(vf,og,end-vf->offset);
  155488. if(ret==OV_EREAD)return(OV_EREAD);
  155489. if(ret<0){
  155490. break;
  155491. }else{
  155492. offset=ret;
  155493. }
  155494. }
  155495. }
  155496. /* we have the offset. Actually snork and hold the page now */
  155497. _seek_helper(vf,offset);
  155498. ret=_get_next_page(vf,og,CHUNKSIZE);
  155499. if(ret<0)
  155500. /* this shouldn't be possible */
  155501. return(OV_EFAULT);
  155502. return(offset);
  155503. }
  155504. /* finds each bitstream link one at a time using a bisection search
  155505. (has to begin by knowing the offset of the lb's initial page).
  155506. Recurses for each link so it can alloc the link storage after
  155507. finding them all, then unroll and fill the cache at the same time */
  155508. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155509. ogg_int64_t begin,
  155510. ogg_int64_t searched,
  155511. ogg_int64_t end,
  155512. long currentno,
  155513. long m){
  155514. ogg_int64_t endsearched=end;
  155515. ogg_int64_t next=end;
  155516. ogg_page og;
  155517. ogg_int64_t ret;
  155518. /* the below guards against garbage seperating the last and
  155519. first pages of two links. */
  155520. while(searched<endsearched){
  155521. ogg_int64_t bisect;
  155522. if(endsearched-searched<CHUNKSIZE){
  155523. bisect=searched;
  155524. }else{
  155525. bisect=(searched+endsearched)/2;
  155526. }
  155527. _seek_helper(vf,bisect);
  155528. ret=_get_next_page(vf,&og,-1);
  155529. if(ret==OV_EREAD)return(OV_EREAD);
  155530. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155531. endsearched=bisect;
  155532. if(ret>=0)next=ret;
  155533. }else{
  155534. searched=ret+og.header_len+og.body_len;
  155535. }
  155536. }
  155537. _seek_helper(vf,next);
  155538. ret=_get_next_page(vf,&og,-1);
  155539. if(ret==OV_EREAD)return(OV_EREAD);
  155540. if(searched>=end || ret<0){
  155541. vf->links=m+1;
  155542. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155543. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155544. vf->offsets[m+1]=searched;
  155545. }else{
  155546. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155547. end,ogg_page_serialno(&og),m+1);
  155548. if(ret==OV_EREAD)return(OV_EREAD);
  155549. }
  155550. vf->offsets[m]=begin;
  155551. vf->serialnos[m]=currentno;
  155552. return(0);
  155553. }
  155554. /* uses the local ogg_stream storage in vf; this is important for
  155555. non-streaming input sources */
  155556. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155557. long *serialno,ogg_page *og_ptr){
  155558. ogg_page og;
  155559. ogg_packet op;
  155560. int i,ret;
  155561. if(!og_ptr){
  155562. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155563. if(llret==OV_EREAD)return(OV_EREAD);
  155564. if(llret<0)return OV_ENOTVORBIS;
  155565. og_ptr=&og;
  155566. }
  155567. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155568. if(serialno)*serialno=vf->os.serialno;
  155569. vf->ready_state=STREAMSET;
  155570. /* extract the initial header from the first page and verify that the
  155571. Ogg bitstream is in fact Vorbis data */
  155572. vorbis_info_init(vi);
  155573. vorbis_comment_init(vc);
  155574. i=0;
  155575. while(i<3){
  155576. ogg_stream_pagein(&vf->os,og_ptr);
  155577. while(i<3){
  155578. int result=ogg_stream_packetout(&vf->os,&op);
  155579. if(result==0)break;
  155580. if(result==-1){
  155581. ret=OV_EBADHEADER;
  155582. goto bail_header;
  155583. }
  155584. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155585. goto bail_header;
  155586. }
  155587. i++;
  155588. }
  155589. if(i<3)
  155590. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155591. ret=OV_EBADHEADER;
  155592. goto bail_header;
  155593. }
  155594. }
  155595. return 0;
  155596. bail_header:
  155597. vorbis_info_clear(vi);
  155598. vorbis_comment_clear(vc);
  155599. vf->ready_state=OPENED;
  155600. return ret;
  155601. }
  155602. /* last step of the OggVorbis_File initialization; get all the
  155603. vorbis_info structs and PCM positions. Only called by the seekable
  155604. initialization (local stream storage is hacked slightly; pay
  155605. attention to how that's done) */
  155606. /* this is void and does not propogate errors up because we want to be
  155607. able to open and use damaged bitstreams as well as we can. Just
  155608. watch out for missing information for links in the OggVorbis_File
  155609. struct */
  155610. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155611. ogg_page og;
  155612. int i;
  155613. ogg_int64_t ret;
  155614. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155615. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155616. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155617. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155618. for(i=0;i<vf->links;i++){
  155619. if(i==0){
  155620. /* we already grabbed the initial header earlier. Just set the offset */
  155621. vf->dataoffsets[i]=dataoffset;
  155622. _seek_helper(vf,dataoffset);
  155623. }else{
  155624. /* seek to the location of the initial header */
  155625. _seek_helper(vf,vf->offsets[i]);
  155626. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155627. vf->dataoffsets[i]=-1;
  155628. }else{
  155629. vf->dataoffsets[i]=vf->offset;
  155630. }
  155631. }
  155632. /* fetch beginning PCM offset */
  155633. if(vf->dataoffsets[i]!=-1){
  155634. ogg_int64_t accumulated=0;
  155635. long lastblock=-1;
  155636. int result;
  155637. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155638. while(1){
  155639. ogg_packet op;
  155640. ret=_get_next_page(vf,&og,-1);
  155641. if(ret<0)
  155642. /* this should not be possible unless the file is
  155643. truncated/mangled */
  155644. break;
  155645. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155646. break;
  155647. /* count blocksizes of all frames in the page */
  155648. ogg_stream_pagein(&vf->os,&og);
  155649. while((result=ogg_stream_packetout(&vf->os,&op))){
  155650. if(result>0){ /* ignore holes */
  155651. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155652. if(lastblock!=-1)
  155653. accumulated+=(lastblock+thisblock)>>2;
  155654. lastblock=thisblock;
  155655. }
  155656. }
  155657. if(ogg_page_granulepos(&og)!=-1){
  155658. /* pcm offset of last packet on the first audio page */
  155659. accumulated= ogg_page_granulepos(&og)-accumulated;
  155660. break;
  155661. }
  155662. }
  155663. /* less than zero? This is a stream with samples trimmed off
  155664. the beginning, a normal occurrence; set the offset to zero */
  155665. if(accumulated<0)accumulated=0;
  155666. vf->pcmlengths[i*2]=accumulated;
  155667. }
  155668. /* get the PCM length of this link. To do this,
  155669. get the last page of the stream */
  155670. {
  155671. ogg_int64_t end=vf->offsets[i+1];
  155672. _seek_helper(vf,end);
  155673. while(1){
  155674. ret=_get_prev_page(vf,&og);
  155675. if(ret<0){
  155676. /* this should not be possible */
  155677. vorbis_info_clear(vf->vi+i);
  155678. vorbis_comment_clear(vf->vc+i);
  155679. break;
  155680. }
  155681. if(ogg_page_granulepos(&og)!=-1){
  155682. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155683. break;
  155684. }
  155685. vf->offset=ret;
  155686. }
  155687. }
  155688. }
  155689. }
  155690. static int _make_decode_ready(OggVorbis_File *vf){
  155691. if(vf->ready_state>STREAMSET)return 0;
  155692. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155693. if(vf->seekable){
  155694. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155695. return OV_EBADLINK;
  155696. }else{
  155697. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155698. return OV_EBADLINK;
  155699. }
  155700. vorbis_block_init(&vf->vd,&vf->vb);
  155701. vf->ready_state=INITSET;
  155702. vf->bittrack=0.f;
  155703. vf->samptrack=0.f;
  155704. return 0;
  155705. }
  155706. static int _open_seekable2(OggVorbis_File *vf){
  155707. long serialno=vf->current_serialno;
  155708. ogg_int64_t dataoffset=vf->offset, end;
  155709. ogg_page og;
  155710. /* we're partially open and have a first link header state in
  155711. storage in vf */
  155712. /* we can seek, so set out learning all about this file */
  155713. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155714. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155715. /* We get the offset for the last page of the physical bitstream.
  155716. Most OggVorbis files will contain a single logical bitstream */
  155717. end=_get_prev_page(vf,&og);
  155718. if(end<0)return(end);
  155719. /* more than one logical bitstream? */
  155720. if(ogg_page_serialno(&og)!=serialno){
  155721. /* Chained bitstream. Bisect-search each logical bitstream
  155722. section. Do so based on serial number only */
  155723. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155724. }else{
  155725. /* Only one logical bitstream */
  155726. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155727. }
  155728. /* the initial header memory is referenced by vf after; don't free it */
  155729. _prefetch_all_headers(vf,dataoffset);
  155730. return(ov_raw_seek(vf,0));
  155731. }
  155732. /* clear out the current logical bitstream decoder */
  155733. static void _decode_clear(OggVorbis_File *vf){
  155734. vorbis_dsp_clear(&vf->vd);
  155735. vorbis_block_clear(&vf->vb);
  155736. vf->ready_state=OPENED;
  155737. }
  155738. /* fetch and process a packet. Handles the case where we're at a
  155739. bitstream boundary and dumps the decoding machine. If the decoding
  155740. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155741. date (seek and read both use this. seek uses a special hack with
  155742. readp).
  155743. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155744. 0) need more data (only if readp==0)
  155745. 1) got a packet
  155746. */
  155747. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155748. ogg_packet *op_in,
  155749. int readp,
  155750. int spanp){
  155751. ogg_page og;
  155752. /* handle one packet. Try to fetch it from current stream state */
  155753. /* extract packets from page */
  155754. while(1){
  155755. /* process a packet if we can. If the machine isn't loaded,
  155756. neither is a page */
  155757. if(vf->ready_state==INITSET){
  155758. while(1) {
  155759. ogg_packet op;
  155760. ogg_packet *op_ptr=(op_in?op_in:&op);
  155761. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155762. ogg_int64_t granulepos;
  155763. op_in=NULL;
  155764. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155765. if(result>0){
  155766. /* got a packet. process it */
  155767. granulepos=op_ptr->granulepos;
  155768. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155769. header handling. The
  155770. header packets aren't
  155771. audio, so if/when we
  155772. submit them,
  155773. vorbis_synthesis will
  155774. reject them */
  155775. /* suck in the synthesis data and track bitrate */
  155776. {
  155777. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155778. /* for proper use of libvorbis within libvorbisfile,
  155779. oldsamples will always be zero. */
  155780. if(oldsamples)return(OV_EFAULT);
  155781. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155782. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155783. vf->bittrack+=op_ptr->bytes*8;
  155784. }
  155785. /* update the pcm offset. */
  155786. if(granulepos!=-1 && !op_ptr->e_o_s){
  155787. int link=(vf->seekable?vf->current_link:0);
  155788. int i,samples;
  155789. /* this packet has a pcm_offset on it (the last packet
  155790. completed on a page carries the offset) After processing
  155791. (above), we know the pcm position of the *last* sample
  155792. ready to be returned. Find the offset of the *first*
  155793. As an aside, this trick is inaccurate if we begin
  155794. reading anew right at the last page; the end-of-stream
  155795. granulepos declares the last frame in the stream, and the
  155796. last packet of the last page may be a partial frame.
  155797. So, we need a previous granulepos from an in-sequence page
  155798. to have a reference point. Thus the !op_ptr->e_o_s clause
  155799. above */
  155800. if(vf->seekable && link>0)
  155801. granulepos-=vf->pcmlengths[link*2];
  155802. if(granulepos<0)granulepos=0; /* actually, this
  155803. shouldn't be possible
  155804. here unless the stream
  155805. is very broken */
  155806. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155807. granulepos-=samples;
  155808. for(i=0;i<link;i++)
  155809. granulepos+=vf->pcmlengths[i*2+1];
  155810. vf->pcm_offset=granulepos;
  155811. }
  155812. return(1);
  155813. }
  155814. }
  155815. else
  155816. break;
  155817. }
  155818. }
  155819. if(vf->ready_state>=OPENED){
  155820. ogg_int64_t ret;
  155821. if(!readp)return(0);
  155822. if((ret=_get_next_page(vf,&og,-1))<0){
  155823. return(OV_EOF); /* eof.
  155824. leave unitialized */
  155825. }
  155826. /* bitrate tracking; add the header's bytes here, the body bytes
  155827. are done by packet above */
  155828. vf->bittrack+=og.header_len*8;
  155829. /* has our decoding just traversed a bitstream boundary? */
  155830. if(vf->ready_state==INITSET){
  155831. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155832. if(!spanp)
  155833. return(OV_EOF);
  155834. _decode_clear(vf);
  155835. if(!vf->seekable){
  155836. vorbis_info_clear(vf->vi);
  155837. vorbis_comment_clear(vf->vc);
  155838. }
  155839. }
  155840. }
  155841. }
  155842. /* Do we need to load a new machine before submitting the page? */
  155843. /* This is different in the seekable and non-seekable cases.
  155844. In the seekable case, we already have all the header
  155845. information loaded and cached; we just initialize the machine
  155846. with it and continue on our merry way.
  155847. In the non-seekable (streaming) case, we'll only be at a
  155848. boundary if we just left the previous logical bitstream and
  155849. we're now nominally at the header of the next bitstream
  155850. */
  155851. if(vf->ready_state!=INITSET){
  155852. int link;
  155853. if(vf->ready_state<STREAMSET){
  155854. if(vf->seekable){
  155855. vf->current_serialno=ogg_page_serialno(&og);
  155856. /* match the serialno to bitstream section. We use this rather than
  155857. offset positions to avoid problems near logical bitstream
  155858. boundaries */
  155859. for(link=0;link<vf->links;link++)
  155860. if(vf->serialnos[link]==vf->current_serialno)break;
  155861. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155862. stream. error out,
  155863. leave machine
  155864. uninitialized */
  155865. vf->current_link=link;
  155866. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155867. vf->ready_state=STREAMSET;
  155868. }else{
  155869. /* we're streaming */
  155870. /* fetch the three header packets, build the info struct */
  155871. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155872. if(ret)return(ret);
  155873. vf->current_link++;
  155874. link=0;
  155875. }
  155876. }
  155877. {
  155878. int ret=_make_decode_ready(vf);
  155879. if(ret<0)return ret;
  155880. }
  155881. }
  155882. ogg_stream_pagein(&vf->os,&og);
  155883. }
  155884. }
  155885. /* if, eg, 64 bit stdio is configured by default, this will build with
  155886. fseek64 */
  155887. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155888. if(f==NULL)return(-1);
  155889. return fseek(f,off,whence);
  155890. }
  155891. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155892. long ibytes, ov_callbacks callbacks){
  155893. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155894. int ret;
  155895. memset(vf,0,sizeof(*vf));
  155896. vf->datasource=f;
  155897. vf->callbacks = callbacks;
  155898. /* init the framing state */
  155899. ogg_sync_init(&vf->oy);
  155900. /* perhaps some data was previously read into a buffer for testing
  155901. against other stream types. Allow initialization from this
  155902. previously read data (as we may be reading from a non-seekable
  155903. stream) */
  155904. if(initial){
  155905. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155906. memcpy(buffer,initial,ibytes);
  155907. ogg_sync_wrote(&vf->oy,ibytes);
  155908. }
  155909. /* can we seek? Stevens suggests the seek test was portable */
  155910. if(offsettest!=-1)vf->seekable=1;
  155911. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155912. entry for partial open */
  155913. vf->links=1;
  155914. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155915. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155916. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155917. /* Try to fetch the headers, maintaining all the storage */
  155918. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155919. vf->datasource=NULL;
  155920. ov_clear(vf);
  155921. }else
  155922. vf->ready_state=PARTOPEN;
  155923. return(ret);
  155924. }
  155925. static int _ov_open2(OggVorbis_File *vf){
  155926. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155927. vf->ready_state=OPENED;
  155928. if(vf->seekable){
  155929. int ret=_open_seekable2(vf);
  155930. if(ret){
  155931. vf->datasource=NULL;
  155932. ov_clear(vf);
  155933. }
  155934. return(ret);
  155935. }else
  155936. vf->ready_state=STREAMSET;
  155937. return 0;
  155938. }
  155939. /* clear out the OggVorbis_File struct */
  155940. int ov_clear(OggVorbis_File *vf){
  155941. if(vf){
  155942. vorbis_block_clear(&vf->vb);
  155943. vorbis_dsp_clear(&vf->vd);
  155944. ogg_stream_clear(&vf->os);
  155945. if(vf->vi && vf->links){
  155946. int i;
  155947. for(i=0;i<vf->links;i++){
  155948. vorbis_info_clear(vf->vi+i);
  155949. vorbis_comment_clear(vf->vc+i);
  155950. }
  155951. _ogg_free(vf->vi);
  155952. _ogg_free(vf->vc);
  155953. }
  155954. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155955. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155956. if(vf->serialnos)_ogg_free(vf->serialnos);
  155957. if(vf->offsets)_ogg_free(vf->offsets);
  155958. ogg_sync_clear(&vf->oy);
  155959. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155960. memset(vf,0,sizeof(*vf));
  155961. }
  155962. #ifdef DEBUG_LEAKS
  155963. _VDBG_dump();
  155964. #endif
  155965. return(0);
  155966. }
  155967. /* inspects the OggVorbis file and finds/documents all the logical
  155968. bitstreams contained in it. Tries to be tolerant of logical
  155969. bitstream sections that are truncated/woogie.
  155970. return: -1) error
  155971. 0) OK
  155972. */
  155973. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155974. ov_callbacks callbacks){
  155975. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155976. if(ret)return ret;
  155977. return _ov_open2(vf);
  155978. }
  155979. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155980. ov_callbacks callbacks = {
  155981. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155982. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155983. (int (*)(void *)) fclose,
  155984. (long (*)(void *)) ftell
  155985. };
  155986. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155987. }
  155988. /* cheap hack for game usage where downsampling is desirable; there's
  155989. no need for SRC as we can just do it cheaply in libvorbis. */
  155990. int ov_halfrate(OggVorbis_File *vf,int flag){
  155991. int i;
  155992. if(vf->vi==NULL)return OV_EINVAL;
  155993. if(!vf->seekable)return OV_EINVAL;
  155994. if(vf->ready_state>=STREAMSET)
  155995. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155996. will be able to swap this on the fly, but
  155997. for now dumping the decode machine is needed
  155998. to reinit the MDCT lookups. 1.1 libvorbis
  155999. is planned to be able to switch on the fly */
  156000. for(i=0;i<vf->links;i++){
  156001. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156002. ov_halfrate(vf,0);
  156003. return OV_EINVAL;
  156004. }
  156005. }
  156006. return 0;
  156007. }
  156008. int ov_halfrate_p(OggVorbis_File *vf){
  156009. if(vf->vi==NULL)return OV_EINVAL;
  156010. return vorbis_synthesis_halfrate_p(vf->vi);
  156011. }
  156012. /* Only partially open the vorbis file; test for Vorbisness, and load
  156013. the headers for the first chain. Do not seek (although test for
  156014. seekability). Use ov_test_open to finish opening the file, else
  156015. ov_clear to close/free it. Same return codes as open. */
  156016. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156017. ov_callbacks callbacks)
  156018. {
  156019. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156020. }
  156021. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156022. ov_callbacks callbacks = {
  156023. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156024. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156025. (int (*)(void *)) fclose,
  156026. (long (*)(void *)) ftell
  156027. };
  156028. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156029. }
  156030. int ov_test_open(OggVorbis_File *vf){
  156031. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156032. return _ov_open2(vf);
  156033. }
  156034. /* How many logical bitstreams in this physical bitstream? */
  156035. long ov_streams(OggVorbis_File *vf){
  156036. return vf->links;
  156037. }
  156038. /* Is the FILE * associated with vf seekable? */
  156039. long ov_seekable(OggVorbis_File *vf){
  156040. return vf->seekable;
  156041. }
  156042. /* returns the bitrate for a given logical bitstream or the entire
  156043. physical bitstream. If the file is open for random access, it will
  156044. find the *actual* average bitrate. If the file is streaming, it
  156045. returns the nominal bitrate (if set) else the average of the
  156046. upper/lower bounds (if set) else -1 (unset).
  156047. If you want the actual bitrate field settings, get them from the
  156048. vorbis_info structs */
  156049. long ov_bitrate(OggVorbis_File *vf,int i){
  156050. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156051. if(i>=vf->links)return(OV_EINVAL);
  156052. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156053. if(i<0){
  156054. ogg_int64_t bits=0;
  156055. int i;
  156056. float br;
  156057. for(i=0;i<vf->links;i++)
  156058. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156059. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156060. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156061. * so this is slightly transformed to make it work.
  156062. */
  156063. br = bits/ov_time_total(vf,-1);
  156064. return(rint(br));
  156065. }else{
  156066. if(vf->seekable){
  156067. /* return the actual bitrate */
  156068. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156069. }else{
  156070. /* return nominal if set */
  156071. if(vf->vi[i].bitrate_nominal>0){
  156072. return vf->vi[i].bitrate_nominal;
  156073. }else{
  156074. if(vf->vi[i].bitrate_upper>0){
  156075. if(vf->vi[i].bitrate_lower>0){
  156076. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156077. }else{
  156078. return vf->vi[i].bitrate_upper;
  156079. }
  156080. }
  156081. return(OV_FALSE);
  156082. }
  156083. }
  156084. }
  156085. }
  156086. /* returns the actual bitrate since last call. returns -1 if no
  156087. additional data to offer since last call (or at beginning of stream),
  156088. EINVAL if stream is only partially open
  156089. */
  156090. long ov_bitrate_instant(OggVorbis_File *vf){
  156091. int link=(vf->seekable?vf->current_link:0);
  156092. long ret;
  156093. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156094. if(vf->samptrack==0)return(OV_FALSE);
  156095. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156096. vf->bittrack=0.f;
  156097. vf->samptrack=0.f;
  156098. return(ret);
  156099. }
  156100. /* Guess */
  156101. long ov_serialnumber(OggVorbis_File *vf,int i){
  156102. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156103. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156104. if(i<0){
  156105. return(vf->current_serialno);
  156106. }else{
  156107. return(vf->serialnos[i]);
  156108. }
  156109. }
  156110. /* returns: total raw (compressed) length of content if i==-1
  156111. raw (compressed) length of that logical bitstream for i==0 to n
  156112. OV_EINVAL if the stream is not seekable (we can't know the length)
  156113. or if stream is only partially open
  156114. */
  156115. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156116. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156117. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156118. if(i<0){
  156119. ogg_int64_t acc=0;
  156120. int i;
  156121. for(i=0;i<vf->links;i++)
  156122. acc+=ov_raw_total(vf,i);
  156123. return(acc);
  156124. }else{
  156125. return(vf->offsets[i+1]-vf->offsets[i]);
  156126. }
  156127. }
  156128. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156129. (samples) of that logical bitstream for i==0 to n
  156130. OV_EINVAL if the stream is not seekable (we can't know the
  156131. length) or only partially open
  156132. */
  156133. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156134. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156135. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156136. if(i<0){
  156137. ogg_int64_t acc=0;
  156138. int i;
  156139. for(i=0;i<vf->links;i++)
  156140. acc+=ov_pcm_total(vf,i);
  156141. return(acc);
  156142. }else{
  156143. return(vf->pcmlengths[i*2+1]);
  156144. }
  156145. }
  156146. /* returns: total seconds of content if i==-1
  156147. seconds in that logical bitstream for i==0 to n
  156148. OV_EINVAL if the stream is not seekable (we can't know the
  156149. length) or only partially open
  156150. */
  156151. double ov_time_total(OggVorbis_File *vf,int i){
  156152. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156153. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156154. if(i<0){
  156155. double acc=0;
  156156. int i;
  156157. for(i=0;i<vf->links;i++)
  156158. acc+=ov_time_total(vf,i);
  156159. return(acc);
  156160. }else{
  156161. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156162. }
  156163. }
  156164. /* seek to an offset relative to the *compressed* data. This also
  156165. scans packets to update the PCM cursor. It will cross a logical
  156166. bitstream boundary, but only if it can't get any packets out of the
  156167. tail of the bitstream we seek to (so no surprises).
  156168. returns zero on success, nonzero on failure */
  156169. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156170. ogg_stream_state work_os;
  156171. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156172. if(!vf->seekable)
  156173. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156174. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156175. /* don't yet clear out decoding machine (if it's initialized), in
  156176. the case we're in the same link. Restart the decode lapping, and
  156177. let _fetch_and_process_packet deal with a potential bitstream
  156178. boundary */
  156179. vf->pcm_offset=-1;
  156180. ogg_stream_reset_serialno(&vf->os,
  156181. vf->current_serialno); /* must set serialno */
  156182. vorbis_synthesis_restart(&vf->vd);
  156183. _seek_helper(vf,pos);
  156184. /* we need to make sure the pcm_offset is set, but we don't want to
  156185. advance the raw cursor past good packets just to get to the first
  156186. with a granulepos. That's not equivalent behavior to beginning
  156187. decoding as immediately after the seek position as possible.
  156188. So, a hack. We use two stream states; a local scratch state and
  156189. the shared vf->os stream state. We use the local state to
  156190. scan, and the shared state as a buffer for later decode.
  156191. Unfortuantely, on the last page we still advance to last packet
  156192. because the granulepos on the last page is not necessarily on a
  156193. packet boundary, and we need to make sure the granpos is
  156194. correct.
  156195. */
  156196. {
  156197. ogg_page og;
  156198. ogg_packet op;
  156199. int lastblock=0;
  156200. int accblock=0;
  156201. int thisblock;
  156202. int eosflag;
  156203. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156204. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156205. return from not necessarily
  156206. starting from the beginning */
  156207. while(1){
  156208. if(vf->ready_state>=STREAMSET){
  156209. /* snarf/scan a packet if we can */
  156210. int result=ogg_stream_packetout(&work_os,&op);
  156211. if(result>0){
  156212. if(vf->vi[vf->current_link].codec_setup){
  156213. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156214. if(thisblock<0){
  156215. ogg_stream_packetout(&vf->os,NULL);
  156216. thisblock=0;
  156217. }else{
  156218. if(eosflag)
  156219. ogg_stream_packetout(&vf->os,NULL);
  156220. else
  156221. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156222. }
  156223. if(op.granulepos!=-1){
  156224. int i,link=vf->current_link;
  156225. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156226. if(granulepos<0)granulepos=0;
  156227. for(i=0;i<link;i++)
  156228. granulepos+=vf->pcmlengths[i*2+1];
  156229. vf->pcm_offset=granulepos-accblock;
  156230. break;
  156231. }
  156232. lastblock=thisblock;
  156233. continue;
  156234. }else
  156235. ogg_stream_packetout(&vf->os,NULL);
  156236. }
  156237. }
  156238. if(!lastblock){
  156239. if(_get_next_page(vf,&og,-1)<0){
  156240. vf->pcm_offset=ov_pcm_total(vf,-1);
  156241. break;
  156242. }
  156243. }else{
  156244. /* huh? Bogus stream with packets but no granulepos */
  156245. vf->pcm_offset=-1;
  156246. break;
  156247. }
  156248. /* has our decoding just traversed a bitstream boundary? */
  156249. if(vf->ready_state>=STREAMSET)
  156250. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156251. _decode_clear(vf); /* clear out stream state */
  156252. ogg_stream_clear(&work_os);
  156253. }
  156254. if(vf->ready_state<STREAMSET){
  156255. int link;
  156256. vf->current_serialno=ogg_page_serialno(&og);
  156257. for(link=0;link<vf->links;link++)
  156258. if(vf->serialnos[link]==vf->current_serialno)break;
  156259. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156260. error out, leave
  156261. machine uninitialized */
  156262. vf->current_link=link;
  156263. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156264. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156265. vf->ready_state=STREAMSET;
  156266. }
  156267. ogg_stream_pagein(&vf->os,&og);
  156268. ogg_stream_pagein(&work_os,&og);
  156269. eosflag=ogg_page_eos(&og);
  156270. }
  156271. }
  156272. ogg_stream_clear(&work_os);
  156273. vf->bittrack=0.f;
  156274. vf->samptrack=0.f;
  156275. return(0);
  156276. seek_error:
  156277. /* dump the machine so we're in a known state */
  156278. vf->pcm_offset=-1;
  156279. ogg_stream_clear(&work_os);
  156280. _decode_clear(vf);
  156281. return OV_EBADLINK;
  156282. }
  156283. /* Page granularity seek (faster than sample granularity because we
  156284. don't do the last bit of decode to find a specific sample).
  156285. Seek to the last [granule marked] page preceeding the specified pos
  156286. location, such that decoding past the returned point will quickly
  156287. arrive at the requested position. */
  156288. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156289. int link=-1;
  156290. ogg_int64_t result=0;
  156291. ogg_int64_t total=ov_pcm_total(vf,-1);
  156292. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156293. if(!vf->seekable)return(OV_ENOSEEK);
  156294. if(pos<0 || pos>total)return(OV_EINVAL);
  156295. /* which bitstream section does this pcm offset occur in? */
  156296. for(link=vf->links-1;link>=0;link--){
  156297. total-=vf->pcmlengths[link*2+1];
  156298. if(pos>=total)break;
  156299. }
  156300. /* search within the logical bitstream for the page with the highest
  156301. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156302. missing pages or incorrect frame number information in the
  156303. bitstream could make our task impossible. Account for that (it
  156304. would be an error condition) */
  156305. /* new search algorithm by HB (Nicholas Vinen) */
  156306. {
  156307. ogg_int64_t end=vf->offsets[link+1];
  156308. ogg_int64_t begin=vf->offsets[link];
  156309. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156310. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156311. ogg_int64_t target=pos-total+begintime;
  156312. ogg_int64_t best=begin;
  156313. ogg_page og;
  156314. while(begin<end){
  156315. ogg_int64_t bisect;
  156316. if(end-begin<CHUNKSIZE){
  156317. bisect=begin;
  156318. }else{
  156319. /* take a (pretty decent) guess. */
  156320. bisect=begin +
  156321. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156322. if(bisect<=begin)
  156323. bisect=begin+1;
  156324. }
  156325. _seek_helper(vf,bisect);
  156326. while(begin<end){
  156327. result=_get_next_page(vf,&og,end-vf->offset);
  156328. if(result==OV_EREAD) goto seek_error;
  156329. if(result<0){
  156330. if(bisect<=begin+1)
  156331. end=begin; /* found it */
  156332. else{
  156333. if(bisect==0) goto seek_error;
  156334. bisect-=CHUNKSIZE;
  156335. if(bisect<=begin)bisect=begin+1;
  156336. _seek_helper(vf,bisect);
  156337. }
  156338. }else{
  156339. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156340. if(granulepos==-1)continue;
  156341. if(granulepos<target){
  156342. best=result; /* raw offset of packet with granulepos */
  156343. begin=vf->offset; /* raw offset of next page */
  156344. begintime=granulepos;
  156345. if(target-begintime>44100)break;
  156346. bisect=begin; /* *not* begin + 1 */
  156347. }else{
  156348. if(bisect<=begin+1)
  156349. end=begin; /* found it */
  156350. else{
  156351. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156352. end=result;
  156353. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156354. if(bisect<=begin)bisect=begin+1;
  156355. _seek_helper(vf,bisect);
  156356. }else{
  156357. end=result;
  156358. endtime=granulepos;
  156359. break;
  156360. }
  156361. }
  156362. }
  156363. }
  156364. }
  156365. }
  156366. /* found our page. seek to it, update pcm offset. Easier case than
  156367. raw_seek, don't keep packets preceeding granulepos. */
  156368. {
  156369. ogg_page og;
  156370. ogg_packet op;
  156371. /* seek */
  156372. _seek_helper(vf,best);
  156373. vf->pcm_offset=-1;
  156374. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156375. if(link!=vf->current_link){
  156376. /* Different link; dump entire decode machine */
  156377. _decode_clear(vf);
  156378. vf->current_link=link;
  156379. vf->current_serialno=ogg_page_serialno(&og);
  156380. vf->ready_state=STREAMSET;
  156381. }else{
  156382. vorbis_synthesis_restart(&vf->vd);
  156383. }
  156384. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156385. ogg_stream_pagein(&vf->os,&og);
  156386. /* pull out all but last packet; the one with granulepos */
  156387. while(1){
  156388. result=ogg_stream_packetpeek(&vf->os,&op);
  156389. if(result==0){
  156390. /* !!! the packet finishing this page originated on a
  156391. preceeding page. Keep fetching previous pages until we
  156392. get one with a granulepos or without the 'continued' flag
  156393. set. Then just use raw_seek for simplicity. */
  156394. _seek_helper(vf,best);
  156395. while(1){
  156396. result=_get_prev_page(vf,&og);
  156397. if(result<0) goto seek_error;
  156398. if(ogg_page_granulepos(&og)>-1 ||
  156399. !ogg_page_continued(&og)){
  156400. return ov_raw_seek(vf,result);
  156401. }
  156402. vf->offset=result;
  156403. }
  156404. }
  156405. if(result<0){
  156406. result = OV_EBADPACKET;
  156407. goto seek_error;
  156408. }
  156409. if(op.granulepos!=-1){
  156410. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156411. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156412. vf->pcm_offset+=total;
  156413. break;
  156414. }else
  156415. result=ogg_stream_packetout(&vf->os,NULL);
  156416. }
  156417. }
  156418. }
  156419. /* verify result */
  156420. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156421. result=OV_EFAULT;
  156422. goto seek_error;
  156423. }
  156424. vf->bittrack=0.f;
  156425. vf->samptrack=0.f;
  156426. return(0);
  156427. seek_error:
  156428. /* dump machine so we're in a known state */
  156429. vf->pcm_offset=-1;
  156430. _decode_clear(vf);
  156431. return (int)result;
  156432. }
  156433. /* seek to a sample offset relative to the decompressed pcm stream
  156434. returns zero on success, nonzero on failure */
  156435. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156436. int thisblock,lastblock=0;
  156437. int ret=ov_pcm_seek_page(vf,pos);
  156438. if(ret<0)return(ret);
  156439. if((ret=_make_decode_ready(vf)))return ret;
  156440. /* discard leading packets we don't need for the lapping of the
  156441. position we want; don't decode them */
  156442. while(1){
  156443. ogg_packet op;
  156444. ogg_page og;
  156445. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156446. if(ret>0){
  156447. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156448. if(thisblock<0){
  156449. ogg_stream_packetout(&vf->os,NULL);
  156450. continue; /* non audio packet */
  156451. }
  156452. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156453. if(vf->pcm_offset+((thisblock+
  156454. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156455. /* remove the packet from packet queue and track its granulepos */
  156456. ogg_stream_packetout(&vf->os,NULL);
  156457. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156458. only tracking, no
  156459. pcm_decode */
  156460. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156461. /* end of logical stream case is hard, especially with exact
  156462. length positioning. */
  156463. if(op.granulepos>-1){
  156464. int i;
  156465. /* always believe the stream markers */
  156466. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156467. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156468. for(i=0;i<vf->current_link;i++)
  156469. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156470. }
  156471. lastblock=thisblock;
  156472. }else{
  156473. if(ret<0 && ret!=OV_HOLE)break;
  156474. /* suck in a new page */
  156475. if(_get_next_page(vf,&og,-1)<0)break;
  156476. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156477. if(vf->ready_state<STREAMSET){
  156478. int link;
  156479. vf->current_serialno=ogg_page_serialno(&og);
  156480. for(link=0;link<vf->links;link++)
  156481. if(vf->serialnos[link]==vf->current_serialno)break;
  156482. if(link==vf->links)return(OV_EBADLINK);
  156483. vf->current_link=link;
  156484. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156485. vf->ready_state=STREAMSET;
  156486. ret=_make_decode_ready(vf);
  156487. if(ret)return ret;
  156488. lastblock=0;
  156489. }
  156490. ogg_stream_pagein(&vf->os,&og);
  156491. }
  156492. }
  156493. vf->bittrack=0.f;
  156494. vf->samptrack=0.f;
  156495. /* discard samples until we reach the desired position. Crossing a
  156496. logical bitstream boundary with abandon is OK. */
  156497. while(vf->pcm_offset<pos){
  156498. ogg_int64_t target=pos-vf->pcm_offset;
  156499. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156500. if(samples>target)samples=target;
  156501. vorbis_synthesis_read(&vf->vd,samples);
  156502. vf->pcm_offset+=samples;
  156503. if(samples<target)
  156504. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156505. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156506. }
  156507. return 0;
  156508. }
  156509. /* seek to a playback time relative to the decompressed pcm stream
  156510. returns zero on success, nonzero on failure */
  156511. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156512. /* translate time to PCM position and call ov_pcm_seek */
  156513. int link=-1;
  156514. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156515. double time_total=ov_time_total(vf,-1);
  156516. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156517. if(!vf->seekable)return(OV_ENOSEEK);
  156518. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156519. /* which bitstream section does this time offset occur in? */
  156520. for(link=vf->links-1;link>=0;link--){
  156521. pcm_total-=vf->pcmlengths[link*2+1];
  156522. time_total-=ov_time_total(vf,link);
  156523. if(seconds>=time_total)break;
  156524. }
  156525. /* enough information to convert time offset to pcm offset */
  156526. {
  156527. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156528. return(ov_pcm_seek(vf,target));
  156529. }
  156530. }
  156531. /* page-granularity version of ov_time_seek
  156532. returns zero on success, nonzero on failure */
  156533. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156534. /* translate time to PCM position and call ov_pcm_seek */
  156535. int link=-1;
  156536. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156537. double time_total=ov_time_total(vf,-1);
  156538. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156539. if(!vf->seekable)return(OV_ENOSEEK);
  156540. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156541. /* which bitstream section does this time offset occur in? */
  156542. for(link=vf->links-1;link>=0;link--){
  156543. pcm_total-=vf->pcmlengths[link*2+1];
  156544. time_total-=ov_time_total(vf,link);
  156545. if(seconds>=time_total)break;
  156546. }
  156547. /* enough information to convert time offset to pcm offset */
  156548. {
  156549. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156550. return(ov_pcm_seek_page(vf,target));
  156551. }
  156552. }
  156553. /* tell the current stream offset cursor. Note that seek followed by
  156554. tell will likely not give the set offset due to caching */
  156555. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156556. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156557. return(vf->offset);
  156558. }
  156559. /* return PCM offset (sample) of next PCM sample to be read */
  156560. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156561. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156562. return(vf->pcm_offset);
  156563. }
  156564. /* return time offset (seconds) of next PCM sample to be read */
  156565. double ov_time_tell(OggVorbis_File *vf){
  156566. int link=0;
  156567. ogg_int64_t pcm_total=0;
  156568. double time_total=0.f;
  156569. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156570. if(vf->seekable){
  156571. pcm_total=ov_pcm_total(vf,-1);
  156572. time_total=ov_time_total(vf,-1);
  156573. /* which bitstream section does this time offset occur in? */
  156574. for(link=vf->links-1;link>=0;link--){
  156575. pcm_total-=vf->pcmlengths[link*2+1];
  156576. time_total-=ov_time_total(vf,link);
  156577. if(vf->pcm_offset>=pcm_total)break;
  156578. }
  156579. }
  156580. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156581. }
  156582. /* link: -1) return the vorbis_info struct for the bitstream section
  156583. currently being decoded
  156584. 0-n) to request information for a specific bitstream section
  156585. In the case of a non-seekable bitstream, any call returns the
  156586. current bitstream. NULL in the case that the machine is not
  156587. initialized */
  156588. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156589. if(vf->seekable){
  156590. if(link<0)
  156591. if(vf->ready_state>=STREAMSET)
  156592. return vf->vi+vf->current_link;
  156593. else
  156594. return vf->vi;
  156595. else
  156596. if(link>=vf->links)
  156597. return NULL;
  156598. else
  156599. return vf->vi+link;
  156600. }else{
  156601. return vf->vi;
  156602. }
  156603. }
  156604. /* grr, strong typing, grr, no templates/inheritence, grr */
  156605. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156606. if(vf->seekable){
  156607. if(link<0)
  156608. if(vf->ready_state>=STREAMSET)
  156609. return vf->vc+vf->current_link;
  156610. else
  156611. return vf->vc;
  156612. else
  156613. if(link>=vf->links)
  156614. return NULL;
  156615. else
  156616. return vf->vc+link;
  156617. }else{
  156618. return vf->vc;
  156619. }
  156620. }
  156621. static int host_is_big_endian() {
  156622. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156623. unsigned char *bytewise = (unsigned char *)&pattern;
  156624. if (bytewise[0] == 0xfe) return 1;
  156625. return 0;
  156626. }
  156627. /* up to this point, everything could more or less hide the multiple
  156628. logical bitstream nature of chaining from the toplevel application
  156629. if the toplevel application didn't particularly care. However, at
  156630. the point that we actually read audio back, the multiple-section
  156631. nature must surface: Multiple bitstream sections do not necessarily
  156632. have to have the same number of channels or sampling rate.
  156633. ov_read returns the sequential logical bitstream number currently
  156634. being decoded along with the PCM data in order that the toplevel
  156635. application can take action on channel/sample rate changes. This
  156636. number will be incremented even for streamed (non-seekable) streams
  156637. (for seekable streams, it represents the actual logical bitstream
  156638. index within the physical bitstream. Note that the accessor
  156639. functions above are aware of this dichotomy).
  156640. input values: buffer) a buffer to hold packed PCM data for return
  156641. length) the byte length requested to be placed into buffer
  156642. bigendianp) should the data be packed LSB first (0) or
  156643. MSB first (1)
  156644. word) word size for output. currently 1 (byte) or
  156645. 2 (16 bit short)
  156646. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156647. 0) EOF
  156648. n) number of bytes of PCM actually returned. The
  156649. below works on a packet-by-packet basis, so the
  156650. return length is not related to the 'length' passed
  156651. in, just guaranteed to fit.
  156652. *section) set to the logical bitstream number */
  156653. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156654. int bigendianp,int word,int sgned,int *bitstream){
  156655. int i,j;
  156656. int host_endian = host_is_big_endian();
  156657. float **pcm;
  156658. long samples;
  156659. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156660. while(1){
  156661. if(vf->ready_state==INITSET){
  156662. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156663. if(samples)break;
  156664. }
  156665. /* suck in another packet */
  156666. {
  156667. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156668. if(ret==OV_EOF)
  156669. return(0);
  156670. if(ret<=0)
  156671. return(ret);
  156672. }
  156673. }
  156674. if(samples>0){
  156675. /* yay! proceed to pack data into the byte buffer */
  156676. long channels=ov_info(vf,-1)->channels;
  156677. long bytespersample=word * channels;
  156678. vorbis_fpu_control fpu;
  156679. (void) fpu; // (to avoid a warning about it being unused)
  156680. if(samples>length/bytespersample)samples=length/bytespersample;
  156681. if(samples <= 0)
  156682. return OV_EINVAL;
  156683. /* a tight loop to pack each size */
  156684. {
  156685. int val;
  156686. if(word==1){
  156687. int off=(sgned?0:128);
  156688. vorbis_fpu_setround(&fpu);
  156689. for(j=0;j<samples;j++)
  156690. for(i=0;i<channels;i++){
  156691. val=vorbis_ftoi(pcm[i][j]*128.f);
  156692. if(val>127)val=127;
  156693. else if(val<-128)val=-128;
  156694. *buffer++=val+off;
  156695. }
  156696. vorbis_fpu_restore(fpu);
  156697. }else{
  156698. int off=(sgned?0:32768);
  156699. if(host_endian==bigendianp){
  156700. if(sgned){
  156701. vorbis_fpu_setround(&fpu);
  156702. for(i=0;i<channels;i++) { /* It's faster in this order */
  156703. float *src=pcm[i];
  156704. short *dest=((short *)buffer)+i;
  156705. for(j=0;j<samples;j++) {
  156706. val=vorbis_ftoi(src[j]*32768.f);
  156707. if(val>32767)val=32767;
  156708. else if(val<-32768)val=-32768;
  156709. *dest=val;
  156710. dest+=channels;
  156711. }
  156712. }
  156713. vorbis_fpu_restore(fpu);
  156714. }else{
  156715. vorbis_fpu_setround(&fpu);
  156716. for(i=0;i<channels;i++) {
  156717. float *src=pcm[i];
  156718. short *dest=((short *)buffer)+i;
  156719. for(j=0;j<samples;j++) {
  156720. val=vorbis_ftoi(src[j]*32768.f);
  156721. if(val>32767)val=32767;
  156722. else if(val<-32768)val=-32768;
  156723. *dest=val+off;
  156724. dest+=channels;
  156725. }
  156726. }
  156727. vorbis_fpu_restore(fpu);
  156728. }
  156729. }else if(bigendianp){
  156730. vorbis_fpu_setround(&fpu);
  156731. for(j=0;j<samples;j++)
  156732. for(i=0;i<channels;i++){
  156733. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156734. if(val>32767)val=32767;
  156735. else if(val<-32768)val=-32768;
  156736. val+=off;
  156737. *buffer++=(val>>8);
  156738. *buffer++=(val&0xff);
  156739. }
  156740. vorbis_fpu_restore(fpu);
  156741. }else{
  156742. int val;
  156743. vorbis_fpu_setround(&fpu);
  156744. for(j=0;j<samples;j++)
  156745. for(i=0;i<channels;i++){
  156746. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156747. if(val>32767)val=32767;
  156748. else if(val<-32768)val=-32768;
  156749. val+=off;
  156750. *buffer++=(val&0xff);
  156751. *buffer++=(val>>8);
  156752. }
  156753. vorbis_fpu_restore(fpu);
  156754. }
  156755. }
  156756. }
  156757. vorbis_synthesis_read(&vf->vd,samples);
  156758. vf->pcm_offset+=samples;
  156759. if(bitstream)*bitstream=vf->current_link;
  156760. return(samples*bytespersample);
  156761. }else{
  156762. return(samples);
  156763. }
  156764. }
  156765. /* input values: pcm_channels) a float vector per channel of output
  156766. length) the sample length being read by the app
  156767. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156768. 0) EOF
  156769. n) number of samples of PCM actually returned. The
  156770. below works on a packet-by-packet basis, so the
  156771. return length is not related to the 'length' passed
  156772. in, just guaranteed to fit.
  156773. *section) set to the logical bitstream number */
  156774. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156775. int *bitstream){
  156776. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156777. while(1){
  156778. if(vf->ready_state==INITSET){
  156779. float **pcm;
  156780. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156781. if(samples){
  156782. if(pcm_channels)*pcm_channels=pcm;
  156783. if(samples>length)samples=length;
  156784. vorbis_synthesis_read(&vf->vd,samples);
  156785. vf->pcm_offset+=samples;
  156786. if(bitstream)*bitstream=vf->current_link;
  156787. return samples;
  156788. }
  156789. }
  156790. /* suck in another packet */
  156791. {
  156792. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156793. if(ret==OV_EOF)return(0);
  156794. if(ret<=0)return(ret);
  156795. }
  156796. }
  156797. }
  156798. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156799. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156800. ogg_int64_t off);
  156801. static void _ov_splice(float **pcm,float **lappcm,
  156802. int n1, int n2,
  156803. int ch1, int ch2,
  156804. float *w1, float *w2){
  156805. int i,j;
  156806. float *w=w1;
  156807. int n=n1;
  156808. if(n1>n2){
  156809. n=n2;
  156810. w=w2;
  156811. }
  156812. /* splice */
  156813. for(j=0;j<ch1 && j<ch2;j++){
  156814. float *s=lappcm[j];
  156815. float *d=pcm[j];
  156816. for(i=0;i<n;i++){
  156817. float wd=w[i]*w[i];
  156818. float ws=1.-wd;
  156819. d[i]=d[i]*wd + s[i]*ws;
  156820. }
  156821. }
  156822. /* window from zero */
  156823. for(;j<ch2;j++){
  156824. float *d=pcm[j];
  156825. for(i=0;i<n;i++){
  156826. float wd=w[i]*w[i];
  156827. d[i]=d[i]*wd;
  156828. }
  156829. }
  156830. }
  156831. /* make sure vf is INITSET */
  156832. static int _ov_initset(OggVorbis_File *vf){
  156833. while(1){
  156834. if(vf->ready_state==INITSET)break;
  156835. /* suck in another packet */
  156836. {
  156837. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156838. if(ret<0 && ret!=OV_HOLE)return(ret);
  156839. }
  156840. }
  156841. return 0;
  156842. }
  156843. /* make sure vf is INITSET and that we have a primed buffer; if
  156844. we're crosslapping at a stream section boundary, this also makes
  156845. sure we're sanity checking against the right stream information */
  156846. static int _ov_initprime(OggVorbis_File *vf){
  156847. vorbis_dsp_state *vd=&vf->vd;
  156848. while(1){
  156849. if(vf->ready_state==INITSET)
  156850. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156851. /* suck in another packet */
  156852. {
  156853. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156854. if(ret<0 && ret!=OV_HOLE)return(ret);
  156855. }
  156856. }
  156857. return 0;
  156858. }
  156859. /* grab enough data for lapping from vf; this may be in the form of
  156860. unreturned, already-decoded pcm, remaining PCM we will need to
  156861. decode, or synthetic postextrapolation from last packets. */
  156862. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156863. float **lappcm,int lapsize){
  156864. int lapcount=0,i;
  156865. float **pcm;
  156866. /* try first to decode the lapping data */
  156867. while(lapcount<lapsize){
  156868. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156869. if(samples){
  156870. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156871. for(i=0;i<vi->channels;i++)
  156872. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156873. lapcount+=samples;
  156874. vorbis_synthesis_read(vd,samples);
  156875. }else{
  156876. /* suck in another packet */
  156877. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156878. if(ret==OV_EOF)break;
  156879. }
  156880. }
  156881. if(lapcount<lapsize){
  156882. /* failed to get lapping data from normal decode; pry it from the
  156883. postextrapolation buffering, or the second half of the MDCT
  156884. from the last packet */
  156885. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156886. if(samples==0){
  156887. for(i=0;i<vi->channels;i++)
  156888. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156889. lapcount=lapsize;
  156890. }else{
  156891. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156892. for(i=0;i<vi->channels;i++)
  156893. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156894. lapcount+=samples;
  156895. }
  156896. }
  156897. }
  156898. /* this sets up crosslapping of a sample by using trailing data from
  156899. sample 1 and lapping it into the windowing buffer of sample 2 */
  156900. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156901. vorbis_info *vi1,*vi2;
  156902. float **lappcm;
  156903. float **pcm;
  156904. float *w1,*w2;
  156905. int n1,n2,i,ret,hs1,hs2;
  156906. if(vf1==vf2)return(0); /* degenerate case */
  156907. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156908. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156909. /* the relevant overlap buffers must be pre-checked and pre-primed
  156910. before looking at settings in the event that priming would cross
  156911. a bitstream boundary. So, do it now */
  156912. ret=_ov_initset(vf1);
  156913. if(ret)return(ret);
  156914. ret=_ov_initprime(vf2);
  156915. if(ret)return(ret);
  156916. vi1=ov_info(vf1,-1);
  156917. vi2=ov_info(vf2,-1);
  156918. hs1=ov_halfrate_p(vf1);
  156919. hs2=ov_halfrate_p(vf2);
  156920. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156921. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156922. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156923. w1=vorbis_window(&vf1->vd,0);
  156924. w2=vorbis_window(&vf2->vd,0);
  156925. for(i=0;i<vi1->channels;i++)
  156926. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156927. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156928. /* have a lapping buffer from vf1; now to splice it into the lapping
  156929. buffer of vf2 */
  156930. /* consolidate and expose the buffer. */
  156931. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156932. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156933. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156934. /* splice */
  156935. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156936. /* done */
  156937. return(0);
  156938. }
  156939. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156940. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156941. vorbis_info *vi;
  156942. float **lappcm;
  156943. float **pcm;
  156944. float *w1,*w2;
  156945. int n1,n2,ch1,ch2,hs;
  156946. int i,ret;
  156947. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156948. ret=_ov_initset(vf);
  156949. if(ret)return(ret);
  156950. vi=ov_info(vf,-1);
  156951. hs=ov_halfrate_p(vf);
  156952. ch1=vi->channels;
  156953. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156954. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156955. persistent; even if the decode state
  156956. from this link gets dumped, this
  156957. window array continues to exist */
  156958. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156959. for(i=0;i<ch1;i++)
  156960. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156961. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156962. /* have lapping data; seek and prime the buffer */
  156963. ret=localseek(vf,pos);
  156964. if(ret)return ret;
  156965. ret=_ov_initprime(vf);
  156966. if(ret)return(ret);
  156967. /* Guard against cross-link changes; they're perfectly legal */
  156968. vi=ov_info(vf,-1);
  156969. ch2=vi->channels;
  156970. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156971. w2=vorbis_window(&vf->vd,0);
  156972. /* consolidate and expose the buffer. */
  156973. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156974. /* splice */
  156975. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156976. /* done */
  156977. return(0);
  156978. }
  156979. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156980. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156981. }
  156982. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156983. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156984. }
  156985. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156986. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156987. }
  156988. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156989. int (*localseek)(OggVorbis_File *,double)){
  156990. vorbis_info *vi;
  156991. float **lappcm;
  156992. float **pcm;
  156993. float *w1,*w2;
  156994. int n1,n2,ch1,ch2,hs;
  156995. int i,ret;
  156996. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156997. ret=_ov_initset(vf);
  156998. if(ret)return(ret);
  156999. vi=ov_info(vf,-1);
  157000. hs=ov_halfrate_p(vf);
  157001. ch1=vi->channels;
  157002. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157003. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157004. persistent; even if the decode state
  157005. from this link gets dumped, this
  157006. window array continues to exist */
  157007. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157008. for(i=0;i<ch1;i++)
  157009. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157010. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157011. /* have lapping data; seek and prime the buffer */
  157012. ret=localseek(vf,pos);
  157013. if(ret)return ret;
  157014. ret=_ov_initprime(vf);
  157015. if(ret)return(ret);
  157016. /* Guard against cross-link changes; they're perfectly legal */
  157017. vi=ov_info(vf,-1);
  157018. ch2=vi->channels;
  157019. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157020. w2=vorbis_window(&vf->vd,0);
  157021. /* consolidate and expose the buffer. */
  157022. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157023. /* splice */
  157024. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157025. /* done */
  157026. return(0);
  157027. }
  157028. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157029. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157030. }
  157031. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157032. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157033. }
  157034. #endif
  157035. /*** End of inlined file: vorbisfile.c ***/
  157036. /*** Start of inlined file: window.c ***/
  157037. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157038. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157039. // tasks..
  157040. #if JUCE_MSVC
  157041. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157042. #endif
  157043. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157044. #if JUCE_USE_OGGVORBIS
  157045. #include <stdlib.h>
  157046. #include <math.h>
  157047. static float vwin64[32] = {
  157048. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157049. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157050. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157051. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157052. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157053. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157054. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157055. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157056. };
  157057. static float vwin128[64] = {
  157058. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157059. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157060. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157061. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157062. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157063. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157064. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157065. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157066. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157067. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157068. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157069. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157070. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157071. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157072. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157073. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157074. };
  157075. static float vwin256[128] = {
  157076. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157077. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157078. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157079. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157080. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157081. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157082. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157083. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157084. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157085. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157086. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157087. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157088. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157089. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157090. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157091. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157092. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157093. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157094. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157095. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157096. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157097. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157098. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157099. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157100. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157101. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157102. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157103. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157104. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157105. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157106. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157107. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157108. };
  157109. static float vwin512[256] = {
  157110. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157111. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157112. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157113. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157114. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157115. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157116. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157117. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157118. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157119. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157120. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157121. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157122. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157123. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157124. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157125. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157126. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157127. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157128. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157129. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157130. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157131. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157132. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157133. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157134. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157135. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157136. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157137. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157138. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157139. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157140. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157141. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157142. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157143. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157144. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157145. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157146. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157147. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157148. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157149. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157150. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157151. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157152. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157153. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157154. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157155. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157156. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157157. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157158. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157159. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157160. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157161. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157162. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157163. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157164. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157165. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157166. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157167. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157168. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157169. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157170. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157171. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157172. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157173. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157174. };
  157175. static float vwin1024[512] = {
  157176. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157177. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157178. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157179. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157180. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157181. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157182. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157183. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157184. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157185. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157186. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157187. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157188. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157189. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157190. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157191. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157192. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157193. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157194. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157195. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157196. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157197. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157198. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157199. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157200. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157201. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157202. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157203. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157204. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157205. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157206. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157207. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157208. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157209. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157210. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157211. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157212. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157213. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157214. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157215. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157216. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157217. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157218. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157219. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157220. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157221. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157222. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157223. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157224. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157225. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157226. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157227. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157228. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157229. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157230. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157231. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157232. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157233. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157234. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157235. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157236. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157237. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157238. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157239. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157240. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157241. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157242. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157243. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157244. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157245. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157246. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157247. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157248. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157249. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157250. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157251. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157252. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157253. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157254. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157255. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157256. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157257. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157258. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157259. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157260. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157261. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157262. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157263. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157264. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157265. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157266. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157267. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157268. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157269. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157270. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157271. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157272. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157273. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157274. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157275. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157276. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157277. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157278. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157279. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157280. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157281. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157282. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157283. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157284. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157285. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157286. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157287. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157288. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157289. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157290. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157291. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157292. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157293. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157294. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157295. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157296. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157297. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157298. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157299. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157300. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157301. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157302. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157303. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157304. };
  157305. static float vwin2048[1024] = {
  157306. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157307. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157308. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157309. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157310. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157311. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157312. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157313. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157314. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157315. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157316. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157317. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157318. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157319. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157320. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157321. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157322. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157323. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157324. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157325. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157326. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157327. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157328. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157329. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157330. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157331. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157332. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157333. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157334. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157335. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157336. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157337. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157338. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157339. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157340. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157341. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157342. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157343. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157344. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157345. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157346. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157347. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157348. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157349. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157350. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157351. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157352. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157353. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157354. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157355. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157356. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157357. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157358. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157359. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157360. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157361. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157362. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157363. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157364. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157365. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157366. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157367. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157368. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157369. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157370. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157371. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157372. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157373. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157374. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157375. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157376. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157377. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157378. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157379. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157380. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157381. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157382. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157383. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157384. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157385. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157386. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157387. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157388. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157389. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157390. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157391. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157392. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157393. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157394. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157395. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157396. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157397. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157398. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157399. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157400. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157401. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157402. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157403. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157404. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157405. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157406. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157407. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157408. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157409. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157410. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157411. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157412. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157413. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157414. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157415. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157416. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157417. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157418. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157419. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157420. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157421. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157422. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157423. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157424. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157425. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157426. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157427. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157428. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157429. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157430. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157431. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157432. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157433. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157434. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157435. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157436. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157437. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157438. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157439. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157440. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157441. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157442. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157443. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157444. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157445. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157446. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157447. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157448. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157449. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157450. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157451. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157452. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157453. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157454. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157455. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157456. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157457. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157458. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157459. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157460. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157461. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157462. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157463. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157464. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157465. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157466. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157467. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157468. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157469. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157470. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157471. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157472. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157473. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157474. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157475. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157476. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157477. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157478. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157479. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157480. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157481. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157482. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157483. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157484. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157485. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157486. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157487. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157488. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157489. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157490. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157491. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157492. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157493. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157494. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157495. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157496. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157497. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157498. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157499. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157500. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157501. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157502. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157503. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157504. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157505. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157506. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157507. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157508. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157509. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157510. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157511. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157512. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157513. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157514. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157515. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157516. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157517. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157518. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157519. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157520. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157521. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157522. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157523. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157524. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157525. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157526. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157527. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157528. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157529. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157530. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157531. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157532. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157533. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157534. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157535. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157536. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157537. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157538. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157539. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157540. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157541. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157542. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157543. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157544. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157545. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157546. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157547. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157548. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157549. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157550. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157551. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157552. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157553. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157554. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157555. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157556. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157557. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157558. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157559. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157560. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157561. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157562. };
  157563. static float vwin4096[2048] = {
  157564. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157565. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157566. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157567. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157568. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157569. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157570. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157571. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157572. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157573. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157574. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157575. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157576. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157577. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157578. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157579. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157580. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157581. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157582. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157583. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157584. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157585. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157586. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157587. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157588. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157589. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157590. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157591. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157592. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157593. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157594. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157595. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157596. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157597. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157598. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157599. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157600. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157601. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157602. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157603. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157604. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157605. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157606. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157607. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157608. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157609. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157610. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157611. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157612. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157613. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157614. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157615. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157616. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157617. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157618. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157619. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157620. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157621. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157622. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157623. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157624. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157625. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157626. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157627. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157628. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157629. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157630. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157631. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157632. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157633. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157634. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157635. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157636. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157637. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157638. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157639. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157640. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157641. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157642. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157643. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157644. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157645. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157646. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157647. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157648. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157649. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157650. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157651. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157652. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157653. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157654. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157655. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157656. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157657. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157658. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157659. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157660. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157661. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157662. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157663. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157664. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157665. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157666. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157667. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157668. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157669. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157670. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157671. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157672. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157673. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157674. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157675. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157676. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157677. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157678. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157679. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157680. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157681. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157682. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157683. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157684. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157685. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157686. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157687. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157688. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157689. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157690. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157691. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157692. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157693. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157694. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157695. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157696. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157697. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157698. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157699. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157700. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157701. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157702. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157703. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157704. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157705. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157706. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157707. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157708. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157709. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157710. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157711. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157712. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157713. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157714. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157715. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157716. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157717. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157718. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157719. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157720. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157721. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157722. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157723. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157724. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157725. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157726. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157727. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157728. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157729. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157730. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157731. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157732. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157733. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157734. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157735. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157736. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157737. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157738. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157739. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157740. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157741. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157742. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157743. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157744. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157745. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157746. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157747. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157748. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157749. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157750. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157751. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157752. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157753. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157754. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157755. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157756. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157757. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157758. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157759. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157760. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157761. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157762. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157763. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157764. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157765. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157766. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157767. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157768. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157769. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157770. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157771. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157772. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157773. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157774. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157775. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157776. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157777. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157778. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157779. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157780. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157781. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157782. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157783. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157784. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157785. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157786. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157787. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157788. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157789. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157790. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157791. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157792. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157793. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157794. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157795. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157796. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157797. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157798. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157799. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157800. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157801. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157802. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157803. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157804. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157805. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157806. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157807. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157808. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157809. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157810. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157811. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157812. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157813. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157814. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157815. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157816. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157817. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157818. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157819. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157820. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157821. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157822. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157823. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157824. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157825. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157826. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157827. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157828. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157829. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157830. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157831. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157832. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157833. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157834. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157835. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157836. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157837. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157838. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157839. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157840. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157841. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157842. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157843. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157844. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157845. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157846. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157847. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157848. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157849. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157850. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157851. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157852. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157853. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157854. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157855. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157856. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157857. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157858. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157859. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157860. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157861. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157862. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157863. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157864. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157865. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157866. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157867. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157868. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157869. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157870. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157871. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157872. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157873. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157874. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157875. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157876. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157877. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157878. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157879. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157880. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157881. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157882. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157883. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157884. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157885. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157886. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157887. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157888. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157889. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157890. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157891. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157892. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157893. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157894. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157895. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157896. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157897. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157898. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157899. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157900. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157901. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157902. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157903. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157904. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157905. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157906. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157907. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157908. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157909. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157910. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157911. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157912. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157913. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157914. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157915. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157916. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157917. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157918. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157919. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157920. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157921. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157922. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157923. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157924. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157925. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157926. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157927. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157928. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157929. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157930. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157931. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157932. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157933. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157934. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157935. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157936. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157937. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157938. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157939. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157940. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157941. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157942. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157943. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157944. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157945. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157946. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157947. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157948. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157949. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157950. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157951. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157952. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157953. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157954. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157955. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157956. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157957. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157958. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157959. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157960. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157961. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157962. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157963. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157964. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157965. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157966. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157967. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157968. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157969. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157970. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157971. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157972. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157973. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157974. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157975. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157976. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157977. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157978. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157979. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157980. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157981. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157982. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157983. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157984. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157985. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157986. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157987. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157988. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157989. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157990. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157991. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157992. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157993. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157994. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157995. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157996. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157997. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157998. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157999. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158000. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158001. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158002. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158003. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158004. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158005. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158006. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158007. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158008. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158009. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158010. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158011. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158012. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158013. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158014. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158015. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158016. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158017. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158018. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158019. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158020. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158021. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158022. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158023. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158024. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158025. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158026. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158027. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158028. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158029. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158030. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158031. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158032. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158033. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158034. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158035. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158036. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158037. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158038. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158039. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158040. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158041. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158042. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158043. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158044. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158045. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158046. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158047. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158048. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158049. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158050. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158051. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158052. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158053. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158054. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158055. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158056. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158057. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158058. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158059. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158060. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158061. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158062. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158063. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158064. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158065. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158066. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158067. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158068. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158069. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158070. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158071. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158072. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158073. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158074. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158075. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158076. };
  158077. static float vwin8192[4096] = {
  158078. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158079. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158080. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158081. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158082. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158083. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158084. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158085. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158086. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158087. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158088. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158089. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158090. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158091. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158092. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158093. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158094. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158095. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158096. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158097. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158098. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158099. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158100. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158101. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158102. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158103. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158104. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158105. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158106. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158107. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158108. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158109. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158110. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158111. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158112. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158113. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158114. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158115. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158116. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158117. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158118. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158119. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158120. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158121. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158122. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158123. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158124. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158125. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158126. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158127. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158128. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158129. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158130. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158131. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158132. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158133. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158134. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158135. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158136. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158137. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158138. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158139. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158140. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158141. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158142. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158143. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158144. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158145. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158146. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158147. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158148. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158149. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158150. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158151. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158152. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158153. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158154. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158155. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158156. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158157. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158158. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158159. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158160. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158161. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158162. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158163. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158164. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158165. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158166. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158167. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158168. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158169. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158170. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158171. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158172. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158173. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158174. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158175. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158176. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158177. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158178. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158179. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158180. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158181. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158182. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158183. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158184. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158185. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158186. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158187. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158188. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158189. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158190. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158191. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158192. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158193. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158194. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158195. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158196. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158197. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158198. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158199. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158200. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158201. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158202. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158203. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158204. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158205. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158206. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158207. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158208. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158209. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158210. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158211. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158212. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158213. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158214. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158215. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158216. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158217. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158218. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158219. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158220. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158221. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158222. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158223. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158224. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158225. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158226. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158227. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158228. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158229. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158230. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158231. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158232. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158233. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158234. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158235. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158236. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158237. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158238. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158239. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158240. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158241. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158242. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158243. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158244. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158245. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158246. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158247. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158248. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158249. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158250. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158251. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158252. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158253. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158254. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158255. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158256. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158257. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158258. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158259. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158260. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158261. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158262. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158263. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158264. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158265. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158266. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158267. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158268. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158269. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158270. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158271. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158272. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158273. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158274. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158275. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158276. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158277. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158278. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158279. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158280. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158281. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158282. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158283. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158284. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158285. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158286. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158287. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158288. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158289. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158290. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158291. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158292. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158293. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158294. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158295. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158296. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158297. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158298. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158299. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158300. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158301. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158302. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158303. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158304. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158305. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158306. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158307. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158308. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158309. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158310. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158311. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158312. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158313. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158314. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158315. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158316. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158317. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158318. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158319. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158320. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158321. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158322. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158323. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158324. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158325. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158326. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158327. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158328. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158329. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158330. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158331. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158332. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158333. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158334. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158335. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158336. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158337. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158338. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158339. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158340. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158341. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158342. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158343. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158344. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158345. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158346. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158347. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158348. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158349. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158350. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158351. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158352. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158353. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158354. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158355. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158356. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158357. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158358. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158359. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158360. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158361. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158362. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158363. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158364. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158365. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158366. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158367. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158368. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158369. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158370. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158371. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158372. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158373. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158374. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158375. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158376. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158377. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158378. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158379. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158380. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158381. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158382. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158383. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158384. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158385. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158386. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158387. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158388. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158389. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158390. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158391. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158392. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158393. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158394. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158395. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158396. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158397. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158398. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158399. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158400. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158401. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158402. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158403. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158404. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158405. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158406. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158407. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158408. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158409. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158410. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158411. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158412. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158413. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158414. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158415. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158416. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158417. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158418. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158419. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158420. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158421. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158422. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158423. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158424. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158425. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158426. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158427. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158428. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158429. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158430. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158431. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158432. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158433. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158434. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158435. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158436. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158437. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158438. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158439. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158440. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158441. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158442. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158443. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158444. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158445. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158446. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158447. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158448. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158449. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158450. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158451. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158452. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158453. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158454. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158455. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158456. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158457. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158458. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158459. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158460. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158461. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158462. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158463. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158464. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158465. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158466. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158467. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158468. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158469. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158470. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158471. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158472. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158473. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158474. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158475. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158476. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158477. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158478. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158479. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158480. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158481. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158482. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158483. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158484. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158485. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158486. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158487. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158488. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158489. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158490. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158491. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158492. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158493. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158494. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158495. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158496. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158497. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158498. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158499. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158500. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158501. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158502. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158503. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158504. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158505. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158506. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158507. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158508. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158509. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158510. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158511. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158512. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158513. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158514. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158515. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158516. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158517. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158518. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158519. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158520. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158521. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158522. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158523. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158524. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158525. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158526. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158527. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158528. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158529. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158530. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158531. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158532. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158533. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158534. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158535. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158536. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158537. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158538. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158539. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158540. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158541. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158542. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158543. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158544. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158545. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158546. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158547. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158548. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158549. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158550. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158551. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158552. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158553. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158554. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158555. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158556. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158557. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158558. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158559. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158560. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158561. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158562. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158563. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158564. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158565. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158566. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158567. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158568. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158569. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158570. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158571. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158572. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158573. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158574. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158575. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158576. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158577. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158578. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158579. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158580. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158581. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158582. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158583. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158584. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158585. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158586. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158587. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158588. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158589. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158590. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158591. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158592. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158593. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158594. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158595. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158596. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158597. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158598. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158599. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158600. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158601. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158602. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158603. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158604. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158605. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158606. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158607. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158608. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158609. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158610. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158611. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158612. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158613. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158614. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158615. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158616. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158617. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158618. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158619. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158620. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158621. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158622. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158623. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158624. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158625. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158626. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158627. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158628. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158629. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158630. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158631. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158632. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158633. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158634. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158635. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158636. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158637. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158638. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158639. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158640. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158641. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158642. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158643. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158644. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158645. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158646. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158647. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158648. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158649. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158650. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158651. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158652. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158653. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158654. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158655. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158656. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158657. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158658. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158659. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158660. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158661. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158662. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158663. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158664. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158665. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158666. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158667. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158668. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158669. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158670. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158671. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158672. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158673. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158674. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158675. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158676. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158677. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158678. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158679. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158680. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158681. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158682. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158683. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158684. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158685. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158686. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158687. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158688. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158689. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158690. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158691. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158692. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158693. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158694. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158695. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158696. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158697. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158698. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158699. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158700. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158701. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158702. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158703. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158704. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158705. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158706. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158707. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158708. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158709. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158710. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158711. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158712. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158713. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158714. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158715. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158716. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158717. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158718. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158719. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158720. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158721. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158722. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158723. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158724. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158725. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158726. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158727. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158728. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158729. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158730. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158731. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158732. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158733. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158734. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158735. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158736. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158737. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158738. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158739. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158740. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158741. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158742. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158743. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158744. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158745. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158746. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158747. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158748. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158749. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158750. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158751. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158752. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158753. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158754. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158755. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158756. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158757. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158758. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158759. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158760. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158761. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158762. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158763. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158764. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158765. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158766. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158767. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158768. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158769. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158770. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158771. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158772. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158773. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158774. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158775. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158776. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158777. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158778. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158779. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158780. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158781. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158782. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158783. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158784. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158785. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158786. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158787. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158788. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158789. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158790. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158791. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158792. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158793. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158794. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158795. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158796. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158797. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158798. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158799. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158800. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158801. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158802. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158803. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158804. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158805. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158806. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158807. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158808. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158809. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158810. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158811. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158812. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158813. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158814. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158815. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158816. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158817. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158818. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158819. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158820. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158821. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158822. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158823. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158824. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158825. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158826. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158827. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158828. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158829. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158830. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158831. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158832. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158833. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158834. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158835. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158836. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158837. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158838. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158839. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158840. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158841. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158842. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158843. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158844. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158845. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158846. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158847. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158848. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158849. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158850. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158851. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158852. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158853. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158854. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158855. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158856. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158857. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158858. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158859. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158860. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158861. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158862. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158863. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158864. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158865. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158866. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158867. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158868. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158869. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158870. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158871. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158872. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158873. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158874. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158875. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158876. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158877. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158878. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158879. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158880. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158881. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158882. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158883. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158884. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158885. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158886. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158887. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158888. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158889. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158890. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158891. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158892. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158893. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158894. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158895. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158896. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158897. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158898. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158899. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158900. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158901. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158902. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158903. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158904. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158905. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158906. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158907. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158908. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158909. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158910. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158911. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158912. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158913. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158914. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158915. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158916. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158917. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158918. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158919. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158920. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158921. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158922. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158923. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158924. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158925. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158926. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158927. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158928. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158929. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158930. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158931. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158932. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158933. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158934. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158935. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158936. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158937. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158938. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158939. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158940. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158941. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158942. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158943. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158944. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158945. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158946. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158947. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158948. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158949. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158950. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158951. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158952. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158953. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158954. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158955. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158956. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158957. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158958. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158959. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158960. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158961. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158962. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158963. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158964. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158965. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158966. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158967. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158968. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158969. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158970. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158971. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158972. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158973. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158974. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158975. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158976. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158977. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158978. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158979. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158980. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158981. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158982. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158983. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158984. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158985. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158986. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158987. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158988. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158989. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158990. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158991. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158992. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158993. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158994. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158995. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158996. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158997. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158998. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158999. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159000. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159001. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159002. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159003. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159004. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159005. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159006. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159007. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159008. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159009. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159010. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159011. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159012. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159013. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159014. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159015. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159016. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159017. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159018. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159019. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159020. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159021. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159022. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159023. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159024. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159025. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159026. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159027. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159028. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159029. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159030. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159031. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159032. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159033. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159034. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159035. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159036. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159037. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159038. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159039. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159040. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159041. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159042. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159043. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159044. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159045. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159046. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159047. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159048. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159049. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159050. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159051. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159052. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159053. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159054. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159055. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159056. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159057. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159058. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159059. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159060. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159061. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159062. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159063. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159064. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159065. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159066. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159067. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159068. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159069. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159070. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159071. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159072. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159073. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159074. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159075. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159076. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159077. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159078. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159079. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159080. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159081. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159082. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159083. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159084. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159085. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159086. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159087. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159088. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159089. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159090. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159091. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159092. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159093. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159094. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159095. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159096. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159097. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159098. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159099. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159100. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159101. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159102. };
  159103. static float *vwin[8] = {
  159104. vwin64,
  159105. vwin128,
  159106. vwin256,
  159107. vwin512,
  159108. vwin1024,
  159109. vwin2048,
  159110. vwin4096,
  159111. vwin8192,
  159112. };
  159113. float *_vorbis_window_get(int n){
  159114. return vwin[n];
  159115. }
  159116. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159117. int lW,int W,int nW){
  159118. lW=(W?lW:0);
  159119. nW=(W?nW:0);
  159120. {
  159121. float *windowLW=vwin[winno[lW]];
  159122. float *windowNW=vwin[winno[nW]];
  159123. long n=blocksizes[W];
  159124. long ln=blocksizes[lW];
  159125. long rn=blocksizes[nW];
  159126. long leftbegin=n/4-ln/4;
  159127. long leftend=leftbegin+ln/2;
  159128. long rightbegin=n/2+n/4-rn/4;
  159129. long rightend=rightbegin+rn/2;
  159130. int i,p;
  159131. for(i=0;i<leftbegin;i++)
  159132. d[i]=0.f;
  159133. for(p=0;i<leftend;i++,p++)
  159134. d[i]*=windowLW[p];
  159135. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159136. d[i]*=windowNW[p];
  159137. for(;i<n;i++)
  159138. d[i]=0.f;
  159139. }
  159140. }
  159141. #endif
  159142. /*** End of inlined file: window.c ***/
  159143. #else
  159144. #include <vorbis/vorbisenc.h>
  159145. #include <vorbis/codec.h>
  159146. #include <vorbis/vorbisfile.h>
  159147. #endif
  159148. }
  159149. #undef max
  159150. #undef min
  159151. BEGIN_JUCE_NAMESPACE
  159152. static const char* const oggFormatName = "Ogg-Vorbis file";
  159153. static const char* const oggExtensions[] = { ".ogg", 0 };
  159154. class OggReader : public AudioFormatReader
  159155. {
  159156. OggVorbisNamespace::OggVorbis_File ovFile;
  159157. OggVorbisNamespace::ov_callbacks callbacks;
  159158. AudioSampleBuffer reservoir;
  159159. int reservoirStart, samplesInReservoir;
  159160. public:
  159161. OggReader (InputStream* const inp)
  159162. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159163. reservoir (2, 4096),
  159164. reservoirStart (0),
  159165. samplesInReservoir (0)
  159166. {
  159167. using namespace OggVorbisNamespace;
  159168. sampleRate = 0;
  159169. usesFloatingPointData = true;
  159170. callbacks.read_func = &oggReadCallback;
  159171. callbacks.seek_func = &oggSeekCallback;
  159172. callbacks.close_func = &oggCloseCallback;
  159173. callbacks.tell_func = &oggTellCallback;
  159174. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159175. if (err == 0)
  159176. {
  159177. vorbis_info* info = ov_info (&ovFile, -1);
  159178. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159179. numChannels = info->channels;
  159180. bitsPerSample = 16;
  159181. sampleRate = info->rate;
  159182. reservoir.setSize (numChannels,
  159183. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159184. }
  159185. }
  159186. ~OggReader()
  159187. {
  159188. OggVorbisNamespace::ov_clear (&ovFile);
  159189. }
  159190. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159191. int64 startSampleInFile, int numSamples)
  159192. {
  159193. while (numSamples > 0)
  159194. {
  159195. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159196. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159197. {
  159198. // got a few samples overlapping, so use them before seeking..
  159199. const int numToUse = jmin (numSamples, numAvailable);
  159200. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159201. if (destSamples[i] != 0)
  159202. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159203. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159204. sizeof (float) * numToUse);
  159205. startSampleInFile += numToUse;
  159206. numSamples -= numToUse;
  159207. startOffsetInDestBuffer += numToUse;
  159208. if (numSamples == 0)
  159209. break;
  159210. }
  159211. if (startSampleInFile < reservoirStart
  159212. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159213. {
  159214. // buffer miss, so refill the reservoir
  159215. int bitStream = 0;
  159216. reservoirStart = jmax (0, (int) startSampleInFile);
  159217. samplesInReservoir = reservoir.getNumSamples();
  159218. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159219. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159220. int offset = 0;
  159221. int numToRead = samplesInReservoir;
  159222. while (numToRead > 0)
  159223. {
  159224. float** dataIn = 0;
  159225. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159226. if (samps <= 0)
  159227. break;
  159228. jassert (samps <= numToRead);
  159229. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159230. {
  159231. memcpy (reservoir.getSampleData (i, offset),
  159232. dataIn[i],
  159233. sizeof (float) * samps);
  159234. }
  159235. numToRead -= samps;
  159236. offset += samps;
  159237. }
  159238. if (numToRead > 0)
  159239. reservoir.clear (offset, numToRead);
  159240. }
  159241. }
  159242. if (numSamples > 0)
  159243. {
  159244. for (int i = numDestChannels; --i >= 0;)
  159245. if (destSamples[i] != 0)
  159246. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159247. sizeof (int) * numSamples);
  159248. }
  159249. return true;
  159250. }
  159251. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159252. {
  159253. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159254. }
  159255. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159256. {
  159257. InputStream* const in = static_cast <InputStream*> (datasource);
  159258. if (whence == SEEK_CUR)
  159259. offset += in->getPosition();
  159260. else if (whence == SEEK_END)
  159261. offset += in->getTotalLength();
  159262. in->setPosition (offset);
  159263. return 0;
  159264. }
  159265. static int oggCloseCallback (void*)
  159266. {
  159267. return 0;
  159268. }
  159269. static long oggTellCallback (void* datasource)
  159270. {
  159271. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159272. }
  159273. juce_UseDebuggingNewOperator
  159274. };
  159275. class OggWriter : public AudioFormatWriter
  159276. {
  159277. OggVorbisNamespace::ogg_stream_state os;
  159278. OggVorbisNamespace::ogg_page og;
  159279. OggVorbisNamespace::ogg_packet op;
  159280. OggVorbisNamespace::vorbis_info vi;
  159281. OggVorbisNamespace::vorbis_comment vc;
  159282. OggVorbisNamespace::vorbis_dsp_state vd;
  159283. OggVorbisNamespace::vorbis_block vb;
  159284. public:
  159285. bool ok;
  159286. OggWriter (OutputStream* const out,
  159287. const double sampleRate,
  159288. const int numChannels,
  159289. const int bitsPerSample,
  159290. const int qualityIndex)
  159291. : AudioFormatWriter (out, TRANS (oggFormatName),
  159292. sampleRate,
  159293. numChannels,
  159294. bitsPerSample)
  159295. {
  159296. using namespace OggVorbisNamespace;
  159297. ok = false;
  159298. vorbis_info_init (&vi);
  159299. if (vorbis_encode_init_vbr (&vi,
  159300. numChannels,
  159301. (int) sampleRate,
  159302. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159303. {
  159304. vorbis_comment_init (&vc);
  159305. if (JUCEApplication::getInstance() != 0)
  159306. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159307. vorbis_analysis_init (&vd, &vi);
  159308. vorbis_block_init (&vd, &vb);
  159309. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159310. ogg_packet header;
  159311. ogg_packet header_comm;
  159312. ogg_packet header_code;
  159313. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159314. ogg_stream_packetin (&os, &header);
  159315. ogg_stream_packetin (&os, &header_comm);
  159316. ogg_stream_packetin (&os, &header_code);
  159317. for (;;)
  159318. {
  159319. if (ogg_stream_flush (&os, &og) == 0)
  159320. break;
  159321. output->write (og.header, og.header_len);
  159322. output->write (og.body, og.body_len);
  159323. }
  159324. ok = true;
  159325. }
  159326. }
  159327. ~OggWriter()
  159328. {
  159329. using namespace OggVorbisNamespace;
  159330. if (ok)
  159331. {
  159332. // write a zero-length packet to show ogg that we're finished..
  159333. write (0, 0);
  159334. ogg_stream_clear (&os);
  159335. vorbis_block_clear (&vb);
  159336. vorbis_dsp_clear (&vd);
  159337. vorbis_comment_clear (&vc);
  159338. vorbis_info_clear (&vi);
  159339. output->flush();
  159340. }
  159341. else
  159342. {
  159343. vorbis_info_clear (&vi);
  159344. output = 0; // to stop the base class deleting this, as it needs to be returned
  159345. // to the caller of createWriter()
  159346. }
  159347. }
  159348. bool write (const int** samplesToWrite, int numSamples)
  159349. {
  159350. using namespace OggVorbisNamespace;
  159351. if (! ok)
  159352. return false;
  159353. if (numSamples > 0)
  159354. {
  159355. const double gain = 1.0 / 0x80000000u;
  159356. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159357. for (int i = numChannels; --i >= 0;)
  159358. {
  159359. float* const dst = vorbisBuffer[i];
  159360. const int* const src = samplesToWrite [i];
  159361. if (src != 0 && dst != 0)
  159362. {
  159363. for (int j = 0; j < numSamples; ++j)
  159364. dst[j] = (float) (src[j] * gain);
  159365. }
  159366. }
  159367. }
  159368. vorbis_analysis_wrote (&vd, numSamples);
  159369. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159370. {
  159371. vorbis_analysis (&vb, 0);
  159372. vorbis_bitrate_addblock (&vb);
  159373. while (vorbis_bitrate_flushpacket (&vd, &op))
  159374. {
  159375. ogg_stream_packetin (&os, &op);
  159376. for (;;)
  159377. {
  159378. if (ogg_stream_pageout (&os, &og) == 0)
  159379. break;
  159380. output->write (og.header, og.header_len);
  159381. output->write (og.body, og.body_len);
  159382. if (ogg_page_eos (&og))
  159383. break;
  159384. }
  159385. }
  159386. }
  159387. return true;
  159388. }
  159389. juce_UseDebuggingNewOperator
  159390. };
  159391. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159392. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159393. {
  159394. }
  159395. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159396. {
  159397. }
  159398. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159399. {
  159400. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159401. return Array <int> (rates);
  159402. }
  159403. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159404. {
  159405. Array <int> depths;
  159406. depths.add (32);
  159407. return depths;
  159408. }
  159409. bool OggVorbisAudioFormat::canDoStereo()
  159410. {
  159411. return true;
  159412. }
  159413. bool OggVorbisAudioFormat::canDoMono()
  159414. {
  159415. return true;
  159416. }
  159417. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159418. const bool deleteStreamIfOpeningFails)
  159419. {
  159420. ScopedPointer <OggReader> r (new OggReader (in));
  159421. if (r->sampleRate != 0)
  159422. return r.release();
  159423. if (! deleteStreamIfOpeningFails)
  159424. r->input = 0;
  159425. return 0;
  159426. }
  159427. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159428. double sampleRate,
  159429. unsigned int numChannels,
  159430. int bitsPerSample,
  159431. const StringPairArray& /*metadataValues*/,
  159432. int qualityOptionIndex)
  159433. {
  159434. ScopedPointer <OggWriter> w (new OggWriter (out,
  159435. sampleRate,
  159436. numChannels,
  159437. bitsPerSample,
  159438. qualityOptionIndex));
  159439. return w->ok ? w.release() : 0;
  159440. }
  159441. bool OggVorbisAudioFormat::isCompressed()
  159442. {
  159443. return true;
  159444. }
  159445. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159446. {
  159447. StringArray s;
  159448. s.add ("Low Quality");
  159449. s.add ("Medium Quality");
  159450. s.add ("High Quality");
  159451. return s;
  159452. }
  159453. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159454. {
  159455. FileInputStream* const in = source.createInputStream();
  159456. if (in != 0)
  159457. {
  159458. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159459. if (r != 0)
  159460. {
  159461. const int64 numSamps = r->lengthInSamples;
  159462. r = 0;
  159463. const int64 fileNumSamps = source.getSize() / 4;
  159464. const double ratio = numSamps / (double) fileNumSamps;
  159465. if (ratio > 12.0)
  159466. return 0;
  159467. else if (ratio > 6.0)
  159468. return 1;
  159469. else
  159470. return 2;
  159471. }
  159472. }
  159473. return 1;
  159474. }
  159475. END_JUCE_NAMESPACE
  159476. #endif
  159477. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159478. #endif
  159479. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159480. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159481. #if JUCE_MSVC
  159482. #pragma warning (push)
  159483. #endif
  159484. namespace jpeglibNamespace
  159485. {
  159486. #if JUCE_INCLUDE_JPEGLIB_CODE
  159487. #if JUCE_MINGW
  159488. typedef unsigned char boolean;
  159489. #endif
  159490. extern "C"
  159491. {
  159492. #define JPEG_INTERNALS
  159493. #undef FAR
  159494. /*** Start of inlined file: jpeglib.h ***/
  159495. #ifndef JPEGLIB_H
  159496. #define JPEGLIB_H
  159497. /*
  159498. * First we include the configuration files that record how this
  159499. * installation of the JPEG library is set up. jconfig.h can be
  159500. * generated automatically for many systems. jmorecfg.h contains
  159501. * manual configuration options that most people need not worry about.
  159502. */
  159503. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159504. /*** Start of inlined file: jconfig.h ***/
  159505. /* see jconfig.doc for explanations */
  159506. // disable all the warnings under MSVC
  159507. #ifdef _MSC_VER
  159508. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159509. #endif
  159510. #ifdef __BORLANDC__
  159511. #pragma warn -8057
  159512. #pragma warn -8019
  159513. #pragma warn -8004
  159514. #pragma warn -8008
  159515. #endif
  159516. #define HAVE_PROTOTYPES
  159517. #define HAVE_UNSIGNED_CHAR
  159518. #define HAVE_UNSIGNED_SHORT
  159519. /* #define void char */
  159520. /* #define const */
  159521. #undef CHAR_IS_UNSIGNED
  159522. #define HAVE_STDDEF_H
  159523. #define HAVE_STDLIB_H
  159524. #undef NEED_BSD_STRINGS
  159525. #undef NEED_SYS_TYPES_H
  159526. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159527. #undef NEED_SHORT_EXTERNAL_NAMES
  159528. #undef INCOMPLETE_TYPES_BROKEN
  159529. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159530. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159531. typedef unsigned char boolean;
  159532. #endif
  159533. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159534. #ifdef JPEG_INTERNALS
  159535. #undef RIGHT_SHIFT_IS_UNSIGNED
  159536. #endif /* JPEG_INTERNALS */
  159537. #ifdef JPEG_CJPEG_DJPEG
  159538. #define BMP_SUPPORTED /* BMP image file format */
  159539. #define GIF_SUPPORTED /* GIF image file format */
  159540. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159541. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159542. #define TARGA_SUPPORTED /* Targa image file format */
  159543. #define TWO_FILE_COMMANDLINE /* optional */
  159544. #define USE_SETMODE /* Microsoft has setmode() */
  159545. #undef NEED_SIGNAL_CATCHER
  159546. #undef DONT_USE_B_MODE
  159547. #undef PROGRESS_REPORT /* optional */
  159548. #endif /* JPEG_CJPEG_DJPEG */
  159549. /*** End of inlined file: jconfig.h ***/
  159550. /* widely used configuration options */
  159551. #endif
  159552. /*** Start of inlined file: jmorecfg.h ***/
  159553. /*
  159554. * Define BITS_IN_JSAMPLE as either
  159555. * 8 for 8-bit sample values (the usual setting)
  159556. * 12 for 12-bit sample values
  159557. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159558. * JPEG standard, and the IJG code does not support anything else!
  159559. * We do not support run-time selection of data precision, sorry.
  159560. */
  159561. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159562. /*
  159563. * Maximum number of components (color channels) allowed in JPEG image.
  159564. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159565. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159566. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159567. * really short on memory. (Each allowed component costs a hundred or so
  159568. * bytes of storage, whether actually used in an image or not.)
  159569. */
  159570. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159571. /*
  159572. * Basic data types.
  159573. * You may need to change these if you have a machine with unusual data
  159574. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159575. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159576. * but it had better be at least 16.
  159577. */
  159578. /* Representation of a single sample (pixel element value).
  159579. * We frequently allocate large arrays of these, so it's important to keep
  159580. * them small. But if you have memory to burn and access to char or short
  159581. * arrays is very slow on your hardware, you might want to change these.
  159582. */
  159583. #if BITS_IN_JSAMPLE == 8
  159584. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159585. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159586. */
  159587. #ifdef HAVE_UNSIGNED_CHAR
  159588. typedef unsigned char JSAMPLE;
  159589. #define GETJSAMPLE(value) ((int) (value))
  159590. #else /* not HAVE_UNSIGNED_CHAR */
  159591. typedef char JSAMPLE;
  159592. #ifdef CHAR_IS_UNSIGNED
  159593. #define GETJSAMPLE(value) ((int) (value))
  159594. #else
  159595. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159596. #endif /* CHAR_IS_UNSIGNED */
  159597. #endif /* HAVE_UNSIGNED_CHAR */
  159598. #define MAXJSAMPLE 255
  159599. #define CENTERJSAMPLE 128
  159600. #endif /* BITS_IN_JSAMPLE == 8 */
  159601. #if BITS_IN_JSAMPLE == 12
  159602. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159603. * On nearly all machines "short" will do nicely.
  159604. */
  159605. typedef short JSAMPLE;
  159606. #define GETJSAMPLE(value) ((int) (value))
  159607. #define MAXJSAMPLE 4095
  159608. #define CENTERJSAMPLE 2048
  159609. #endif /* BITS_IN_JSAMPLE == 12 */
  159610. /* Representation of a DCT frequency coefficient.
  159611. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159612. * Again, we allocate large arrays of these, but you can change to int
  159613. * if you have memory to burn and "short" is really slow.
  159614. */
  159615. typedef short JCOEF;
  159616. /* Compressed datastreams are represented as arrays of JOCTET.
  159617. * These must be EXACTLY 8 bits wide, at least once they are written to
  159618. * external storage. Note that when using the stdio data source/destination
  159619. * managers, this is also the data type passed to fread/fwrite.
  159620. */
  159621. #ifdef HAVE_UNSIGNED_CHAR
  159622. typedef unsigned char JOCTET;
  159623. #define GETJOCTET(value) (value)
  159624. #else /* not HAVE_UNSIGNED_CHAR */
  159625. typedef char JOCTET;
  159626. #ifdef CHAR_IS_UNSIGNED
  159627. #define GETJOCTET(value) (value)
  159628. #else
  159629. #define GETJOCTET(value) ((value) & 0xFF)
  159630. #endif /* CHAR_IS_UNSIGNED */
  159631. #endif /* HAVE_UNSIGNED_CHAR */
  159632. /* These typedefs are used for various table entries and so forth.
  159633. * They must be at least as wide as specified; but making them too big
  159634. * won't cost a huge amount of memory, so we don't provide special
  159635. * extraction code like we did for JSAMPLE. (In other words, these
  159636. * typedefs live at a different point on the speed/space tradeoff curve.)
  159637. */
  159638. /* UINT8 must hold at least the values 0..255. */
  159639. #ifdef HAVE_UNSIGNED_CHAR
  159640. typedef unsigned char UINT8;
  159641. #else /* not HAVE_UNSIGNED_CHAR */
  159642. #ifdef CHAR_IS_UNSIGNED
  159643. typedef char UINT8;
  159644. #else /* not CHAR_IS_UNSIGNED */
  159645. typedef short UINT8;
  159646. #endif /* CHAR_IS_UNSIGNED */
  159647. #endif /* HAVE_UNSIGNED_CHAR */
  159648. /* UINT16 must hold at least the values 0..65535. */
  159649. #ifdef HAVE_UNSIGNED_SHORT
  159650. typedef unsigned short UINT16;
  159651. #else /* not HAVE_UNSIGNED_SHORT */
  159652. typedef unsigned int UINT16;
  159653. #endif /* HAVE_UNSIGNED_SHORT */
  159654. /* INT16 must hold at least the values -32768..32767. */
  159655. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159656. typedef short INT16;
  159657. #endif
  159658. /* INT32 must hold at least signed 32-bit values. */
  159659. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159660. typedef long INT32;
  159661. #endif
  159662. /* Datatype used for image dimensions. The JPEG standard only supports
  159663. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159664. * "unsigned int" is sufficient on all machines. However, if you need to
  159665. * handle larger images and you don't mind deviating from the spec, you
  159666. * can change this datatype.
  159667. */
  159668. typedef unsigned int JDIMENSION;
  159669. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159670. /* These macros are used in all function definitions and extern declarations.
  159671. * You could modify them if you need to change function linkage conventions;
  159672. * in particular, you'll need to do that to make the library a Windows DLL.
  159673. * Another application is to make all functions global for use with debuggers
  159674. * or code profilers that require it.
  159675. */
  159676. /* a function called through method pointers: */
  159677. #define METHODDEF(type) static type
  159678. /* a function used only in its module: */
  159679. #define LOCAL(type) static type
  159680. /* a function referenced thru EXTERNs: */
  159681. #define GLOBAL(type) type
  159682. /* a reference to a GLOBAL function: */
  159683. #define EXTERN(type) extern type
  159684. /* This macro is used to declare a "method", that is, a function pointer.
  159685. * We want to supply prototype parameters if the compiler can cope.
  159686. * Note that the arglist parameter must be parenthesized!
  159687. * Again, you can customize this if you need special linkage keywords.
  159688. */
  159689. #ifdef HAVE_PROTOTYPES
  159690. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159691. #else
  159692. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159693. #endif
  159694. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159695. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159696. * by just saying "FAR *" where such a pointer is needed. In a few places
  159697. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159698. */
  159699. #ifdef NEED_FAR_POINTERS
  159700. #define FAR far
  159701. #else
  159702. #define FAR
  159703. #endif
  159704. /*
  159705. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159706. * in standard header files. Or you may have conflicts with application-
  159707. * specific header files that you want to include together with these files.
  159708. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159709. */
  159710. #ifndef HAVE_BOOLEAN
  159711. typedef int boolean;
  159712. #endif
  159713. #ifndef FALSE /* in case these macros already exist */
  159714. #define FALSE 0 /* values of boolean */
  159715. #endif
  159716. #ifndef TRUE
  159717. #define TRUE 1
  159718. #endif
  159719. /*
  159720. * The remaining options affect code selection within the JPEG library,
  159721. * but they don't need to be visible to most applications using the library.
  159722. * To minimize application namespace pollution, the symbols won't be
  159723. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159724. */
  159725. #ifdef JPEG_INTERNALS
  159726. #define JPEG_INTERNAL_OPTIONS
  159727. #endif
  159728. #ifdef JPEG_INTERNAL_OPTIONS
  159729. /*
  159730. * These defines indicate whether to include various optional functions.
  159731. * Undefining some of these symbols will produce a smaller but less capable
  159732. * library. Note that you can leave certain source files out of the
  159733. * compilation/linking process if you've #undef'd the corresponding symbols.
  159734. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159735. */
  159736. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159737. /* Capability options common to encoder and decoder: */
  159738. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159739. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159740. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159741. /* Encoder capability options: */
  159742. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159743. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159744. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159745. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159746. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159747. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159748. * precision, so jchuff.c normally uses entropy optimization to compute
  159749. * usable tables for higher precision. If you don't want to do optimization,
  159750. * you'll have to supply different default Huffman tables.
  159751. * The exact same statements apply for progressive JPEG: the default tables
  159752. * don't work for progressive mode. (This may get fixed, however.)
  159753. */
  159754. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159755. /* Decoder capability options: */
  159756. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159757. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159758. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159759. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159760. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159761. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159762. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159763. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159764. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159765. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159766. /* more capability options later, no doubt */
  159767. /*
  159768. * Ordering of RGB data in scanlines passed to or from the application.
  159769. * If your application wants to deal with data in the order B,G,R, just
  159770. * change these macros. You can also deal with formats such as R,G,B,X
  159771. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159772. * the offsets will also change the order in which colormap data is organized.
  159773. * RESTRICTIONS:
  159774. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159775. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159776. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159777. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159778. * is not 3 (they don't understand about dummy color components!). So you
  159779. * can't use color quantization if you change that value.
  159780. */
  159781. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159782. #define RGB_GREEN 1 /* Offset of Green */
  159783. #define RGB_BLUE 2 /* Offset of Blue */
  159784. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159785. /* Definitions for speed-related optimizations. */
  159786. /* If your compiler supports inline functions, define INLINE
  159787. * as the inline keyword; otherwise define it as empty.
  159788. */
  159789. #ifndef INLINE
  159790. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159791. #define INLINE __inline__
  159792. #endif
  159793. #ifndef INLINE
  159794. #define INLINE /* default is to define it as empty */
  159795. #endif
  159796. #endif
  159797. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159798. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159799. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159800. */
  159801. #ifndef MULTIPLIER
  159802. #define MULTIPLIER int /* type for fastest integer multiply */
  159803. #endif
  159804. /* FAST_FLOAT should be either float or double, whichever is done faster
  159805. * by your compiler. (Note that this type is only used in the floating point
  159806. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159807. * Typically, float is faster in ANSI C compilers, while double is faster in
  159808. * pre-ANSI compilers (because they insist on converting to double anyway).
  159809. * The code below therefore chooses float if we have ANSI-style prototypes.
  159810. */
  159811. #ifndef FAST_FLOAT
  159812. #ifdef HAVE_PROTOTYPES
  159813. #define FAST_FLOAT float
  159814. #else
  159815. #define FAST_FLOAT double
  159816. #endif
  159817. #endif
  159818. #endif /* JPEG_INTERNAL_OPTIONS */
  159819. /*** End of inlined file: jmorecfg.h ***/
  159820. /* seldom changed options */
  159821. /* Version ID for the JPEG library.
  159822. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159823. */
  159824. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159825. /* Various constants determining the sizes of things.
  159826. * All of these are specified by the JPEG standard, so don't change them
  159827. * if you want to be compatible.
  159828. */
  159829. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159830. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159831. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159832. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159833. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159834. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159835. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159836. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159837. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159838. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159839. * to handle it. We even let you do this from the jconfig.h file. However,
  159840. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159841. * sometimes emits noncompliant files doesn't mean you should too.
  159842. */
  159843. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159844. #ifndef D_MAX_BLOCKS_IN_MCU
  159845. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159846. #endif
  159847. /* Data structures for images (arrays of samples and of DCT coefficients).
  159848. * On 80x86 machines, the image arrays are too big for near pointers,
  159849. * but the pointer arrays can fit in near memory.
  159850. */
  159851. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159852. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159853. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159854. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159855. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159856. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159857. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159858. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159859. /* Types for JPEG compression parameters and working tables. */
  159860. /* DCT coefficient quantization tables. */
  159861. typedef struct {
  159862. /* This array gives the coefficient quantizers in natural array order
  159863. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159864. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159865. */
  159866. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159867. /* This field is used only during compression. It's initialized FALSE when
  159868. * the table is created, and set TRUE when it's been output to the file.
  159869. * You could suppress output of a table by setting this to TRUE.
  159870. * (See jpeg_suppress_tables for an example.)
  159871. */
  159872. boolean sent_table; /* TRUE when table has been output */
  159873. } JQUANT_TBL;
  159874. /* Huffman coding tables. */
  159875. typedef struct {
  159876. /* These two fields directly represent the contents of a JPEG DHT marker */
  159877. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159878. /* length k bits; bits[0] is unused */
  159879. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159880. /* This field is used only during compression. It's initialized FALSE when
  159881. * the table is created, and set TRUE when it's been output to the file.
  159882. * You could suppress output of a table by setting this to TRUE.
  159883. * (See jpeg_suppress_tables for an example.)
  159884. */
  159885. boolean sent_table; /* TRUE when table has been output */
  159886. } JHUFF_TBL;
  159887. /* Basic info about one component (color channel). */
  159888. typedef struct {
  159889. /* These values are fixed over the whole image. */
  159890. /* For compression, they must be supplied by parameter setup; */
  159891. /* for decompression, they are read from the SOF marker. */
  159892. int component_id; /* identifier for this component (0..255) */
  159893. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159894. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159895. int v_samp_factor; /* vertical sampling factor (1..4) */
  159896. int quant_tbl_no; /* quantization table selector (0..3) */
  159897. /* These values may vary between scans. */
  159898. /* For compression, they must be supplied by parameter setup; */
  159899. /* for decompression, they are read from the SOS marker. */
  159900. /* The decompressor output side may not use these variables. */
  159901. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159902. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159903. /* Remaining fields should be treated as private by applications. */
  159904. /* These values are computed during compression or decompression startup: */
  159905. /* Component's size in DCT blocks.
  159906. * Any dummy blocks added to complete an MCU are not counted; therefore
  159907. * these values do not depend on whether a scan is interleaved or not.
  159908. */
  159909. JDIMENSION width_in_blocks;
  159910. JDIMENSION height_in_blocks;
  159911. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159912. * For decompression this is the size of the output from one DCT block,
  159913. * reflecting any scaling we choose to apply during the IDCT step.
  159914. * Values of 1,2,4,8 are likely to be supported. Note that different
  159915. * components may receive different IDCT scalings.
  159916. */
  159917. int DCT_scaled_size;
  159918. /* The downsampled dimensions are the component's actual, unpadded number
  159919. * of samples at the main buffer (preprocessing/compression interface), thus
  159920. * downsampled_width = ceil(image_width * Hi/Hmax)
  159921. * and similarly for height. For decompression, IDCT scaling is included, so
  159922. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159923. */
  159924. JDIMENSION downsampled_width; /* actual width in samples */
  159925. JDIMENSION downsampled_height; /* actual height in samples */
  159926. /* This flag is used only for decompression. In cases where some of the
  159927. * components will be ignored (eg grayscale output from YCbCr image),
  159928. * we can skip most computations for the unused components.
  159929. */
  159930. boolean component_needed; /* do we need the value of this component? */
  159931. /* These values are computed before starting a scan of the component. */
  159932. /* The decompressor output side may not use these variables. */
  159933. int MCU_width; /* number of blocks per MCU, horizontally */
  159934. int MCU_height; /* number of blocks per MCU, vertically */
  159935. int MCU_blocks; /* MCU_width * MCU_height */
  159936. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159937. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159938. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159939. /* Saved quantization table for component; NULL if none yet saved.
  159940. * See jdinput.c comments about the need for this information.
  159941. * This field is currently used only for decompression.
  159942. */
  159943. JQUANT_TBL * quant_table;
  159944. /* Private per-component storage for DCT or IDCT subsystem. */
  159945. void * dct_table;
  159946. } jpeg_component_info;
  159947. /* The script for encoding a multiple-scan file is an array of these: */
  159948. typedef struct {
  159949. int comps_in_scan; /* number of components encoded in this scan */
  159950. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159951. int Ss, Se; /* progressive JPEG spectral selection parms */
  159952. int Ah, Al; /* progressive JPEG successive approx. parms */
  159953. } jpeg_scan_info;
  159954. /* The decompressor can save APPn and COM markers in a list of these: */
  159955. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159956. struct jpeg_marker_struct {
  159957. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159958. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159959. unsigned int original_length; /* # bytes of data in the file */
  159960. unsigned int data_length; /* # bytes of data saved at data[] */
  159961. JOCTET FAR * data; /* the data contained in the marker */
  159962. /* the marker length word is not counted in data_length or original_length */
  159963. };
  159964. /* Known color spaces. */
  159965. typedef enum {
  159966. JCS_UNKNOWN, /* error/unspecified */
  159967. JCS_GRAYSCALE, /* monochrome */
  159968. JCS_RGB, /* red/green/blue */
  159969. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159970. JCS_CMYK, /* C/M/Y/K */
  159971. JCS_YCCK /* Y/Cb/Cr/K */
  159972. } J_COLOR_SPACE;
  159973. /* DCT/IDCT algorithm options. */
  159974. typedef enum {
  159975. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159976. JDCT_IFAST, /* faster, less accurate integer method */
  159977. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159978. } J_DCT_METHOD;
  159979. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159980. #define JDCT_DEFAULT JDCT_ISLOW
  159981. #endif
  159982. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159983. #define JDCT_FASTEST JDCT_IFAST
  159984. #endif
  159985. /* Dithering options for decompression. */
  159986. typedef enum {
  159987. JDITHER_NONE, /* no dithering */
  159988. JDITHER_ORDERED, /* simple ordered dither */
  159989. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159990. } J_DITHER_MODE;
  159991. /* Common fields between JPEG compression and decompression master structs. */
  159992. #define jpeg_common_fields \
  159993. struct jpeg_error_mgr * err; /* Error handler module */\
  159994. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159995. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159996. void * client_data; /* Available for use by application */\
  159997. boolean is_decompressor; /* So common code can tell which is which */\
  159998. int global_state /* For checking call sequence validity */
  159999. /* Routines that are to be used by both halves of the library are declared
  160000. * to receive a pointer to this structure. There are no actual instances of
  160001. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160002. */
  160003. struct jpeg_common_struct {
  160004. jpeg_common_fields; /* Fields common to both master struct types */
  160005. /* Additional fields follow in an actual jpeg_compress_struct or
  160006. * jpeg_decompress_struct. All three structs must agree on these
  160007. * initial fields! (This would be a lot cleaner in C++.)
  160008. */
  160009. };
  160010. typedef struct jpeg_common_struct * j_common_ptr;
  160011. typedef struct jpeg_compress_struct * j_compress_ptr;
  160012. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160013. /* Master record for a compression instance */
  160014. struct jpeg_compress_struct {
  160015. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160016. /* Destination for compressed data */
  160017. struct jpeg_destination_mgr * dest;
  160018. /* Description of source image --- these fields must be filled in by
  160019. * outer application before starting compression. in_color_space must
  160020. * be correct before you can even call jpeg_set_defaults().
  160021. */
  160022. JDIMENSION image_width; /* input image width */
  160023. JDIMENSION image_height; /* input image height */
  160024. int input_components; /* # of color components in input image */
  160025. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160026. double input_gamma; /* image gamma of input image */
  160027. /* Compression parameters --- these fields must be set before calling
  160028. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160029. * initialize everything to reasonable defaults, then changing anything
  160030. * the application specifically wants to change. That way you won't get
  160031. * burnt when new parameters are added. Also note that there are several
  160032. * helper routines to simplify changing parameters.
  160033. */
  160034. int data_precision; /* bits of precision in image data */
  160035. int num_components; /* # of color components in JPEG image */
  160036. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160037. jpeg_component_info * comp_info;
  160038. /* comp_info[i] describes component that appears i'th in SOF */
  160039. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160040. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160041. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160042. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160043. /* ptrs to Huffman coding tables, or NULL if not defined */
  160044. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160045. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160046. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160047. int num_scans; /* # of entries in scan_info array */
  160048. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160049. /* The default value of scan_info is NULL, which causes a single-scan
  160050. * sequential JPEG file to be emitted. To create a multi-scan file,
  160051. * set num_scans and scan_info to point to an array of scan definitions.
  160052. */
  160053. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160054. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160055. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160056. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160057. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160058. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160059. /* The restart interval can be specified in absolute MCUs by setting
  160060. * restart_interval, or in MCU rows by setting restart_in_rows
  160061. * (in which case the correct restart_interval will be figured
  160062. * for each scan).
  160063. */
  160064. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160065. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160066. /* Parameters controlling emission of special markers. */
  160067. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160068. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160069. UINT8 JFIF_minor_version;
  160070. /* These three values are not used by the JPEG code, merely copied */
  160071. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160072. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160073. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160074. UINT8 density_unit; /* JFIF code for pixel size units */
  160075. UINT16 X_density; /* Horizontal pixel density */
  160076. UINT16 Y_density; /* Vertical pixel density */
  160077. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160078. /* State variable: index of next scanline to be written to
  160079. * jpeg_write_scanlines(). Application may use this to control its
  160080. * processing loop, e.g., "while (next_scanline < image_height)".
  160081. */
  160082. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160083. /* Remaining fields are known throughout compressor, but generally
  160084. * should not be touched by a surrounding application.
  160085. */
  160086. /*
  160087. * These fields are computed during compression startup
  160088. */
  160089. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160090. int max_h_samp_factor; /* largest h_samp_factor */
  160091. int max_v_samp_factor; /* largest v_samp_factor */
  160092. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160093. /* The coefficient controller receives data in units of MCU rows as defined
  160094. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160095. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160096. * "iMCU" (interleaved MCU) row.
  160097. */
  160098. /*
  160099. * These fields are valid during any one scan.
  160100. * They describe the components and MCUs actually appearing in the scan.
  160101. */
  160102. int comps_in_scan; /* # of JPEG components in this scan */
  160103. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160104. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160105. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160106. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160107. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160108. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160109. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160110. /* i'th block in an MCU */
  160111. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160112. /*
  160113. * Links to compression subobjects (methods and private variables of modules)
  160114. */
  160115. struct jpeg_comp_master * master;
  160116. struct jpeg_c_main_controller * main;
  160117. struct jpeg_c_prep_controller * prep;
  160118. struct jpeg_c_coef_controller * coef;
  160119. struct jpeg_marker_writer * marker;
  160120. struct jpeg_color_converter * cconvert;
  160121. struct jpeg_downsampler * downsample;
  160122. struct jpeg_forward_dct * fdct;
  160123. struct jpeg_entropy_encoder * entropy;
  160124. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160125. int script_space_size;
  160126. };
  160127. /* Master record for a decompression instance */
  160128. struct jpeg_decompress_struct {
  160129. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160130. /* Source of compressed data */
  160131. struct jpeg_source_mgr * src;
  160132. /* Basic description of image --- filled in by jpeg_read_header(). */
  160133. /* Application may inspect these values to decide how to process image. */
  160134. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160135. JDIMENSION image_height; /* nominal image height */
  160136. int num_components; /* # of color components in JPEG image */
  160137. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160138. /* Decompression processing parameters --- these fields must be set before
  160139. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160140. * them to default values.
  160141. */
  160142. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160143. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160144. double output_gamma; /* image gamma wanted in output */
  160145. boolean buffered_image; /* TRUE=multiple output passes */
  160146. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160147. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160148. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160149. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160150. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160151. /* the following are ignored if not quantize_colors: */
  160152. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160153. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160154. int desired_number_of_colors; /* max # colors to use in created colormap */
  160155. /* these are significant only in buffered-image mode: */
  160156. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160157. boolean enable_external_quant;/* enable future use of external colormap */
  160158. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160159. /* Description of actual output image that will be returned to application.
  160160. * These fields are computed by jpeg_start_decompress().
  160161. * You can also use jpeg_calc_output_dimensions() to determine these values
  160162. * in advance of calling jpeg_start_decompress().
  160163. */
  160164. JDIMENSION output_width; /* scaled image width */
  160165. JDIMENSION output_height; /* scaled image height */
  160166. int out_color_components; /* # of color components in out_color_space */
  160167. int output_components; /* # of color components returned */
  160168. /* output_components is 1 (a colormap index) when quantizing colors;
  160169. * otherwise it equals out_color_components.
  160170. */
  160171. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160172. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160173. * high, space and time will be wasted due to unnecessary data copying.
  160174. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160175. */
  160176. /* When quantizing colors, the output colormap is described by these fields.
  160177. * The application can supply a colormap by setting colormap non-NULL before
  160178. * calling jpeg_start_decompress; otherwise a colormap is created during
  160179. * jpeg_start_decompress or jpeg_start_output.
  160180. * The map has out_color_components rows and actual_number_of_colors columns.
  160181. */
  160182. int actual_number_of_colors; /* number of entries in use */
  160183. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160184. /* State variables: these variables indicate the progress of decompression.
  160185. * The application may examine these but must not modify them.
  160186. */
  160187. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160188. * Application may use this to control its processing loop, e.g.,
  160189. * "while (output_scanline < output_height)".
  160190. */
  160191. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160192. /* Current input scan number and number of iMCU rows completed in scan.
  160193. * These indicate the progress of the decompressor input side.
  160194. */
  160195. int input_scan_number; /* Number of SOS markers seen so far */
  160196. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160197. /* The "output scan number" is the notional scan being displayed by the
  160198. * output side. The decompressor will not allow output scan/row number
  160199. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160200. */
  160201. int output_scan_number; /* Nominal scan number being displayed */
  160202. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160203. /* Current progression status. coef_bits[c][i] indicates the precision
  160204. * with which component c's DCT coefficient i (in zigzag order) is known.
  160205. * It is -1 when no data has yet been received, otherwise it is the point
  160206. * transform (shift) value for the most recent scan of the coefficient
  160207. * (thus, 0 at completion of the progression).
  160208. * This pointer is NULL when reading a non-progressive file.
  160209. */
  160210. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160211. /* Internal JPEG parameters --- the application usually need not look at
  160212. * these fields. Note that the decompressor output side may not use
  160213. * any parameters that can change between scans.
  160214. */
  160215. /* Quantization and Huffman tables are carried forward across input
  160216. * datastreams when processing abbreviated JPEG datastreams.
  160217. */
  160218. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160219. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160220. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160221. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160222. /* ptrs to Huffman coding tables, or NULL if not defined */
  160223. /* These parameters are never carried across datastreams, since they
  160224. * are given in SOF/SOS markers or defined to be reset by SOI.
  160225. */
  160226. int data_precision; /* bits of precision in image data */
  160227. jpeg_component_info * comp_info;
  160228. /* comp_info[i] describes component that appears i'th in SOF */
  160229. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160230. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160231. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160232. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160233. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160234. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160235. /* These fields record data obtained from optional markers recognized by
  160236. * the JPEG library.
  160237. */
  160238. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160239. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160240. UINT8 JFIF_major_version; /* JFIF version number */
  160241. UINT8 JFIF_minor_version;
  160242. UINT8 density_unit; /* JFIF code for pixel size units */
  160243. UINT16 X_density; /* Horizontal pixel density */
  160244. UINT16 Y_density; /* Vertical pixel density */
  160245. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160246. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160247. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160248. /* Aside from the specific data retained from APPn markers known to the
  160249. * library, the uninterpreted contents of any or all APPn and COM markers
  160250. * can be saved in a list for examination by the application.
  160251. */
  160252. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160253. /* Remaining fields are known throughout decompressor, but generally
  160254. * should not be touched by a surrounding application.
  160255. */
  160256. /*
  160257. * These fields are computed during decompression startup
  160258. */
  160259. int max_h_samp_factor; /* largest h_samp_factor */
  160260. int max_v_samp_factor; /* largest v_samp_factor */
  160261. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160262. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160263. /* The coefficient controller's input and output progress is measured in
  160264. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160265. * in fully interleaved JPEG scans, but are used whether the scan is
  160266. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160267. * rows of each component. Therefore, the IDCT output contains
  160268. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160269. */
  160270. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160271. /*
  160272. * These fields are valid during any one scan.
  160273. * They describe the components and MCUs actually appearing in the scan.
  160274. * Note that the decompressor output side must not use these fields.
  160275. */
  160276. int comps_in_scan; /* # of JPEG components in this scan */
  160277. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160278. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160279. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160280. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160281. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160282. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160283. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160284. /* i'th block in an MCU */
  160285. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160286. /* This field is shared between entropy decoder and marker parser.
  160287. * It is either zero or the code of a JPEG marker that has been
  160288. * read from the data source, but has not yet been processed.
  160289. */
  160290. int unread_marker;
  160291. /*
  160292. * Links to decompression subobjects (methods, private variables of modules)
  160293. */
  160294. struct jpeg_decomp_master * master;
  160295. struct jpeg_d_main_controller * main;
  160296. struct jpeg_d_coef_controller * coef;
  160297. struct jpeg_d_post_controller * post;
  160298. struct jpeg_input_controller * inputctl;
  160299. struct jpeg_marker_reader * marker;
  160300. struct jpeg_entropy_decoder * entropy;
  160301. struct jpeg_inverse_dct * idct;
  160302. struct jpeg_upsampler * upsample;
  160303. struct jpeg_color_deconverter * cconvert;
  160304. struct jpeg_color_quantizer * cquantize;
  160305. };
  160306. /* "Object" declarations for JPEG modules that may be supplied or called
  160307. * directly by the surrounding application.
  160308. * As with all objects in the JPEG library, these structs only define the
  160309. * publicly visible methods and state variables of a module. Additional
  160310. * private fields may exist after the public ones.
  160311. */
  160312. /* Error handler object */
  160313. struct jpeg_error_mgr {
  160314. /* Error exit handler: does not return to caller */
  160315. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160316. /* Conditionally emit a trace or warning message */
  160317. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160318. /* Routine that actually outputs a trace or error message */
  160319. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160320. /* Format a message string for the most recent JPEG error or message */
  160321. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160322. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160323. /* Reset error state variables at start of a new image */
  160324. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160325. /* The message ID code and any parameters are saved here.
  160326. * A message can have one string parameter or up to 8 int parameters.
  160327. */
  160328. int msg_code;
  160329. #define JMSG_STR_PARM_MAX 80
  160330. union {
  160331. int i[8];
  160332. char s[JMSG_STR_PARM_MAX];
  160333. } msg_parm;
  160334. /* Standard state variables for error facility */
  160335. int trace_level; /* max msg_level that will be displayed */
  160336. /* For recoverable corrupt-data errors, we emit a warning message,
  160337. * but keep going unless emit_message chooses to abort. emit_message
  160338. * should count warnings in num_warnings. The surrounding application
  160339. * can check for bad data by seeing if num_warnings is nonzero at the
  160340. * end of processing.
  160341. */
  160342. long num_warnings; /* number of corrupt-data warnings */
  160343. /* These fields point to the table(s) of error message strings.
  160344. * An application can change the table pointer to switch to a different
  160345. * message list (typically, to change the language in which errors are
  160346. * reported). Some applications may wish to add additional error codes
  160347. * that will be handled by the JPEG library error mechanism; the second
  160348. * table pointer is used for this purpose.
  160349. *
  160350. * First table includes all errors generated by JPEG library itself.
  160351. * Error code 0 is reserved for a "no such error string" message.
  160352. */
  160353. const char * const * jpeg_message_table; /* Library errors */
  160354. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160355. /* Second table can be added by application (see cjpeg/djpeg for example).
  160356. * It contains strings numbered first_addon_message..last_addon_message.
  160357. */
  160358. const char * const * addon_message_table; /* Non-library errors */
  160359. int first_addon_message; /* code for first string in addon table */
  160360. int last_addon_message; /* code for last string in addon table */
  160361. };
  160362. /* Progress monitor object */
  160363. struct jpeg_progress_mgr {
  160364. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160365. long pass_counter; /* work units completed in this pass */
  160366. long pass_limit; /* total number of work units in this pass */
  160367. int completed_passes; /* passes completed so far */
  160368. int total_passes; /* total number of passes expected */
  160369. };
  160370. /* Data destination object for compression */
  160371. struct jpeg_destination_mgr {
  160372. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160373. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160374. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160375. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160376. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160377. };
  160378. /* Data source object for decompression */
  160379. struct jpeg_source_mgr {
  160380. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160381. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160382. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160383. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160384. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160385. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160386. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160387. };
  160388. /* Memory manager object.
  160389. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160390. * and "really big" objects (virtual arrays with backing store if needed).
  160391. * The memory manager does not allow individual objects to be freed; rather,
  160392. * each created object is assigned to a pool, and whole pools can be freed
  160393. * at once. This is faster and more convenient than remembering exactly what
  160394. * to free, especially where malloc()/free() are not too speedy.
  160395. * NB: alloc routines never return NULL. They exit to error_exit if not
  160396. * successful.
  160397. */
  160398. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160399. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160400. #define JPOOL_NUMPOOLS 2
  160401. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160402. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160403. struct jpeg_memory_mgr {
  160404. /* Method pointers */
  160405. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160406. size_t sizeofobject));
  160407. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160408. size_t sizeofobject));
  160409. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160410. JDIMENSION samplesperrow,
  160411. JDIMENSION numrows));
  160412. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160413. JDIMENSION blocksperrow,
  160414. JDIMENSION numrows));
  160415. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160416. int pool_id,
  160417. boolean pre_zero,
  160418. JDIMENSION samplesperrow,
  160419. JDIMENSION numrows,
  160420. JDIMENSION maxaccess));
  160421. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160422. int pool_id,
  160423. boolean pre_zero,
  160424. JDIMENSION blocksperrow,
  160425. JDIMENSION numrows,
  160426. JDIMENSION maxaccess));
  160427. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160428. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160429. jvirt_sarray_ptr ptr,
  160430. JDIMENSION start_row,
  160431. JDIMENSION num_rows,
  160432. boolean writable));
  160433. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160434. jvirt_barray_ptr ptr,
  160435. JDIMENSION start_row,
  160436. JDIMENSION num_rows,
  160437. boolean writable));
  160438. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160439. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160440. /* Limit on memory allocation for this JPEG object. (Note that this is
  160441. * merely advisory, not a guaranteed maximum; it only affects the space
  160442. * used for virtual-array buffers.) May be changed by outer application
  160443. * after creating the JPEG object.
  160444. */
  160445. long max_memory_to_use;
  160446. /* Maximum allocation request accepted by alloc_large. */
  160447. long max_alloc_chunk;
  160448. };
  160449. /* Routine signature for application-supplied marker processing methods.
  160450. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160451. */
  160452. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160453. /* Declarations for routines called by application.
  160454. * The JPP macro hides prototype parameters from compilers that can't cope.
  160455. * Note JPP requires double parentheses.
  160456. */
  160457. #ifdef HAVE_PROTOTYPES
  160458. #define JPP(arglist) arglist
  160459. #else
  160460. #define JPP(arglist) ()
  160461. #endif
  160462. /* Short forms of external names for systems with brain-damaged linkers.
  160463. * We shorten external names to be unique in the first six letters, which
  160464. * is good enough for all known systems.
  160465. * (If your compiler itself needs names to be unique in less than 15
  160466. * characters, you are out of luck. Get a better compiler.)
  160467. */
  160468. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160469. #define jpeg_std_error jStdError
  160470. #define jpeg_CreateCompress jCreaCompress
  160471. #define jpeg_CreateDecompress jCreaDecompress
  160472. #define jpeg_destroy_compress jDestCompress
  160473. #define jpeg_destroy_decompress jDestDecompress
  160474. #define jpeg_stdio_dest jStdDest
  160475. #define jpeg_stdio_src jStdSrc
  160476. #define jpeg_set_defaults jSetDefaults
  160477. #define jpeg_set_colorspace jSetColorspace
  160478. #define jpeg_default_colorspace jDefColorspace
  160479. #define jpeg_set_quality jSetQuality
  160480. #define jpeg_set_linear_quality jSetLQuality
  160481. #define jpeg_add_quant_table jAddQuantTable
  160482. #define jpeg_quality_scaling jQualityScaling
  160483. #define jpeg_simple_progression jSimProgress
  160484. #define jpeg_suppress_tables jSuppressTables
  160485. #define jpeg_alloc_quant_table jAlcQTable
  160486. #define jpeg_alloc_huff_table jAlcHTable
  160487. #define jpeg_start_compress jStrtCompress
  160488. #define jpeg_write_scanlines jWrtScanlines
  160489. #define jpeg_finish_compress jFinCompress
  160490. #define jpeg_write_raw_data jWrtRawData
  160491. #define jpeg_write_marker jWrtMarker
  160492. #define jpeg_write_m_header jWrtMHeader
  160493. #define jpeg_write_m_byte jWrtMByte
  160494. #define jpeg_write_tables jWrtTables
  160495. #define jpeg_read_header jReadHeader
  160496. #define jpeg_start_decompress jStrtDecompress
  160497. #define jpeg_read_scanlines jReadScanlines
  160498. #define jpeg_finish_decompress jFinDecompress
  160499. #define jpeg_read_raw_data jReadRawData
  160500. #define jpeg_has_multiple_scans jHasMultScn
  160501. #define jpeg_start_output jStrtOutput
  160502. #define jpeg_finish_output jFinOutput
  160503. #define jpeg_input_complete jInComplete
  160504. #define jpeg_new_colormap jNewCMap
  160505. #define jpeg_consume_input jConsumeInput
  160506. #define jpeg_calc_output_dimensions jCalcDimensions
  160507. #define jpeg_save_markers jSaveMarkers
  160508. #define jpeg_set_marker_processor jSetMarker
  160509. #define jpeg_read_coefficients jReadCoefs
  160510. #define jpeg_write_coefficients jWrtCoefs
  160511. #define jpeg_copy_critical_parameters jCopyCrit
  160512. #define jpeg_abort_compress jAbrtCompress
  160513. #define jpeg_abort_decompress jAbrtDecompress
  160514. #define jpeg_abort jAbort
  160515. #define jpeg_destroy jDestroy
  160516. #define jpeg_resync_to_restart jResyncRestart
  160517. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160518. /* Default error-management setup */
  160519. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160520. JPP((struct jpeg_error_mgr * err));
  160521. /* Initialization of JPEG compression objects.
  160522. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160523. * names that applications should call. These expand to calls on
  160524. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160525. * passed for version mismatch checking.
  160526. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160527. */
  160528. #define jpeg_create_compress(cinfo) \
  160529. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160530. (size_t) sizeof(struct jpeg_compress_struct))
  160531. #define jpeg_create_decompress(cinfo) \
  160532. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160533. (size_t) sizeof(struct jpeg_decompress_struct))
  160534. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160535. int version, size_t structsize));
  160536. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160537. int version, size_t structsize));
  160538. /* Destruction of JPEG compression objects */
  160539. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160540. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160541. /* Standard data source and destination managers: stdio streams. */
  160542. /* Caller is responsible for opening the file before and closing after. */
  160543. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160544. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160545. /* Default parameter setup for compression */
  160546. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160547. /* Compression parameter setup aids */
  160548. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160549. J_COLOR_SPACE colorspace));
  160550. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160551. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160552. boolean force_baseline));
  160553. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160554. int scale_factor,
  160555. boolean force_baseline));
  160556. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160557. const unsigned int *basic_table,
  160558. int scale_factor,
  160559. boolean force_baseline));
  160560. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160561. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160562. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160563. boolean suppress));
  160564. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160565. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160566. /* Main entry points for compression */
  160567. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160568. boolean write_all_tables));
  160569. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160570. JSAMPARRAY scanlines,
  160571. JDIMENSION num_lines));
  160572. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160573. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160574. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160575. JSAMPIMAGE data,
  160576. JDIMENSION num_lines));
  160577. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160578. EXTERN(void) jpeg_write_marker
  160579. JPP((j_compress_ptr cinfo, int marker,
  160580. const JOCTET * dataptr, unsigned int datalen));
  160581. /* Same, but piecemeal. */
  160582. EXTERN(void) jpeg_write_m_header
  160583. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160584. EXTERN(void) jpeg_write_m_byte
  160585. JPP((j_compress_ptr cinfo, int val));
  160586. /* Alternate compression function: just write an abbreviated table file */
  160587. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160588. /* Decompression startup: read start of JPEG datastream to see what's there */
  160589. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160590. boolean require_image));
  160591. /* Return value is one of: */
  160592. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160593. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160594. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160595. /* If you pass require_image = TRUE (normal case), you need not check for
  160596. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160597. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160598. * give a suspension return (the stdio source module doesn't).
  160599. */
  160600. /* Main entry points for decompression */
  160601. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160602. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160603. JSAMPARRAY scanlines,
  160604. JDIMENSION max_lines));
  160605. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160606. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160607. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160608. JSAMPIMAGE data,
  160609. JDIMENSION max_lines));
  160610. /* Additional entry points for buffered-image mode. */
  160611. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160612. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160613. int scan_number));
  160614. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160615. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160616. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160617. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160618. /* Return value is one of: */
  160619. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160620. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160621. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160622. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160623. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160624. /* Precalculate output dimensions for current decompression parameters. */
  160625. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160626. /* Control saving of COM and APPn markers into marker_list. */
  160627. EXTERN(void) jpeg_save_markers
  160628. JPP((j_decompress_ptr cinfo, int marker_code,
  160629. unsigned int length_limit));
  160630. /* Install a special processing method for COM or APPn markers. */
  160631. EXTERN(void) jpeg_set_marker_processor
  160632. JPP((j_decompress_ptr cinfo, int marker_code,
  160633. jpeg_marker_parser_method routine));
  160634. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160635. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160636. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160637. jvirt_barray_ptr * coef_arrays));
  160638. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160639. j_compress_ptr dstinfo));
  160640. /* If you choose to abort compression or decompression before completing
  160641. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160642. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160643. * if you're done with the JPEG object, but if you want to clean it up and
  160644. * reuse it, call this:
  160645. */
  160646. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160647. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160648. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160649. * flavor of JPEG object. These may be more convenient in some places.
  160650. */
  160651. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160652. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160653. /* Default restart-marker-resync procedure for use by data source modules */
  160654. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160655. int desired));
  160656. /* These marker codes are exported since applications and data source modules
  160657. * are likely to want to use them.
  160658. */
  160659. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160660. #define JPEG_EOI 0xD9 /* EOI marker code */
  160661. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160662. #define JPEG_COM 0xFE /* COM marker code */
  160663. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160664. * for structure definitions that are never filled in, keep it quiet by
  160665. * supplying dummy definitions for the various substructures.
  160666. */
  160667. #ifdef INCOMPLETE_TYPES_BROKEN
  160668. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160669. struct jvirt_sarray_control { long dummy; };
  160670. struct jvirt_barray_control { long dummy; };
  160671. struct jpeg_comp_master { long dummy; };
  160672. struct jpeg_c_main_controller { long dummy; };
  160673. struct jpeg_c_prep_controller { long dummy; };
  160674. struct jpeg_c_coef_controller { long dummy; };
  160675. struct jpeg_marker_writer { long dummy; };
  160676. struct jpeg_color_converter { long dummy; };
  160677. struct jpeg_downsampler { long dummy; };
  160678. struct jpeg_forward_dct { long dummy; };
  160679. struct jpeg_entropy_encoder { long dummy; };
  160680. struct jpeg_decomp_master { long dummy; };
  160681. struct jpeg_d_main_controller { long dummy; };
  160682. struct jpeg_d_coef_controller { long dummy; };
  160683. struct jpeg_d_post_controller { long dummy; };
  160684. struct jpeg_input_controller { long dummy; };
  160685. struct jpeg_marker_reader { long dummy; };
  160686. struct jpeg_entropy_decoder { long dummy; };
  160687. struct jpeg_inverse_dct { long dummy; };
  160688. struct jpeg_upsampler { long dummy; };
  160689. struct jpeg_color_deconverter { long dummy; };
  160690. struct jpeg_color_quantizer { long dummy; };
  160691. #endif /* JPEG_INTERNALS */
  160692. #endif /* INCOMPLETE_TYPES_BROKEN */
  160693. /*
  160694. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160695. * The internal structure declarations are read only when that is true.
  160696. * Applications using the library should not include jpegint.h, but may wish
  160697. * to include jerror.h.
  160698. */
  160699. #ifdef JPEG_INTERNALS
  160700. /*** Start of inlined file: jpegint.h ***/
  160701. /* Declarations for both compression & decompression */
  160702. typedef enum { /* Operating modes for buffer controllers */
  160703. JBUF_PASS_THRU, /* Plain stripwise operation */
  160704. /* Remaining modes require a full-image buffer to have been created */
  160705. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160706. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160707. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160708. } J_BUF_MODE;
  160709. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160710. #define CSTATE_START 100 /* after create_compress */
  160711. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160712. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160713. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160714. #define DSTATE_START 200 /* after create_decompress */
  160715. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160716. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160717. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160718. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160719. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160720. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160721. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160722. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160723. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160724. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160725. /* Declarations for compression modules */
  160726. /* Master control module */
  160727. struct jpeg_comp_master {
  160728. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160729. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160730. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160731. /* State variables made visible to other modules */
  160732. boolean call_pass_startup; /* True if pass_startup must be called */
  160733. boolean is_last_pass; /* True during last pass */
  160734. };
  160735. /* Main buffer control (downsampled-data buffer) */
  160736. struct jpeg_c_main_controller {
  160737. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160738. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160739. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160740. JDIMENSION in_rows_avail));
  160741. };
  160742. /* Compression preprocessing (downsampling input buffer control) */
  160743. struct jpeg_c_prep_controller {
  160744. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160745. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160746. JSAMPARRAY input_buf,
  160747. JDIMENSION *in_row_ctr,
  160748. JDIMENSION in_rows_avail,
  160749. JSAMPIMAGE output_buf,
  160750. JDIMENSION *out_row_group_ctr,
  160751. JDIMENSION out_row_groups_avail));
  160752. };
  160753. /* Coefficient buffer control */
  160754. struct jpeg_c_coef_controller {
  160755. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160756. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160757. JSAMPIMAGE input_buf));
  160758. };
  160759. /* Colorspace conversion */
  160760. struct jpeg_color_converter {
  160761. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160762. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160763. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160764. JDIMENSION output_row, int num_rows));
  160765. };
  160766. /* Downsampling */
  160767. struct jpeg_downsampler {
  160768. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160769. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160770. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160771. JSAMPIMAGE output_buf,
  160772. JDIMENSION out_row_group_index));
  160773. boolean need_context_rows; /* TRUE if need rows above & below */
  160774. };
  160775. /* Forward DCT (also controls coefficient quantization) */
  160776. struct jpeg_forward_dct {
  160777. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160778. /* perhaps this should be an array??? */
  160779. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160780. jpeg_component_info * compptr,
  160781. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160782. JDIMENSION start_row, JDIMENSION start_col,
  160783. JDIMENSION num_blocks));
  160784. };
  160785. /* Entropy encoding */
  160786. struct jpeg_entropy_encoder {
  160787. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160788. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160789. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160790. };
  160791. /* Marker writing */
  160792. struct jpeg_marker_writer {
  160793. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160794. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160795. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160796. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160797. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160798. /* These routines are exported to allow insertion of extra markers */
  160799. /* Probably only COM and APPn markers should be written this way */
  160800. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160801. unsigned int datalen));
  160802. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160803. };
  160804. /* Declarations for decompression modules */
  160805. /* Master control module */
  160806. struct jpeg_decomp_master {
  160807. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160808. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160809. /* State variables made visible to other modules */
  160810. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160811. };
  160812. /* Input control module */
  160813. struct jpeg_input_controller {
  160814. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160815. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160816. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160817. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160818. /* State variables made visible to other modules */
  160819. boolean has_multiple_scans; /* True if file has multiple scans */
  160820. boolean eoi_reached; /* True when EOI has been consumed */
  160821. };
  160822. /* Main buffer control (downsampled-data buffer) */
  160823. struct jpeg_d_main_controller {
  160824. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160825. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160826. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160827. JDIMENSION out_rows_avail));
  160828. };
  160829. /* Coefficient buffer control */
  160830. struct jpeg_d_coef_controller {
  160831. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160832. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160833. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160834. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160835. JSAMPIMAGE output_buf));
  160836. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160837. jvirt_barray_ptr *coef_arrays;
  160838. };
  160839. /* Decompression postprocessing (color quantization buffer control) */
  160840. struct jpeg_d_post_controller {
  160841. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160842. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160843. JSAMPIMAGE input_buf,
  160844. JDIMENSION *in_row_group_ctr,
  160845. JDIMENSION in_row_groups_avail,
  160846. JSAMPARRAY output_buf,
  160847. JDIMENSION *out_row_ctr,
  160848. JDIMENSION out_rows_avail));
  160849. };
  160850. /* Marker reading & parsing */
  160851. struct jpeg_marker_reader {
  160852. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160853. /* Read markers until SOS or EOI.
  160854. * Returns same codes as are defined for jpeg_consume_input:
  160855. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160856. */
  160857. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160858. /* Read a restart marker --- exported for use by entropy decoder only */
  160859. jpeg_marker_parser_method read_restart_marker;
  160860. /* State of marker reader --- nominally internal, but applications
  160861. * supplying COM or APPn handlers might like to know the state.
  160862. */
  160863. boolean saw_SOI; /* found SOI? */
  160864. boolean saw_SOF; /* found SOF? */
  160865. int next_restart_num; /* next restart number expected (0-7) */
  160866. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160867. };
  160868. /* Entropy decoding */
  160869. struct jpeg_entropy_decoder {
  160870. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160871. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160872. JBLOCKROW *MCU_data));
  160873. /* This is here to share code between baseline and progressive decoders; */
  160874. /* other modules probably should not use it */
  160875. boolean insufficient_data; /* set TRUE after emitting warning */
  160876. };
  160877. /* Inverse DCT (also performs dequantization) */
  160878. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160879. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160880. JCOEFPTR coef_block,
  160881. JSAMPARRAY output_buf, JDIMENSION output_col));
  160882. struct jpeg_inverse_dct {
  160883. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160884. /* It is useful to allow each component to have a separate IDCT method. */
  160885. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160886. };
  160887. /* Upsampling (note that upsampler must also call color converter) */
  160888. struct jpeg_upsampler {
  160889. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160890. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160891. JSAMPIMAGE input_buf,
  160892. JDIMENSION *in_row_group_ctr,
  160893. JDIMENSION in_row_groups_avail,
  160894. JSAMPARRAY output_buf,
  160895. JDIMENSION *out_row_ctr,
  160896. JDIMENSION out_rows_avail));
  160897. boolean need_context_rows; /* TRUE if need rows above & below */
  160898. };
  160899. /* Colorspace conversion */
  160900. struct jpeg_color_deconverter {
  160901. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160902. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160903. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160904. JSAMPARRAY output_buf, int num_rows));
  160905. };
  160906. /* Color quantization or color precision reduction */
  160907. struct jpeg_color_quantizer {
  160908. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160909. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160910. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160911. int num_rows));
  160912. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160913. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160914. };
  160915. /* Miscellaneous useful macros */
  160916. #undef MAX
  160917. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160918. #undef MIN
  160919. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160920. /* We assume that right shift corresponds to signed division by 2 with
  160921. * rounding towards minus infinity. This is correct for typical "arithmetic
  160922. * shift" instructions that shift in copies of the sign bit. But some
  160923. * C compilers implement >> with an unsigned shift. For these machines you
  160924. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160925. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160926. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160927. * included in the variables of any routine using RIGHT_SHIFT.
  160928. */
  160929. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160930. #define SHIFT_TEMPS INT32 shift_temp;
  160931. #define RIGHT_SHIFT(x,shft) \
  160932. ((shift_temp = (x)) < 0 ? \
  160933. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160934. (shift_temp >> (shft)))
  160935. #else
  160936. #define SHIFT_TEMPS
  160937. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160938. #endif
  160939. /* Short forms of external names for systems with brain-damaged linkers. */
  160940. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160941. #define jinit_compress_master jICompress
  160942. #define jinit_c_master_control jICMaster
  160943. #define jinit_c_main_controller jICMainC
  160944. #define jinit_c_prep_controller jICPrepC
  160945. #define jinit_c_coef_controller jICCoefC
  160946. #define jinit_color_converter jICColor
  160947. #define jinit_downsampler jIDownsampler
  160948. #define jinit_forward_dct jIFDCT
  160949. #define jinit_huff_encoder jIHEncoder
  160950. #define jinit_phuff_encoder jIPHEncoder
  160951. #define jinit_marker_writer jIMWriter
  160952. #define jinit_master_decompress jIDMaster
  160953. #define jinit_d_main_controller jIDMainC
  160954. #define jinit_d_coef_controller jIDCoefC
  160955. #define jinit_d_post_controller jIDPostC
  160956. #define jinit_input_controller jIInCtlr
  160957. #define jinit_marker_reader jIMReader
  160958. #define jinit_huff_decoder jIHDecoder
  160959. #define jinit_phuff_decoder jIPHDecoder
  160960. #define jinit_inverse_dct jIIDCT
  160961. #define jinit_upsampler jIUpsampler
  160962. #define jinit_color_deconverter jIDColor
  160963. #define jinit_1pass_quantizer jI1Quant
  160964. #define jinit_2pass_quantizer jI2Quant
  160965. #define jinit_merged_upsampler jIMUpsampler
  160966. #define jinit_memory_mgr jIMemMgr
  160967. #define jdiv_round_up jDivRound
  160968. #define jround_up jRound
  160969. #define jcopy_sample_rows jCopySamples
  160970. #define jcopy_block_row jCopyBlocks
  160971. #define jzero_far jZeroFar
  160972. #define jpeg_zigzag_order jZIGTable
  160973. #define jpeg_natural_order jZAGTable
  160974. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160975. /* Compression module initialization routines */
  160976. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160977. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160978. boolean transcode_only));
  160979. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160980. boolean need_full_buffer));
  160981. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160982. boolean need_full_buffer));
  160983. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160984. boolean need_full_buffer));
  160985. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160986. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160987. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160988. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160989. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160990. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160991. /* Decompression module initialization routines */
  160992. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160993. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160994. boolean need_full_buffer));
  160995. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160996. boolean need_full_buffer));
  160997. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160998. boolean need_full_buffer));
  160999. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161000. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161001. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161002. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161003. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161004. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161005. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161006. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161007. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161008. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161009. /* Memory manager initialization */
  161010. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161011. /* Utility routines in jutils.c */
  161012. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161013. EXTERN(long) jround_up JPP((long a, long b));
  161014. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161015. JSAMPARRAY output_array, int dest_row,
  161016. int num_rows, JDIMENSION num_cols));
  161017. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161018. JDIMENSION num_blocks));
  161019. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161020. /* Constant tables in jutils.c */
  161021. #if 0 /* This table is not actually needed in v6a */
  161022. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161023. #endif
  161024. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161025. /* Suppress undefined-structure complaints if necessary. */
  161026. #ifdef INCOMPLETE_TYPES_BROKEN
  161027. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161028. struct jvirt_sarray_control { long dummy; };
  161029. struct jvirt_barray_control { long dummy; };
  161030. #endif
  161031. #endif /* INCOMPLETE_TYPES_BROKEN */
  161032. /*** End of inlined file: jpegint.h ***/
  161033. /* fetch private declarations */
  161034. /*** Start of inlined file: jerror.h ***/
  161035. /*
  161036. * To define the enum list of message codes, include this file without
  161037. * defining macro JMESSAGE. To create a message string table, include it
  161038. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161039. */
  161040. #ifndef JMESSAGE
  161041. #ifndef JERROR_H
  161042. /* First time through, define the enum list */
  161043. #define JMAKE_ENUM_LIST
  161044. #else
  161045. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161046. #define JMESSAGE(code,string)
  161047. #endif /* JERROR_H */
  161048. #endif /* JMESSAGE */
  161049. #ifdef JMAKE_ENUM_LIST
  161050. typedef enum {
  161051. #define JMESSAGE(code,string) code ,
  161052. #endif /* JMAKE_ENUM_LIST */
  161053. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161054. /* For maintenance convenience, list is alphabetical by message code name */
  161055. JMESSAGE(JERR_ARITH_NOTIMPL,
  161056. "Sorry, there are legal restrictions on arithmetic coding")
  161057. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161058. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161059. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161060. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161061. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161062. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161063. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161064. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161065. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161066. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161067. JMESSAGE(JERR_BAD_LIB_VERSION,
  161068. "Wrong JPEG library version: library is %d, caller expects %d")
  161069. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161070. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161071. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161072. JMESSAGE(JERR_BAD_PROGRESSION,
  161073. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161074. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161075. "Invalid progressive parameters at scan script entry %d")
  161076. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161077. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161078. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161079. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161080. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161081. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161082. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161083. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161084. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161085. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161086. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161087. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161088. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161089. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161090. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161091. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161092. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161093. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161094. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161095. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161096. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161097. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161098. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161099. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161100. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161101. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161102. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161103. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161104. "Cannot transcode due to multiple use of quantization table %d")
  161105. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161106. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161107. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161108. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161109. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161110. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161111. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161112. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161113. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161114. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161115. JMESSAGE(JERR_QUANT_COMPONENTS,
  161116. "Cannot quantize more than %d color components")
  161117. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161118. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161119. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161120. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161121. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161122. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161123. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161124. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161125. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161126. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161127. JMESSAGE(JERR_TFILE_WRITE,
  161128. "Write failed on temporary file --- out of disk space?")
  161129. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161130. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161131. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161132. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161133. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161134. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161135. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161136. JMESSAGE(JMSG_VERSION, JVERSION)
  161137. JMESSAGE(JTRC_16BIT_TABLES,
  161138. "Caution: quantization tables are too coarse for baseline JPEG")
  161139. JMESSAGE(JTRC_ADOBE,
  161140. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161141. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161142. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161143. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161144. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161145. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161146. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161147. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161148. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161149. JMESSAGE(JTRC_EOI, "End Of Image")
  161150. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161151. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161152. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161153. "Warning: thumbnail image size does not match data length %u")
  161154. JMESSAGE(JTRC_JFIF_EXTENSION,
  161155. "JFIF extension marker: type 0x%02x, length %u")
  161156. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161157. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161158. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161159. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161160. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161161. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161162. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161163. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161164. JMESSAGE(JTRC_RST, "RST%d")
  161165. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161166. "Smoothing not supported with nonstandard sampling ratios")
  161167. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161168. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161169. JMESSAGE(JTRC_SOI, "Start of Image")
  161170. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161171. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161172. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161173. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161174. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161175. JMESSAGE(JTRC_THUMB_JPEG,
  161176. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161177. JMESSAGE(JTRC_THUMB_PALETTE,
  161178. "JFIF extension marker: palette thumbnail image, length %u")
  161179. JMESSAGE(JTRC_THUMB_RGB,
  161180. "JFIF extension marker: RGB thumbnail image, length %u")
  161181. JMESSAGE(JTRC_UNKNOWN_IDS,
  161182. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161183. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161184. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161185. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161186. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161187. "Inconsistent progression sequence for component %d coefficient %d")
  161188. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161189. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161190. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161191. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161192. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161193. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161194. JMESSAGE(JWRN_MUST_RESYNC,
  161195. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161196. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161197. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161198. #ifdef JMAKE_ENUM_LIST
  161199. JMSG_LASTMSGCODE
  161200. } J_MESSAGE_CODE;
  161201. #undef JMAKE_ENUM_LIST
  161202. #endif /* JMAKE_ENUM_LIST */
  161203. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161204. #undef JMESSAGE
  161205. #ifndef JERROR_H
  161206. #define JERROR_H
  161207. /* Macros to simplify using the error and trace message stuff */
  161208. /* The first parameter is either type of cinfo pointer */
  161209. /* Fatal errors (print message and exit) */
  161210. #define ERREXIT(cinfo,code) \
  161211. ((cinfo)->err->msg_code = (code), \
  161212. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161213. #define ERREXIT1(cinfo,code,p1) \
  161214. ((cinfo)->err->msg_code = (code), \
  161215. (cinfo)->err->msg_parm.i[0] = (p1), \
  161216. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161217. #define ERREXIT2(cinfo,code,p1,p2) \
  161218. ((cinfo)->err->msg_code = (code), \
  161219. (cinfo)->err->msg_parm.i[0] = (p1), \
  161220. (cinfo)->err->msg_parm.i[1] = (p2), \
  161221. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161222. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161223. ((cinfo)->err->msg_code = (code), \
  161224. (cinfo)->err->msg_parm.i[0] = (p1), \
  161225. (cinfo)->err->msg_parm.i[1] = (p2), \
  161226. (cinfo)->err->msg_parm.i[2] = (p3), \
  161227. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161228. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161229. ((cinfo)->err->msg_code = (code), \
  161230. (cinfo)->err->msg_parm.i[0] = (p1), \
  161231. (cinfo)->err->msg_parm.i[1] = (p2), \
  161232. (cinfo)->err->msg_parm.i[2] = (p3), \
  161233. (cinfo)->err->msg_parm.i[3] = (p4), \
  161234. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161235. #define ERREXITS(cinfo,code,str) \
  161236. ((cinfo)->err->msg_code = (code), \
  161237. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161238. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161239. #define MAKESTMT(stuff) do { stuff } while (0)
  161240. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161241. #define WARNMS(cinfo,code) \
  161242. ((cinfo)->err->msg_code = (code), \
  161243. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161244. #define WARNMS1(cinfo,code,p1) \
  161245. ((cinfo)->err->msg_code = (code), \
  161246. (cinfo)->err->msg_parm.i[0] = (p1), \
  161247. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161248. #define WARNMS2(cinfo,code,p1,p2) \
  161249. ((cinfo)->err->msg_code = (code), \
  161250. (cinfo)->err->msg_parm.i[0] = (p1), \
  161251. (cinfo)->err->msg_parm.i[1] = (p2), \
  161252. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161253. /* Informational/debugging messages */
  161254. #define TRACEMS(cinfo,lvl,code) \
  161255. ((cinfo)->err->msg_code = (code), \
  161256. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161257. #define TRACEMS1(cinfo,lvl,code,p1) \
  161258. ((cinfo)->err->msg_code = (code), \
  161259. (cinfo)->err->msg_parm.i[0] = (p1), \
  161260. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161261. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161262. ((cinfo)->err->msg_code = (code), \
  161263. (cinfo)->err->msg_parm.i[0] = (p1), \
  161264. (cinfo)->err->msg_parm.i[1] = (p2), \
  161265. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161266. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161267. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161268. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161269. (cinfo)->err->msg_code = (code); \
  161270. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161271. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161272. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161273. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161274. (cinfo)->err->msg_code = (code); \
  161275. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161276. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161277. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161278. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161279. _mp[4] = (p5); \
  161280. (cinfo)->err->msg_code = (code); \
  161281. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161282. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161283. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161284. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161285. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161286. (cinfo)->err->msg_code = (code); \
  161287. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161288. #define TRACEMSS(cinfo,lvl,code,str) \
  161289. ((cinfo)->err->msg_code = (code), \
  161290. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161291. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161292. #endif /* JERROR_H */
  161293. /*** End of inlined file: jerror.h ***/
  161294. /* fetch error codes too */
  161295. #endif
  161296. #endif /* JPEGLIB_H */
  161297. /*** End of inlined file: jpeglib.h ***/
  161298. /*** Start of inlined file: jcapimin.c ***/
  161299. #define JPEG_INTERNALS
  161300. /*** Start of inlined file: jinclude.h ***/
  161301. /* Include auto-config file to find out which system include files we need. */
  161302. #ifndef __jinclude_h__
  161303. #define __jinclude_h__
  161304. /*** Start of inlined file: jconfig.h ***/
  161305. /* see jconfig.doc for explanations */
  161306. // disable all the warnings under MSVC
  161307. #ifdef _MSC_VER
  161308. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161309. #endif
  161310. #ifdef __BORLANDC__
  161311. #pragma warn -8057
  161312. #pragma warn -8019
  161313. #pragma warn -8004
  161314. #pragma warn -8008
  161315. #endif
  161316. #define HAVE_PROTOTYPES
  161317. #define HAVE_UNSIGNED_CHAR
  161318. #define HAVE_UNSIGNED_SHORT
  161319. /* #define void char */
  161320. /* #define const */
  161321. #undef CHAR_IS_UNSIGNED
  161322. #define HAVE_STDDEF_H
  161323. #define HAVE_STDLIB_H
  161324. #undef NEED_BSD_STRINGS
  161325. #undef NEED_SYS_TYPES_H
  161326. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161327. #undef NEED_SHORT_EXTERNAL_NAMES
  161328. #undef INCOMPLETE_TYPES_BROKEN
  161329. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161330. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161331. typedef unsigned char boolean;
  161332. #endif
  161333. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161334. #ifdef JPEG_INTERNALS
  161335. #undef RIGHT_SHIFT_IS_UNSIGNED
  161336. #endif /* JPEG_INTERNALS */
  161337. #ifdef JPEG_CJPEG_DJPEG
  161338. #define BMP_SUPPORTED /* BMP image file format */
  161339. #define GIF_SUPPORTED /* GIF image file format */
  161340. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161341. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161342. #define TARGA_SUPPORTED /* Targa image file format */
  161343. #define TWO_FILE_COMMANDLINE /* optional */
  161344. #define USE_SETMODE /* Microsoft has setmode() */
  161345. #undef NEED_SIGNAL_CATCHER
  161346. #undef DONT_USE_B_MODE
  161347. #undef PROGRESS_REPORT /* optional */
  161348. #endif /* JPEG_CJPEG_DJPEG */
  161349. /*** End of inlined file: jconfig.h ***/
  161350. /* auto configuration options */
  161351. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161352. /*
  161353. * We need the NULL macro and size_t typedef.
  161354. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161355. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161356. * pull in <sys/types.h> as well.
  161357. * Note that the core JPEG library does not require <stdio.h>;
  161358. * only the default error handler and data source/destination modules do.
  161359. * But we must pull it in because of the references to FILE in jpeglib.h.
  161360. * You can remove those references if you want to compile without <stdio.h>.
  161361. */
  161362. #ifdef HAVE_STDDEF_H
  161363. #include <stddef.h>
  161364. #endif
  161365. #ifdef HAVE_STDLIB_H
  161366. #include <stdlib.h>
  161367. #endif
  161368. #ifdef NEED_SYS_TYPES_H
  161369. #include <sys/types.h>
  161370. #endif
  161371. #include <stdio.h>
  161372. /*
  161373. * We need memory copying and zeroing functions, plus strncpy().
  161374. * ANSI and System V implementations declare these in <string.h>.
  161375. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161376. * Some systems may declare memset and memcpy in <memory.h>.
  161377. *
  161378. * NOTE: we assume the size parameters to these functions are of type size_t.
  161379. * Change the casts in these macros if not!
  161380. */
  161381. #ifdef NEED_BSD_STRINGS
  161382. #include <strings.h>
  161383. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161384. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161385. #else /* not BSD, assume ANSI/SysV string lib */
  161386. #include <string.h>
  161387. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161388. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161389. #endif
  161390. /*
  161391. * In ANSI C, and indeed any rational implementation, size_t is also the
  161392. * type returned by sizeof(). However, it seems there are some irrational
  161393. * implementations out there, in which sizeof() returns an int even though
  161394. * size_t is defined as long or unsigned long. To ensure consistent results
  161395. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161396. */
  161397. #define SIZEOF(object) ((size_t) sizeof(object))
  161398. /*
  161399. * The modules that use fread() and fwrite() always invoke them through
  161400. * these macros. On some systems you may need to twiddle the argument casts.
  161401. * CAUTION: argument order is different from underlying functions!
  161402. */
  161403. #define JFREAD(file,buf,sizeofbuf) \
  161404. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161405. #define JFWRITE(file,buf,sizeofbuf) \
  161406. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161407. typedef enum { /* JPEG marker codes */
  161408. M_SOF0 = 0xc0,
  161409. M_SOF1 = 0xc1,
  161410. M_SOF2 = 0xc2,
  161411. M_SOF3 = 0xc3,
  161412. M_SOF5 = 0xc5,
  161413. M_SOF6 = 0xc6,
  161414. M_SOF7 = 0xc7,
  161415. M_JPG = 0xc8,
  161416. M_SOF9 = 0xc9,
  161417. M_SOF10 = 0xca,
  161418. M_SOF11 = 0xcb,
  161419. M_SOF13 = 0xcd,
  161420. M_SOF14 = 0xce,
  161421. M_SOF15 = 0xcf,
  161422. M_DHT = 0xc4,
  161423. M_DAC = 0xcc,
  161424. M_RST0 = 0xd0,
  161425. M_RST1 = 0xd1,
  161426. M_RST2 = 0xd2,
  161427. M_RST3 = 0xd3,
  161428. M_RST4 = 0xd4,
  161429. M_RST5 = 0xd5,
  161430. M_RST6 = 0xd6,
  161431. M_RST7 = 0xd7,
  161432. M_SOI = 0xd8,
  161433. M_EOI = 0xd9,
  161434. M_SOS = 0xda,
  161435. M_DQT = 0xdb,
  161436. M_DNL = 0xdc,
  161437. M_DRI = 0xdd,
  161438. M_DHP = 0xde,
  161439. M_EXP = 0xdf,
  161440. M_APP0 = 0xe0,
  161441. M_APP1 = 0xe1,
  161442. M_APP2 = 0xe2,
  161443. M_APP3 = 0xe3,
  161444. M_APP4 = 0xe4,
  161445. M_APP5 = 0xe5,
  161446. M_APP6 = 0xe6,
  161447. M_APP7 = 0xe7,
  161448. M_APP8 = 0xe8,
  161449. M_APP9 = 0xe9,
  161450. M_APP10 = 0xea,
  161451. M_APP11 = 0xeb,
  161452. M_APP12 = 0xec,
  161453. M_APP13 = 0xed,
  161454. M_APP14 = 0xee,
  161455. M_APP15 = 0xef,
  161456. M_JPG0 = 0xf0,
  161457. M_JPG13 = 0xfd,
  161458. M_COM = 0xfe,
  161459. M_TEM = 0x01,
  161460. M_ERROR = 0x100
  161461. } JPEG_MARKER;
  161462. /*
  161463. * Figure F.12: extend sign bit.
  161464. * On some machines, a shift and add will be faster than a table lookup.
  161465. */
  161466. #ifdef AVOID_TABLES
  161467. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161468. #else
  161469. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161470. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161471. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161472. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161473. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161474. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161475. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161476. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161477. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161478. #endif /* AVOID_TABLES */
  161479. #endif
  161480. /*** End of inlined file: jinclude.h ***/
  161481. /*
  161482. * Initialization of a JPEG compression object.
  161483. * The error manager must already be set up (in case memory manager fails).
  161484. */
  161485. GLOBAL(void)
  161486. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161487. {
  161488. int i;
  161489. /* Guard against version mismatches between library and caller. */
  161490. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161491. if (version != JPEG_LIB_VERSION)
  161492. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161493. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161494. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161495. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161496. /* For debugging purposes, we zero the whole master structure.
  161497. * But the application has already set the err pointer, and may have set
  161498. * client_data, so we have to save and restore those fields.
  161499. * Note: if application hasn't set client_data, tools like Purify may
  161500. * complain here.
  161501. */
  161502. {
  161503. struct jpeg_error_mgr * err = cinfo->err;
  161504. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161505. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161506. cinfo->err = err;
  161507. cinfo->client_data = client_data;
  161508. }
  161509. cinfo->is_decompressor = FALSE;
  161510. /* Initialize a memory manager instance for this object */
  161511. jinit_memory_mgr((j_common_ptr) cinfo);
  161512. /* Zero out pointers to permanent structures. */
  161513. cinfo->progress = NULL;
  161514. cinfo->dest = NULL;
  161515. cinfo->comp_info = NULL;
  161516. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161517. cinfo->quant_tbl_ptrs[i] = NULL;
  161518. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161519. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161520. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161521. }
  161522. cinfo->script_space = NULL;
  161523. cinfo->input_gamma = 1.0; /* in case application forgets */
  161524. /* OK, I'm ready */
  161525. cinfo->global_state = CSTATE_START;
  161526. }
  161527. /*
  161528. * Destruction of a JPEG compression object
  161529. */
  161530. GLOBAL(void)
  161531. jpeg_destroy_compress (j_compress_ptr cinfo)
  161532. {
  161533. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161534. }
  161535. /*
  161536. * Abort processing of a JPEG compression operation,
  161537. * but don't destroy the object itself.
  161538. */
  161539. GLOBAL(void)
  161540. jpeg_abort_compress (j_compress_ptr cinfo)
  161541. {
  161542. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161543. }
  161544. /*
  161545. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161546. * Marks all currently defined tables as already written (if suppress)
  161547. * or not written (if !suppress). This will control whether they get emitted
  161548. * by a subsequent jpeg_start_compress call.
  161549. *
  161550. * This routine is exported for use by applications that want to produce
  161551. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161552. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161553. * jcparam.o would be linked whether the application used it or not.
  161554. */
  161555. GLOBAL(void)
  161556. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161557. {
  161558. int i;
  161559. JQUANT_TBL * qtbl;
  161560. JHUFF_TBL * htbl;
  161561. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161562. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161563. qtbl->sent_table = suppress;
  161564. }
  161565. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161566. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161567. htbl->sent_table = suppress;
  161568. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161569. htbl->sent_table = suppress;
  161570. }
  161571. }
  161572. /*
  161573. * Finish JPEG compression.
  161574. *
  161575. * If a multipass operating mode was selected, this may do a great deal of
  161576. * work including most of the actual output.
  161577. */
  161578. GLOBAL(void)
  161579. jpeg_finish_compress (j_compress_ptr cinfo)
  161580. {
  161581. JDIMENSION iMCU_row;
  161582. if (cinfo->global_state == CSTATE_SCANNING ||
  161583. cinfo->global_state == CSTATE_RAW_OK) {
  161584. /* Terminate first pass */
  161585. if (cinfo->next_scanline < cinfo->image_height)
  161586. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161587. (*cinfo->master->finish_pass) (cinfo);
  161588. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161589. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161590. /* Perform any remaining passes */
  161591. while (! cinfo->master->is_last_pass) {
  161592. (*cinfo->master->prepare_for_pass) (cinfo);
  161593. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161594. if (cinfo->progress != NULL) {
  161595. cinfo->progress->pass_counter = (long) iMCU_row;
  161596. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161597. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161598. }
  161599. /* We bypass the main controller and invoke coef controller directly;
  161600. * all work is being done from the coefficient buffer.
  161601. */
  161602. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161603. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161604. }
  161605. (*cinfo->master->finish_pass) (cinfo);
  161606. }
  161607. /* Write EOI, do final cleanup */
  161608. (*cinfo->marker->write_file_trailer) (cinfo);
  161609. (*cinfo->dest->term_destination) (cinfo);
  161610. /* We can use jpeg_abort to release memory and reset global_state */
  161611. jpeg_abort((j_common_ptr) cinfo);
  161612. }
  161613. /*
  161614. * Write a special marker.
  161615. * This is only recommended for writing COM or APPn markers.
  161616. * Must be called after jpeg_start_compress() and before
  161617. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161618. */
  161619. GLOBAL(void)
  161620. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161621. const JOCTET *dataptr, unsigned int datalen)
  161622. {
  161623. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161624. if (cinfo->next_scanline != 0 ||
  161625. (cinfo->global_state != CSTATE_SCANNING &&
  161626. cinfo->global_state != CSTATE_RAW_OK &&
  161627. cinfo->global_state != CSTATE_WRCOEFS))
  161628. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161629. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161630. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161631. while (datalen--) {
  161632. (*write_marker_byte) (cinfo, *dataptr);
  161633. dataptr++;
  161634. }
  161635. }
  161636. /* Same, but piecemeal. */
  161637. GLOBAL(void)
  161638. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161639. {
  161640. if (cinfo->next_scanline != 0 ||
  161641. (cinfo->global_state != CSTATE_SCANNING &&
  161642. cinfo->global_state != CSTATE_RAW_OK &&
  161643. cinfo->global_state != CSTATE_WRCOEFS))
  161644. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161645. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161646. }
  161647. GLOBAL(void)
  161648. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161649. {
  161650. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161651. }
  161652. /*
  161653. * Alternate compression function: just write an abbreviated table file.
  161654. * Before calling this, all parameters and a data destination must be set up.
  161655. *
  161656. * To produce a pair of files containing abbreviated tables and abbreviated
  161657. * image data, one would proceed as follows:
  161658. *
  161659. * initialize JPEG object
  161660. * set JPEG parameters
  161661. * set destination to table file
  161662. * jpeg_write_tables(cinfo);
  161663. * set destination to image file
  161664. * jpeg_start_compress(cinfo, FALSE);
  161665. * write data...
  161666. * jpeg_finish_compress(cinfo);
  161667. *
  161668. * jpeg_write_tables has the side effect of marking all tables written
  161669. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161670. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161671. */
  161672. GLOBAL(void)
  161673. jpeg_write_tables (j_compress_ptr cinfo)
  161674. {
  161675. if (cinfo->global_state != CSTATE_START)
  161676. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161677. /* (Re)initialize error mgr and destination modules */
  161678. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161679. (*cinfo->dest->init_destination) (cinfo);
  161680. /* Initialize the marker writer ... bit of a crock to do it here. */
  161681. jinit_marker_writer(cinfo);
  161682. /* Write them tables! */
  161683. (*cinfo->marker->write_tables_only) (cinfo);
  161684. /* And clean up. */
  161685. (*cinfo->dest->term_destination) (cinfo);
  161686. /*
  161687. * In library releases up through v6a, we called jpeg_abort() here to free
  161688. * any working memory allocated by the destination manager and marker
  161689. * writer. Some applications had a problem with that: they allocated space
  161690. * of their own from the library memory manager, and didn't want it to go
  161691. * away during write_tables. So now we do nothing. This will cause a
  161692. * memory leak if an app calls write_tables repeatedly without doing a full
  161693. * compression cycle or otherwise resetting the JPEG object. However, that
  161694. * seems less bad than unexpectedly freeing memory in the normal case.
  161695. * An app that prefers the old behavior can call jpeg_abort for itself after
  161696. * each call to jpeg_write_tables().
  161697. */
  161698. }
  161699. /*** End of inlined file: jcapimin.c ***/
  161700. /*** Start of inlined file: jcapistd.c ***/
  161701. #define JPEG_INTERNALS
  161702. /*
  161703. * Compression initialization.
  161704. * Before calling this, all parameters and a data destination must be set up.
  161705. *
  161706. * We require a write_all_tables parameter as a failsafe check when writing
  161707. * multiple datastreams from the same compression object. Since prior runs
  161708. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161709. * would emit an abbreviated stream (no tables) by default. This may be what
  161710. * is wanted, but for safety's sake it should not be the default behavior:
  161711. * programmers should have to make a deliberate choice to emit abbreviated
  161712. * images. Therefore the documentation and examples should encourage people
  161713. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161714. * wrong thing.
  161715. */
  161716. GLOBAL(void)
  161717. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161718. {
  161719. if (cinfo->global_state != CSTATE_START)
  161720. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161721. if (write_all_tables)
  161722. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161723. /* (Re)initialize error mgr and destination modules */
  161724. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161725. (*cinfo->dest->init_destination) (cinfo);
  161726. /* Perform master selection of active modules */
  161727. jinit_compress_master(cinfo);
  161728. /* Set up for the first pass */
  161729. (*cinfo->master->prepare_for_pass) (cinfo);
  161730. /* Ready for application to drive first pass through jpeg_write_scanlines
  161731. * or jpeg_write_raw_data.
  161732. */
  161733. cinfo->next_scanline = 0;
  161734. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161735. }
  161736. /*
  161737. * Write some scanlines of data to the JPEG compressor.
  161738. *
  161739. * The return value will be the number of lines actually written.
  161740. * This should be less than the supplied num_lines only in case that
  161741. * the data destination module has requested suspension of the compressor,
  161742. * or if more than image_height scanlines are passed in.
  161743. *
  161744. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161745. * this likely signals an application programmer error. However,
  161746. * excess scanlines passed in the last valid call are *silently* ignored,
  161747. * so that the application need not adjust num_lines for end-of-image
  161748. * when using a multiple-scanline buffer.
  161749. */
  161750. GLOBAL(JDIMENSION)
  161751. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161752. JDIMENSION num_lines)
  161753. {
  161754. JDIMENSION row_ctr, rows_left;
  161755. if (cinfo->global_state != CSTATE_SCANNING)
  161756. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161757. if (cinfo->next_scanline >= cinfo->image_height)
  161758. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161759. /* Call progress monitor hook if present */
  161760. if (cinfo->progress != NULL) {
  161761. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161762. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161763. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161764. }
  161765. /* Give master control module another chance if this is first call to
  161766. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161767. * delayed so that application can write COM, etc, markers between
  161768. * jpeg_start_compress and jpeg_write_scanlines.
  161769. */
  161770. if (cinfo->master->call_pass_startup)
  161771. (*cinfo->master->pass_startup) (cinfo);
  161772. /* Ignore any extra scanlines at bottom of image. */
  161773. rows_left = cinfo->image_height - cinfo->next_scanline;
  161774. if (num_lines > rows_left)
  161775. num_lines = rows_left;
  161776. row_ctr = 0;
  161777. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161778. cinfo->next_scanline += row_ctr;
  161779. return row_ctr;
  161780. }
  161781. /*
  161782. * Alternate entry point to write raw data.
  161783. * Processes exactly one iMCU row per call, unless suspended.
  161784. */
  161785. GLOBAL(JDIMENSION)
  161786. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161787. JDIMENSION num_lines)
  161788. {
  161789. JDIMENSION lines_per_iMCU_row;
  161790. if (cinfo->global_state != CSTATE_RAW_OK)
  161791. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161792. if (cinfo->next_scanline >= cinfo->image_height) {
  161793. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161794. return 0;
  161795. }
  161796. /* Call progress monitor hook if present */
  161797. if (cinfo->progress != NULL) {
  161798. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161799. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161800. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161801. }
  161802. /* Give master control module another chance if this is first call to
  161803. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161804. * delayed so that application can write COM, etc, markers between
  161805. * jpeg_start_compress and jpeg_write_raw_data.
  161806. */
  161807. if (cinfo->master->call_pass_startup)
  161808. (*cinfo->master->pass_startup) (cinfo);
  161809. /* Verify that at least one iMCU row has been passed. */
  161810. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161811. if (num_lines < lines_per_iMCU_row)
  161812. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161813. /* Directly compress the row. */
  161814. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161815. /* If compressor did not consume the whole row, suspend processing. */
  161816. return 0;
  161817. }
  161818. /* OK, we processed one iMCU row. */
  161819. cinfo->next_scanline += lines_per_iMCU_row;
  161820. return lines_per_iMCU_row;
  161821. }
  161822. /*** End of inlined file: jcapistd.c ***/
  161823. /*** Start of inlined file: jccoefct.c ***/
  161824. #define JPEG_INTERNALS
  161825. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161826. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161827. * step is run during the first pass, and subsequent passes need only read
  161828. * the buffered coefficients.
  161829. */
  161830. #ifdef ENTROPY_OPT_SUPPORTED
  161831. #define FULL_COEF_BUFFER_SUPPORTED
  161832. #else
  161833. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161834. #define FULL_COEF_BUFFER_SUPPORTED
  161835. #endif
  161836. #endif
  161837. /* Private buffer controller object */
  161838. typedef struct {
  161839. struct jpeg_c_coef_controller pub; /* public fields */
  161840. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161841. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161842. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161843. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161844. /* For single-pass compression, it's sufficient to buffer just one MCU
  161845. * (although this may prove a bit slow in practice). We allocate a
  161846. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161847. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161848. * it's not really very big; this is to keep the module interfaces unchanged
  161849. * when a large coefficient buffer is necessary.)
  161850. * In multi-pass modes, this array points to the current MCU's blocks
  161851. * within the virtual arrays.
  161852. */
  161853. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161854. /* In multi-pass modes, we need a virtual block array for each component. */
  161855. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161856. } my_coef_controller;
  161857. typedef my_coef_controller * my_coef_ptr;
  161858. /* Forward declarations */
  161859. METHODDEF(boolean) compress_data
  161860. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161861. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161862. METHODDEF(boolean) compress_first_pass
  161863. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161864. METHODDEF(boolean) compress_output
  161865. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161866. #endif
  161867. LOCAL(void)
  161868. start_iMCU_row (j_compress_ptr cinfo)
  161869. /* Reset within-iMCU-row counters for a new row */
  161870. {
  161871. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161872. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161873. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161874. * But at the bottom of the image, process only what's left.
  161875. */
  161876. if (cinfo->comps_in_scan > 1) {
  161877. coef->MCU_rows_per_iMCU_row = 1;
  161878. } else {
  161879. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161880. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161881. else
  161882. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161883. }
  161884. coef->mcu_ctr = 0;
  161885. coef->MCU_vert_offset = 0;
  161886. }
  161887. /*
  161888. * Initialize for a processing pass.
  161889. */
  161890. METHODDEF(void)
  161891. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161892. {
  161893. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161894. coef->iMCU_row_num = 0;
  161895. start_iMCU_row(cinfo);
  161896. switch (pass_mode) {
  161897. case JBUF_PASS_THRU:
  161898. if (coef->whole_image[0] != NULL)
  161899. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161900. coef->pub.compress_data = compress_data;
  161901. break;
  161902. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161903. case JBUF_SAVE_AND_PASS:
  161904. if (coef->whole_image[0] == NULL)
  161905. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161906. coef->pub.compress_data = compress_first_pass;
  161907. break;
  161908. case JBUF_CRANK_DEST:
  161909. if (coef->whole_image[0] == NULL)
  161910. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161911. coef->pub.compress_data = compress_output;
  161912. break;
  161913. #endif
  161914. default:
  161915. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161916. break;
  161917. }
  161918. }
  161919. /*
  161920. * Process some data in the single-pass case.
  161921. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161922. * per call, ie, v_samp_factor block rows for each component in the image.
  161923. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161924. *
  161925. * NB: input_buf contains a plane for each component in image,
  161926. * which we index according to the component's SOF position.
  161927. */
  161928. METHODDEF(boolean)
  161929. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161930. {
  161931. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161932. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161933. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161934. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161935. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161936. JDIMENSION ypos, xpos;
  161937. jpeg_component_info *compptr;
  161938. /* Loop to write as much as one whole iMCU row */
  161939. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161940. yoffset++) {
  161941. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161942. MCU_col_num++) {
  161943. /* Determine where data comes from in input_buf and do the DCT thing.
  161944. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161945. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161946. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161947. * specially. The data in them does not matter for image reconstruction,
  161948. * so we fill them with values that will encode to the smallest amount of
  161949. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161950. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161951. */
  161952. blkn = 0;
  161953. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161954. compptr = cinfo->cur_comp_info[ci];
  161955. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161956. : compptr->last_col_width;
  161957. xpos = MCU_col_num * compptr->MCU_sample_width;
  161958. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161959. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161960. if (coef->iMCU_row_num < last_iMCU_row ||
  161961. yoffset+yindex < compptr->last_row_height) {
  161962. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161963. input_buf[compptr->component_index],
  161964. coef->MCU_buffer[blkn],
  161965. ypos, xpos, (JDIMENSION) blockcnt);
  161966. if (blockcnt < compptr->MCU_width) {
  161967. /* Create some dummy blocks at the right edge of the image. */
  161968. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161969. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161970. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161971. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161972. }
  161973. }
  161974. } else {
  161975. /* Create a row of dummy blocks at the bottom of the image. */
  161976. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161977. compptr->MCU_width * SIZEOF(JBLOCK));
  161978. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161979. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161980. }
  161981. }
  161982. blkn += compptr->MCU_width;
  161983. ypos += DCTSIZE;
  161984. }
  161985. }
  161986. /* Try to write the MCU. In event of a suspension failure, we will
  161987. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161988. */
  161989. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161990. /* Suspension forced; update state counters and exit */
  161991. coef->MCU_vert_offset = yoffset;
  161992. coef->mcu_ctr = MCU_col_num;
  161993. return FALSE;
  161994. }
  161995. }
  161996. /* Completed an MCU row, but perhaps not an iMCU row */
  161997. coef->mcu_ctr = 0;
  161998. }
  161999. /* Completed the iMCU row, advance counters for next one */
  162000. coef->iMCU_row_num++;
  162001. start_iMCU_row(cinfo);
  162002. return TRUE;
  162003. }
  162004. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162005. /*
  162006. * Process some data in the first pass of a multi-pass case.
  162007. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162008. * per call, ie, v_samp_factor block rows for each component in the image.
  162009. * This amount of data is read from the source buffer, DCT'd and quantized,
  162010. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162011. * as needed at the right and lower edges. (The dummy blocks are constructed
  162012. * in the virtual arrays, which have been padded appropriately.) This makes
  162013. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162014. *
  162015. * We must also emit the data to the entropy encoder. This is conveniently
  162016. * done by calling compress_output() after we've loaded the current strip
  162017. * of the virtual arrays.
  162018. *
  162019. * NB: input_buf contains a plane for each component in image. All
  162020. * components are DCT'd and loaded into the virtual arrays in this pass.
  162021. * However, it may be that only a subset of the components are emitted to
  162022. * the entropy encoder during this first pass; be careful about looking
  162023. * at the scan-dependent variables (MCU dimensions, etc).
  162024. */
  162025. METHODDEF(boolean)
  162026. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162027. {
  162028. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162029. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162030. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162031. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162032. JCOEF lastDC;
  162033. jpeg_component_info *compptr;
  162034. JBLOCKARRAY buffer;
  162035. JBLOCKROW thisblockrow, lastblockrow;
  162036. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162037. ci++, compptr++) {
  162038. /* Align the virtual buffer for this component. */
  162039. buffer = (*cinfo->mem->access_virt_barray)
  162040. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162041. coef->iMCU_row_num * compptr->v_samp_factor,
  162042. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162043. /* Count non-dummy DCT block rows in this iMCU row. */
  162044. if (coef->iMCU_row_num < last_iMCU_row)
  162045. block_rows = compptr->v_samp_factor;
  162046. else {
  162047. /* NB: can't use last_row_height here, since may not be set! */
  162048. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162049. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162050. }
  162051. blocks_across = compptr->width_in_blocks;
  162052. h_samp_factor = compptr->h_samp_factor;
  162053. /* Count number of dummy blocks to be added at the right margin. */
  162054. ndummy = (int) (blocks_across % h_samp_factor);
  162055. if (ndummy > 0)
  162056. ndummy = h_samp_factor - ndummy;
  162057. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162058. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162059. */
  162060. for (block_row = 0; block_row < block_rows; block_row++) {
  162061. thisblockrow = buffer[block_row];
  162062. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162063. input_buf[ci], thisblockrow,
  162064. (JDIMENSION) (block_row * DCTSIZE),
  162065. (JDIMENSION) 0, blocks_across);
  162066. if (ndummy > 0) {
  162067. /* Create dummy blocks at the right edge of the image. */
  162068. thisblockrow += blocks_across; /* => first dummy block */
  162069. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162070. lastDC = thisblockrow[-1][0];
  162071. for (bi = 0; bi < ndummy; bi++) {
  162072. thisblockrow[bi][0] = lastDC;
  162073. }
  162074. }
  162075. }
  162076. /* If at end of image, create dummy block rows as needed.
  162077. * The tricky part here is that within each MCU, we want the DC values
  162078. * of the dummy blocks to match the last real block's DC value.
  162079. * This squeezes a few more bytes out of the resulting file...
  162080. */
  162081. if (coef->iMCU_row_num == last_iMCU_row) {
  162082. blocks_across += ndummy; /* include lower right corner */
  162083. MCUs_across = blocks_across / h_samp_factor;
  162084. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162085. block_row++) {
  162086. thisblockrow = buffer[block_row];
  162087. lastblockrow = buffer[block_row-1];
  162088. jzero_far((void FAR *) thisblockrow,
  162089. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162090. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162091. lastDC = lastblockrow[h_samp_factor-1][0];
  162092. for (bi = 0; bi < h_samp_factor; bi++) {
  162093. thisblockrow[bi][0] = lastDC;
  162094. }
  162095. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162096. lastblockrow += h_samp_factor;
  162097. }
  162098. }
  162099. }
  162100. }
  162101. /* NB: compress_output will increment iMCU_row_num if successful.
  162102. * A suspension return will result in redoing all the work above next time.
  162103. */
  162104. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162105. return compress_output(cinfo, input_buf);
  162106. }
  162107. /*
  162108. * Process some data in subsequent passes of a multi-pass case.
  162109. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162110. * per call, ie, v_samp_factor block rows for each component in the scan.
  162111. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162112. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162113. *
  162114. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162115. */
  162116. METHODDEF(boolean)
  162117. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162118. {
  162119. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162120. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162121. int blkn, ci, xindex, yindex, yoffset;
  162122. JDIMENSION start_col;
  162123. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162124. JBLOCKROW buffer_ptr;
  162125. jpeg_component_info *compptr;
  162126. /* Align the virtual buffers for the components used in this scan.
  162127. * NB: during first pass, this is safe only because the buffers will
  162128. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162129. */
  162130. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162131. compptr = cinfo->cur_comp_info[ci];
  162132. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162133. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162134. coef->iMCU_row_num * compptr->v_samp_factor,
  162135. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162136. }
  162137. /* Loop to process one whole iMCU row */
  162138. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162139. yoffset++) {
  162140. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162141. MCU_col_num++) {
  162142. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162143. blkn = 0; /* index of current DCT block within MCU */
  162144. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162145. compptr = cinfo->cur_comp_info[ci];
  162146. start_col = MCU_col_num * compptr->MCU_width;
  162147. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162148. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162149. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162150. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162151. }
  162152. }
  162153. }
  162154. /* Try to write the MCU. */
  162155. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162156. /* Suspension forced; update state counters and exit */
  162157. coef->MCU_vert_offset = yoffset;
  162158. coef->mcu_ctr = MCU_col_num;
  162159. return FALSE;
  162160. }
  162161. }
  162162. /* Completed an MCU row, but perhaps not an iMCU row */
  162163. coef->mcu_ctr = 0;
  162164. }
  162165. /* Completed the iMCU row, advance counters for next one */
  162166. coef->iMCU_row_num++;
  162167. start_iMCU_row(cinfo);
  162168. return TRUE;
  162169. }
  162170. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162171. /*
  162172. * Initialize coefficient buffer controller.
  162173. */
  162174. GLOBAL(void)
  162175. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162176. {
  162177. my_coef_ptr coef;
  162178. coef = (my_coef_ptr)
  162179. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162180. SIZEOF(my_coef_controller));
  162181. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162182. coef->pub.start_pass = start_pass_coef;
  162183. /* Create the coefficient buffer. */
  162184. if (need_full_buffer) {
  162185. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162186. /* Allocate a full-image virtual array for each component, */
  162187. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162188. int ci;
  162189. jpeg_component_info *compptr;
  162190. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162191. ci++, compptr++) {
  162192. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162193. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162194. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162195. (long) compptr->h_samp_factor),
  162196. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162197. (long) compptr->v_samp_factor),
  162198. (JDIMENSION) compptr->v_samp_factor);
  162199. }
  162200. #else
  162201. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162202. #endif
  162203. } else {
  162204. /* We only need a single-MCU buffer. */
  162205. JBLOCKROW buffer;
  162206. int i;
  162207. buffer = (JBLOCKROW)
  162208. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162209. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162210. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162211. coef->MCU_buffer[i] = buffer + i;
  162212. }
  162213. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162214. }
  162215. }
  162216. /*** End of inlined file: jccoefct.c ***/
  162217. /*** Start of inlined file: jccolor.c ***/
  162218. #define JPEG_INTERNALS
  162219. /* Private subobject */
  162220. typedef struct {
  162221. struct jpeg_color_converter pub; /* public fields */
  162222. /* Private state for RGB->YCC conversion */
  162223. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162224. } my_color_converter;
  162225. typedef my_color_converter * my_cconvert_ptr;
  162226. /**************** RGB -> YCbCr conversion: most common case **************/
  162227. /*
  162228. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162229. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162230. * The conversion equations to be implemented are therefore
  162231. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162232. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162233. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162234. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162235. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162236. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162237. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162238. * were not represented exactly. Now we sacrifice exact representation of
  162239. * maximum red and maximum blue in order to get exact grayscales.
  162240. *
  162241. * To avoid floating-point arithmetic, we represent the fractional constants
  162242. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162243. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162244. *
  162245. * For even more speed, we avoid doing any multiplications in the inner loop
  162246. * by precalculating the constants times R,G,B for all possible values.
  162247. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162248. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162249. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162250. * colorspace anyway.
  162251. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162252. * in the tables to save adding them separately in the inner loop.
  162253. */
  162254. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162255. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162256. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162257. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162258. /* We allocate one big table and divide it up into eight parts, instead of
  162259. * doing eight alloc_small requests. This lets us use a single table base
  162260. * address, which can be held in a register in the inner loops on many
  162261. * machines (more than can hold all eight addresses, anyway).
  162262. */
  162263. #define R_Y_OFF 0 /* offset to R => Y section */
  162264. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162265. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162266. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162267. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162268. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162269. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162270. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162271. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162272. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162273. /*
  162274. * Initialize for RGB->YCC colorspace conversion.
  162275. */
  162276. METHODDEF(void)
  162277. rgb_ycc_start (j_compress_ptr cinfo)
  162278. {
  162279. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162280. INT32 * rgb_ycc_tab;
  162281. INT32 i;
  162282. /* Allocate and fill in the conversion tables. */
  162283. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162284. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162285. (TABLE_SIZE * SIZEOF(INT32)));
  162286. for (i = 0; i <= MAXJSAMPLE; i++) {
  162287. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162288. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162289. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162290. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162291. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162292. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162293. * This ensures that the maximum output will round to MAXJSAMPLE
  162294. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162295. */
  162296. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162297. /* B=>Cb and R=>Cr tables are the same
  162298. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162299. */
  162300. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162301. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162302. }
  162303. }
  162304. /*
  162305. * Convert some rows of samples to the JPEG colorspace.
  162306. *
  162307. * Note that we change from the application's interleaved-pixel format
  162308. * to our internal noninterleaved, one-plane-per-component format.
  162309. * The input buffer is therefore three times as wide as the output buffer.
  162310. *
  162311. * A starting row offset is provided only for the output buffer. The caller
  162312. * can easily adjust the passed input_buf value to accommodate any row
  162313. * offset required on that side.
  162314. */
  162315. METHODDEF(void)
  162316. rgb_ycc_convert (j_compress_ptr cinfo,
  162317. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162318. JDIMENSION output_row, int num_rows)
  162319. {
  162320. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162321. register int r, g, b;
  162322. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162323. register JSAMPROW inptr;
  162324. register JSAMPROW outptr0, outptr1, outptr2;
  162325. register JDIMENSION col;
  162326. JDIMENSION num_cols = cinfo->image_width;
  162327. while (--num_rows >= 0) {
  162328. inptr = *input_buf++;
  162329. outptr0 = output_buf[0][output_row];
  162330. outptr1 = output_buf[1][output_row];
  162331. outptr2 = output_buf[2][output_row];
  162332. output_row++;
  162333. for (col = 0; col < num_cols; col++) {
  162334. r = GETJSAMPLE(inptr[RGB_RED]);
  162335. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162336. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162337. inptr += RGB_PIXELSIZE;
  162338. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162339. * must be too; we do not need an explicit range-limiting operation.
  162340. * Hence the value being shifted is never negative, and we don't
  162341. * need the general RIGHT_SHIFT macro.
  162342. */
  162343. /* Y */
  162344. outptr0[col] = (JSAMPLE)
  162345. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162346. >> SCALEBITS);
  162347. /* Cb */
  162348. outptr1[col] = (JSAMPLE)
  162349. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162350. >> SCALEBITS);
  162351. /* Cr */
  162352. outptr2[col] = (JSAMPLE)
  162353. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162354. >> SCALEBITS);
  162355. }
  162356. }
  162357. }
  162358. /**************** Cases other than RGB -> YCbCr **************/
  162359. /*
  162360. * Convert some rows of samples to the JPEG colorspace.
  162361. * This version handles RGB->grayscale conversion, which is the same
  162362. * as the RGB->Y portion of RGB->YCbCr.
  162363. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162364. */
  162365. METHODDEF(void)
  162366. rgb_gray_convert (j_compress_ptr cinfo,
  162367. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162368. JDIMENSION output_row, int num_rows)
  162369. {
  162370. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162371. register int r, g, b;
  162372. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162373. register JSAMPROW inptr;
  162374. register JSAMPROW outptr;
  162375. register JDIMENSION col;
  162376. JDIMENSION num_cols = cinfo->image_width;
  162377. while (--num_rows >= 0) {
  162378. inptr = *input_buf++;
  162379. outptr = output_buf[0][output_row];
  162380. output_row++;
  162381. for (col = 0; col < num_cols; col++) {
  162382. r = GETJSAMPLE(inptr[RGB_RED]);
  162383. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162384. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162385. inptr += RGB_PIXELSIZE;
  162386. /* Y */
  162387. outptr[col] = (JSAMPLE)
  162388. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162389. >> SCALEBITS);
  162390. }
  162391. }
  162392. }
  162393. /*
  162394. * Convert some rows of samples to the JPEG colorspace.
  162395. * This version handles Adobe-style CMYK->YCCK conversion,
  162396. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162397. * conversion as above, while passing K (black) unchanged.
  162398. * We assume rgb_ycc_start has been called.
  162399. */
  162400. METHODDEF(void)
  162401. cmyk_ycck_convert (j_compress_ptr cinfo,
  162402. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162403. JDIMENSION output_row, int num_rows)
  162404. {
  162405. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162406. register int r, g, b;
  162407. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162408. register JSAMPROW inptr;
  162409. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162410. register JDIMENSION col;
  162411. JDIMENSION num_cols = cinfo->image_width;
  162412. while (--num_rows >= 0) {
  162413. inptr = *input_buf++;
  162414. outptr0 = output_buf[0][output_row];
  162415. outptr1 = output_buf[1][output_row];
  162416. outptr2 = output_buf[2][output_row];
  162417. outptr3 = output_buf[3][output_row];
  162418. output_row++;
  162419. for (col = 0; col < num_cols; col++) {
  162420. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162421. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162422. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162423. /* K passes through as-is */
  162424. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162425. inptr += 4;
  162426. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162427. * must be too; we do not need an explicit range-limiting operation.
  162428. * Hence the value being shifted is never negative, and we don't
  162429. * need the general RIGHT_SHIFT macro.
  162430. */
  162431. /* Y */
  162432. outptr0[col] = (JSAMPLE)
  162433. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162434. >> SCALEBITS);
  162435. /* Cb */
  162436. outptr1[col] = (JSAMPLE)
  162437. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162438. >> SCALEBITS);
  162439. /* Cr */
  162440. outptr2[col] = (JSAMPLE)
  162441. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162442. >> SCALEBITS);
  162443. }
  162444. }
  162445. }
  162446. /*
  162447. * Convert some rows of samples to the JPEG colorspace.
  162448. * This version handles grayscale output with no conversion.
  162449. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162450. */
  162451. METHODDEF(void)
  162452. grayscale_convert (j_compress_ptr cinfo,
  162453. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162454. JDIMENSION output_row, int num_rows)
  162455. {
  162456. register JSAMPROW inptr;
  162457. register JSAMPROW outptr;
  162458. register JDIMENSION col;
  162459. JDIMENSION num_cols = cinfo->image_width;
  162460. int instride = cinfo->input_components;
  162461. while (--num_rows >= 0) {
  162462. inptr = *input_buf++;
  162463. outptr = output_buf[0][output_row];
  162464. output_row++;
  162465. for (col = 0; col < num_cols; col++) {
  162466. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162467. inptr += instride;
  162468. }
  162469. }
  162470. }
  162471. /*
  162472. * Convert some rows of samples to the JPEG colorspace.
  162473. * This version handles multi-component colorspaces without conversion.
  162474. * We assume input_components == num_components.
  162475. */
  162476. METHODDEF(void)
  162477. null_convert (j_compress_ptr cinfo,
  162478. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162479. JDIMENSION output_row, int num_rows)
  162480. {
  162481. register JSAMPROW inptr;
  162482. register JSAMPROW outptr;
  162483. register JDIMENSION col;
  162484. register int ci;
  162485. int nc = cinfo->num_components;
  162486. JDIMENSION num_cols = cinfo->image_width;
  162487. while (--num_rows >= 0) {
  162488. /* It seems fastest to make a separate pass for each component. */
  162489. for (ci = 0; ci < nc; ci++) {
  162490. inptr = *input_buf;
  162491. outptr = output_buf[ci][output_row];
  162492. for (col = 0; col < num_cols; col++) {
  162493. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162494. inptr += nc;
  162495. }
  162496. }
  162497. input_buf++;
  162498. output_row++;
  162499. }
  162500. }
  162501. /*
  162502. * Empty method for start_pass.
  162503. */
  162504. METHODDEF(void)
  162505. null_method (j_compress_ptr)
  162506. {
  162507. /* no work needed */
  162508. }
  162509. /*
  162510. * Module initialization routine for input colorspace conversion.
  162511. */
  162512. GLOBAL(void)
  162513. jinit_color_converter (j_compress_ptr cinfo)
  162514. {
  162515. my_cconvert_ptr cconvert;
  162516. cconvert = (my_cconvert_ptr)
  162517. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162518. SIZEOF(my_color_converter));
  162519. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162520. /* set start_pass to null method until we find out differently */
  162521. cconvert->pub.start_pass = null_method;
  162522. /* Make sure input_components agrees with in_color_space */
  162523. switch (cinfo->in_color_space) {
  162524. case JCS_GRAYSCALE:
  162525. if (cinfo->input_components != 1)
  162526. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162527. break;
  162528. case JCS_RGB:
  162529. #if RGB_PIXELSIZE != 3
  162530. if (cinfo->input_components != RGB_PIXELSIZE)
  162531. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162532. break;
  162533. #endif /* else share code with YCbCr */
  162534. case JCS_YCbCr:
  162535. if (cinfo->input_components != 3)
  162536. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162537. break;
  162538. case JCS_CMYK:
  162539. case JCS_YCCK:
  162540. if (cinfo->input_components != 4)
  162541. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162542. break;
  162543. default: /* JCS_UNKNOWN can be anything */
  162544. if (cinfo->input_components < 1)
  162545. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162546. break;
  162547. }
  162548. /* Check num_components, set conversion method based on requested space */
  162549. switch (cinfo->jpeg_color_space) {
  162550. case JCS_GRAYSCALE:
  162551. if (cinfo->num_components != 1)
  162552. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162553. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162554. cconvert->pub.color_convert = grayscale_convert;
  162555. else if (cinfo->in_color_space == JCS_RGB) {
  162556. cconvert->pub.start_pass = rgb_ycc_start;
  162557. cconvert->pub.color_convert = rgb_gray_convert;
  162558. } else if (cinfo->in_color_space == JCS_YCbCr)
  162559. cconvert->pub.color_convert = grayscale_convert;
  162560. else
  162561. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162562. break;
  162563. case JCS_RGB:
  162564. if (cinfo->num_components != 3)
  162565. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162566. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162567. cconvert->pub.color_convert = null_convert;
  162568. else
  162569. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162570. break;
  162571. case JCS_YCbCr:
  162572. if (cinfo->num_components != 3)
  162573. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162574. if (cinfo->in_color_space == JCS_RGB) {
  162575. cconvert->pub.start_pass = rgb_ycc_start;
  162576. cconvert->pub.color_convert = rgb_ycc_convert;
  162577. } else if (cinfo->in_color_space == JCS_YCbCr)
  162578. cconvert->pub.color_convert = null_convert;
  162579. else
  162580. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162581. break;
  162582. case JCS_CMYK:
  162583. if (cinfo->num_components != 4)
  162584. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162585. if (cinfo->in_color_space == JCS_CMYK)
  162586. cconvert->pub.color_convert = null_convert;
  162587. else
  162588. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162589. break;
  162590. case JCS_YCCK:
  162591. if (cinfo->num_components != 4)
  162592. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162593. if (cinfo->in_color_space == JCS_CMYK) {
  162594. cconvert->pub.start_pass = rgb_ycc_start;
  162595. cconvert->pub.color_convert = cmyk_ycck_convert;
  162596. } else if (cinfo->in_color_space == JCS_YCCK)
  162597. cconvert->pub.color_convert = null_convert;
  162598. else
  162599. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162600. break;
  162601. default: /* allow null conversion of JCS_UNKNOWN */
  162602. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162603. cinfo->num_components != cinfo->input_components)
  162604. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162605. cconvert->pub.color_convert = null_convert;
  162606. break;
  162607. }
  162608. }
  162609. /*** End of inlined file: jccolor.c ***/
  162610. #undef FIX
  162611. /*** Start of inlined file: jcdctmgr.c ***/
  162612. #define JPEG_INTERNALS
  162613. /*** Start of inlined file: jdct.h ***/
  162614. /*
  162615. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162616. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162617. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162618. * implementations use an array of type FAST_FLOAT, instead.)
  162619. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162620. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162621. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162622. * convention improves accuracy in integer implementations and saves some
  162623. * work in floating-point ones.
  162624. * Quantization of the output coefficients is done by jcdctmgr.c.
  162625. */
  162626. #ifndef __jdct_h__
  162627. #define __jdct_h__
  162628. #if BITS_IN_JSAMPLE == 8
  162629. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162630. #else
  162631. typedef INT32 DCTELEM; /* must have 32 bits */
  162632. #endif
  162633. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162634. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162635. /*
  162636. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162637. * to an output sample array. The routine must dequantize the input data as
  162638. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162639. * pointed to by compptr->dct_table. The output data is to be placed into the
  162640. * sample array starting at a specified column. (Any row offset needed will
  162641. * be applied to the array pointer before it is passed to the IDCT code.)
  162642. * Note that the number of samples emitted by the IDCT routine is
  162643. * DCT_scaled_size * DCT_scaled_size.
  162644. */
  162645. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162646. /*
  162647. * Each IDCT routine has its own ideas about the best dct_table element type.
  162648. */
  162649. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162650. #if BITS_IN_JSAMPLE == 8
  162651. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162652. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162653. #else
  162654. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162655. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162656. #endif
  162657. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162658. /*
  162659. * Each IDCT routine is responsible for range-limiting its results and
  162660. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162661. * be quite far out of range if the input data is corrupt, so a bulletproof
  162662. * range-limiting step is required. We use a mask-and-table-lookup method
  162663. * to do the combined operations quickly. See the comments with
  162664. * prepare_range_limit_table (in jdmaster.c) for more info.
  162665. */
  162666. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162667. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162668. /* Short forms of external names for systems with brain-damaged linkers. */
  162669. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162670. #define jpeg_fdct_islow jFDislow
  162671. #define jpeg_fdct_ifast jFDifast
  162672. #define jpeg_fdct_float jFDfloat
  162673. #define jpeg_idct_islow jRDislow
  162674. #define jpeg_idct_ifast jRDifast
  162675. #define jpeg_idct_float jRDfloat
  162676. #define jpeg_idct_4x4 jRD4x4
  162677. #define jpeg_idct_2x2 jRD2x2
  162678. #define jpeg_idct_1x1 jRD1x1
  162679. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162680. /* Extern declarations for the forward and inverse DCT routines. */
  162681. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162682. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162683. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162684. EXTERN(void) jpeg_idct_islow
  162685. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162686. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162687. EXTERN(void) jpeg_idct_ifast
  162688. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162689. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162690. EXTERN(void) jpeg_idct_float
  162691. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162692. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162693. EXTERN(void) jpeg_idct_4x4
  162694. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162695. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162696. EXTERN(void) jpeg_idct_2x2
  162697. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162698. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162699. EXTERN(void) jpeg_idct_1x1
  162700. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162701. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162702. /*
  162703. * Macros for handling fixed-point arithmetic; these are used by many
  162704. * but not all of the DCT/IDCT modules.
  162705. *
  162706. * All values are expected to be of type INT32.
  162707. * Fractional constants are scaled left by CONST_BITS bits.
  162708. * CONST_BITS is defined within each module using these macros,
  162709. * and may differ from one module to the next.
  162710. */
  162711. #define ONE ((INT32) 1)
  162712. #define CONST_SCALE (ONE << CONST_BITS)
  162713. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162714. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162715. * thus causing a lot of useless floating-point operations at run time.
  162716. */
  162717. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162718. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162719. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162720. * the fudge factor is correct for either sign of X.
  162721. */
  162722. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162723. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162724. * This macro is used only when the two inputs will actually be no more than
  162725. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162726. * full 32x32 multiply. This provides a useful speedup on many machines.
  162727. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162728. * in C, but some C compilers will do the right thing if you provide the
  162729. * correct combination of casts.
  162730. */
  162731. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162732. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162733. #endif
  162734. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162735. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162736. #endif
  162737. #ifndef MULTIPLY16C16 /* default definition */
  162738. #define MULTIPLY16C16(var,const) ((var) * (const))
  162739. #endif
  162740. /* Same except both inputs are variables. */
  162741. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162742. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162743. #endif
  162744. #ifndef MULTIPLY16V16 /* default definition */
  162745. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162746. #endif
  162747. #endif
  162748. /*** End of inlined file: jdct.h ***/
  162749. /* Private declarations for DCT subsystem */
  162750. /* Private subobject for this module */
  162751. typedef struct {
  162752. struct jpeg_forward_dct pub; /* public fields */
  162753. /* Pointer to the DCT routine actually in use */
  162754. forward_DCT_method_ptr do_dct;
  162755. /* The actual post-DCT divisors --- not identical to the quant table
  162756. * entries, because of scaling (especially for an unnormalized DCT).
  162757. * Each table is given in normal array order.
  162758. */
  162759. DCTELEM * divisors[NUM_QUANT_TBLS];
  162760. #ifdef DCT_FLOAT_SUPPORTED
  162761. /* Same as above for the floating-point case. */
  162762. float_DCT_method_ptr do_float_dct;
  162763. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162764. #endif
  162765. } my_fdct_controller;
  162766. typedef my_fdct_controller * my_fdct_ptr;
  162767. /*
  162768. * Initialize for a processing pass.
  162769. * Verify that all referenced Q-tables are present, and set up
  162770. * the divisor table for each one.
  162771. * In the current implementation, DCT of all components is done during
  162772. * the first pass, even if only some components will be output in the
  162773. * first scan. Hence all components should be examined here.
  162774. */
  162775. METHODDEF(void)
  162776. start_pass_fdctmgr (j_compress_ptr cinfo)
  162777. {
  162778. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162779. int ci, qtblno, i;
  162780. jpeg_component_info *compptr;
  162781. JQUANT_TBL * qtbl;
  162782. DCTELEM * dtbl;
  162783. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162784. ci++, compptr++) {
  162785. qtblno = compptr->quant_tbl_no;
  162786. /* Make sure specified quantization table is present */
  162787. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162788. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162789. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162790. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162791. /* Compute divisors for this quant table */
  162792. /* We may do this more than once for same table, but it's not a big deal */
  162793. switch (cinfo->dct_method) {
  162794. #ifdef DCT_ISLOW_SUPPORTED
  162795. case JDCT_ISLOW:
  162796. /* For LL&M IDCT method, divisors are equal to raw quantization
  162797. * coefficients multiplied by 8 (to counteract scaling).
  162798. */
  162799. if (fdct->divisors[qtblno] == NULL) {
  162800. fdct->divisors[qtblno] = (DCTELEM *)
  162801. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162802. DCTSIZE2 * SIZEOF(DCTELEM));
  162803. }
  162804. dtbl = fdct->divisors[qtblno];
  162805. for (i = 0; i < DCTSIZE2; i++) {
  162806. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162807. }
  162808. break;
  162809. #endif
  162810. #ifdef DCT_IFAST_SUPPORTED
  162811. case JDCT_IFAST:
  162812. {
  162813. /* For AA&N IDCT method, divisors are equal to quantization
  162814. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162815. * scalefactor[0] = 1
  162816. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162817. * We apply a further scale factor of 8.
  162818. */
  162819. #define CONST_BITS 14
  162820. static const INT16 aanscales[DCTSIZE2] = {
  162821. /* precomputed values scaled up by 14 bits */
  162822. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162823. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162824. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162825. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162826. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162827. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162828. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162829. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162830. };
  162831. SHIFT_TEMPS
  162832. if (fdct->divisors[qtblno] == NULL) {
  162833. fdct->divisors[qtblno] = (DCTELEM *)
  162834. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162835. DCTSIZE2 * SIZEOF(DCTELEM));
  162836. }
  162837. dtbl = fdct->divisors[qtblno];
  162838. for (i = 0; i < DCTSIZE2; i++) {
  162839. dtbl[i] = (DCTELEM)
  162840. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162841. (INT32) aanscales[i]),
  162842. CONST_BITS-3);
  162843. }
  162844. }
  162845. break;
  162846. #endif
  162847. #ifdef DCT_FLOAT_SUPPORTED
  162848. case JDCT_FLOAT:
  162849. {
  162850. /* For float AA&N IDCT method, divisors are equal to quantization
  162851. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162852. * scalefactor[0] = 1
  162853. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162854. * We apply a further scale factor of 8.
  162855. * What's actually stored is 1/divisor so that the inner loop can
  162856. * use a multiplication rather than a division.
  162857. */
  162858. FAST_FLOAT * fdtbl;
  162859. int row, col;
  162860. static const double aanscalefactor[DCTSIZE] = {
  162861. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162862. 1.0, 0.785694958, 0.541196100, 0.275899379
  162863. };
  162864. if (fdct->float_divisors[qtblno] == NULL) {
  162865. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162866. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162867. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162868. }
  162869. fdtbl = fdct->float_divisors[qtblno];
  162870. i = 0;
  162871. for (row = 0; row < DCTSIZE; row++) {
  162872. for (col = 0; col < DCTSIZE; col++) {
  162873. fdtbl[i] = (FAST_FLOAT)
  162874. (1.0 / (((double) qtbl->quantval[i] *
  162875. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162876. i++;
  162877. }
  162878. }
  162879. }
  162880. break;
  162881. #endif
  162882. default:
  162883. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162884. break;
  162885. }
  162886. }
  162887. }
  162888. /*
  162889. * Perform forward DCT on one or more blocks of a component.
  162890. *
  162891. * The input samples are taken from the sample_data[] array starting at
  162892. * position start_row/start_col, and moving to the right for any additional
  162893. * blocks. The quantized coefficients are returned in coef_blocks[].
  162894. */
  162895. METHODDEF(void)
  162896. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162897. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162898. JDIMENSION start_row, JDIMENSION start_col,
  162899. JDIMENSION num_blocks)
  162900. /* This version is used for integer DCT implementations. */
  162901. {
  162902. /* This routine is heavily used, so it's worth coding it tightly. */
  162903. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162904. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162905. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162906. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162907. JDIMENSION bi;
  162908. sample_data += start_row; /* fold in the vertical offset once */
  162909. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162910. /* Load data into workspace, applying unsigned->signed conversion */
  162911. { register DCTELEM *workspaceptr;
  162912. register JSAMPROW elemptr;
  162913. register int elemr;
  162914. workspaceptr = workspace;
  162915. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162916. elemptr = sample_data[elemr] + start_col;
  162917. #if DCTSIZE == 8 /* unroll the inner loop */
  162918. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162919. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162920. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162921. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162922. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162923. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162924. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162925. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162926. #else
  162927. { register int elemc;
  162928. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162929. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162930. }
  162931. }
  162932. #endif
  162933. }
  162934. }
  162935. /* Perform the DCT */
  162936. (*do_dct) (workspace);
  162937. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162938. { register DCTELEM temp, qval;
  162939. register int i;
  162940. register JCOEFPTR output_ptr = coef_blocks[bi];
  162941. for (i = 0; i < DCTSIZE2; i++) {
  162942. qval = divisors[i];
  162943. temp = workspace[i];
  162944. /* Divide the coefficient value by qval, ensuring proper rounding.
  162945. * Since C does not specify the direction of rounding for negative
  162946. * quotients, we have to force the dividend positive for portability.
  162947. *
  162948. * In most files, at least half of the output values will be zero
  162949. * (at default quantization settings, more like three-quarters...)
  162950. * so we should ensure that this case is fast. On many machines,
  162951. * a comparison is enough cheaper than a divide to make a special test
  162952. * a win. Since both inputs will be nonnegative, we need only test
  162953. * for a < b to discover whether a/b is 0.
  162954. * If your machine's division is fast enough, define FAST_DIVIDE.
  162955. */
  162956. #ifdef FAST_DIVIDE
  162957. #define DIVIDE_BY(a,b) a /= b
  162958. #else
  162959. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162960. #endif
  162961. if (temp < 0) {
  162962. temp = -temp;
  162963. temp += qval>>1; /* for rounding */
  162964. DIVIDE_BY(temp, qval);
  162965. temp = -temp;
  162966. } else {
  162967. temp += qval>>1; /* for rounding */
  162968. DIVIDE_BY(temp, qval);
  162969. }
  162970. output_ptr[i] = (JCOEF) temp;
  162971. }
  162972. }
  162973. }
  162974. }
  162975. #ifdef DCT_FLOAT_SUPPORTED
  162976. METHODDEF(void)
  162977. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162978. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162979. JDIMENSION start_row, JDIMENSION start_col,
  162980. JDIMENSION num_blocks)
  162981. /* This version is used for floating-point DCT implementations. */
  162982. {
  162983. /* This routine is heavily used, so it's worth coding it tightly. */
  162984. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162985. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162986. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162987. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162988. JDIMENSION bi;
  162989. sample_data += start_row; /* fold in the vertical offset once */
  162990. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162991. /* Load data into workspace, applying unsigned->signed conversion */
  162992. { register FAST_FLOAT *workspaceptr;
  162993. register JSAMPROW elemptr;
  162994. register int elemr;
  162995. workspaceptr = workspace;
  162996. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162997. elemptr = sample_data[elemr] + start_col;
  162998. #if DCTSIZE == 8 /* unroll the inner loop */
  162999. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163000. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163001. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163002. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163003. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163004. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163005. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163006. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163007. #else
  163008. { register int elemc;
  163009. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163010. *workspaceptr++ = (FAST_FLOAT)
  163011. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163012. }
  163013. }
  163014. #endif
  163015. }
  163016. }
  163017. /* Perform the DCT */
  163018. (*do_dct) (workspace);
  163019. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163020. { register FAST_FLOAT temp;
  163021. register int i;
  163022. register JCOEFPTR output_ptr = coef_blocks[bi];
  163023. for (i = 0; i < DCTSIZE2; i++) {
  163024. /* Apply the quantization and scaling factor */
  163025. temp = workspace[i] * divisors[i];
  163026. /* Round to nearest integer.
  163027. * Since C does not specify the direction of rounding for negative
  163028. * quotients, we have to force the dividend positive for portability.
  163029. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163030. * code should work for either 16-bit or 32-bit ints.
  163031. */
  163032. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163033. }
  163034. }
  163035. }
  163036. }
  163037. #endif /* DCT_FLOAT_SUPPORTED */
  163038. /*
  163039. * Initialize FDCT manager.
  163040. */
  163041. GLOBAL(void)
  163042. jinit_forward_dct (j_compress_ptr cinfo)
  163043. {
  163044. my_fdct_ptr fdct;
  163045. int i;
  163046. fdct = (my_fdct_ptr)
  163047. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163048. SIZEOF(my_fdct_controller));
  163049. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163050. fdct->pub.start_pass = start_pass_fdctmgr;
  163051. switch (cinfo->dct_method) {
  163052. #ifdef DCT_ISLOW_SUPPORTED
  163053. case JDCT_ISLOW:
  163054. fdct->pub.forward_DCT = forward_DCT;
  163055. fdct->do_dct = jpeg_fdct_islow;
  163056. break;
  163057. #endif
  163058. #ifdef DCT_IFAST_SUPPORTED
  163059. case JDCT_IFAST:
  163060. fdct->pub.forward_DCT = forward_DCT;
  163061. fdct->do_dct = jpeg_fdct_ifast;
  163062. break;
  163063. #endif
  163064. #ifdef DCT_FLOAT_SUPPORTED
  163065. case JDCT_FLOAT:
  163066. fdct->pub.forward_DCT = forward_DCT_float;
  163067. fdct->do_float_dct = jpeg_fdct_float;
  163068. break;
  163069. #endif
  163070. default:
  163071. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163072. break;
  163073. }
  163074. /* Mark divisor tables unallocated */
  163075. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163076. fdct->divisors[i] = NULL;
  163077. #ifdef DCT_FLOAT_SUPPORTED
  163078. fdct->float_divisors[i] = NULL;
  163079. #endif
  163080. }
  163081. }
  163082. /*** End of inlined file: jcdctmgr.c ***/
  163083. #undef CONST_BITS
  163084. /*** Start of inlined file: jchuff.c ***/
  163085. #define JPEG_INTERNALS
  163086. /*** Start of inlined file: jchuff.h ***/
  163087. /* The legal range of a DCT coefficient is
  163088. * -1024 .. +1023 for 8-bit data;
  163089. * -16384 .. +16383 for 12-bit data.
  163090. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163091. */
  163092. #ifndef _jchuff_h_
  163093. #define _jchuff_h_
  163094. #if BITS_IN_JSAMPLE == 8
  163095. #define MAX_COEF_BITS 10
  163096. #else
  163097. #define MAX_COEF_BITS 14
  163098. #endif
  163099. /* Derived data constructed for each Huffman table */
  163100. typedef struct {
  163101. unsigned int ehufco[256]; /* code for each symbol */
  163102. char ehufsi[256]; /* length of code for each symbol */
  163103. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163104. } c_derived_tbl;
  163105. /* Short forms of external names for systems with brain-damaged linkers. */
  163106. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163107. #define jpeg_make_c_derived_tbl jMkCDerived
  163108. #define jpeg_gen_optimal_table jGenOptTbl
  163109. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163110. /* Expand a Huffman table definition into the derived format */
  163111. EXTERN(void) jpeg_make_c_derived_tbl
  163112. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163113. c_derived_tbl ** pdtbl));
  163114. /* Generate an optimal table definition given the specified counts */
  163115. EXTERN(void) jpeg_gen_optimal_table
  163116. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163117. #endif
  163118. /*** End of inlined file: jchuff.h ***/
  163119. /* Declarations shared with jcphuff.c */
  163120. /* Expanded entropy encoder object for Huffman encoding.
  163121. *
  163122. * The savable_state subrecord contains fields that change within an MCU,
  163123. * but must not be updated permanently until we complete the MCU.
  163124. */
  163125. typedef struct {
  163126. INT32 put_buffer; /* current bit-accumulation buffer */
  163127. int put_bits; /* # of bits now in it */
  163128. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163129. } savable_state;
  163130. /* This macro is to work around compilers with missing or broken
  163131. * structure assignment. You'll need to fix this code if you have
  163132. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163133. */
  163134. #ifndef NO_STRUCT_ASSIGN
  163135. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163136. #else
  163137. #if MAX_COMPS_IN_SCAN == 4
  163138. #define ASSIGN_STATE(dest,src) \
  163139. ((dest).put_buffer = (src).put_buffer, \
  163140. (dest).put_bits = (src).put_bits, \
  163141. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163142. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163143. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163144. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163145. #endif
  163146. #endif
  163147. typedef struct {
  163148. struct jpeg_entropy_encoder pub; /* public fields */
  163149. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163150. /* These fields are NOT loaded into local working state. */
  163151. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163152. int next_restart_num; /* next restart number to write (0-7) */
  163153. /* Pointers to derived tables (these workspaces have image lifespan) */
  163154. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163155. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163156. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163157. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163158. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163159. #endif
  163160. } huff_entropy_encoder;
  163161. typedef huff_entropy_encoder * huff_entropy_ptr;
  163162. /* Working state while writing an MCU.
  163163. * This struct contains all the fields that are needed by subroutines.
  163164. */
  163165. typedef struct {
  163166. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163167. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163168. savable_state cur; /* Current bit buffer & DC state */
  163169. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163170. } working_state;
  163171. /* Forward declarations */
  163172. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163173. JBLOCKROW *MCU_data));
  163174. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163175. #ifdef ENTROPY_OPT_SUPPORTED
  163176. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163177. JBLOCKROW *MCU_data));
  163178. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163179. #endif
  163180. /*
  163181. * Initialize for a Huffman-compressed scan.
  163182. * If gather_statistics is TRUE, we do not output anything during the scan,
  163183. * just count the Huffman symbols used and generate Huffman code tables.
  163184. */
  163185. METHODDEF(void)
  163186. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163187. {
  163188. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163189. int ci, dctbl, actbl;
  163190. jpeg_component_info * compptr;
  163191. if (gather_statistics) {
  163192. #ifdef ENTROPY_OPT_SUPPORTED
  163193. entropy->pub.encode_mcu = encode_mcu_gather;
  163194. entropy->pub.finish_pass = finish_pass_gather;
  163195. #else
  163196. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163197. #endif
  163198. } else {
  163199. entropy->pub.encode_mcu = encode_mcu_huff;
  163200. entropy->pub.finish_pass = finish_pass_huff;
  163201. }
  163202. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163203. compptr = cinfo->cur_comp_info[ci];
  163204. dctbl = compptr->dc_tbl_no;
  163205. actbl = compptr->ac_tbl_no;
  163206. if (gather_statistics) {
  163207. #ifdef ENTROPY_OPT_SUPPORTED
  163208. /* Check for invalid table indexes */
  163209. /* (make_c_derived_tbl does this in the other path) */
  163210. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163211. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163212. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163213. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163214. /* Allocate and zero the statistics tables */
  163215. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163216. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163217. entropy->dc_count_ptrs[dctbl] = (long *)
  163218. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163219. 257 * SIZEOF(long));
  163220. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163221. if (entropy->ac_count_ptrs[actbl] == NULL)
  163222. entropy->ac_count_ptrs[actbl] = (long *)
  163223. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163224. 257 * SIZEOF(long));
  163225. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163226. #endif
  163227. } else {
  163228. /* Compute derived values for Huffman tables */
  163229. /* We may do this more than once for a table, but it's not expensive */
  163230. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163231. & entropy->dc_derived_tbls[dctbl]);
  163232. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163233. & entropy->ac_derived_tbls[actbl]);
  163234. }
  163235. /* Initialize DC predictions to 0 */
  163236. entropy->saved.last_dc_val[ci] = 0;
  163237. }
  163238. /* Initialize bit buffer to empty */
  163239. entropy->saved.put_buffer = 0;
  163240. entropy->saved.put_bits = 0;
  163241. /* Initialize restart stuff */
  163242. entropy->restarts_to_go = cinfo->restart_interval;
  163243. entropy->next_restart_num = 0;
  163244. }
  163245. /*
  163246. * Compute the derived values for a Huffman table.
  163247. * This routine also performs some validation checks on the table.
  163248. *
  163249. * Note this is also used by jcphuff.c.
  163250. */
  163251. GLOBAL(void)
  163252. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163253. c_derived_tbl ** pdtbl)
  163254. {
  163255. JHUFF_TBL *htbl;
  163256. c_derived_tbl *dtbl;
  163257. int p, i, l, lastp, si, maxsymbol;
  163258. char huffsize[257];
  163259. unsigned int huffcode[257];
  163260. unsigned int code;
  163261. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163262. * paralleling the order of the symbols themselves in htbl->huffval[].
  163263. */
  163264. /* Find the input Huffman table */
  163265. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163266. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163267. htbl =
  163268. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163269. if (htbl == NULL)
  163270. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163271. /* Allocate a workspace if we haven't already done so. */
  163272. if (*pdtbl == NULL)
  163273. *pdtbl = (c_derived_tbl *)
  163274. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163275. SIZEOF(c_derived_tbl));
  163276. dtbl = *pdtbl;
  163277. /* Figure C.1: make table of Huffman code length for each symbol */
  163278. p = 0;
  163279. for (l = 1; l <= 16; l++) {
  163280. i = (int) htbl->bits[l];
  163281. if (i < 0 || p + i > 256) /* protect against table overrun */
  163282. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163283. while (i--)
  163284. huffsize[p++] = (char) l;
  163285. }
  163286. huffsize[p] = 0;
  163287. lastp = p;
  163288. /* Figure C.2: generate the codes themselves */
  163289. /* We also validate that the counts represent a legal Huffman code tree. */
  163290. code = 0;
  163291. si = huffsize[0];
  163292. p = 0;
  163293. while (huffsize[p]) {
  163294. while (((int) huffsize[p]) == si) {
  163295. huffcode[p++] = code;
  163296. code++;
  163297. }
  163298. /* code is now 1 more than the last code used for codelength si; but
  163299. * it must still fit in si bits, since no code is allowed to be all ones.
  163300. */
  163301. if (((INT32) code) >= (((INT32) 1) << si))
  163302. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163303. code <<= 1;
  163304. si++;
  163305. }
  163306. /* Figure C.3: generate encoding tables */
  163307. /* These are code and size indexed by symbol value */
  163308. /* Set all codeless symbols to have code length 0;
  163309. * this lets us detect duplicate VAL entries here, and later
  163310. * allows emit_bits to detect any attempt to emit such symbols.
  163311. */
  163312. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163313. /* This is also a convenient place to check for out-of-range
  163314. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163315. * but only 0..15 for DC. (We could constrain them further
  163316. * based on data depth and mode, but this seems enough.)
  163317. */
  163318. maxsymbol = isDC ? 15 : 255;
  163319. for (p = 0; p < lastp; p++) {
  163320. i = htbl->huffval[p];
  163321. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163322. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163323. dtbl->ehufco[i] = huffcode[p];
  163324. dtbl->ehufsi[i] = huffsize[p];
  163325. }
  163326. }
  163327. /* Outputting bytes to the file */
  163328. /* Emit a byte, taking 'action' if must suspend. */
  163329. #define emit_byte(state,val,action) \
  163330. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163331. if (--(state)->free_in_buffer == 0) \
  163332. if (! dump_buffer(state)) \
  163333. { action; } }
  163334. LOCAL(boolean)
  163335. dump_buffer (working_state * state)
  163336. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163337. {
  163338. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163339. if (! (*dest->empty_output_buffer) (state->cinfo))
  163340. return FALSE;
  163341. /* After a successful buffer dump, must reset buffer pointers */
  163342. state->next_output_byte = dest->next_output_byte;
  163343. state->free_in_buffer = dest->free_in_buffer;
  163344. return TRUE;
  163345. }
  163346. /* Outputting bits to the file */
  163347. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163348. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163349. * in one call, and we never retain more than 7 bits in put_buffer
  163350. * between calls, so 24 bits are sufficient.
  163351. */
  163352. INLINE
  163353. LOCAL(boolean)
  163354. emit_bits (working_state * state, unsigned int code, int size)
  163355. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163356. {
  163357. /* This routine is heavily used, so it's worth coding tightly. */
  163358. register INT32 put_buffer = (INT32) code;
  163359. register int put_bits = state->cur.put_bits;
  163360. /* if size is 0, caller used an invalid Huffman table entry */
  163361. if (size == 0)
  163362. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163363. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163364. put_bits += size; /* new number of bits in buffer */
  163365. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163366. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163367. while (put_bits >= 8) {
  163368. int c = (int) ((put_buffer >> 16) & 0xFF);
  163369. emit_byte(state, c, return FALSE);
  163370. if (c == 0xFF) { /* need to stuff a zero byte? */
  163371. emit_byte(state, 0, return FALSE);
  163372. }
  163373. put_buffer <<= 8;
  163374. put_bits -= 8;
  163375. }
  163376. state->cur.put_buffer = put_buffer; /* update state variables */
  163377. state->cur.put_bits = put_bits;
  163378. return TRUE;
  163379. }
  163380. LOCAL(boolean)
  163381. flush_bits (working_state * state)
  163382. {
  163383. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163384. return FALSE;
  163385. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163386. state->cur.put_bits = 0;
  163387. return TRUE;
  163388. }
  163389. /* Encode a single block's worth of coefficients */
  163390. LOCAL(boolean)
  163391. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163392. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163393. {
  163394. register int temp, temp2;
  163395. register int nbits;
  163396. register int k, r, i;
  163397. /* Encode the DC coefficient difference per section F.1.2.1 */
  163398. temp = temp2 = block[0] - last_dc_val;
  163399. if (temp < 0) {
  163400. temp = -temp; /* temp is abs value of input */
  163401. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163402. /* This code assumes we are on a two's complement machine */
  163403. temp2--;
  163404. }
  163405. /* Find the number of bits needed for the magnitude of the coefficient */
  163406. nbits = 0;
  163407. while (temp) {
  163408. nbits++;
  163409. temp >>= 1;
  163410. }
  163411. /* Check for out-of-range coefficient values.
  163412. * Since we're encoding a difference, the range limit is twice as much.
  163413. */
  163414. if (nbits > MAX_COEF_BITS+1)
  163415. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163416. /* Emit the Huffman-coded symbol for the number of bits */
  163417. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163418. return FALSE;
  163419. /* Emit that number of bits of the value, if positive, */
  163420. /* or the complement of its magnitude, if negative. */
  163421. if (nbits) /* emit_bits rejects calls with size 0 */
  163422. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163423. return FALSE;
  163424. /* Encode the AC coefficients per section F.1.2.2 */
  163425. r = 0; /* r = run length of zeros */
  163426. for (k = 1; k < DCTSIZE2; k++) {
  163427. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163428. r++;
  163429. } else {
  163430. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163431. while (r > 15) {
  163432. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163433. return FALSE;
  163434. r -= 16;
  163435. }
  163436. temp2 = temp;
  163437. if (temp < 0) {
  163438. temp = -temp; /* temp is abs value of input */
  163439. /* This code assumes we are on a two's complement machine */
  163440. temp2--;
  163441. }
  163442. /* Find the number of bits needed for the magnitude of the coefficient */
  163443. nbits = 1; /* there must be at least one 1 bit */
  163444. while ((temp >>= 1))
  163445. nbits++;
  163446. /* Check for out-of-range coefficient values */
  163447. if (nbits > MAX_COEF_BITS)
  163448. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163449. /* Emit Huffman symbol for run length / number of bits */
  163450. i = (r << 4) + nbits;
  163451. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163452. return FALSE;
  163453. /* Emit that number of bits of the value, if positive, */
  163454. /* or the complement of its magnitude, if negative. */
  163455. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163456. return FALSE;
  163457. r = 0;
  163458. }
  163459. }
  163460. /* If the last coef(s) were zero, emit an end-of-block code */
  163461. if (r > 0)
  163462. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163463. return FALSE;
  163464. return TRUE;
  163465. }
  163466. /*
  163467. * Emit a restart marker & resynchronize predictions.
  163468. */
  163469. LOCAL(boolean)
  163470. emit_restart (working_state * state, int restart_num)
  163471. {
  163472. int ci;
  163473. if (! flush_bits(state))
  163474. return FALSE;
  163475. emit_byte(state, 0xFF, return FALSE);
  163476. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163477. /* Re-initialize DC predictions to 0 */
  163478. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163479. state->cur.last_dc_val[ci] = 0;
  163480. /* The restart counter is not updated until we successfully write the MCU. */
  163481. return TRUE;
  163482. }
  163483. /*
  163484. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163485. */
  163486. METHODDEF(boolean)
  163487. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163488. {
  163489. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163490. working_state state;
  163491. int blkn, ci;
  163492. jpeg_component_info * compptr;
  163493. /* Load up working state */
  163494. state.next_output_byte = cinfo->dest->next_output_byte;
  163495. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163496. ASSIGN_STATE(state.cur, entropy->saved);
  163497. state.cinfo = cinfo;
  163498. /* Emit restart marker if needed */
  163499. if (cinfo->restart_interval) {
  163500. if (entropy->restarts_to_go == 0)
  163501. if (! emit_restart(&state, entropy->next_restart_num))
  163502. return FALSE;
  163503. }
  163504. /* Encode the MCU data blocks */
  163505. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163506. ci = cinfo->MCU_membership[blkn];
  163507. compptr = cinfo->cur_comp_info[ci];
  163508. if (! encode_one_block(&state,
  163509. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163510. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163511. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163512. return FALSE;
  163513. /* Update last_dc_val */
  163514. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163515. }
  163516. /* Completed MCU, so update state */
  163517. cinfo->dest->next_output_byte = state.next_output_byte;
  163518. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163519. ASSIGN_STATE(entropy->saved, state.cur);
  163520. /* Update restart-interval state too */
  163521. if (cinfo->restart_interval) {
  163522. if (entropy->restarts_to_go == 0) {
  163523. entropy->restarts_to_go = cinfo->restart_interval;
  163524. entropy->next_restart_num++;
  163525. entropy->next_restart_num &= 7;
  163526. }
  163527. entropy->restarts_to_go--;
  163528. }
  163529. return TRUE;
  163530. }
  163531. /*
  163532. * Finish up at the end of a Huffman-compressed scan.
  163533. */
  163534. METHODDEF(void)
  163535. finish_pass_huff (j_compress_ptr cinfo)
  163536. {
  163537. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163538. working_state state;
  163539. /* Load up working state ... flush_bits needs it */
  163540. state.next_output_byte = cinfo->dest->next_output_byte;
  163541. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163542. ASSIGN_STATE(state.cur, entropy->saved);
  163543. state.cinfo = cinfo;
  163544. /* Flush out the last data */
  163545. if (! flush_bits(&state))
  163546. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163547. /* Update state */
  163548. cinfo->dest->next_output_byte = state.next_output_byte;
  163549. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163550. ASSIGN_STATE(entropy->saved, state.cur);
  163551. }
  163552. /*
  163553. * Huffman coding optimization.
  163554. *
  163555. * We first scan the supplied data and count the number of uses of each symbol
  163556. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163557. * Then we build a Huffman coding tree for the observed counts.
  163558. * Symbols which are not needed at all for the particular image are not
  163559. * assigned any code, which saves space in the DHT marker as well as in
  163560. * the compressed data.
  163561. */
  163562. #ifdef ENTROPY_OPT_SUPPORTED
  163563. /* Process a single block's worth of coefficients */
  163564. LOCAL(void)
  163565. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163566. long dc_counts[], long ac_counts[])
  163567. {
  163568. register int temp;
  163569. register int nbits;
  163570. register int k, r;
  163571. /* Encode the DC coefficient difference per section F.1.2.1 */
  163572. temp = block[0] - last_dc_val;
  163573. if (temp < 0)
  163574. temp = -temp;
  163575. /* Find the number of bits needed for the magnitude of the coefficient */
  163576. nbits = 0;
  163577. while (temp) {
  163578. nbits++;
  163579. temp >>= 1;
  163580. }
  163581. /* Check for out-of-range coefficient values.
  163582. * Since we're encoding a difference, the range limit is twice as much.
  163583. */
  163584. if (nbits > MAX_COEF_BITS+1)
  163585. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163586. /* Count the Huffman symbol for the number of bits */
  163587. dc_counts[nbits]++;
  163588. /* Encode the AC coefficients per section F.1.2.2 */
  163589. r = 0; /* r = run length of zeros */
  163590. for (k = 1; k < DCTSIZE2; k++) {
  163591. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163592. r++;
  163593. } else {
  163594. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163595. while (r > 15) {
  163596. ac_counts[0xF0]++;
  163597. r -= 16;
  163598. }
  163599. /* Find the number of bits needed for the magnitude of the coefficient */
  163600. if (temp < 0)
  163601. temp = -temp;
  163602. /* Find the number of bits needed for the magnitude of the coefficient */
  163603. nbits = 1; /* there must be at least one 1 bit */
  163604. while ((temp >>= 1))
  163605. nbits++;
  163606. /* Check for out-of-range coefficient values */
  163607. if (nbits > MAX_COEF_BITS)
  163608. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163609. /* Count Huffman symbol for run length / number of bits */
  163610. ac_counts[(r << 4) + nbits]++;
  163611. r = 0;
  163612. }
  163613. }
  163614. /* If the last coef(s) were zero, emit an end-of-block code */
  163615. if (r > 0)
  163616. ac_counts[0]++;
  163617. }
  163618. /*
  163619. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163620. * No data is actually output, so no suspension return is possible.
  163621. */
  163622. METHODDEF(boolean)
  163623. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163624. {
  163625. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163626. int blkn, ci;
  163627. jpeg_component_info * compptr;
  163628. /* Take care of restart intervals if needed */
  163629. if (cinfo->restart_interval) {
  163630. if (entropy->restarts_to_go == 0) {
  163631. /* Re-initialize DC predictions to 0 */
  163632. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163633. entropy->saved.last_dc_val[ci] = 0;
  163634. /* Update restart state */
  163635. entropy->restarts_to_go = cinfo->restart_interval;
  163636. }
  163637. entropy->restarts_to_go--;
  163638. }
  163639. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163640. ci = cinfo->MCU_membership[blkn];
  163641. compptr = cinfo->cur_comp_info[ci];
  163642. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163643. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163644. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163645. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163646. }
  163647. return TRUE;
  163648. }
  163649. /*
  163650. * Generate the best Huffman code table for the given counts, fill htbl.
  163651. * Note this is also used by jcphuff.c.
  163652. *
  163653. * The JPEG standard requires that no symbol be assigned a codeword of all
  163654. * one bits (so that padding bits added at the end of a compressed segment
  163655. * can't look like a valid code). Because of the canonical ordering of
  163656. * codewords, this just means that there must be an unused slot in the
  163657. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163658. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163659. * with count 1. In theory that's not optimal; giving it count zero but
  163660. * including it in the symbol set anyway should give a better Huffman code.
  163661. * But the theoretically better code actually seems to come out worse in
  163662. * practice, because it produces more all-ones bytes (which incur stuffed
  163663. * zero bytes in the final file). In any case the difference is tiny.
  163664. *
  163665. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163666. * If some symbols have a very small but nonzero probability, the Huffman tree
  163667. * must be adjusted to meet the code length restriction. We currently use
  163668. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163669. * optimal; it may not choose the best possible limited-length code. But
  163670. * typically only very-low-frequency symbols will be given less-than-optimal
  163671. * lengths, so the code is almost optimal. Experimental comparisons against
  163672. * an optimal limited-length-code algorithm indicate that the difference is
  163673. * microscopic --- usually less than a hundredth of a percent of total size.
  163674. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163675. */
  163676. GLOBAL(void)
  163677. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163678. {
  163679. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163680. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163681. int codesize[257]; /* codesize[k] = code length of symbol k */
  163682. int others[257]; /* next symbol in current branch of tree */
  163683. int c1, c2;
  163684. int p, i, j;
  163685. long v;
  163686. /* This algorithm is explained in section K.2 of the JPEG standard */
  163687. MEMZERO(bits, SIZEOF(bits));
  163688. MEMZERO(codesize, SIZEOF(codesize));
  163689. for (i = 0; i < 257; i++)
  163690. others[i] = -1; /* init links to empty */
  163691. freq[256] = 1; /* make sure 256 has a nonzero count */
  163692. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163693. * that no real symbol is given code-value of all ones, because 256
  163694. * will be placed last in the largest codeword category.
  163695. */
  163696. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163697. for (;;) {
  163698. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163699. /* In case of ties, take the larger symbol number */
  163700. c1 = -1;
  163701. v = 1000000000L;
  163702. for (i = 0; i <= 256; i++) {
  163703. if (freq[i] && freq[i] <= v) {
  163704. v = freq[i];
  163705. c1 = i;
  163706. }
  163707. }
  163708. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163709. /* In case of ties, take the larger symbol number */
  163710. c2 = -1;
  163711. v = 1000000000L;
  163712. for (i = 0; i <= 256; i++) {
  163713. if (freq[i] && freq[i] <= v && i != c1) {
  163714. v = freq[i];
  163715. c2 = i;
  163716. }
  163717. }
  163718. /* Done if we've merged everything into one frequency */
  163719. if (c2 < 0)
  163720. break;
  163721. /* Else merge the two counts/trees */
  163722. freq[c1] += freq[c2];
  163723. freq[c2] = 0;
  163724. /* Increment the codesize of everything in c1's tree branch */
  163725. codesize[c1]++;
  163726. while (others[c1] >= 0) {
  163727. c1 = others[c1];
  163728. codesize[c1]++;
  163729. }
  163730. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163731. /* Increment the codesize of everything in c2's tree branch */
  163732. codesize[c2]++;
  163733. while (others[c2] >= 0) {
  163734. c2 = others[c2];
  163735. codesize[c2]++;
  163736. }
  163737. }
  163738. /* Now count the number of symbols of each code length */
  163739. for (i = 0; i <= 256; i++) {
  163740. if (codesize[i]) {
  163741. /* The JPEG standard seems to think that this can't happen, */
  163742. /* but I'm paranoid... */
  163743. if (codesize[i] > MAX_CLEN)
  163744. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163745. bits[codesize[i]]++;
  163746. }
  163747. }
  163748. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163749. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163750. * Here is what the JPEG spec says about how this next bit works:
  163751. * Since symbols are paired for the longest Huffman code, the symbols are
  163752. * removed from this length category two at a time. The prefix for the pair
  163753. * (which is one bit shorter) is allocated to one of the pair; then,
  163754. * skipping the BITS entry for that prefix length, a code word from the next
  163755. * shortest nonzero BITS entry is converted into a prefix for two code words
  163756. * one bit longer.
  163757. */
  163758. for (i = MAX_CLEN; i > 16; i--) {
  163759. while (bits[i] > 0) {
  163760. j = i - 2; /* find length of new prefix to be used */
  163761. while (bits[j] == 0)
  163762. j--;
  163763. bits[i] -= 2; /* remove two symbols */
  163764. bits[i-1]++; /* one goes in this length */
  163765. bits[j+1] += 2; /* two new symbols in this length */
  163766. bits[j]--; /* symbol of this length is now a prefix */
  163767. }
  163768. }
  163769. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163770. while (bits[i] == 0) /* find largest codelength still in use */
  163771. i--;
  163772. bits[i]--;
  163773. /* Return final symbol counts (only for lengths 0..16) */
  163774. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163775. /* Return a list of the symbols sorted by code length */
  163776. /* It's not real clear to me why we don't need to consider the codelength
  163777. * changes made above, but the JPEG spec seems to think this works.
  163778. */
  163779. p = 0;
  163780. for (i = 1; i <= MAX_CLEN; i++) {
  163781. for (j = 0; j <= 255; j++) {
  163782. if (codesize[j] == i) {
  163783. htbl->huffval[p] = (UINT8) j;
  163784. p++;
  163785. }
  163786. }
  163787. }
  163788. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163789. htbl->sent_table = FALSE;
  163790. }
  163791. /*
  163792. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163793. */
  163794. METHODDEF(void)
  163795. finish_pass_gather (j_compress_ptr cinfo)
  163796. {
  163797. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163798. int ci, dctbl, actbl;
  163799. jpeg_component_info * compptr;
  163800. JHUFF_TBL **htblptr;
  163801. boolean did_dc[NUM_HUFF_TBLS];
  163802. boolean did_ac[NUM_HUFF_TBLS];
  163803. /* It's important not to apply jpeg_gen_optimal_table more than once
  163804. * per table, because it clobbers the input frequency counts!
  163805. */
  163806. MEMZERO(did_dc, SIZEOF(did_dc));
  163807. MEMZERO(did_ac, SIZEOF(did_ac));
  163808. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163809. compptr = cinfo->cur_comp_info[ci];
  163810. dctbl = compptr->dc_tbl_no;
  163811. actbl = compptr->ac_tbl_no;
  163812. if (! did_dc[dctbl]) {
  163813. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163814. if (*htblptr == NULL)
  163815. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163816. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163817. did_dc[dctbl] = TRUE;
  163818. }
  163819. if (! did_ac[actbl]) {
  163820. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163821. if (*htblptr == NULL)
  163822. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163823. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163824. did_ac[actbl] = TRUE;
  163825. }
  163826. }
  163827. }
  163828. #endif /* ENTROPY_OPT_SUPPORTED */
  163829. /*
  163830. * Module initialization routine for Huffman entropy encoding.
  163831. */
  163832. GLOBAL(void)
  163833. jinit_huff_encoder (j_compress_ptr cinfo)
  163834. {
  163835. huff_entropy_ptr entropy;
  163836. int i;
  163837. entropy = (huff_entropy_ptr)
  163838. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163839. SIZEOF(huff_entropy_encoder));
  163840. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163841. entropy->pub.start_pass = start_pass_huff;
  163842. /* Mark tables unallocated */
  163843. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163844. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163845. #ifdef ENTROPY_OPT_SUPPORTED
  163846. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163847. #endif
  163848. }
  163849. }
  163850. /*** End of inlined file: jchuff.c ***/
  163851. #undef emit_byte
  163852. /*** Start of inlined file: jcinit.c ***/
  163853. #define JPEG_INTERNALS
  163854. /*
  163855. * Master selection of compression modules.
  163856. * This is done once at the start of processing an image. We determine
  163857. * which modules will be used and give them appropriate initialization calls.
  163858. */
  163859. GLOBAL(void)
  163860. jinit_compress_master (j_compress_ptr cinfo)
  163861. {
  163862. /* Initialize master control (includes parameter checking/processing) */
  163863. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163864. /* Preprocessing */
  163865. if (! cinfo->raw_data_in) {
  163866. jinit_color_converter(cinfo);
  163867. jinit_downsampler(cinfo);
  163868. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163869. }
  163870. /* Forward DCT */
  163871. jinit_forward_dct(cinfo);
  163872. /* Entropy encoding: either Huffman or arithmetic coding. */
  163873. if (cinfo->arith_code) {
  163874. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163875. } else {
  163876. if (cinfo->progressive_mode) {
  163877. #ifdef C_PROGRESSIVE_SUPPORTED
  163878. jinit_phuff_encoder(cinfo);
  163879. #else
  163880. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163881. #endif
  163882. } else
  163883. jinit_huff_encoder(cinfo);
  163884. }
  163885. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163886. jinit_c_coef_controller(cinfo,
  163887. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163888. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163889. jinit_marker_writer(cinfo);
  163890. /* We can now tell the memory manager to allocate virtual arrays. */
  163891. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163892. /* Write the datastream header (SOI) immediately.
  163893. * Frame and scan headers are postponed till later.
  163894. * This lets application insert special markers after the SOI.
  163895. */
  163896. (*cinfo->marker->write_file_header) (cinfo);
  163897. }
  163898. /*** End of inlined file: jcinit.c ***/
  163899. /*** Start of inlined file: jcmainct.c ***/
  163900. #define JPEG_INTERNALS
  163901. /* Note: currently, there is no operating mode in which a full-image buffer
  163902. * is needed at this step. If there were, that mode could not be used with
  163903. * "raw data" input, since this module is bypassed in that case. However,
  163904. * we've left the code here for possible use in special applications.
  163905. */
  163906. #undef FULL_MAIN_BUFFER_SUPPORTED
  163907. /* Private buffer controller object */
  163908. typedef struct {
  163909. struct jpeg_c_main_controller pub; /* public fields */
  163910. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163911. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163912. boolean suspended; /* remember if we suspended output */
  163913. J_BUF_MODE pass_mode; /* current operating mode */
  163914. /* If using just a strip buffer, this points to the entire set of buffers
  163915. * (we allocate one for each component). In the full-image case, this
  163916. * points to the currently accessible strips of the virtual arrays.
  163917. */
  163918. JSAMPARRAY buffer[MAX_COMPONENTS];
  163919. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163920. /* If using full-image storage, this array holds pointers to virtual-array
  163921. * control blocks for each component. Unused if not full-image storage.
  163922. */
  163923. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163924. #endif
  163925. } my_main_controller;
  163926. typedef my_main_controller * my_main_ptr;
  163927. /* Forward declarations */
  163928. METHODDEF(void) process_data_simple_main
  163929. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163930. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163931. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163932. METHODDEF(void) process_data_buffer_main
  163933. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163934. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163935. #endif
  163936. /*
  163937. * Initialize for a processing pass.
  163938. */
  163939. METHODDEF(void)
  163940. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163941. {
  163942. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163943. /* Do nothing in raw-data mode. */
  163944. if (cinfo->raw_data_in)
  163945. return;
  163946. main_->cur_iMCU_row = 0; /* initialize counters */
  163947. main_->rowgroup_ctr = 0;
  163948. main_->suspended = FALSE;
  163949. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163950. switch (pass_mode) {
  163951. case JBUF_PASS_THRU:
  163952. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163953. if (main_->whole_image[0] != NULL)
  163954. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163955. #endif
  163956. main_->pub.process_data = process_data_simple_main;
  163957. break;
  163958. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163959. case JBUF_SAVE_SOURCE:
  163960. case JBUF_CRANK_DEST:
  163961. case JBUF_SAVE_AND_PASS:
  163962. if (main_->whole_image[0] == NULL)
  163963. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163964. main_->pub.process_data = process_data_buffer_main;
  163965. break;
  163966. #endif
  163967. default:
  163968. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163969. break;
  163970. }
  163971. }
  163972. /*
  163973. * Process some data.
  163974. * This routine handles the simple pass-through mode,
  163975. * where we have only a strip buffer.
  163976. */
  163977. METHODDEF(void)
  163978. process_data_simple_main (j_compress_ptr cinfo,
  163979. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163980. JDIMENSION in_rows_avail)
  163981. {
  163982. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163983. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163984. /* Read input data if we haven't filled the main buffer yet */
  163985. if (main_->rowgroup_ctr < DCTSIZE)
  163986. (*cinfo->prep->pre_process_data) (cinfo,
  163987. input_buf, in_row_ctr, in_rows_avail,
  163988. main_->buffer, &main_->rowgroup_ctr,
  163989. (JDIMENSION) DCTSIZE);
  163990. /* If we don't have a full iMCU row buffered, return to application for
  163991. * more data. Note that preprocessor will always pad to fill the iMCU row
  163992. * at the bottom of the image.
  163993. */
  163994. if (main_->rowgroup_ctr != DCTSIZE)
  163995. return;
  163996. /* Send the completed row to the compressor */
  163997. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163998. /* If compressor did not consume the whole row, then we must need to
  163999. * suspend processing and return to the application. In this situation
  164000. * we pretend we didn't yet consume the last input row; otherwise, if
  164001. * it happened to be the last row of the image, the application would
  164002. * think we were done.
  164003. */
  164004. if (! main_->suspended) {
  164005. (*in_row_ctr)--;
  164006. main_->suspended = TRUE;
  164007. }
  164008. return;
  164009. }
  164010. /* We did finish the row. Undo our little suspension hack if a previous
  164011. * call suspended; then mark the main buffer empty.
  164012. */
  164013. if (main_->suspended) {
  164014. (*in_row_ctr)++;
  164015. main_->suspended = FALSE;
  164016. }
  164017. main_->rowgroup_ctr = 0;
  164018. main_->cur_iMCU_row++;
  164019. }
  164020. }
  164021. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164022. /*
  164023. * Process some data.
  164024. * This routine handles all of the modes that use a full-size buffer.
  164025. */
  164026. METHODDEF(void)
  164027. process_data_buffer_main (j_compress_ptr cinfo,
  164028. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164029. JDIMENSION in_rows_avail)
  164030. {
  164031. my_main_ptr main = (my_main_ptr) cinfo->main;
  164032. int ci;
  164033. jpeg_component_info *compptr;
  164034. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164035. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164036. /* Realign the virtual buffers if at the start of an iMCU row. */
  164037. if (main->rowgroup_ctr == 0) {
  164038. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164039. ci++, compptr++) {
  164040. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164041. ((j_common_ptr) cinfo, main->whole_image[ci],
  164042. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164043. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164044. }
  164045. /* In a read pass, pretend we just read some source data. */
  164046. if (! writing) {
  164047. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164048. main->rowgroup_ctr = DCTSIZE;
  164049. }
  164050. }
  164051. /* If a write pass, read input data until the current iMCU row is full. */
  164052. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164053. if (writing) {
  164054. (*cinfo->prep->pre_process_data) (cinfo,
  164055. input_buf, in_row_ctr, in_rows_avail,
  164056. main->buffer, &main->rowgroup_ctr,
  164057. (JDIMENSION) DCTSIZE);
  164058. /* Return to application if we need more data to fill the iMCU row. */
  164059. if (main->rowgroup_ctr < DCTSIZE)
  164060. return;
  164061. }
  164062. /* Emit data, unless this is a sink-only pass. */
  164063. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164064. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164065. /* If compressor did not consume the whole row, then we must need to
  164066. * suspend processing and return to the application. In this situation
  164067. * we pretend we didn't yet consume the last input row; otherwise, if
  164068. * it happened to be the last row of the image, the application would
  164069. * think we were done.
  164070. */
  164071. if (! main->suspended) {
  164072. (*in_row_ctr)--;
  164073. main->suspended = TRUE;
  164074. }
  164075. return;
  164076. }
  164077. /* We did finish the row. Undo our little suspension hack if a previous
  164078. * call suspended; then mark the main buffer empty.
  164079. */
  164080. if (main->suspended) {
  164081. (*in_row_ctr)++;
  164082. main->suspended = FALSE;
  164083. }
  164084. }
  164085. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164086. main->rowgroup_ctr = 0;
  164087. main->cur_iMCU_row++;
  164088. }
  164089. }
  164090. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164091. /*
  164092. * Initialize main buffer controller.
  164093. */
  164094. GLOBAL(void)
  164095. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164096. {
  164097. my_main_ptr main_;
  164098. int ci;
  164099. jpeg_component_info *compptr;
  164100. main_ = (my_main_ptr)
  164101. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164102. SIZEOF(my_main_controller));
  164103. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164104. main_->pub.start_pass = start_pass_main;
  164105. /* We don't need to create a buffer in raw-data mode. */
  164106. if (cinfo->raw_data_in)
  164107. return;
  164108. /* Create the buffer. It holds downsampled data, so each component
  164109. * may be of a different size.
  164110. */
  164111. if (need_full_buffer) {
  164112. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164113. /* Allocate a full-image virtual array for each component */
  164114. /* Note we pad the bottom to a multiple of the iMCU height */
  164115. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164116. ci++, compptr++) {
  164117. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164118. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164119. compptr->width_in_blocks * DCTSIZE,
  164120. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164121. (long) compptr->v_samp_factor) * DCTSIZE,
  164122. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164123. }
  164124. #else
  164125. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164126. #endif
  164127. } else {
  164128. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164129. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164130. #endif
  164131. /* Allocate a strip buffer for each component */
  164132. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164133. ci++, compptr++) {
  164134. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164135. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164136. compptr->width_in_blocks * DCTSIZE,
  164137. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164138. }
  164139. }
  164140. }
  164141. /*** End of inlined file: jcmainct.c ***/
  164142. /*** Start of inlined file: jcmarker.c ***/
  164143. #define JPEG_INTERNALS
  164144. /* Private state */
  164145. typedef struct {
  164146. struct jpeg_marker_writer pub; /* public fields */
  164147. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164148. } my_marker_writer;
  164149. typedef my_marker_writer * my_marker_ptr;
  164150. /*
  164151. * Basic output routines.
  164152. *
  164153. * Note that we do not support suspension while writing a marker.
  164154. * Therefore, an application using suspension must ensure that there is
  164155. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164156. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164157. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164158. * modes are not supported at all with suspension, so those two are the only
  164159. * points where markers will be written.
  164160. */
  164161. LOCAL(void)
  164162. emit_byte (j_compress_ptr cinfo, int val)
  164163. /* Emit a byte */
  164164. {
  164165. struct jpeg_destination_mgr * dest = cinfo->dest;
  164166. *(dest->next_output_byte)++ = (JOCTET) val;
  164167. if (--dest->free_in_buffer == 0) {
  164168. if (! (*dest->empty_output_buffer) (cinfo))
  164169. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164170. }
  164171. }
  164172. LOCAL(void)
  164173. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164174. /* Emit a marker code */
  164175. {
  164176. emit_byte(cinfo, 0xFF);
  164177. emit_byte(cinfo, (int) mark);
  164178. }
  164179. LOCAL(void)
  164180. emit_2bytes (j_compress_ptr cinfo, int value)
  164181. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164182. {
  164183. emit_byte(cinfo, (value >> 8) & 0xFF);
  164184. emit_byte(cinfo, value & 0xFF);
  164185. }
  164186. /*
  164187. * Routines to write specific marker types.
  164188. */
  164189. LOCAL(int)
  164190. emit_dqt (j_compress_ptr cinfo, int index)
  164191. /* Emit a DQT marker */
  164192. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164193. {
  164194. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164195. int prec;
  164196. int i;
  164197. if (qtbl == NULL)
  164198. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164199. prec = 0;
  164200. for (i = 0; i < DCTSIZE2; i++) {
  164201. if (qtbl->quantval[i] > 255)
  164202. prec = 1;
  164203. }
  164204. if (! qtbl->sent_table) {
  164205. emit_marker(cinfo, M_DQT);
  164206. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164207. emit_byte(cinfo, index + (prec<<4));
  164208. for (i = 0; i < DCTSIZE2; i++) {
  164209. /* The table entries must be emitted in zigzag order. */
  164210. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164211. if (prec)
  164212. emit_byte(cinfo, (int) (qval >> 8));
  164213. emit_byte(cinfo, (int) (qval & 0xFF));
  164214. }
  164215. qtbl->sent_table = TRUE;
  164216. }
  164217. return prec;
  164218. }
  164219. LOCAL(void)
  164220. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164221. /* Emit a DHT marker */
  164222. {
  164223. JHUFF_TBL * htbl;
  164224. int length, i;
  164225. if (is_ac) {
  164226. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164227. index += 0x10; /* output index has AC bit set */
  164228. } else {
  164229. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164230. }
  164231. if (htbl == NULL)
  164232. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164233. if (! htbl->sent_table) {
  164234. emit_marker(cinfo, M_DHT);
  164235. length = 0;
  164236. for (i = 1; i <= 16; i++)
  164237. length += htbl->bits[i];
  164238. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164239. emit_byte(cinfo, index);
  164240. for (i = 1; i <= 16; i++)
  164241. emit_byte(cinfo, htbl->bits[i]);
  164242. for (i = 0; i < length; i++)
  164243. emit_byte(cinfo, htbl->huffval[i]);
  164244. htbl->sent_table = TRUE;
  164245. }
  164246. }
  164247. LOCAL(void)
  164248. emit_dac (j_compress_ptr)
  164249. /* Emit a DAC marker */
  164250. /* Since the useful info is so small, we want to emit all the tables in */
  164251. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164252. {
  164253. #ifdef C_ARITH_CODING_SUPPORTED
  164254. char dc_in_use[NUM_ARITH_TBLS];
  164255. char ac_in_use[NUM_ARITH_TBLS];
  164256. int length, i;
  164257. jpeg_component_info *compptr;
  164258. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164259. dc_in_use[i] = ac_in_use[i] = 0;
  164260. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164261. compptr = cinfo->cur_comp_info[i];
  164262. dc_in_use[compptr->dc_tbl_no] = 1;
  164263. ac_in_use[compptr->ac_tbl_no] = 1;
  164264. }
  164265. length = 0;
  164266. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164267. length += dc_in_use[i] + ac_in_use[i];
  164268. emit_marker(cinfo, M_DAC);
  164269. emit_2bytes(cinfo, length*2 + 2);
  164270. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164271. if (dc_in_use[i]) {
  164272. emit_byte(cinfo, i);
  164273. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164274. }
  164275. if (ac_in_use[i]) {
  164276. emit_byte(cinfo, i + 0x10);
  164277. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164278. }
  164279. }
  164280. #endif /* C_ARITH_CODING_SUPPORTED */
  164281. }
  164282. LOCAL(void)
  164283. emit_dri (j_compress_ptr cinfo)
  164284. /* Emit a DRI marker */
  164285. {
  164286. emit_marker(cinfo, M_DRI);
  164287. emit_2bytes(cinfo, 4); /* fixed length */
  164288. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164289. }
  164290. LOCAL(void)
  164291. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164292. /* Emit a SOF marker */
  164293. {
  164294. int ci;
  164295. jpeg_component_info *compptr;
  164296. emit_marker(cinfo, code);
  164297. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164298. /* Make sure image isn't bigger than SOF field can handle */
  164299. if ((long) cinfo->image_height > 65535L ||
  164300. (long) cinfo->image_width > 65535L)
  164301. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164302. emit_byte(cinfo, cinfo->data_precision);
  164303. emit_2bytes(cinfo, (int) cinfo->image_height);
  164304. emit_2bytes(cinfo, (int) cinfo->image_width);
  164305. emit_byte(cinfo, cinfo->num_components);
  164306. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164307. ci++, compptr++) {
  164308. emit_byte(cinfo, compptr->component_id);
  164309. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164310. emit_byte(cinfo, compptr->quant_tbl_no);
  164311. }
  164312. }
  164313. LOCAL(void)
  164314. emit_sos (j_compress_ptr cinfo)
  164315. /* Emit a SOS marker */
  164316. {
  164317. int i, td, ta;
  164318. jpeg_component_info *compptr;
  164319. emit_marker(cinfo, M_SOS);
  164320. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164321. emit_byte(cinfo, cinfo->comps_in_scan);
  164322. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164323. compptr = cinfo->cur_comp_info[i];
  164324. emit_byte(cinfo, compptr->component_id);
  164325. td = compptr->dc_tbl_no;
  164326. ta = compptr->ac_tbl_no;
  164327. if (cinfo->progressive_mode) {
  164328. /* Progressive mode: only DC or only AC tables are used in one scan;
  164329. * furthermore, Huffman coding of DC refinement uses no table at all.
  164330. * We emit 0 for unused field(s); this is recommended by the P&M text
  164331. * but does not seem to be specified in the standard.
  164332. */
  164333. if (cinfo->Ss == 0) {
  164334. ta = 0; /* DC scan */
  164335. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164336. td = 0; /* no DC table either */
  164337. } else {
  164338. td = 0; /* AC scan */
  164339. }
  164340. }
  164341. emit_byte(cinfo, (td << 4) + ta);
  164342. }
  164343. emit_byte(cinfo, cinfo->Ss);
  164344. emit_byte(cinfo, cinfo->Se);
  164345. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164346. }
  164347. LOCAL(void)
  164348. emit_jfif_app0 (j_compress_ptr cinfo)
  164349. /* Emit a JFIF-compliant APP0 marker */
  164350. {
  164351. /*
  164352. * Length of APP0 block (2 bytes)
  164353. * Block ID (4 bytes - ASCII "JFIF")
  164354. * Zero byte (1 byte to terminate the ID string)
  164355. * Version Major, Minor (2 bytes - major first)
  164356. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164357. * Xdpu (2 bytes - dots per unit horizontal)
  164358. * Ydpu (2 bytes - dots per unit vertical)
  164359. * Thumbnail X size (1 byte)
  164360. * Thumbnail Y size (1 byte)
  164361. */
  164362. emit_marker(cinfo, M_APP0);
  164363. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164364. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164365. emit_byte(cinfo, 0x46);
  164366. emit_byte(cinfo, 0x49);
  164367. emit_byte(cinfo, 0x46);
  164368. emit_byte(cinfo, 0);
  164369. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164370. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164371. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164372. emit_2bytes(cinfo, (int) cinfo->X_density);
  164373. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164374. emit_byte(cinfo, 0); /* No thumbnail image */
  164375. emit_byte(cinfo, 0);
  164376. }
  164377. LOCAL(void)
  164378. emit_adobe_app14 (j_compress_ptr cinfo)
  164379. /* Emit an Adobe APP14 marker */
  164380. {
  164381. /*
  164382. * Length of APP14 block (2 bytes)
  164383. * Block ID (5 bytes - ASCII "Adobe")
  164384. * Version Number (2 bytes - currently 100)
  164385. * Flags0 (2 bytes - currently 0)
  164386. * Flags1 (2 bytes - currently 0)
  164387. * Color transform (1 byte)
  164388. *
  164389. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164390. * now in circulation seem to use Version = 100, so that's what we write.
  164391. *
  164392. * We write the color transform byte as 1 if the JPEG color space is
  164393. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164394. * whether the encoder performed a transformation, which is pretty useless.
  164395. */
  164396. emit_marker(cinfo, M_APP14);
  164397. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164398. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164399. emit_byte(cinfo, 0x64);
  164400. emit_byte(cinfo, 0x6F);
  164401. emit_byte(cinfo, 0x62);
  164402. emit_byte(cinfo, 0x65);
  164403. emit_2bytes(cinfo, 100); /* Version */
  164404. emit_2bytes(cinfo, 0); /* Flags0 */
  164405. emit_2bytes(cinfo, 0); /* Flags1 */
  164406. switch (cinfo->jpeg_color_space) {
  164407. case JCS_YCbCr:
  164408. emit_byte(cinfo, 1); /* Color transform = 1 */
  164409. break;
  164410. case JCS_YCCK:
  164411. emit_byte(cinfo, 2); /* Color transform = 2 */
  164412. break;
  164413. default:
  164414. emit_byte(cinfo, 0); /* Color transform = 0 */
  164415. break;
  164416. }
  164417. }
  164418. /*
  164419. * These routines allow writing an arbitrary marker with parameters.
  164420. * The only intended use is to emit COM or APPn markers after calling
  164421. * write_file_header and before calling write_frame_header.
  164422. * Other uses are not guaranteed to produce desirable results.
  164423. * Counting the parameter bytes properly is the caller's responsibility.
  164424. */
  164425. METHODDEF(void)
  164426. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164427. /* Emit an arbitrary marker header */
  164428. {
  164429. if (datalen > (unsigned int) 65533) /* safety check */
  164430. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164431. emit_marker(cinfo, (JPEG_MARKER) marker);
  164432. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164433. }
  164434. METHODDEF(void)
  164435. write_marker_byte (j_compress_ptr cinfo, int val)
  164436. /* Emit one byte of marker parameters following write_marker_header */
  164437. {
  164438. emit_byte(cinfo, val);
  164439. }
  164440. /*
  164441. * Write datastream header.
  164442. * This consists of an SOI and optional APPn markers.
  164443. * We recommend use of the JFIF marker, but not the Adobe marker,
  164444. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164445. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164446. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164447. * Note that an application can write additional header markers after
  164448. * jpeg_start_compress returns.
  164449. */
  164450. METHODDEF(void)
  164451. write_file_header (j_compress_ptr cinfo)
  164452. {
  164453. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164454. emit_marker(cinfo, M_SOI); /* first the SOI */
  164455. /* SOI is defined to reset restart interval to 0 */
  164456. marker->last_restart_interval = 0;
  164457. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164458. emit_jfif_app0(cinfo);
  164459. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164460. emit_adobe_app14(cinfo);
  164461. }
  164462. /*
  164463. * Write frame header.
  164464. * This consists of DQT and SOFn markers.
  164465. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164466. * This avoids compatibility problems with incorrect implementations that
  164467. * try to error-check the quant table numbers as soon as they see the SOF.
  164468. */
  164469. METHODDEF(void)
  164470. write_frame_header (j_compress_ptr cinfo)
  164471. {
  164472. int ci, prec;
  164473. boolean is_baseline;
  164474. jpeg_component_info *compptr;
  164475. /* Emit DQT for each quantization table.
  164476. * Note that emit_dqt() suppresses any duplicate tables.
  164477. */
  164478. prec = 0;
  164479. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164480. ci++, compptr++) {
  164481. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164482. }
  164483. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164484. /* Check for a non-baseline specification.
  164485. * Note we assume that Huffman table numbers won't be changed later.
  164486. */
  164487. if (cinfo->arith_code || cinfo->progressive_mode ||
  164488. cinfo->data_precision != 8) {
  164489. is_baseline = FALSE;
  164490. } else {
  164491. is_baseline = TRUE;
  164492. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164493. ci++, compptr++) {
  164494. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164495. is_baseline = FALSE;
  164496. }
  164497. if (prec && is_baseline) {
  164498. is_baseline = FALSE;
  164499. /* If it's baseline except for quantizer size, warn the user */
  164500. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164501. }
  164502. }
  164503. /* Emit the proper SOF marker */
  164504. if (cinfo->arith_code) {
  164505. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164506. } else {
  164507. if (cinfo->progressive_mode)
  164508. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164509. else if (is_baseline)
  164510. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164511. else
  164512. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164513. }
  164514. }
  164515. /*
  164516. * Write scan header.
  164517. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164518. * Compressed data will be written following the SOS.
  164519. */
  164520. METHODDEF(void)
  164521. write_scan_header (j_compress_ptr cinfo)
  164522. {
  164523. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164524. int i;
  164525. jpeg_component_info *compptr;
  164526. if (cinfo->arith_code) {
  164527. /* Emit arith conditioning info. We may have some duplication
  164528. * if the file has multiple scans, but it's so small it's hardly
  164529. * worth worrying about.
  164530. */
  164531. emit_dac(cinfo);
  164532. } else {
  164533. /* Emit Huffman tables.
  164534. * Note that emit_dht() suppresses any duplicate tables.
  164535. */
  164536. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164537. compptr = cinfo->cur_comp_info[i];
  164538. if (cinfo->progressive_mode) {
  164539. /* Progressive mode: only DC or only AC tables are used in one scan */
  164540. if (cinfo->Ss == 0) {
  164541. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164542. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164543. } else {
  164544. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164545. }
  164546. } else {
  164547. /* Sequential mode: need both DC and AC tables */
  164548. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164549. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164550. }
  164551. }
  164552. }
  164553. /* Emit DRI if required --- note that DRI value could change for each scan.
  164554. * We avoid wasting space with unnecessary DRIs, however.
  164555. */
  164556. if (cinfo->restart_interval != marker->last_restart_interval) {
  164557. emit_dri(cinfo);
  164558. marker->last_restart_interval = cinfo->restart_interval;
  164559. }
  164560. emit_sos(cinfo);
  164561. }
  164562. /*
  164563. * Write datastream trailer.
  164564. */
  164565. METHODDEF(void)
  164566. write_file_trailer (j_compress_ptr cinfo)
  164567. {
  164568. emit_marker(cinfo, M_EOI);
  164569. }
  164570. /*
  164571. * Write an abbreviated table-specification datastream.
  164572. * This consists of SOI, DQT and DHT tables, and EOI.
  164573. * Any table that is defined and not marked sent_table = TRUE will be
  164574. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164575. */
  164576. METHODDEF(void)
  164577. write_tables_only (j_compress_ptr cinfo)
  164578. {
  164579. int i;
  164580. emit_marker(cinfo, M_SOI);
  164581. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164582. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164583. (void) emit_dqt(cinfo, i);
  164584. }
  164585. if (! cinfo->arith_code) {
  164586. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164587. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164588. emit_dht(cinfo, i, FALSE);
  164589. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164590. emit_dht(cinfo, i, TRUE);
  164591. }
  164592. }
  164593. emit_marker(cinfo, M_EOI);
  164594. }
  164595. /*
  164596. * Initialize the marker writer module.
  164597. */
  164598. GLOBAL(void)
  164599. jinit_marker_writer (j_compress_ptr cinfo)
  164600. {
  164601. my_marker_ptr marker;
  164602. /* Create the subobject */
  164603. marker = (my_marker_ptr)
  164604. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164605. SIZEOF(my_marker_writer));
  164606. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164607. /* Initialize method pointers */
  164608. marker->pub.write_file_header = write_file_header;
  164609. marker->pub.write_frame_header = write_frame_header;
  164610. marker->pub.write_scan_header = write_scan_header;
  164611. marker->pub.write_file_trailer = write_file_trailer;
  164612. marker->pub.write_tables_only = write_tables_only;
  164613. marker->pub.write_marker_header = write_marker_header;
  164614. marker->pub.write_marker_byte = write_marker_byte;
  164615. /* Initialize private state */
  164616. marker->last_restart_interval = 0;
  164617. }
  164618. /*** End of inlined file: jcmarker.c ***/
  164619. /*** Start of inlined file: jcmaster.c ***/
  164620. #define JPEG_INTERNALS
  164621. /* Private state */
  164622. typedef enum {
  164623. main_pass, /* input data, also do first output step */
  164624. huff_opt_pass, /* Huffman code optimization pass */
  164625. output_pass /* data output pass */
  164626. } c_pass_type;
  164627. typedef struct {
  164628. struct jpeg_comp_master pub; /* public fields */
  164629. c_pass_type pass_type; /* the type of the current pass */
  164630. int pass_number; /* # of passes completed */
  164631. int total_passes; /* total # of passes needed */
  164632. int scan_number; /* current index in scan_info[] */
  164633. } my_comp_master;
  164634. typedef my_comp_master * my_master_ptr;
  164635. /*
  164636. * Support routines that do various essential calculations.
  164637. */
  164638. LOCAL(void)
  164639. initial_setup (j_compress_ptr cinfo)
  164640. /* Do computations that are needed before master selection phase */
  164641. {
  164642. int ci;
  164643. jpeg_component_info *compptr;
  164644. long samplesperrow;
  164645. JDIMENSION jd_samplesperrow;
  164646. /* Sanity check on image dimensions */
  164647. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164648. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164649. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164650. /* Make sure image isn't bigger than I can handle */
  164651. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164652. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164653. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164654. /* Width of an input scanline must be representable as JDIMENSION. */
  164655. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164656. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164657. if ((long) jd_samplesperrow != samplesperrow)
  164658. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164659. /* For now, precision must match compiled-in value... */
  164660. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164661. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164662. /* Check that number of components won't exceed internal array sizes */
  164663. if (cinfo->num_components > MAX_COMPONENTS)
  164664. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164665. MAX_COMPONENTS);
  164666. /* Compute maximum sampling factors; check factor validity */
  164667. cinfo->max_h_samp_factor = 1;
  164668. cinfo->max_v_samp_factor = 1;
  164669. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164670. ci++, compptr++) {
  164671. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164672. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164673. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164674. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164675. compptr->h_samp_factor);
  164676. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164677. compptr->v_samp_factor);
  164678. }
  164679. /* Compute dimensions of components */
  164680. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164681. ci++, compptr++) {
  164682. /* Fill in the correct component_index value; don't rely on application */
  164683. compptr->component_index = ci;
  164684. /* For compression, we never do DCT scaling. */
  164685. compptr->DCT_scaled_size = DCTSIZE;
  164686. /* Size in DCT blocks */
  164687. compptr->width_in_blocks = (JDIMENSION)
  164688. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164689. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164690. compptr->height_in_blocks = (JDIMENSION)
  164691. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164692. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164693. /* Size in samples */
  164694. compptr->downsampled_width = (JDIMENSION)
  164695. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164696. (long) cinfo->max_h_samp_factor);
  164697. compptr->downsampled_height = (JDIMENSION)
  164698. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164699. (long) cinfo->max_v_samp_factor);
  164700. /* Mark component needed (this flag isn't actually used for compression) */
  164701. compptr->component_needed = TRUE;
  164702. }
  164703. /* Compute number of fully interleaved MCU rows (number of times that
  164704. * main controller will call coefficient controller).
  164705. */
  164706. cinfo->total_iMCU_rows = (JDIMENSION)
  164707. jdiv_round_up((long) cinfo->image_height,
  164708. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164709. }
  164710. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164711. LOCAL(void)
  164712. validate_script (j_compress_ptr cinfo)
  164713. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164714. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164715. */
  164716. {
  164717. const jpeg_scan_info * scanptr;
  164718. int scanno, ncomps, ci, coefi, thisi;
  164719. int Ss, Se, Ah, Al;
  164720. boolean component_sent[MAX_COMPONENTS];
  164721. #ifdef C_PROGRESSIVE_SUPPORTED
  164722. int * last_bitpos_ptr;
  164723. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164724. /* -1 until that coefficient has been seen; then last Al for it */
  164725. #endif
  164726. if (cinfo->num_scans <= 0)
  164727. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164728. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164729. * for progressive JPEG, no scan can have this.
  164730. */
  164731. scanptr = cinfo->scan_info;
  164732. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164733. #ifdef C_PROGRESSIVE_SUPPORTED
  164734. cinfo->progressive_mode = TRUE;
  164735. last_bitpos_ptr = & last_bitpos[0][0];
  164736. for (ci = 0; ci < cinfo->num_components; ci++)
  164737. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164738. *last_bitpos_ptr++ = -1;
  164739. #else
  164740. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164741. #endif
  164742. } else {
  164743. cinfo->progressive_mode = FALSE;
  164744. for (ci = 0; ci < cinfo->num_components; ci++)
  164745. component_sent[ci] = FALSE;
  164746. }
  164747. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164748. /* Validate component indexes */
  164749. ncomps = scanptr->comps_in_scan;
  164750. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164751. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164752. for (ci = 0; ci < ncomps; ci++) {
  164753. thisi = scanptr->component_index[ci];
  164754. if (thisi < 0 || thisi >= cinfo->num_components)
  164755. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164756. /* Components must appear in SOF order within each scan */
  164757. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164758. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164759. }
  164760. /* Validate progression parameters */
  164761. Ss = scanptr->Ss;
  164762. Se = scanptr->Se;
  164763. Ah = scanptr->Ah;
  164764. Al = scanptr->Al;
  164765. if (cinfo->progressive_mode) {
  164766. #ifdef C_PROGRESSIVE_SUPPORTED
  164767. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164768. * seems wrong: the upper bound ought to depend on data precision.
  164769. * Perhaps they really meant 0..N+1 for N-bit precision.
  164770. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164771. * out-of-range reconstructed DC values during the first DC scan,
  164772. * which might cause problems for some decoders.
  164773. */
  164774. #if BITS_IN_JSAMPLE == 8
  164775. #define MAX_AH_AL 10
  164776. #else
  164777. #define MAX_AH_AL 13
  164778. #endif
  164779. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164780. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164781. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164782. if (Ss == 0) {
  164783. if (Se != 0) /* DC and AC together not OK */
  164784. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164785. } else {
  164786. if (ncomps != 1) /* AC scans must be for only one component */
  164787. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164788. }
  164789. for (ci = 0; ci < ncomps; ci++) {
  164790. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164791. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164792. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164793. for (coefi = Ss; coefi <= Se; coefi++) {
  164794. if (last_bitpos_ptr[coefi] < 0) {
  164795. /* first scan of this coefficient */
  164796. if (Ah != 0)
  164797. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164798. } else {
  164799. /* not first scan */
  164800. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164801. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164802. }
  164803. last_bitpos_ptr[coefi] = Al;
  164804. }
  164805. }
  164806. #endif
  164807. } else {
  164808. /* For sequential JPEG, all progression parameters must be these: */
  164809. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164810. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164811. /* Make sure components are not sent twice */
  164812. for (ci = 0; ci < ncomps; ci++) {
  164813. thisi = scanptr->component_index[ci];
  164814. if (component_sent[thisi])
  164815. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164816. component_sent[thisi] = TRUE;
  164817. }
  164818. }
  164819. }
  164820. /* Now verify that everything got sent. */
  164821. if (cinfo->progressive_mode) {
  164822. #ifdef C_PROGRESSIVE_SUPPORTED
  164823. /* For progressive mode, we only check that at least some DC data
  164824. * got sent for each component; the spec does not require that all bits
  164825. * of all coefficients be transmitted. Would it be wiser to enforce
  164826. * transmission of all coefficient bits??
  164827. */
  164828. for (ci = 0; ci < cinfo->num_components; ci++) {
  164829. if (last_bitpos[ci][0] < 0)
  164830. ERREXIT(cinfo, JERR_MISSING_DATA);
  164831. }
  164832. #endif
  164833. } else {
  164834. for (ci = 0; ci < cinfo->num_components; ci++) {
  164835. if (! component_sent[ci])
  164836. ERREXIT(cinfo, JERR_MISSING_DATA);
  164837. }
  164838. }
  164839. }
  164840. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164841. LOCAL(void)
  164842. select_scan_parameters (j_compress_ptr cinfo)
  164843. /* Set up the scan parameters for the current scan */
  164844. {
  164845. int ci;
  164846. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164847. if (cinfo->scan_info != NULL) {
  164848. /* Prepare for current scan --- the script is already validated */
  164849. my_master_ptr master = (my_master_ptr) cinfo->master;
  164850. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164851. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164852. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164853. cinfo->cur_comp_info[ci] =
  164854. &cinfo->comp_info[scanptr->component_index[ci]];
  164855. }
  164856. cinfo->Ss = scanptr->Ss;
  164857. cinfo->Se = scanptr->Se;
  164858. cinfo->Ah = scanptr->Ah;
  164859. cinfo->Al = scanptr->Al;
  164860. }
  164861. else
  164862. #endif
  164863. {
  164864. /* Prepare for single sequential-JPEG scan containing all components */
  164865. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164866. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164867. MAX_COMPS_IN_SCAN);
  164868. cinfo->comps_in_scan = cinfo->num_components;
  164869. for (ci = 0; ci < cinfo->num_components; ci++) {
  164870. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164871. }
  164872. cinfo->Ss = 0;
  164873. cinfo->Se = DCTSIZE2-1;
  164874. cinfo->Ah = 0;
  164875. cinfo->Al = 0;
  164876. }
  164877. }
  164878. LOCAL(void)
  164879. per_scan_setup (j_compress_ptr cinfo)
  164880. /* Do computations that are needed before processing a JPEG scan */
  164881. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164882. {
  164883. int ci, mcublks, tmp;
  164884. jpeg_component_info *compptr;
  164885. if (cinfo->comps_in_scan == 1) {
  164886. /* Noninterleaved (single-component) scan */
  164887. compptr = cinfo->cur_comp_info[0];
  164888. /* Overall image size in MCUs */
  164889. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164890. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164891. /* For noninterleaved scan, always one block per MCU */
  164892. compptr->MCU_width = 1;
  164893. compptr->MCU_height = 1;
  164894. compptr->MCU_blocks = 1;
  164895. compptr->MCU_sample_width = DCTSIZE;
  164896. compptr->last_col_width = 1;
  164897. /* For noninterleaved scans, it is convenient to define last_row_height
  164898. * as the number of block rows present in the last iMCU row.
  164899. */
  164900. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164901. if (tmp == 0) tmp = compptr->v_samp_factor;
  164902. compptr->last_row_height = tmp;
  164903. /* Prepare array describing MCU composition */
  164904. cinfo->blocks_in_MCU = 1;
  164905. cinfo->MCU_membership[0] = 0;
  164906. } else {
  164907. /* Interleaved (multi-component) scan */
  164908. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164909. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164910. MAX_COMPS_IN_SCAN);
  164911. /* Overall image size in MCUs */
  164912. cinfo->MCUs_per_row = (JDIMENSION)
  164913. jdiv_round_up((long) cinfo->image_width,
  164914. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164915. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164916. jdiv_round_up((long) cinfo->image_height,
  164917. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164918. cinfo->blocks_in_MCU = 0;
  164919. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164920. compptr = cinfo->cur_comp_info[ci];
  164921. /* Sampling factors give # of blocks of component in each MCU */
  164922. compptr->MCU_width = compptr->h_samp_factor;
  164923. compptr->MCU_height = compptr->v_samp_factor;
  164924. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164925. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164926. /* Figure number of non-dummy blocks in last MCU column & row */
  164927. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164928. if (tmp == 0) tmp = compptr->MCU_width;
  164929. compptr->last_col_width = tmp;
  164930. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164931. if (tmp == 0) tmp = compptr->MCU_height;
  164932. compptr->last_row_height = tmp;
  164933. /* Prepare array describing MCU composition */
  164934. mcublks = compptr->MCU_blocks;
  164935. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164936. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164937. while (mcublks-- > 0) {
  164938. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164939. }
  164940. }
  164941. }
  164942. /* Convert restart specified in rows to actual MCU count. */
  164943. /* Note that count must fit in 16 bits, so we provide limiting. */
  164944. if (cinfo->restart_in_rows > 0) {
  164945. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164946. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164947. }
  164948. }
  164949. /*
  164950. * Per-pass setup.
  164951. * This is called at the beginning of each pass. We determine which modules
  164952. * will be active during this pass and give them appropriate start_pass calls.
  164953. * We also set is_last_pass to indicate whether any more passes will be
  164954. * required.
  164955. */
  164956. METHODDEF(void)
  164957. prepare_for_pass (j_compress_ptr cinfo)
  164958. {
  164959. my_master_ptr master = (my_master_ptr) cinfo->master;
  164960. switch (master->pass_type) {
  164961. case main_pass:
  164962. /* Initial pass: will collect input data, and do either Huffman
  164963. * optimization or data output for the first scan.
  164964. */
  164965. select_scan_parameters(cinfo);
  164966. per_scan_setup(cinfo);
  164967. if (! cinfo->raw_data_in) {
  164968. (*cinfo->cconvert->start_pass) (cinfo);
  164969. (*cinfo->downsample->start_pass) (cinfo);
  164970. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164971. }
  164972. (*cinfo->fdct->start_pass) (cinfo);
  164973. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164974. (*cinfo->coef->start_pass) (cinfo,
  164975. (master->total_passes > 1 ?
  164976. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164977. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164978. if (cinfo->optimize_coding) {
  164979. /* No immediate data output; postpone writing frame/scan headers */
  164980. master->pub.call_pass_startup = FALSE;
  164981. } else {
  164982. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164983. master->pub.call_pass_startup = TRUE;
  164984. }
  164985. break;
  164986. #ifdef ENTROPY_OPT_SUPPORTED
  164987. case huff_opt_pass:
  164988. /* Do Huffman optimization for a scan after the first one. */
  164989. select_scan_parameters(cinfo);
  164990. per_scan_setup(cinfo);
  164991. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164992. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164993. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164994. master->pub.call_pass_startup = FALSE;
  164995. break;
  164996. }
  164997. /* Special case: Huffman DC refinement scans need no Huffman table
  164998. * and therefore we can skip the optimization pass for them.
  164999. */
  165000. master->pass_type = output_pass;
  165001. master->pass_number++;
  165002. /*FALLTHROUGH*/
  165003. #endif
  165004. case output_pass:
  165005. /* Do a data-output pass. */
  165006. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165007. if (! cinfo->optimize_coding) {
  165008. select_scan_parameters(cinfo);
  165009. per_scan_setup(cinfo);
  165010. }
  165011. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165012. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165013. /* We emit frame/scan headers now */
  165014. if (master->scan_number == 0)
  165015. (*cinfo->marker->write_frame_header) (cinfo);
  165016. (*cinfo->marker->write_scan_header) (cinfo);
  165017. master->pub.call_pass_startup = FALSE;
  165018. break;
  165019. default:
  165020. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165021. }
  165022. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165023. /* Set up progress monitor's pass info if present */
  165024. if (cinfo->progress != NULL) {
  165025. cinfo->progress->completed_passes = master->pass_number;
  165026. cinfo->progress->total_passes = master->total_passes;
  165027. }
  165028. }
  165029. /*
  165030. * Special start-of-pass hook.
  165031. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165032. * In single-pass processing, we need this hook because we don't want to
  165033. * write frame/scan headers during jpeg_start_compress; we want to let the
  165034. * application write COM markers etc. between jpeg_start_compress and the
  165035. * jpeg_write_scanlines loop.
  165036. * In multi-pass processing, this routine is not used.
  165037. */
  165038. METHODDEF(void)
  165039. pass_startup (j_compress_ptr cinfo)
  165040. {
  165041. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165042. (*cinfo->marker->write_frame_header) (cinfo);
  165043. (*cinfo->marker->write_scan_header) (cinfo);
  165044. }
  165045. /*
  165046. * Finish up at end of pass.
  165047. */
  165048. METHODDEF(void)
  165049. finish_pass_master (j_compress_ptr cinfo)
  165050. {
  165051. my_master_ptr master = (my_master_ptr) cinfo->master;
  165052. /* The entropy coder always needs an end-of-pass call,
  165053. * either to analyze statistics or to flush its output buffer.
  165054. */
  165055. (*cinfo->entropy->finish_pass) (cinfo);
  165056. /* Update state for next pass */
  165057. switch (master->pass_type) {
  165058. case main_pass:
  165059. /* next pass is either output of scan 0 (after optimization)
  165060. * or output of scan 1 (if no optimization).
  165061. */
  165062. master->pass_type = output_pass;
  165063. if (! cinfo->optimize_coding)
  165064. master->scan_number++;
  165065. break;
  165066. case huff_opt_pass:
  165067. /* next pass is always output of current scan */
  165068. master->pass_type = output_pass;
  165069. break;
  165070. case output_pass:
  165071. /* next pass is either optimization or output of next scan */
  165072. if (cinfo->optimize_coding)
  165073. master->pass_type = huff_opt_pass;
  165074. master->scan_number++;
  165075. break;
  165076. }
  165077. master->pass_number++;
  165078. }
  165079. /*
  165080. * Initialize master compression control.
  165081. */
  165082. GLOBAL(void)
  165083. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165084. {
  165085. my_master_ptr master;
  165086. master = (my_master_ptr)
  165087. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165088. SIZEOF(my_comp_master));
  165089. cinfo->master = (struct jpeg_comp_master *) master;
  165090. master->pub.prepare_for_pass = prepare_for_pass;
  165091. master->pub.pass_startup = pass_startup;
  165092. master->pub.finish_pass = finish_pass_master;
  165093. master->pub.is_last_pass = FALSE;
  165094. /* Validate parameters, determine derived values */
  165095. initial_setup(cinfo);
  165096. if (cinfo->scan_info != NULL) {
  165097. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165098. validate_script(cinfo);
  165099. #else
  165100. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165101. #endif
  165102. } else {
  165103. cinfo->progressive_mode = FALSE;
  165104. cinfo->num_scans = 1;
  165105. }
  165106. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165107. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165108. /* Initialize my private state */
  165109. if (transcode_only) {
  165110. /* no main pass in transcoding */
  165111. if (cinfo->optimize_coding)
  165112. master->pass_type = huff_opt_pass;
  165113. else
  165114. master->pass_type = output_pass;
  165115. } else {
  165116. /* for normal compression, first pass is always this type: */
  165117. master->pass_type = main_pass;
  165118. }
  165119. master->scan_number = 0;
  165120. master->pass_number = 0;
  165121. if (cinfo->optimize_coding)
  165122. master->total_passes = cinfo->num_scans * 2;
  165123. else
  165124. master->total_passes = cinfo->num_scans;
  165125. }
  165126. /*** End of inlined file: jcmaster.c ***/
  165127. /*** Start of inlined file: jcomapi.c ***/
  165128. #define JPEG_INTERNALS
  165129. /*
  165130. * Abort processing of a JPEG compression or decompression operation,
  165131. * but don't destroy the object itself.
  165132. *
  165133. * For this, we merely clean up all the nonpermanent memory pools.
  165134. * Note that temp files (virtual arrays) are not allowed to belong to
  165135. * the permanent pool, so we will be able to close all temp files here.
  165136. * Closing a data source or destination, if necessary, is the application's
  165137. * responsibility.
  165138. */
  165139. GLOBAL(void)
  165140. jpeg_abort (j_common_ptr cinfo)
  165141. {
  165142. int pool;
  165143. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165144. if (cinfo->mem == NULL)
  165145. return;
  165146. /* Releasing pools in reverse order might help avoid fragmentation
  165147. * with some (brain-damaged) malloc libraries.
  165148. */
  165149. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165150. (*cinfo->mem->free_pool) (cinfo, pool);
  165151. }
  165152. /* Reset overall state for possible reuse of object */
  165153. if (cinfo->is_decompressor) {
  165154. cinfo->global_state = DSTATE_START;
  165155. /* Try to keep application from accessing now-deleted marker list.
  165156. * A bit kludgy to do it here, but this is the most central place.
  165157. */
  165158. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165159. } else {
  165160. cinfo->global_state = CSTATE_START;
  165161. }
  165162. }
  165163. /*
  165164. * Destruction of a JPEG object.
  165165. *
  165166. * Everything gets deallocated except the master jpeg_compress_struct itself
  165167. * and the error manager struct. Both of these are supplied by the application
  165168. * and must be freed, if necessary, by the application. (Often they are on
  165169. * the stack and so don't need to be freed anyway.)
  165170. * Closing a data source or destination, if necessary, is the application's
  165171. * responsibility.
  165172. */
  165173. GLOBAL(void)
  165174. jpeg_destroy (j_common_ptr cinfo)
  165175. {
  165176. /* We need only tell the memory manager to release everything. */
  165177. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165178. if (cinfo->mem != NULL)
  165179. (*cinfo->mem->self_destruct) (cinfo);
  165180. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165181. cinfo->global_state = 0; /* mark it destroyed */
  165182. }
  165183. /*
  165184. * Convenience routines for allocating quantization and Huffman tables.
  165185. * (Would jutils.c be a more reasonable place to put these?)
  165186. */
  165187. GLOBAL(JQUANT_TBL *)
  165188. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165189. {
  165190. JQUANT_TBL *tbl;
  165191. tbl = (JQUANT_TBL *)
  165192. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165193. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165194. return tbl;
  165195. }
  165196. GLOBAL(JHUFF_TBL *)
  165197. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165198. {
  165199. JHUFF_TBL *tbl;
  165200. tbl = (JHUFF_TBL *)
  165201. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165202. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165203. return tbl;
  165204. }
  165205. /*** End of inlined file: jcomapi.c ***/
  165206. /*** Start of inlined file: jcparam.c ***/
  165207. #define JPEG_INTERNALS
  165208. /*
  165209. * Quantization table setup routines
  165210. */
  165211. GLOBAL(void)
  165212. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165213. const unsigned int *basic_table,
  165214. int scale_factor, boolean force_baseline)
  165215. /* Define a quantization table equal to the basic_table times
  165216. * a scale factor (given as a percentage).
  165217. * If force_baseline is TRUE, the computed quantization table entries
  165218. * are limited to 1..255 for JPEG baseline compatibility.
  165219. */
  165220. {
  165221. JQUANT_TBL ** qtblptr;
  165222. int i;
  165223. long temp;
  165224. /* Safety check to ensure start_compress not called yet. */
  165225. if (cinfo->global_state != CSTATE_START)
  165226. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165227. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165228. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165229. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165230. if (*qtblptr == NULL)
  165231. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165232. for (i = 0; i < DCTSIZE2; i++) {
  165233. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165234. /* limit the values to the valid range */
  165235. if (temp <= 0L) temp = 1L;
  165236. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165237. if (force_baseline && temp > 255L)
  165238. temp = 255L; /* limit to baseline range if requested */
  165239. (*qtblptr)->quantval[i] = (UINT16) temp;
  165240. }
  165241. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165242. (*qtblptr)->sent_table = FALSE;
  165243. }
  165244. GLOBAL(void)
  165245. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165246. boolean force_baseline)
  165247. /* Set or change the 'quality' (quantization) setting, using default tables
  165248. * and a straight percentage-scaling quality scale. In most cases it's better
  165249. * to use jpeg_set_quality (below); this entry point is provided for
  165250. * applications that insist on a linear percentage scaling.
  165251. */
  165252. {
  165253. /* These are the sample quantization tables given in JPEG spec section K.1.
  165254. * The spec says that the values given produce "good" quality, and
  165255. * when divided by 2, "very good" quality.
  165256. */
  165257. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165258. 16, 11, 10, 16, 24, 40, 51, 61,
  165259. 12, 12, 14, 19, 26, 58, 60, 55,
  165260. 14, 13, 16, 24, 40, 57, 69, 56,
  165261. 14, 17, 22, 29, 51, 87, 80, 62,
  165262. 18, 22, 37, 56, 68, 109, 103, 77,
  165263. 24, 35, 55, 64, 81, 104, 113, 92,
  165264. 49, 64, 78, 87, 103, 121, 120, 101,
  165265. 72, 92, 95, 98, 112, 100, 103, 99
  165266. };
  165267. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165268. 17, 18, 24, 47, 99, 99, 99, 99,
  165269. 18, 21, 26, 66, 99, 99, 99, 99,
  165270. 24, 26, 56, 99, 99, 99, 99, 99,
  165271. 47, 66, 99, 99, 99, 99, 99, 99,
  165272. 99, 99, 99, 99, 99, 99, 99, 99,
  165273. 99, 99, 99, 99, 99, 99, 99, 99,
  165274. 99, 99, 99, 99, 99, 99, 99, 99,
  165275. 99, 99, 99, 99, 99, 99, 99, 99
  165276. };
  165277. /* Set up two quantization tables using the specified scaling */
  165278. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165279. scale_factor, force_baseline);
  165280. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165281. scale_factor, force_baseline);
  165282. }
  165283. GLOBAL(int)
  165284. jpeg_quality_scaling (int quality)
  165285. /* Convert a user-specified quality rating to a percentage scaling factor
  165286. * for an underlying quantization table, using our recommended scaling curve.
  165287. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165288. */
  165289. {
  165290. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165291. if (quality <= 0) quality = 1;
  165292. if (quality > 100) quality = 100;
  165293. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165294. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165295. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165296. * to make all the table entries 1 (hence, minimum quantization loss).
  165297. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165298. */
  165299. if (quality < 50)
  165300. quality = 5000 / quality;
  165301. else
  165302. quality = 200 - quality*2;
  165303. return quality;
  165304. }
  165305. GLOBAL(void)
  165306. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165307. /* Set or change the 'quality' (quantization) setting, using default tables.
  165308. * This is the standard quality-adjusting entry point for typical user
  165309. * interfaces; only those who want detailed control over quantization tables
  165310. * would use the preceding three routines directly.
  165311. */
  165312. {
  165313. /* Convert user 0-100 rating to percentage scaling */
  165314. quality = jpeg_quality_scaling(quality);
  165315. /* Set up standard quality tables */
  165316. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165317. }
  165318. /*
  165319. * Huffman table setup routines
  165320. */
  165321. LOCAL(void)
  165322. add_huff_table (j_compress_ptr cinfo,
  165323. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165324. /* Define a Huffman table */
  165325. {
  165326. int nsymbols, len;
  165327. if (*htblptr == NULL)
  165328. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165329. /* Copy the number-of-symbols-of-each-code-length counts */
  165330. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165331. /* Validate the counts. We do this here mainly so we can copy the right
  165332. * number of symbols from the val[] array, without risking marching off
  165333. * the end of memory. jchuff.c will do a more thorough test later.
  165334. */
  165335. nsymbols = 0;
  165336. for (len = 1; len <= 16; len++)
  165337. nsymbols += bits[len];
  165338. if (nsymbols < 1 || nsymbols > 256)
  165339. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165340. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165341. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165342. (*htblptr)->sent_table = FALSE;
  165343. }
  165344. LOCAL(void)
  165345. std_huff_tables (j_compress_ptr cinfo)
  165346. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165347. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165348. {
  165349. static const UINT8 bits_dc_luminance[17] =
  165350. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165351. static const UINT8 val_dc_luminance[] =
  165352. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165353. static const UINT8 bits_dc_chrominance[17] =
  165354. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165355. static const UINT8 val_dc_chrominance[] =
  165356. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165357. static const UINT8 bits_ac_luminance[17] =
  165358. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165359. static const UINT8 val_ac_luminance[] =
  165360. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165361. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165362. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165363. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165364. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165365. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165366. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165367. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165368. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165369. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165370. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165371. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165372. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165373. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165374. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165375. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165376. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165377. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165378. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165379. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165380. 0xf9, 0xfa };
  165381. static const UINT8 bits_ac_chrominance[17] =
  165382. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165383. static const UINT8 val_ac_chrominance[] =
  165384. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165385. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165386. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165387. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165388. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165389. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165390. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165391. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165392. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165393. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165394. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165395. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165396. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165397. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165398. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165399. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165400. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165401. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165402. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165403. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165404. 0xf9, 0xfa };
  165405. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165406. bits_dc_luminance, val_dc_luminance);
  165407. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165408. bits_ac_luminance, val_ac_luminance);
  165409. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165410. bits_dc_chrominance, val_dc_chrominance);
  165411. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165412. bits_ac_chrominance, val_ac_chrominance);
  165413. }
  165414. /*
  165415. * Default parameter setup for compression.
  165416. *
  165417. * Applications that don't choose to use this routine must do their
  165418. * own setup of all these parameters. Alternately, you can call this
  165419. * to establish defaults and then alter parameters selectively. This
  165420. * is the recommended approach since, if we add any new parameters,
  165421. * your code will still work (they'll be set to reasonable defaults).
  165422. */
  165423. GLOBAL(void)
  165424. jpeg_set_defaults (j_compress_ptr cinfo)
  165425. {
  165426. int i;
  165427. /* Safety check to ensure start_compress not called yet. */
  165428. if (cinfo->global_state != CSTATE_START)
  165429. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165430. /* Allocate comp_info array large enough for maximum component count.
  165431. * Array is made permanent in case application wants to compress
  165432. * multiple images at same param settings.
  165433. */
  165434. if (cinfo->comp_info == NULL)
  165435. cinfo->comp_info = (jpeg_component_info *)
  165436. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165437. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165438. /* Initialize everything not dependent on the color space */
  165439. cinfo->data_precision = BITS_IN_JSAMPLE;
  165440. /* Set up two quantization tables using default quality of 75 */
  165441. jpeg_set_quality(cinfo, 75, TRUE);
  165442. /* Set up two Huffman tables */
  165443. std_huff_tables(cinfo);
  165444. /* Initialize default arithmetic coding conditioning */
  165445. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165446. cinfo->arith_dc_L[i] = 0;
  165447. cinfo->arith_dc_U[i] = 1;
  165448. cinfo->arith_ac_K[i] = 5;
  165449. }
  165450. /* Default is no multiple-scan output */
  165451. cinfo->scan_info = NULL;
  165452. cinfo->num_scans = 0;
  165453. /* Expect normal source image, not raw downsampled data */
  165454. cinfo->raw_data_in = FALSE;
  165455. /* Use Huffman coding, not arithmetic coding, by default */
  165456. cinfo->arith_code = FALSE;
  165457. /* By default, don't do extra passes to optimize entropy coding */
  165458. cinfo->optimize_coding = FALSE;
  165459. /* The standard Huffman tables are only valid for 8-bit data precision.
  165460. * If the precision is higher, force optimization on so that usable
  165461. * tables will be computed. This test can be removed if default tables
  165462. * are supplied that are valid for the desired precision.
  165463. */
  165464. if (cinfo->data_precision > 8)
  165465. cinfo->optimize_coding = TRUE;
  165466. /* By default, use the simpler non-cosited sampling alignment */
  165467. cinfo->CCIR601_sampling = FALSE;
  165468. /* No input smoothing */
  165469. cinfo->smoothing_factor = 0;
  165470. /* DCT algorithm preference */
  165471. cinfo->dct_method = JDCT_DEFAULT;
  165472. /* No restart markers */
  165473. cinfo->restart_interval = 0;
  165474. cinfo->restart_in_rows = 0;
  165475. /* Fill in default JFIF marker parameters. Note that whether the marker
  165476. * will actually be written is determined by jpeg_set_colorspace.
  165477. *
  165478. * By default, the library emits JFIF version code 1.01.
  165479. * An application that wants to emit JFIF 1.02 extension markers should set
  165480. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165481. * to 1.02, but there may still be some decoders in use that will complain
  165482. * about that; saying 1.01 should minimize compatibility problems.
  165483. */
  165484. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165485. cinfo->JFIF_minor_version = 1;
  165486. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165487. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165488. cinfo->Y_density = 1;
  165489. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165490. jpeg_default_colorspace(cinfo);
  165491. }
  165492. /*
  165493. * Select an appropriate JPEG colorspace for in_color_space.
  165494. */
  165495. GLOBAL(void)
  165496. jpeg_default_colorspace (j_compress_ptr cinfo)
  165497. {
  165498. switch (cinfo->in_color_space) {
  165499. case JCS_GRAYSCALE:
  165500. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165501. break;
  165502. case JCS_RGB:
  165503. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165504. break;
  165505. case JCS_YCbCr:
  165506. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165507. break;
  165508. case JCS_CMYK:
  165509. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165510. break;
  165511. case JCS_YCCK:
  165512. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165513. break;
  165514. case JCS_UNKNOWN:
  165515. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165516. break;
  165517. default:
  165518. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165519. }
  165520. }
  165521. /*
  165522. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165523. */
  165524. GLOBAL(void)
  165525. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165526. {
  165527. jpeg_component_info * compptr;
  165528. int ci;
  165529. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165530. (compptr = &cinfo->comp_info[index], \
  165531. compptr->component_id = (id), \
  165532. compptr->h_samp_factor = (hsamp), \
  165533. compptr->v_samp_factor = (vsamp), \
  165534. compptr->quant_tbl_no = (quant), \
  165535. compptr->dc_tbl_no = (dctbl), \
  165536. compptr->ac_tbl_no = (actbl) )
  165537. /* Safety check to ensure start_compress not called yet. */
  165538. if (cinfo->global_state != CSTATE_START)
  165539. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165540. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165541. * tables 1 for chrominance components.
  165542. */
  165543. cinfo->jpeg_color_space = colorspace;
  165544. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165545. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165546. switch (colorspace) {
  165547. case JCS_GRAYSCALE:
  165548. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165549. cinfo->num_components = 1;
  165550. /* JFIF specifies component ID 1 */
  165551. SET_COMP(0, 1, 1,1, 0, 0,0);
  165552. break;
  165553. case JCS_RGB:
  165554. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165555. cinfo->num_components = 3;
  165556. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165557. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165558. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165559. break;
  165560. case JCS_YCbCr:
  165561. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165562. cinfo->num_components = 3;
  165563. /* JFIF specifies component IDs 1,2,3 */
  165564. /* We default to 2x2 subsamples of chrominance */
  165565. SET_COMP(0, 1, 2,2, 0, 0,0);
  165566. SET_COMP(1, 2, 1,1, 1, 1,1);
  165567. SET_COMP(2, 3, 1,1, 1, 1,1);
  165568. break;
  165569. case JCS_CMYK:
  165570. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165571. cinfo->num_components = 4;
  165572. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165573. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165574. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165575. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165576. break;
  165577. case JCS_YCCK:
  165578. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165579. cinfo->num_components = 4;
  165580. SET_COMP(0, 1, 2,2, 0, 0,0);
  165581. SET_COMP(1, 2, 1,1, 1, 1,1);
  165582. SET_COMP(2, 3, 1,1, 1, 1,1);
  165583. SET_COMP(3, 4, 2,2, 0, 0,0);
  165584. break;
  165585. case JCS_UNKNOWN:
  165586. cinfo->num_components = cinfo->input_components;
  165587. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165588. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165589. MAX_COMPONENTS);
  165590. for (ci = 0; ci < cinfo->num_components; ci++) {
  165591. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165592. }
  165593. break;
  165594. default:
  165595. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165596. }
  165597. }
  165598. #ifdef C_PROGRESSIVE_SUPPORTED
  165599. LOCAL(jpeg_scan_info *)
  165600. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165601. int Ss, int Se, int Ah, int Al)
  165602. /* Support routine: generate one scan for specified component */
  165603. {
  165604. scanptr->comps_in_scan = 1;
  165605. scanptr->component_index[0] = ci;
  165606. scanptr->Ss = Ss;
  165607. scanptr->Se = Se;
  165608. scanptr->Ah = Ah;
  165609. scanptr->Al = Al;
  165610. scanptr++;
  165611. return scanptr;
  165612. }
  165613. LOCAL(jpeg_scan_info *)
  165614. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165615. int Ss, int Se, int Ah, int Al)
  165616. /* Support routine: generate one scan for each component */
  165617. {
  165618. int ci;
  165619. for (ci = 0; ci < ncomps; ci++) {
  165620. scanptr->comps_in_scan = 1;
  165621. scanptr->component_index[0] = ci;
  165622. scanptr->Ss = Ss;
  165623. scanptr->Se = Se;
  165624. scanptr->Ah = Ah;
  165625. scanptr->Al = Al;
  165626. scanptr++;
  165627. }
  165628. return scanptr;
  165629. }
  165630. LOCAL(jpeg_scan_info *)
  165631. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165632. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165633. {
  165634. int ci;
  165635. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165636. /* Single interleaved DC scan */
  165637. scanptr->comps_in_scan = ncomps;
  165638. for (ci = 0; ci < ncomps; ci++)
  165639. scanptr->component_index[ci] = ci;
  165640. scanptr->Ss = scanptr->Se = 0;
  165641. scanptr->Ah = Ah;
  165642. scanptr->Al = Al;
  165643. scanptr++;
  165644. } else {
  165645. /* Noninterleaved DC scan for each component */
  165646. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165647. }
  165648. return scanptr;
  165649. }
  165650. /*
  165651. * Create a recommended progressive-JPEG script.
  165652. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165653. */
  165654. GLOBAL(void)
  165655. jpeg_simple_progression (j_compress_ptr cinfo)
  165656. {
  165657. int ncomps = cinfo->num_components;
  165658. int nscans;
  165659. jpeg_scan_info * scanptr;
  165660. /* Safety check to ensure start_compress not called yet. */
  165661. if (cinfo->global_state != CSTATE_START)
  165662. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165663. /* Figure space needed for script. Calculation must match code below! */
  165664. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165665. /* Custom script for YCbCr color images. */
  165666. nscans = 10;
  165667. } else {
  165668. /* All-purpose script for other color spaces. */
  165669. if (ncomps > MAX_COMPS_IN_SCAN)
  165670. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165671. else
  165672. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165673. }
  165674. /* Allocate space for script.
  165675. * We need to put it in the permanent pool in case the application performs
  165676. * multiple compressions without changing the settings. To avoid a memory
  165677. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165678. * object, we try to re-use previously allocated space, and we allocate
  165679. * enough space to handle YCbCr even if initially asked for grayscale.
  165680. */
  165681. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165682. cinfo->script_space_size = MAX(nscans, 10);
  165683. cinfo->script_space = (jpeg_scan_info *)
  165684. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165685. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165686. }
  165687. scanptr = cinfo->script_space;
  165688. cinfo->scan_info = scanptr;
  165689. cinfo->num_scans = nscans;
  165690. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165691. /* Custom script for YCbCr color images. */
  165692. /* Initial DC scan */
  165693. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165694. /* Initial AC scan: get some luma data out in a hurry */
  165695. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165696. /* Chroma data is too small to be worth expending many scans on */
  165697. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165698. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165699. /* Complete spectral selection for luma AC */
  165700. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165701. /* Refine next bit of luma AC */
  165702. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165703. /* Finish DC successive approximation */
  165704. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165705. /* Finish AC successive approximation */
  165706. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165707. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165708. /* Luma bottom bit comes last since it's usually largest scan */
  165709. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165710. } else {
  165711. /* All-purpose script for other color spaces. */
  165712. /* Successive approximation first pass */
  165713. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165714. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165715. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165716. /* Successive approximation second pass */
  165717. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165718. /* Successive approximation final pass */
  165719. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165720. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165721. }
  165722. }
  165723. #endif /* C_PROGRESSIVE_SUPPORTED */
  165724. /*** End of inlined file: jcparam.c ***/
  165725. /*** Start of inlined file: jcphuff.c ***/
  165726. #define JPEG_INTERNALS
  165727. #ifdef C_PROGRESSIVE_SUPPORTED
  165728. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165729. typedef struct {
  165730. struct jpeg_entropy_encoder pub; /* public fields */
  165731. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165732. boolean gather_statistics;
  165733. /* Bit-level coding status.
  165734. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165735. */
  165736. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165737. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165738. INT32 put_buffer; /* current bit-accumulation buffer */
  165739. int put_bits; /* # of bits now in it */
  165740. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165741. /* Coding status for DC components */
  165742. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165743. /* Coding status for AC components */
  165744. int ac_tbl_no; /* the table number of the single component */
  165745. unsigned int EOBRUN; /* run length of EOBs */
  165746. unsigned int BE; /* # of buffered correction bits before MCU */
  165747. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165748. /* packing correction bits tightly would save some space but cost time... */
  165749. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165750. int next_restart_num; /* next restart number to write (0-7) */
  165751. /* Pointers to derived tables (these workspaces have image lifespan).
  165752. * Since any one scan codes only DC or only AC, we only need one set
  165753. * of tables, not one for DC and one for AC.
  165754. */
  165755. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165756. /* Statistics tables for optimization; again, one set is enough */
  165757. long * count_ptrs[NUM_HUFF_TBLS];
  165758. } phuff_entropy_encoder;
  165759. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165760. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165761. * buffer can hold. Larger sizes may slightly improve compression, but
  165762. * 1000 is already well into the realm of overkill.
  165763. * The minimum safe size is 64 bits.
  165764. */
  165765. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165766. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165767. * We assume that int right shift is unsigned if INT32 right shift is,
  165768. * which should be safe.
  165769. */
  165770. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165771. #define ISHIFT_TEMPS int ishift_temp;
  165772. #define IRIGHT_SHIFT(x,shft) \
  165773. ((ishift_temp = (x)) < 0 ? \
  165774. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165775. (ishift_temp >> (shft)))
  165776. #else
  165777. #define ISHIFT_TEMPS
  165778. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165779. #endif
  165780. /* Forward declarations */
  165781. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165782. JBLOCKROW *MCU_data));
  165783. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165784. JBLOCKROW *MCU_data));
  165785. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165786. JBLOCKROW *MCU_data));
  165787. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165788. JBLOCKROW *MCU_data));
  165789. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165790. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165791. /*
  165792. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165793. */
  165794. METHODDEF(void)
  165795. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165796. {
  165797. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165798. boolean is_DC_band;
  165799. int ci, tbl;
  165800. jpeg_component_info * compptr;
  165801. entropy->cinfo = cinfo;
  165802. entropy->gather_statistics = gather_statistics;
  165803. is_DC_band = (cinfo->Ss == 0);
  165804. /* We assume jcmaster.c already validated the scan parameters. */
  165805. /* Select execution routines */
  165806. if (cinfo->Ah == 0) {
  165807. if (is_DC_band)
  165808. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165809. else
  165810. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165811. } else {
  165812. if (is_DC_band)
  165813. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165814. else {
  165815. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165816. /* AC refinement needs a correction bit buffer */
  165817. if (entropy->bit_buffer == NULL)
  165818. entropy->bit_buffer = (char *)
  165819. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165820. MAX_CORR_BITS * SIZEOF(char));
  165821. }
  165822. }
  165823. if (gather_statistics)
  165824. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165825. else
  165826. entropy->pub.finish_pass = finish_pass_phuff;
  165827. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165828. * for AC coefficients.
  165829. */
  165830. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165831. compptr = cinfo->cur_comp_info[ci];
  165832. /* Initialize DC predictions to 0 */
  165833. entropy->last_dc_val[ci] = 0;
  165834. /* Get table index */
  165835. if (is_DC_band) {
  165836. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165837. continue;
  165838. tbl = compptr->dc_tbl_no;
  165839. } else {
  165840. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165841. }
  165842. if (gather_statistics) {
  165843. /* Check for invalid table index */
  165844. /* (make_c_derived_tbl does this in the other path) */
  165845. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165846. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165847. /* Allocate and zero the statistics tables */
  165848. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165849. if (entropy->count_ptrs[tbl] == NULL)
  165850. entropy->count_ptrs[tbl] = (long *)
  165851. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165852. 257 * SIZEOF(long));
  165853. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165854. } else {
  165855. /* Compute derived values for Huffman table */
  165856. /* We may do this more than once for a table, but it's not expensive */
  165857. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165858. & entropy->derived_tbls[tbl]);
  165859. }
  165860. }
  165861. /* Initialize AC stuff */
  165862. entropy->EOBRUN = 0;
  165863. entropy->BE = 0;
  165864. /* Initialize bit buffer to empty */
  165865. entropy->put_buffer = 0;
  165866. entropy->put_bits = 0;
  165867. /* Initialize restart stuff */
  165868. entropy->restarts_to_go = cinfo->restart_interval;
  165869. entropy->next_restart_num = 0;
  165870. }
  165871. /* Outputting bytes to the file.
  165872. * NB: these must be called only when actually outputting,
  165873. * that is, entropy->gather_statistics == FALSE.
  165874. */
  165875. /* Emit a byte */
  165876. #define emit_byte(entropy,val) \
  165877. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165878. if (--(entropy)->free_in_buffer == 0) \
  165879. dump_buffer_p(entropy); }
  165880. LOCAL(void)
  165881. dump_buffer_p (phuff_entropy_ptr entropy)
  165882. /* Empty the output buffer; we do not support suspension in this module. */
  165883. {
  165884. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165885. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165886. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165887. /* After a successful buffer dump, must reset buffer pointers */
  165888. entropy->next_output_byte = dest->next_output_byte;
  165889. entropy->free_in_buffer = dest->free_in_buffer;
  165890. }
  165891. /* Outputting bits to the file */
  165892. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165893. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165894. * in one call, and we never retain more than 7 bits in put_buffer
  165895. * between calls, so 24 bits are sufficient.
  165896. */
  165897. INLINE
  165898. LOCAL(void)
  165899. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165900. /* Emit some bits, unless we are in gather mode */
  165901. {
  165902. /* This routine is heavily used, so it's worth coding tightly. */
  165903. register INT32 put_buffer = (INT32) code;
  165904. register int put_bits = entropy->put_bits;
  165905. /* if size is 0, caller used an invalid Huffman table entry */
  165906. if (size == 0)
  165907. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165908. if (entropy->gather_statistics)
  165909. return; /* do nothing if we're only getting stats */
  165910. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165911. put_bits += size; /* new number of bits in buffer */
  165912. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165913. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165914. while (put_bits >= 8) {
  165915. int c = (int) ((put_buffer >> 16) & 0xFF);
  165916. emit_byte(entropy, c);
  165917. if (c == 0xFF) { /* need to stuff a zero byte? */
  165918. emit_byte(entropy, 0);
  165919. }
  165920. put_buffer <<= 8;
  165921. put_bits -= 8;
  165922. }
  165923. entropy->put_buffer = put_buffer; /* update variables */
  165924. entropy->put_bits = put_bits;
  165925. }
  165926. LOCAL(void)
  165927. flush_bits_p (phuff_entropy_ptr entropy)
  165928. {
  165929. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165930. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165931. entropy->put_bits = 0;
  165932. }
  165933. /*
  165934. * Emit (or just count) a Huffman symbol.
  165935. */
  165936. INLINE
  165937. LOCAL(void)
  165938. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165939. {
  165940. if (entropy->gather_statistics)
  165941. entropy->count_ptrs[tbl_no][symbol]++;
  165942. else {
  165943. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165944. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165945. }
  165946. }
  165947. /*
  165948. * Emit bits from a correction bit buffer.
  165949. */
  165950. LOCAL(void)
  165951. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165952. unsigned int nbits)
  165953. {
  165954. if (entropy->gather_statistics)
  165955. return; /* no real work */
  165956. while (nbits > 0) {
  165957. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165958. bufstart++;
  165959. nbits--;
  165960. }
  165961. }
  165962. /*
  165963. * Emit any pending EOBRUN symbol.
  165964. */
  165965. LOCAL(void)
  165966. emit_eobrun (phuff_entropy_ptr entropy)
  165967. {
  165968. register int temp, nbits;
  165969. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165970. temp = entropy->EOBRUN;
  165971. nbits = 0;
  165972. while ((temp >>= 1))
  165973. nbits++;
  165974. /* safety check: shouldn't happen given limited correction-bit buffer */
  165975. if (nbits > 14)
  165976. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165977. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165978. if (nbits)
  165979. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165980. entropy->EOBRUN = 0;
  165981. /* Emit any buffered correction bits */
  165982. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165983. entropy->BE = 0;
  165984. }
  165985. }
  165986. /*
  165987. * Emit a restart marker & resynchronize predictions.
  165988. */
  165989. LOCAL(void)
  165990. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165991. {
  165992. int ci;
  165993. emit_eobrun(entropy);
  165994. if (! entropy->gather_statistics) {
  165995. flush_bits_p(entropy);
  165996. emit_byte(entropy, 0xFF);
  165997. emit_byte(entropy, JPEG_RST0 + restart_num);
  165998. }
  165999. if (entropy->cinfo->Ss == 0) {
  166000. /* Re-initialize DC predictions to 0 */
  166001. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166002. entropy->last_dc_val[ci] = 0;
  166003. } else {
  166004. /* Re-initialize all AC-related fields to 0 */
  166005. entropy->EOBRUN = 0;
  166006. entropy->BE = 0;
  166007. }
  166008. }
  166009. /*
  166010. * MCU encoding for DC initial scan (either spectral selection,
  166011. * or first pass of successive approximation).
  166012. */
  166013. METHODDEF(boolean)
  166014. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166015. {
  166016. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166017. register int temp, temp2;
  166018. register int nbits;
  166019. int blkn, ci;
  166020. int Al = cinfo->Al;
  166021. JBLOCKROW block;
  166022. jpeg_component_info * compptr;
  166023. ISHIFT_TEMPS
  166024. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166025. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166026. /* Emit restart marker if needed */
  166027. if (cinfo->restart_interval)
  166028. if (entropy->restarts_to_go == 0)
  166029. emit_restart_p(entropy, entropy->next_restart_num);
  166030. /* Encode the MCU data blocks */
  166031. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166032. block = MCU_data[blkn];
  166033. ci = cinfo->MCU_membership[blkn];
  166034. compptr = cinfo->cur_comp_info[ci];
  166035. /* Compute the DC value after the required point transform by Al.
  166036. * This is simply an arithmetic right shift.
  166037. */
  166038. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166039. /* DC differences are figured on the point-transformed values. */
  166040. temp = temp2 - entropy->last_dc_val[ci];
  166041. entropy->last_dc_val[ci] = temp2;
  166042. /* Encode the DC coefficient difference per section G.1.2.1 */
  166043. temp2 = temp;
  166044. if (temp < 0) {
  166045. temp = -temp; /* temp is abs value of input */
  166046. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166047. /* This code assumes we are on a two's complement machine */
  166048. temp2--;
  166049. }
  166050. /* Find the number of bits needed for the magnitude of the coefficient */
  166051. nbits = 0;
  166052. while (temp) {
  166053. nbits++;
  166054. temp >>= 1;
  166055. }
  166056. /* Check for out-of-range coefficient values.
  166057. * Since we're encoding a difference, the range limit is twice as much.
  166058. */
  166059. if (nbits > MAX_COEF_BITS+1)
  166060. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166061. /* Count/emit the Huffman-coded symbol for the number of bits */
  166062. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166063. /* Emit that number of bits of the value, if positive, */
  166064. /* or the complement of its magnitude, if negative. */
  166065. if (nbits) /* emit_bits rejects calls with size 0 */
  166066. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166067. }
  166068. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166069. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166070. /* Update restart-interval state too */
  166071. if (cinfo->restart_interval) {
  166072. if (entropy->restarts_to_go == 0) {
  166073. entropy->restarts_to_go = cinfo->restart_interval;
  166074. entropy->next_restart_num++;
  166075. entropy->next_restart_num &= 7;
  166076. }
  166077. entropy->restarts_to_go--;
  166078. }
  166079. return TRUE;
  166080. }
  166081. /*
  166082. * MCU encoding for AC initial scan (either spectral selection,
  166083. * or first pass of successive approximation).
  166084. */
  166085. METHODDEF(boolean)
  166086. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166087. {
  166088. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166089. register int temp, temp2;
  166090. register int nbits;
  166091. register int r, k;
  166092. int Se = cinfo->Se;
  166093. int Al = cinfo->Al;
  166094. JBLOCKROW block;
  166095. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166096. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166097. /* Emit restart marker if needed */
  166098. if (cinfo->restart_interval)
  166099. if (entropy->restarts_to_go == 0)
  166100. emit_restart_p(entropy, entropy->next_restart_num);
  166101. /* Encode the MCU data block */
  166102. block = MCU_data[0];
  166103. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166104. r = 0; /* r = run length of zeros */
  166105. for (k = cinfo->Ss; k <= Se; k++) {
  166106. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166107. r++;
  166108. continue;
  166109. }
  166110. /* We must apply the point transform by Al. For AC coefficients this
  166111. * is an integer division with rounding towards 0. To do this portably
  166112. * in C, we shift after obtaining the absolute value; so the code is
  166113. * interwoven with finding the abs value (temp) and output bits (temp2).
  166114. */
  166115. if (temp < 0) {
  166116. temp = -temp; /* temp is abs value of input */
  166117. temp >>= Al; /* apply the point transform */
  166118. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166119. temp2 = ~temp;
  166120. } else {
  166121. temp >>= Al; /* apply the point transform */
  166122. temp2 = temp;
  166123. }
  166124. /* Watch out for case that nonzero coef is zero after point transform */
  166125. if (temp == 0) {
  166126. r++;
  166127. continue;
  166128. }
  166129. /* Emit any pending EOBRUN */
  166130. if (entropy->EOBRUN > 0)
  166131. emit_eobrun(entropy);
  166132. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166133. while (r > 15) {
  166134. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166135. r -= 16;
  166136. }
  166137. /* Find the number of bits needed for the magnitude of the coefficient */
  166138. nbits = 1; /* there must be at least one 1 bit */
  166139. while ((temp >>= 1))
  166140. nbits++;
  166141. /* Check for out-of-range coefficient values */
  166142. if (nbits > MAX_COEF_BITS)
  166143. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166144. /* Count/emit Huffman symbol for run length / number of bits */
  166145. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166146. /* Emit that number of bits of the value, if positive, */
  166147. /* or the complement of its magnitude, if negative. */
  166148. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166149. r = 0; /* reset zero run length */
  166150. }
  166151. if (r > 0) { /* If there are trailing zeroes, */
  166152. entropy->EOBRUN++; /* count an EOB */
  166153. if (entropy->EOBRUN == 0x7FFF)
  166154. emit_eobrun(entropy); /* force it out to avoid overflow */
  166155. }
  166156. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166157. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166158. /* Update restart-interval state too */
  166159. if (cinfo->restart_interval) {
  166160. if (entropy->restarts_to_go == 0) {
  166161. entropy->restarts_to_go = cinfo->restart_interval;
  166162. entropy->next_restart_num++;
  166163. entropy->next_restart_num &= 7;
  166164. }
  166165. entropy->restarts_to_go--;
  166166. }
  166167. return TRUE;
  166168. }
  166169. /*
  166170. * MCU encoding for DC successive approximation refinement scan.
  166171. * Note: we assume such scans can be multi-component, although the spec
  166172. * is not very clear on the point.
  166173. */
  166174. METHODDEF(boolean)
  166175. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166176. {
  166177. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166178. register int temp;
  166179. int blkn;
  166180. int Al = cinfo->Al;
  166181. JBLOCKROW block;
  166182. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166183. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166184. /* Emit restart marker if needed */
  166185. if (cinfo->restart_interval)
  166186. if (entropy->restarts_to_go == 0)
  166187. emit_restart_p(entropy, entropy->next_restart_num);
  166188. /* Encode the MCU data blocks */
  166189. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166190. block = MCU_data[blkn];
  166191. /* We simply emit the Al'th bit of the DC coefficient value. */
  166192. temp = (*block)[0];
  166193. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166194. }
  166195. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166196. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166197. /* Update restart-interval state too */
  166198. if (cinfo->restart_interval) {
  166199. if (entropy->restarts_to_go == 0) {
  166200. entropy->restarts_to_go = cinfo->restart_interval;
  166201. entropy->next_restart_num++;
  166202. entropy->next_restart_num &= 7;
  166203. }
  166204. entropy->restarts_to_go--;
  166205. }
  166206. return TRUE;
  166207. }
  166208. /*
  166209. * MCU encoding for AC successive approximation refinement scan.
  166210. */
  166211. METHODDEF(boolean)
  166212. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166213. {
  166214. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166215. register int temp;
  166216. register int r, k;
  166217. int EOB;
  166218. char *BR_buffer;
  166219. unsigned int BR;
  166220. int Se = cinfo->Se;
  166221. int Al = cinfo->Al;
  166222. JBLOCKROW block;
  166223. int absvalues[DCTSIZE2];
  166224. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166225. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166226. /* Emit restart marker if needed */
  166227. if (cinfo->restart_interval)
  166228. if (entropy->restarts_to_go == 0)
  166229. emit_restart_p(entropy, entropy->next_restart_num);
  166230. /* Encode the MCU data block */
  166231. block = MCU_data[0];
  166232. /* It is convenient to make a pre-pass to determine the transformed
  166233. * coefficients' absolute values and the EOB position.
  166234. */
  166235. EOB = 0;
  166236. for (k = cinfo->Ss; k <= Se; k++) {
  166237. temp = (*block)[jpeg_natural_order[k]];
  166238. /* We must apply the point transform by Al. For AC coefficients this
  166239. * is an integer division with rounding towards 0. To do this portably
  166240. * in C, we shift after obtaining the absolute value.
  166241. */
  166242. if (temp < 0)
  166243. temp = -temp; /* temp is abs value of input */
  166244. temp >>= Al; /* apply the point transform */
  166245. absvalues[k] = temp; /* save abs value for main pass */
  166246. if (temp == 1)
  166247. EOB = k; /* EOB = index of last newly-nonzero coef */
  166248. }
  166249. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166250. r = 0; /* r = run length of zeros */
  166251. BR = 0; /* BR = count of buffered bits added now */
  166252. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166253. for (k = cinfo->Ss; k <= Se; k++) {
  166254. if ((temp = absvalues[k]) == 0) {
  166255. r++;
  166256. continue;
  166257. }
  166258. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166259. while (r > 15 && k <= EOB) {
  166260. /* emit any pending EOBRUN and the BE correction bits */
  166261. emit_eobrun(entropy);
  166262. /* Emit ZRL */
  166263. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166264. r -= 16;
  166265. /* Emit buffered correction bits that must be associated with ZRL */
  166266. emit_buffered_bits(entropy, BR_buffer, BR);
  166267. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166268. BR = 0;
  166269. }
  166270. /* If the coef was previously nonzero, it only needs a correction bit.
  166271. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166272. * that we also need to test r > 15. But if r > 15, we can only get here
  166273. * if k > EOB, which implies that this coefficient is not 1.
  166274. */
  166275. if (temp > 1) {
  166276. /* The correction bit is the next bit of the absolute value. */
  166277. BR_buffer[BR++] = (char) (temp & 1);
  166278. continue;
  166279. }
  166280. /* Emit any pending EOBRUN and the BE correction bits */
  166281. emit_eobrun(entropy);
  166282. /* Count/emit Huffman symbol for run length / number of bits */
  166283. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166284. /* Emit output bit for newly-nonzero coef */
  166285. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166286. emit_bits_p(entropy, (unsigned int) temp, 1);
  166287. /* Emit buffered correction bits that must be associated with this code */
  166288. emit_buffered_bits(entropy, BR_buffer, BR);
  166289. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166290. BR = 0;
  166291. r = 0; /* reset zero run length */
  166292. }
  166293. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166294. entropy->EOBRUN++; /* count an EOB */
  166295. entropy->BE += BR; /* concat my correction bits to older ones */
  166296. /* We force out the EOB if we risk either:
  166297. * 1. overflow of the EOB counter;
  166298. * 2. overflow of the correction bit buffer during the next MCU.
  166299. */
  166300. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166301. emit_eobrun(entropy);
  166302. }
  166303. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166304. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166305. /* Update restart-interval state too */
  166306. if (cinfo->restart_interval) {
  166307. if (entropy->restarts_to_go == 0) {
  166308. entropy->restarts_to_go = cinfo->restart_interval;
  166309. entropy->next_restart_num++;
  166310. entropy->next_restart_num &= 7;
  166311. }
  166312. entropy->restarts_to_go--;
  166313. }
  166314. return TRUE;
  166315. }
  166316. /*
  166317. * Finish up at the end of a Huffman-compressed progressive scan.
  166318. */
  166319. METHODDEF(void)
  166320. finish_pass_phuff (j_compress_ptr cinfo)
  166321. {
  166322. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166323. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166324. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166325. /* Flush out any buffered data */
  166326. emit_eobrun(entropy);
  166327. flush_bits_p(entropy);
  166328. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166329. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166330. }
  166331. /*
  166332. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166333. */
  166334. METHODDEF(void)
  166335. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166336. {
  166337. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166338. boolean is_DC_band;
  166339. int ci, tbl;
  166340. jpeg_component_info * compptr;
  166341. JHUFF_TBL **htblptr;
  166342. boolean did[NUM_HUFF_TBLS];
  166343. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166344. emit_eobrun(entropy);
  166345. is_DC_band = (cinfo->Ss == 0);
  166346. /* It's important not to apply jpeg_gen_optimal_table more than once
  166347. * per table, because it clobbers the input frequency counts!
  166348. */
  166349. MEMZERO(did, SIZEOF(did));
  166350. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166351. compptr = cinfo->cur_comp_info[ci];
  166352. if (is_DC_band) {
  166353. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166354. continue;
  166355. tbl = compptr->dc_tbl_no;
  166356. } else {
  166357. tbl = compptr->ac_tbl_no;
  166358. }
  166359. if (! did[tbl]) {
  166360. if (is_DC_band)
  166361. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166362. else
  166363. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166364. if (*htblptr == NULL)
  166365. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166366. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166367. did[tbl] = TRUE;
  166368. }
  166369. }
  166370. }
  166371. /*
  166372. * Module initialization routine for progressive Huffman entropy encoding.
  166373. */
  166374. GLOBAL(void)
  166375. jinit_phuff_encoder (j_compress_ptr cinfo)
  166376. {
  166377. phuff_entropy_ptr entropy;
  166378. int i;
  166379. entropy = (phuff_entropy_ptr)
  166380. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166381. SIZEOF(phuff_entropy_encoder));
  166382. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166383. entropy->pub.start_pass = start_pass_phuff;
  166384. /* Mark tables unallocated */
  166385. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166386. entropy->derived_tbls[i] = NULL;
  166387. entropy->count_ptrs[i] = NULL;
  166388. }
  166389. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166390. }
  166391. #endif /* C_PROGRESSIVE_SUPPORTED */
  166392. /*** End of inlined file: jcphuff.c ***/
  166393. /*** Start of inlined file: jcprepct.c ***/
  166394. #define JPEG_INTERNALS
  166395. /* At present, jcsample.c can request context rows only for smoothing.
  166396. * In the future, we might also need context rows for CCIR601 sampling
  166397. * or other more-complex downsampling procedures. The code to support
  166398. * context rows should be compiled only if needed.
  166399. */
  166400. #ifdef INPUT_SMOOTHING_SUPPORTED
  166401. #define CONTEXT_ROWS_SUPPORTED
  166402. #endif
  166403. /*
  166404. * For the simple (no-context-row) case, we just need to buffer one
  166405. * row group's worth of pixels for the downsampling step. At the bottom of
  166406. * the image, we pad to a full row group by replicating the last pixel row.
  166407. * The downsampler's last output row is then replicated if needed to pad
  166408. * out to a full iMCU row.
  166409. *
  166410. * When providing context rows, we must buffer three row groups' worth of
  166411. * pixels. Three row groups are physically allocated, but the row pointer
  166412. * arrays are made five row groups high, with the extra pointers above and
  166413. * below "wrapping around" to point to the last and first real row groups.
  166414. * This allows the downsampler to access the proper context rows.
  166415. * At the top and bottom of the image, we create dummy context rows by
  166416. * copying the first or last real pixel row. This copying could be avoided
  166417. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166418. * trouble on the compression side.
  166419. */
  166420. /* Private buffer controller object */
  166421. typedef struct {
  166422. struct jpeg_c_prep_controller pub; /* public fields */
  166423. /* Downsampling input buffer. This buffer holds color-converted data
  166424. * until we have enough to do a downsample step.
  166425. */
  166426. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166427. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166428. int next_buf_row; /* index of next row to store in color_buf */
  166429. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166430. int this_row_group; /* starting row index of group to process */
  166431. int next_buf_stop; /* downsample when we reach this index */
  166432. #endif
  166433. } my_prep_controller;
  166434. typedef my_prep_controller * my_prep_ptr;
  166435. /*
  166436. * Initialize for a processing pass.
  166437. */
  166438. METHODDEF(void)
  166439. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166440. {
  166441. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166442. if (pass_mode != JBUF_PASS_THRU)
  166443. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166444. /* Initialize total-height counter for detecting bottom of image */
  166445. prep->rows_to_go = cinfo->image_height;
  166446. /* Mark the conversion buffer empty */
  166447. prep->next_buf_row = 0;
  166448. #ifdef CONTEXT_ROWS_SUPPORTED
  166449. /* Preset additional state variables for context mode.
  166450. * These aren't used in non-context mode, so we needn't test which mode.
  166451. */
  166452. prep->this_row_group = 0;
  166453. /* Set next_buf_stop to stop after two row groups have been read in. */
  166454. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166455. #endif
  166456. }
  166457. /*
  166458. * Expand an image vertically from height input_rows to height output_rows,
  166459. * by duplicating the bottom row.
  166460. */
  166461. LOCAL(void)
  166462. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166463. int input_rows, int output_rows)
  166464. {
  166465. register int row;
  166466. for (row = input_rows; row < output_rows; row++) {
  166467. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166468. 1, num_cols);
  166469. }
  166470. }
  166471. /*
  166472. * Process some data in the simple no-context case.
  166473. *
  166474. * Preprocessor output data is counted in "row groups". A row group
  166475. * is defined to be v_samp_factor sample rows of each component.
  166476. * Downsampling will produce this much data from each max_v_samp_factor
  166477. * input rows.
  166478. */
  166479. METHODDEF(void)
  166480. pre_process_data (j_compress_ptr cinfo,
  166481. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166482. JDIMENSION in_rows_avail,
  166483. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166484. JDIMENSION out_row_groups_avail)
  166485. {
  166486. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166487. int numrows, ci;
  166488. JDIMENSION inrows;
  166489. jpeg_component_info * compptr;
  166490. while (*in_row_ctr < in_rows_avail &&
  166491. *out_row_group_ctr < out_row_groups_avail) {
  166492. /* Do color conversion to fill the conversion buffer. */
  166493. inrows = in_rows_avail - *in_row_ctr;
  166494. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166495. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166496. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166497. prep->color_buf,
  166498. (JDIMENSION) prep->next_buf_row,
  166499. numrows);
  166500. *in_row_ctr += numrows;
  166501. prep->next_buf_row += numrows;
  166502. prep->rows_to_go -= numrows;
  166503. /* If at bottom of image, pad to fill the conversion buffer. */
  166504. if (prep->rows_to_go == 0 &&
  166505. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166506. for (ci = 0; ci < cinfo->num_components; ci++) {
  166507. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166508. prep->next_buf_row, cinfo->max_v_samp_factor);
  166509. }
  166510. prep->next_buf_row = cinfo->max_v_samp_factor;
  166511. }
  166512. /* If we've filled the conversion buffer, empty it. */
  166513. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166514. (*cinfo->downsample->downsample) (cinfo,
  166515. prep->color_buf, (JDIMENSION) 0,
  166516. output_buf, *out_row_group_ctr);
  166517. prep->next_buf_row = 0;
  166518. (*out_row_group_ctr)++;
  166519. }
  166520. /* If at bottom of image, pad the output to a full iMCU height.
  166521. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166522. */
  166523. if (prep->rows_to_go == 0 &&
  166524. *out_row_group_ctr < out_row_groups_avail) {
  166525. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166526. ci++, compptr++) {
  166527. expand_bottom_edge(output_buf[ci],
  166528. compptr->width_in_blocks * DCTSIZE,
  166529. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166530. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166531. }
  166532. *out_row_group_ctr = out_row_groups_avail;
  166533. break; /* can exit outer loop without test */
  166534. }
  166535. }
  166536. }
  166537. #ifdef CONTEXT_ROWS_SUPPORTED
  166538. /*
  166539. * Process some data in the context case.
  166540. */
  166541. METHODDEF(void)
  166542. pre_process_context (j_compress_ptr cinfo,
  166543. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166544. JDIMENSION in_rows_avail,
  166545. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166546. JDIMENSION out_row_groups_avail)
  166547. {
  166548. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166549. int numrows, ci;
  166550. int buf_height = cinfo->max_v_samp_factor * 3;
  166551. JDIMENSION inrows;
  166552. while (*out_row_group_ctr < out_row_groups_avail) {
  166553. if (*in_row_ctr < in_rows_avail) {
  166554. /* Do color conversion to fill the conversion buffer. */
  166555. inrows = in_rows_avail - *in_row_ctr;
  166556. numrows = prep->next_buf_stop - prep->next_buf_row;
  166557. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166558. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166559. prep->color_buf,
  166560. (JDIMENSION) prep->next_buf_row,
  166561. numrows);
  166562. /* Pad at top of image, if first time through */
  166563. if (prep->rows_to_go == cinfo->image_height) {
  166564. for (ci = 0; ci < cinfo->num_components; ci++) {
  166565. int row;
  166566. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166567. jcopy_sample_rows(prep->color_buf[ci], 0,
  166568. prep->color_buf[ci], -row,
  166569. 1, cinfo->image_width);
  166570. }
  166571. }
  166572. }
  166573. *in_row_ctr += numrows;
  166574. prep->next_buf_row += numrows;
  166575. prep->rows_to_go -= numrows;
  166576. } else {
  166577. /* Return for more data, unless we are at the bottom of the image. */
  166578. if (prep->rows_to_go != 0)
  166579. break;
  166580. /* When at bottom of image, pad to fill the conversion buffer. */
  166581. if (prep->next_buf_row < prep->next_buf_stop) {
  166582. for (ci = 0; ci < cinfo->num_components; ci++) {
  166583. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166584. prep->next_buf_row, prep->next_buf_stop);
  166585. }
  166586. prep->next_buf_row = prep->next_buf_stop;
  166587. }
  166588. }
  166589. /* If we've gotten enough data, downsample a row group. */
  166590. if (prep->next_buf_row == prep->next_buf_stop) {
  166591. (*cinfo->downsample->downsample) (cinfo,
  166592. prep->color_buf,
  166593. (JDIMENSION) prep->this_row_group,
  166594. output_buf, *out_row_group_ctr);
  166595. (*out_row_group_ctr)++;
  166596. /* Advance pointers with wraparound as necessary. */
  166597. prep->this_row_group += cinfo->max_v_samp_factor;
  166598. if (prep->this_row_group >= buf_height)
  166599. prep->this_row_group = 0;
  166600. if (prep->next_buf_row >= buf_height)
  166601. prep->next_buf_row = 0;
  166602. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166603. }
  166604. }
  166605. }
  166606. /*
  166607. * Create the wrapped-around downsampling input buffer needed for context mode.
  166608. */
  166609. LOCAL(void)
  166610. create_context_buffer (j_compress_ptr cinfo)
  166611. {
  166612. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166613. int rgroup_height = cinfo->max_v_samp_factor;
  166614. int ci, i;
  166615. jpeg_component_info * compptr;
  166616. JSAMPARRAY true_buffer, fake_buffer;
  166617. /* Grab enough space for fake row pointers for all the components;
  166618. * we need five row groups' worth of pointers for each component.
  166619. */
  166620. fake_buffer = (JSAMPARRAY)
  166621. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166622. (cinfo->num_components * 5 * rgroup_height) *
  166623. SIZEOF(JSAMPROW));
  166624. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166625. ci++, compptr++) {
  166626. /* Allocate the actual buffer space (3 row groups) for this component.
  166627. * We make the buffer wide enough to allow the downsampler to edge-expand
  166628. * horizontally within the buffer, if it so chooses.
  166629. */
  166630. true_buffer = (*cinfo->mem->alloc_sarray)
  166631. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166632. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166633. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166634. (JDIMENSION) (3 * rgroup_height));
  166635. /* Copy true buffer row pointers into the middle of the fake row array */
  166636. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166637. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166638. /* Fill in the above and below wraparound pointers */
  166639. for (i = 0; i < rgroup_height; i++) {
  166640. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166641. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166642. }
  166643. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166644. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166645. }
  166646. }
  166647. #endif /* CONTEXT_ROWS_SUPPORTED */
  166648. /*
  166649. * Initialize preprocessing controller.
  166650. */
  166651. GLOBAL(void)
  166652. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166653. {
  166654. my_prep_ptr prep;
  166655. int ci;
  166656. jpeg_component_info * compptr;
  166657. if (need_full_buffer) /* safety check */
  166658. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166659. prep = (my_prep_ptr)
  166660. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166661. SIZEOF(my_prep_controller));
  166662. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166663. prep->pub.start_pass = start_pass_prep;
  166664. /* Allocate the color conversion buffer.
  166665. * We make the buffer wide enough to allow the downsampler to edge-expand
  166666. * horizontally within the buffer, if it so chooses.
  166667. */
  166668. if (cinfo->downsample->need_context_rows) {
  166669. /* Set up to provide context rows */
  166670. #ifdef CONTEXT_ROWS_SUPPORTED
  166671. prep->pub.pre_process_data = pre_process_context;
  166672. create_context_buffer(cinfo);
  166673. #else
  166674. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166675. #endif
  166676. } else {
  166677. /* No context, just make it tall enough for one row group */
  166678. prep->pub.pre_process_data = pre_process_data;
  166679. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166680. ci++, compptr++) {
  166681. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166682. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166683. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166684. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166685. (JDIMENSION) cinfo->max_v_samp_factor);
  166686. }
  166687. }
  166688. }
  166689. /*** End of inlined file: jcprepct.c ***/
  166690. /*** Start of inlined file: jcsample.c ***/
  166691. #define JPEG_INTERNALS
  166692. /* Pointer to routine to downsample a single component */
  166693. typedef JMETHOD(void, downsample1_ptr,
  166694. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166695. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166696. /* Private subobject */
  166697. typedef struct {
  166698. struct jpeg_downsampler pub; /* public fields */
  166699. /* Downsampling method pointers, one per component */
  166700. downsample1_ptr methods[MAX_COMPONENTS];
  166701. } my_downsampler;
  166702. typedef my_downsampler * my_downsample_ptr;
  166703. /*
  166704. * Initialize for a downsampling pass.
  166705. */
  166706. METHODDEF(void)
  166707. start_pass_downsample (j_compress_ptr)
  166708. {
  166709. /* no work for now */
  166710. }
  166711. /*
  166712. * Expand a component horizontally from width input_cols to width output_cols,
  166713. * by duplicating the rightmost samples.
  166714. */
  166715. LOCAL(void)
  166716. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166717. JDIMENSION input_cols, JDIMENSION output_cols)
  166718. {
  166719. register JSAMPROW ptr;
  166720. register JSAMPLE pixval;
  166721. register int count;
  166722. int row;
  166723. int numcols = (int) (output_cols - input_cols);
  166724. if (numcols > 0) {
  166725. for (row = 0; row < num_rows; row++) {
  166726. ptr = image_data[row] + input_cols;
  166727. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166728. for (count = numcols; count > 0; count--)
  166729. *ptr++ = pixval;
  166730. }
  166731. }
  166732. }
  166733. /*
  166734. * Do downsampling for a whole row group (all components).
  166735. *
  166736. * In this version we simply downsample each component independently.
  166737. */
  166738. METHODDEF(void)
  166739. sep_downsample (j_compress_ptr cinfo,
  166740. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166741. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166742. {
  166743. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166744. int ci;
  166745. jpeg_component_info * compptr;
  166746. JSAMPARRAY in_ptr, out_ptr;
  166747. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166748. ci++, compptr++) {
  166749. in_ptr = input_buf[ci] + in_row_index;
  166750. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166751. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166752. }
  166753. }
  166754. /*
  166755. * Downsample pixel values of a single component.
  166756. * One row group is processed per call.
  166757. * This version handles arbitrary integral sampling ratios, without smoothing.
  166758. * Note that this version is not actually used for customary sampling ratios.
  166759. */
  166760. METHODDEF(void)
  166761. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166762. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166763. {
  166764. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166765. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166766. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166767. JSAMPROW inptr, outptr;
  166768. INT32 outvalue;
  166769. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166770. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166771. numpix = h_expand * v_expand;
  166772. numpix2 = numpix/2;
  166773. /* Expand input data enough to let all the output samples be generated
  166774. * by the standard loop. Special-casing padded output would be more
  166775. * efficient.
  166776. */
  166777. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166778. cinfo->image_width, output_cols * h_expand);
  166779. inrow = 0;
  166780. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166781. outptr = output_data[outrow];
  166782. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166783. outcol++, outcol_h += h_expand) {
  166784. outvalue = 0;
  166785. for (v = 0; v < v_expand; v++) {
  166786. inptr = input_data[inrow+v] + outcol_h;
  166787. for (h = 0; h < h_expand; h++) {
  166788. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166789. }
  166790. }
  166791. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166792. }
  166793. inrow += v_expand;
  166794. }
  166795. }
  166796. /*
  166797. * Downsample pixel values of a single component.
  166798. * This version handles the special case of a full-size component,
  166799. * without smoothing.
  166800. */
  166801. METHODDEF(void)
  166802. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166803. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166804. {
  166805. /* Copy the data */
  166806. jcopy_sample_rows(input_data, 0, output_data, 0,
  166807. cinfo->max_v_samp_factor, cinfo->image_width);
  166808. /* Edge-expand */
  166809. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166810. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166811. }
  166812. /*
  166813. * Downsample pixel values of a single component.
  166814. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166815. * without smoothing.
  166816. *
  166817. * A note about the "bias" calculations: when rounding fractional values to
  166818. * integer, we do not want to always round 0.5 up to the next integer.
  166819. * If we did that, we'd introduce a noticeable bias towards larger values.
  166820. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166821. * alternate pixel locations (a simple ordered dither pattern).
  166822. */
  166823. METHODDEF(void)
  166824. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166825. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166826. {
  166827. int outrow;
  166828. JDIMENSION outcol;
  166829. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166830. register JSAMPROW inptr, outptr;
  166831. register int bias;
  166832. /* Expand input data enough to let all the output samples be generated
  166833. * by the standard loop. Special-casing padded output would be more
  166834. * efficient.
  166835. */
  166836. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166837. cinfo->image_width, output_cols * 2);
  166838. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166839. outptr = output_data[outrow];
  166840. inptr = input_data[outrow];
  166841. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166842. for (outcol = 0; outcol < output_cols; outcol++) {
  166843. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166844. + bias) >> 1);
  166845. bias ^= 1; /* 0=>1, 1=>0 */
  166846. inptr += 2;
  166847. }
  166848. }
  166849. }
  166850. /*
  166851. * Downsample pixel values of a single component.
  166852. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166853. * without smoothing.
  166854. */
  166855. METHODDEF(void)
  166856. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166857. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166858. {
  166859. int inrow, outrow;
  166860. JDIMENSION outcol;
  166861. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166862. register JSAMPROW inptr0, inptr1, outptr;
  166863. register int bias;
  166864. /* Expand input data enough to let all the output samples be generated
  166865. * by the standard loop. Special-casing padded output would be more
  166866. * efficient.
  166867. */
  166868. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166869. cinfo->image_width, output_cols * 2);
  166870. inrow = 0;
  166871. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166872. outptr = output_data[outrow];
  166873. inptr0 = input_data[inrow];
  166874. inptr1 = input_data[inrow+1];
  166875. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166876. for (outcol = 0; outcol < output_cols; outcol++) {
  166877. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166878. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166879. + bias) >> 2);
  166880. bias ^= 3; /* 1=>2, 2=>1 */
  166881. inptr0 += 2; inptr1 += 2;
  166882. }
  166883. inrow += 2;
  166884. }
  166885. }
  166886. #ifdef INPUT_SMOOTHING_SUPPORTED
  166887. /*
  166888. * Downsample pixel values of a single component.
  166889. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166890. * with smoothing. One row of context is required.
  166891. */
  166892. METHODDEF(void)
  166893. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166894. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166895. {
  166896. int inrow, outrow;
  166897. JDIMENSION colctr;
  166898. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166899. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166900. INT32 membersum, neighsum, memberscale, neighscale;
  166901. /* Expand input data enough to let all the output samples be generated
  166902. * by the standard loop. Special-casing padded output would be more
  166903. * efficient.
  166904. */
  166905. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166906. cinfo->image_width, output_cols * 2);
  166907. /* We don't bother to form the individual "smoothed" input pixel values;
  166908. * we can directly compute the output which is the average of the four
  166909. * smoothed values. Each of the four member pixels contributes a fraction
  166910. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166911. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166912. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166913. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166914. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166915. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166916. * factors are scaled by 2^16 = 65536.
  166917. * Also recall that SF = smoothing_factor / 1024.
  166918. */
  166919. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166920. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166921. inrow = 0;
  166922. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166923. outptr = output_data[outrow];
  166924. inptr0 = input_data[inrow];
  166925. inptr1 = input_data[inrow+1];
  166926. above_ptr = input_data[inrow-1];
  166927. below_ptr = input_data[inrow+2];
  166928. /* Special case for first column: pretend column -1 is same as column 0 */
  166929. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166930. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166931. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166932. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166933. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166934. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166935. neighsum += neighsum;
  166936. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166937. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166938. membersum = membersum * memberscale + neighsum * neighscale;
  166939. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166940. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166941. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166942. /* sum of pixels directly mapped to this output element */
  166943. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166944. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166945. /* sum of edge-neighbor pixels */
  166946. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166947. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166948. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166949. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166950. /* The edge-neighbors count twice as much as corner-neighbors */
  166951. neighsum += neighsum;
  166952. /* Add in the corner-neighbors */
  166953. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166954. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166955. /* form final output scaled up by 2^16 */
  166956. membersum = membersum * memberscale + neighsum * neighscale;
  166957. /* round, descale and output it */
  166958. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166959. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166960. }
  166961. /* Special case for last column */
  166962. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166963. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166964. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166965. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166966. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166967. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166968. neighsum += neighsum;
  166969. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166970. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166971. membersum = membersum * memberscale + neighsum * neighscale;
  166972. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166973. inrow += 2;
  166974. }
  166975. }
  166976. /*
  166977. * Downsample pixel values of a single component.
  166978. * This version handles the special case of a full-size component,
  166979. * with smoothing. One row of context is required.
  166980. */
  166981. METHODDEF(void)
  166982. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166983. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166984. {
  166985. int outrow;
  166986. JDIMENSION colctr;
  166987. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166988. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166989. INT32 membersum, neighsum, memberscale, neighscale;
  166990. int colsum, lastcolsum, nextcolsum;
  166991. /* Expand input data enough to let all the output samples be generated
  166992. * by the standard loop. Special-casing padded output would be more
  166993. * efficient.
  166994. */
  166995. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166996. cinfo->image_width, output_cols);
  166997. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166998. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166999. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167000. * Also recall that SF = smoothing_factor / 1024.
  167001. */
  167002. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167003. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167004. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167005. outptr = output_data[outrow];
  167006. inptr = input_data[outrow];
  167007. above_ptr = input_data[outrow-1];
  167008. below_ptr = input_data[outrow+1];
  167009. /* Special case for first column */
  167010. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167011. GETJSAMPLE(*inptr);
  167012. membersum = GETJSAMPLE(*inptr++);
  167013. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167014. GETJSAMPLE(*inptr);
  167015. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167016. membersum = membersum * memberscale + neighsum * neighscale;
  167017. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167018. lastcolsum = colsum; colsum = nextcolsum;
  167019. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167020. membersum = GETJSAMPLE(*inptr++);
  167021. above_ptr++; below_ptr++;
  167022. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167023. GETJSAMPLE(*inptr);
  167024. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167025. membersum = membersum * memberscale + neighsum * neighscale;
  167026. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167027. lastcolsum = colsum; colsum = nextcolsum;
  167028. }
  167029. /* Special case for last column */
  167030. membersum = GETJSAMPLE(*inptr);
  167031. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167032. membersum = membersum * memberscale + neighsum * neighscale;
  167033. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167034. }
  167035. }
  167036. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167037. /*
  167038. * Module initialization routine for downsampling.
  167039. * Note that we must select a routine for each component.
  167040. */
  167041. GLOBAL(void)
  167042. jinit_downsampler (j_compress_ptr cinfo)
  167043. {
  167044. my_downsample_ptr downsample;
  167045. int ci;
  167046. jpeg_component_info * compptr;
  167047. boolean smoothok = TRUE;
  167048. downsample = (my_downsample_ptr)
  167049. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167050. SIZEOF(my_downsampler));
  167051. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167052. downsample->pub.start_pass = start_pass_downsample;
  167053. downsample->pub.downsample = sep_downsample;
  167054. downsample->pub.need_context_rows = FALSE;
  167055. if (cinfo->CCIR601_sampling)
  167056. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167057. /* Verify we can handle the sampling factors, and set up method pointers */
  167058. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167059. ci++, compptr++) {
  167060. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167061. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167062. #ifdef INPUT_SMOOTHING_SUPPORTED
  167063. if (cinfo->smoothing_factor) {
  167064. downsample->methods[ci] = fullsize_smooth_downsample;
  167065. downsample->pub.need_context_rows = TRUE;
  167066. } else
  167067. #endif
  167068. downsample->methods[ci] = fullsize_downsample;
  167069. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167070. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167071. smoothok = FALSE;
  167072. downsample->methods[ci] = h2v1_downsample;
  167073. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167074. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167075. #ifdef INPUT_SMOOTHING_SUPPORTED
  167076. if (cinfo->smoothing_factor) {
  167077. downsample->methods[ci] = h2v2_smooth_downsample;
  167078. downsample->pub.need_context_rows = TRUE;
  167079. } else
  167080. #endif
  167081. downsample->methods[ci] = h2v2_downsample;
  167082. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167083. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167084. smoothok = FALSE;
  167085. downsample->methods[ci] = int_downsample;
  167086. } else
  167087. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167088. }
  167089. #ifdef INPUT_SMOOTHING_SUPPORTED
  167090. if (cinfo->smoothing_factor && !smoothok)
  167091. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167092. #endif
  167093. }
  167094. /*** End of inlined file: jcsample.c ***/
  167095. /*** Start of inlined file: jctrans.c ***/
  167096. #define JPEG_INTERNALS
  167097. /* Forward declarations */
  167098. LOCAL(void) transencode_master_selection
  167099. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167100. LOCAL(void) transencode_coef_controller
  167101. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167102. /*
  167103. * Compression initialization for writing raw-coefficient data.
  167104. * Before calling this, all parameters and a data destination must be set up.
  167105. * Call jpeg_finish_compress() to actually write the data.
  167106. *
  167107. * The number of passed virtual arrays must match cinfo->num_components.
  167108. * Note that the virtual arrays need not be filled or even realized at
  167109. * the time write_coefficients is called; indeed, if the virtual arrays
  167110. * were requested from this compression object's memory manager, they
  167111. * typically will be realized during this routine and filled afterwards.
  167112. */
  167113. GLOBAL(void)
  167114. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167115. {
  167116. if (cinfo->global_state != CSTATE_START)
  167117. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167118. /* Mark all tables to be written */
  167119. jpeg_suppress_tables(cinfo, FALSE);
  167120. /* (Re)initialize error mgr and destination modules */
  167121. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167122. (*cinfo->dest->init_destination) (cinfo);
  167123. /* Perform master selection of active modules */
  167124. transencode_master_selection(cinfo, coef_arrays);
  167125. /* Wait for jpeg_finish_compress() call */
  167126. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167127. cinfo->global_state = CSTATE_WRCOEFS;
  167128. }
  167129. /*
  167130. * Initialize the compression object with default parameters,
  167131. * then copy from the source object all parameters needed for lossless
  167132. * transcoding. Parameters that can be varied without loss (such as
  167133. * scan script and Huffman optimization) are left in their default states.
  167134. */
  167135. GLOBAL(void)
  167136. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167137. j_compress_ptr dstinfo)
  167138. {
  167139. JQUANT_TBL ** qtblptr;
  167140. jpeg_component_info *incomp, *outcomp;
  167141. JQUANT_TBL *c_quant, *slot_quant;
  167142. int tblno, ci, coefi;
  167143. /* Safety check to ensure start_compress not called yet. */
  167144. if (dstinfo->global_state != CSTATE_START)
  167145. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167146. /* Copy fundamental image dimensions */
  167147. dstinfo->image_width = srcinfo->image_width;
  167148. dstinfo->image_height = srcinfo->image_height;
  167149. dstinfo->input_components = srcinfo->num_components;
  167150. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167151. /* Initialize all parameters to default values */
  167152. jpeg_set_defaults(dstinfo);
  167153. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167154. * Fix it to get the right header markers for the image colorspace.
  167155. */
  167156. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167157. dstinfo->data_precision = srcinfo->data_precision;
  167158. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167159. /* Copy the source's quantization tables. */
  167160. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167161. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167162. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167163. if (*qtblptr == NULL)
  167164. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167165. MEMCOPY((*qtblptr)->quantval,
  167166. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167167. SIZEOF((*qtblptr)->quantval));
  167168. (*qtblptr)->sent_table = FALSE;
  167169. }
  167170. }
  167171. /* Copy the source's per-component info.
  167172. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167173. */
  167174. dstinfo->num_components = srcinfo->num_components;
  167175. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167176. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167177. MAX_COMPONENTS);
  167178. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167179. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167180. outcomp->component_id = incomp->component_id;
  167181. outcomp->h_samp_factor = incomp->h_samp_factor;
  167182. outcomp->v_samp_factor = incomp->v_samp_factor;
  167183. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167184. /* Make sure saved quantization table for component matches the qtable
  167185. * slot. If not, the input file re-used this qtable slot.
  167186. * IJG encoder currently cannot duplicate this.
  167187. */
  167188. tblno = outcomp->quant_tbl_no;
  167189. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167190. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167191. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167192. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167193. c_quant = incomp->quant_table;
  167194. if (c_quant != NULL) {
  167195. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167196. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167197. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167198. }
  167199. }
  167200. /* Note: we do not copy the source's Huffman table assignments;
  167201. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167202. */
  167203. }
  167204. /* Also copy JFIF version and resolution information, if available.
  167205. * Strictly speaking this isn't "critical" info, but it's nearly
  167206. * always appropriate to copy it if available. In particular,
  167207. * if the application chooses to copy JFIF 1.02 extension markers from
  167208. * the source file, we need to copy the version to make sure we don't
  167209. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167210. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167211. */
  167212. if (srcinfo->saw_JFIF_marker) {
  167213. if (srcinfo->JFIF_major_version == 1) {
  167214. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167215. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167216. }
  167217. dstinfo->density_unit = srcinfo->density_unit;
  167218. dstinfo->X_density = srcinfo->X_density;
  167219. dstinfo->Y_density = srcinfo->Y_density;
  167220. }
  167221. }
  167222. /*
  167223. * Master selection of compression modules for transcoding.
  167224. * This substitutes for jcinit.c's initialization of the full compressor.
  167225. */
  167226. LOCAL(void)
  167227. transencode_master_selection (j_compress_ptr cinfo,
  167228. jvirt_barray_ptr * coef_arrays)
  167229. {
  167230. /* Although we don't actually use input_components for transcoding,
  167231. * jcmaster.c's initial_setup will complain if input_components is 0.
  167232. */
  167233. cinfo->input_components = 1;
  167234. /* Initialize master control (includes parameter checking/processing) */
  167235. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167236. /* Entropy encoding: either Huffman or arithmetic coding. */
  167237. if (cinfo->arith_code) {
  167238. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167239. } else {
  167240. if (cinfo->progressive_mode) {
  167241. #ifdef C_PROGRESSIVE_SUPPORTED
  167242. jinit_phuff_encoder(cinfo);
  167243. #else
  167244. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167245. #endif
  167246. } else
  167247. jinit_huff_encoder(cinfo);
  167248. }
  167249. /* We need a special coefficient buffer controller. */
  167250. transencode_coef_controller(cinfo, coef_arrays);
  167251. jinit_marker_writer(cinfo);
  167252. /* We can now tell the memory manager to allocate virtual arrays. */
  167253. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167254. /* Write the datastream header (SOI, JFIF) immediately.
  167255. * Frame and scan headers are postponed till later.
  167256. * This lets application insert special markers after the SOI.
  167257. */
  167258. (*cinfo->marker->write_file_header) (cinfo);
  167259. }
  167260. /*
  167261. * The rest of this file is a special implementation of the coefficient
  167262. * buffer controller. This is similar to jccoefct.c, but it handles only
  167263. * output from presupplied virtual arrays. Furthermore, we generate any
  167264. * dummy padding blocks on-the-fly rather than expecting them to be present
  167265. * in the arrays.
  167266. */
  167267. /* Private buffer controller object */
  167268. typedef struct {
  167269. struct jpeg_c_coef_controller pub; /* public fields */
  167270. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167271. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167272. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167273. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167274. /* Virtual block array for each component. */
  167275. jvirt_barray_ptr * whole_image;
  167276. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167277. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167278. } my_coef_controller2;
  167279. typedef my_coef_controller2 * my_coef_ptr2;
  167280. LOCAL(void)
  167281. start_iMCU_row2 (j_compress_ptr cinfo)
  167282. /* Reset within-iMCU-row counters for a new row */
  167283. {
  167284. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167285. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167286. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167287. * But at the bottom of the image, process only what's left.
  167288. */
  167289. if (cinfo->comps_in_scan > 1) {
  167290. coef->MCU_rows_per_iMCU_row = 1;
  167291. } else {
  167292. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167293. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167294. else
  167295. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167296. }
  167297. coef->mcu_ctr = 0;
  167298. coef->MCU_vert_offset = 0;
  167299. }
  167300. /*
  167301. * Initialize for a processing pass.
  167302. */
  167303. METHODDEF(void)
  167304. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167305. {
  167306. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167307. if (pass_mode != JBUF_CRANK_DEST)
  167308. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167309. coef->iMCU_row_num = 0;
  167310. start_iMCU_row2(cinfo);
  167311. }
  167312. /*
  167313. * Process some data.
  167314. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167315. * per call, ie, v_samp_factor block rows for each component in the scan.
  167316. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167317. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167318. *
  167319. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167320. */
  167321. METHODDEF(boolean)
  167322. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167323. {
  167324. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167325. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167326. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167327. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167328. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167329. JDIMENSION start_col;
  167330. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167331. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167332. JBLOCKROW buffer_ptr;
  167333. jpeg_component_info *compptr;
  167334. /* Align the virtual buffers for the components used in this scan. */
  167335. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167336. compptr = cinfo->cur_comp_info[ci];
  167337. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167338. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167339. coef->iMCU_row_num * compptr->v_samp_factor,
  167340. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167341. }
  167342. /* Loop to process one whole iMCU row */
  167343. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167344. yoffset++) {
  167345. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167346. MCU_col_num++) {
  167347. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167348. blkn = 0; /* index of current DCT block within MCU */
  167349. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167350. compptr = cinfo->cur_comp_info[ci];
  167351. start_col = MCU_col_num * compptr->MCU_width;
  167352. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167353. : compptr->last_col_width;
  167354. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167355. if (coef->iMCU_row_num < last_iMCU_row ||
  167356. yindex+yoffset < compptr->last_row_height) {
  167357. /* Fill in pointers to real blocks in this row */
  167358. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167359. for (xindex = 0; xindex < blockcnt; xindex++)
  167360. MCU_buffer[blkn++] = buffer_ptr++;
  167361. } else {
  167362. /* At bottom of image, need a whole row of dummy blocks */
  167363. xindex = 0;
  167364. }
  167365. /* Fill in any dummy blocks needed in this row.
  167366. * Dummy blocks are filled in the same way as in jccoefct.c:
  167367. * all zeroes in the AC entries, DC entries equal to previous
  167368. * block's DC value. The init routine has already zeroed the
  167369. * AC entries, so we need only set the DC entries correctly.
  167370. */
  167371. for (; xindex < compptr->MCU_width; xindex++) {
  167372. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167373. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167374. blkn++;
  167375. }
  167376. }
  167377. }
  167378. /* Try to write the MCU. */
  167379. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167380. /* Suspension forced; update state counters and exit */
  167381. coef->MCU_vert_offset = yoffset;
  167382. coef->mcu_ctr = MCU_col_num;
  167383. return FALSE;
  167384. }
  167385. }
  167386. /* Completed an MCU row, but perhaps not an iMCU row */
  167387. coef->mcu_ctr = 0;
  167388. }
  167389. /* Completed the iMCU row, advance counters for next one */
  167390. coef->iMCU_row_num++;
  167391. start_iMCU_row2(cinfo);
  167392. return TRUE;
  167393. }
  167394. /*
  167395. * Initialize coefficient buffer controller.
  167396. *
  167397. * Each passed coefficient array must be the right size for that
  167398. * coefficient: width_in_blocks wide and height_in_blocks high,
  167399. * with unitheight at least v_samp_factor.
  167400. */
  167401. LOCAL(void)
  167402. transencode_coef_controller (j_compress_ptr cinfo,
  167403. jvirt_barray_ptr * coef_arrays)
  167404. {
  167405. my_coef_ptr2 coef;
  167406. JBLOCKROW buffer;
  167407. int i;
  167408. coef = (my_coef_ptr2)
  167409. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167410. SIZEOF(my_coef_controller2));
  167411. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167412. coef->pub.start_pass = start_pass_coef2;
  167413. coef->pub.compress_data = compress_output2;
  167414. /* Save pointer to virtual arrays */
  167415. coef->whole_image = coef_arrays;
  167416. /* Allocate and pre-zero space for dummy DCT blocks. */
  167417. buffer = (JBLOCKROW)
  167418. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167419. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167420. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167421. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167422. coef->dummy_buffer[i] = buffer + i;
  167423. }
  167424. }
  167425. /*** End of inlined file: jctrans.c ***/
  167426. /*** Start of inlined file: jdapistd.c ***/
  167427. #define JPEG_INTERNALS
  167428. /* Forward declarations */
  167429. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167430. /*
  167431. * Decompression initialization.
  167432. * jpeg_read_header must be completed before calling this.
  167433. *
  167434. * If a multipass operating mode was selected, this will do all but the
  167435. * last pass, and thus may take a great deal of time.
  167436. *
  167437. * Returns FALSE if suspended. The return value need be inspected only if
  167438. * a suspending data source is used.
  167439. */
  167440. GLOBAL(boolean)
  167441. jpeg_start_decompress (j_decompress_ptr cinfo)
  167442. {
  167443. if (cinfo->global_state == DSTATE_READY) {
  167444. /* First call: initialize master control, select active modules */
  167445. jinit_master_decompress(cinfo);
  167446. if (cinfo->buffered_image) {
  167447. /* No more work here; expecting jpeg_start_output next */
  167448. cinfo->global_state = DSTATE_BUFIMAGE;
  167449. return TRUE;
  167450. }
  167451. cinfo->global_state = DSTATE_PRELOAD;
  167452. }
  167453. if (cinfo->global_state == DSTATE_PRELOAD) {
  167454. /* If file has multiple scans, absorb them all into the coef buffer */
  167455. if (cinfo->inputctl->has_multiple_scans) {
  167456. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167457. for (;;) {
  167458. int retcode;
  167459. /* Call progress monitor hook if present */
  167460. if (cinfo->progress != NULL)
  167461. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167462. /* Absorb some more input */
  167463. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167464. if (retcode == JPEG_SUSPENDED)
  167465. return FALSE;
  167466. if (retcode == JPEG_REACHED_EOI)
  167467. break;
  167468. /* Advance progress counter if appropriate */
  167469. if (cinfo->progress != NULL &&
  167470. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167471. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167472. /* jdmaster underestimated number of scans; ratchet up one scan */
  167473. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167474. }
  167475. }
  167476. }
  167477. #else
  167478. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167479. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167480. }
  167481. cinfo->output_scan_number = cinfo->input_scan_number;
  167482. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167483. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167484. /* Perform any dummy output passes, and set up for the final pass */
  167485. return output_pass_setup(cinfo);
  167486. }
  167487. /*
  167488. * Set up for an output pass, and perform any dummy pass(es) needed.
  167489. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167490. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167491. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167492. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167493. */
  167494. LOCAL(boolean)
  167495. output_pass_setup (j_decompress_ptr cinfo)
  167496. {
  167497. if (cinfo->global_state != DSTATE_PRESCAN) {
  167498. /* First call: do pass setup */
  167499. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167500. cinfo->output_scanline = 0;
  167501. cinfo->global_state = DSTATE_PRESCAN;
  167502. }
  167503. /* Loop over any required dummy passes */
  167504. while (cinfo->master->is_dummy_pass) {
  167505. #ifdef QUANT_2PASS_SUPPORTED
  167506. /* Crank through the dummy pass */
  167507. while (cinfo->output_scanline < cinfo->output_height) {
  167508. JDIMENSION last_scanline;
  167509. /* Call progress monitor hook if present */
  167510. if (cinfo->progress != NULL) {
  167511. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167512. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167513. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167514. }
  167515. /* Process some data */
  167516. last_scanline = cinfo->output_scanline;
  167517. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167518. &cinfo->output_scanline, (JDIMENSION) 0);
  167519. if (cinfo->output_scanline == last_scanline)
  167520. return FALSE; /* No progress made, must suspend */
  167521. }
  167522. /* Finish up dummy pass, and set up for another one */
  167523. (*cinfo->master->finish_output_pass) (cinfo);
  167524. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167525. cinfo->output_scanline = 0;
  167526. #else
  167527. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167528. #endif /* QUANT_2PASS_SUPPORTED */
  167529. }
  167530. /* Ready for application to drive output pass through
  167531. * jpeg_read_scanlines or jpeg_read_raw_data.
  167532. */
  167533. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167534. return TRUE;
  167535. }
  167536. /*
  167537. * Read some scanlines of data from the JPEG decompressor.
  167538. *
  167539. * The return value will be the number of lines actually read.
  167540. * This may be less than the number requested in several cases,
  167541. * including bottom of image, data source suspension, and operating
  167542. * modes that emit multiple scanlines at a time.
  167543. *
  167544. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167545. * this likely signals an application programmer error. However,
  167546. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167547. */
  167548. GLOBAL(JDIMENSION)
  167549. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167550. JDIMENSION max_lines)
  167551. {
  167552. JDIMENSION row_ctr;
  167553. if (cinfo->global_state != DSTATE_SCANNING)
  167554. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167555. if (cinfo->output_scanline >= cinfo->output_height) {
  167556. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167557. return 0;
  167558. }
  167559. /* Call progress monitor hook if present */
  167560. if (cinfo->progress != NULL) {
  167561. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167562. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167563. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167564. }
  167565. /* Process some data */
  167566. row_ctr = 0;
  167567. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167568. cinfo->output_scanline += row_ctr;
  167569. return row_ctr;
  167570. }
  167571. /*
  167572. * Alternate entry point to read raw data.
  167573. * Processes exactly one iMCU row per call, unless suspended.
  167574. */
  167575. GLOBAL(JDIMENSION)
  167576. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167577. JDIMENSION max_lines)
  167578. {
  167579. JDIMENSION lines_per_iMCU_row;
  167580. if (cinfo->global_state != DSTATE_RAW_OK)
  167581. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167582. if (cinfo->output_scanline >= cinfo->output_height) {
  167583. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167584. return 0;
  167585. }
  167586. /* Call progress monitor hook if present */
  167587. if (cinfo->progress != NULL) {
  167588. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167589. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167590. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167591. }
  167592. /* Verify that at least one iMCU row can be returned. */
  167593. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167594. if (max_lines < lines_per_iMCU_row)
  167595. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167596. /* Decompress directly into user's buffer. */
  167597. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167598. return 0; /* suspension forced, can do nothing more */
  167599. /* OK, we processed one iMCU row. */
  167600. cinfo->output_scanline += lines_per_iMCU_row;
  167601. return lines_per_iMCU_row;
  167602. }
  167603. /* Additional entry points for buffered-image mode. */
  167604. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167605. /*
  167606. * Initialize for an output pass in buffered-image mode.
  167607. */
  167608. GLOBAL(boolean)
  167609. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167610. {
  167611. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167612. cinfo->global_state != DSTATE_PRESCAN)
  167613. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167614. /* Limit scan number to valid range */
  167615. if (scan_number <= 0)
  167616. scan_number = 1;
  167617. if (cinfo->inputctl->eoi_reached &&
  167618. scan_number > cinfo->input_scan_number)
  167619. scan_number = cinfo->input_scan_number;
  167620. cinfo->output_scan_number = scan_number;
  167621. /* Perform any dummy output passes, and set up for the real pass */
  167622. return output_pass_setup(cinfo);
  167623. }
  167624. /*
  167625. * Finish up after an output pass in buffered-image mode.
  167626. *
  167627. * Returns FALSE if suspended. The return value need be inspected only if
  167628. * a suspending data source is used.
  167629. */
  167630. GLOBAL(boolean)
  167631. jpeg_finish_output (j_decompress_ptr cinfo)
  167632. {
  167633. if ((cinfo->global_state == DSTATE_SCANNING ||
  167634. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167635. /* Terminate this pass. */
  167636. /* We do not require the whole pass to have been completed. */
  167637. (*cinfo->master->finish_output_pass) (cinfo);
  167638. cinfo->global_state = DSTATE_BUFPOST;
  167639. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167640. /* BUFPOST = repeat call after a suspension, anything else is error */
  167641. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167642. }
  167643. /* Read markers looking for SOS or EOI */
  167644. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167645. ! cinfo->inputctl->eoi_reached) {
  167646. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167647. return FALSE; /* Suspend, come back later */
  167648. }
  167649. cinfo->global_state = DSTATE_BUFIMAGE;
  167650. return TRUE;
  167651. }
  167652. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167653. /*** End of inlined file: jdapistd.c ***/
  167654. /*** Start of inlined file: jdapimin.c ***/
  167655. #define JPEG_INTERNALS
  167656. /*
  167657. * Initialization of a JPEG decompression object.
  167658. * The error manager must already be set up (in case memory manager fails).
  167659. */
  167660. GLOBAL(void)
  167661. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167662. {
  167663. int i;
  167664. /* Guard against version mismatches between library and caller. */
  167665. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167666. if (version != JPEG_LIB_VERSION)
  167667. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167668. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167669. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167670. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167671. /* For debugging purposes, we zero the whole master structure.
  167672. * But the application has already set the err pointer, and may have set
  167673. * client_data, so we have to save and restore those fields.
  167674. * Note: if application hasn't set client_data, tools like Purify may
  167675. * complain here.
  167676. */
  167677. {
  167678. struct jpeg_error_mgr * err = cinfo->err;
  167679. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167680. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167681. cinfo->err = err;
  167682. cinfo->client_data = client_data;
  167683. }
  167684. cinfo->is_decompressor = TRUE;
  167685. /* Initialize a memory manager instance for this object */
  167686. jinit_memory_mgr((j_common_ptr) cinfo);
  167687. /* Zero out pointers to permanent structures. */
  167688. cinfo->progress = NULL;
  167689. cinfo->src = NULL;
  167690. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167691. cinfo->quant_tbl_ptrs[i] = NULL;
  167692. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167693. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167694. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167695. }
  167696. /* Initialize marker processor so application can override methods
  167697. * for COM, APPn markers before calling jpeg_read_header.
  167698. */
  167699. cinfo->marker_list = NULL;
  167700. jinit_marker_reader(cinfo);
  167701. /* And initialize the overall input controller. */
  167702. jinit_input_controller(cinfo);
  167703. /* OK, I'm ready */
  167704. cinfo->global_state = DSTATE_START;
  167705. }
  167706. /*
  167707. * Destruction of a JPEG decompression object
  167708. */
  167709. GLOBAL(void)
  167710. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167711. {
  167712. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167713. }
  167714. /*
  167715. * Abort processing of a JPEG decompression operation,
  167716. * but don't destroy the object itself.
  167717. */
  167718. GLOBAL(void)
  167719. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167720. {
  167721. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167722. }
  167723. /*
  167724. * Set default decompression parameters.
  167725. */
  167726. LOCAL(void)
  167727. default_decompress_parms (j_decompress_ptr cinfo)
  167728. {
  167729. /* Guess the input colorspace, and set output colorspace accordingly. */
  167730. /* (Wish JPEG committee had provided a real way to specify this...) */
  167731. /* Note application may override our guesses. */
  167732. switch (cinfo->num_components) {
  167733. case 1:
  167734. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167735. cinfo->out_color_space = JCS_GRAYSCALE;
  167736. break;
  167737. case 3:
  167738. if (cinfo->saw_JFIF_marker) {
  167739. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167740. } else if (cinfo->saw_Adobe_marker) {
  167741. switch (cinfo->Adobe_transform) {
  167742. case 0:
  167743. cinfo->jpeg_color_space = JCS_RGB;
  167744. break;
  167745. case 1:
  167746. cinfo->jpeg_color_space = JCS_YCbCr;
  167747. break;
  167748. default:
  167749. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167750. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167751. break;
  167752. }
  167753. } else {
  167754. /* Saw no special markers, try to guess from the component IDs */
  167755. int cid0 = cinfo->comp_info[0].component_id;
  167756. int cid1 = cinfo->comp_info[1].component_id;
  167757. int cid2 = cinfo->comp_info[2].component_id;
  167758. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167759. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167760. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167761. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167762. else {
  167763. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167764. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167765. }
  167766. }
  167767. /* Always guess RGB is proper output colorspace. */
  167768. cinfo->out_color_space = JCS_RGB;
  167769. break;
  167770. case 4:
  167771. if (cinfo->saw_Adobe_marker) {
  167772. switch (cinfo->Adobe_transform) {
  167773. case 0:
  167774. cinfo->jpeg_color_space = JCS_CMYK;
  167775. break;
  167776. case 2:
  167777. cinfo->jpeg_color_space = JCS_YCCK;
  167778. break;
  167779. default:
  167780. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167781. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167782. break;
  167783. }
  167784. } else {
  167785. /* No special markers, assume straight CMYK. */
  167786. cinfo->jpeg_color_space = JCS_CMYK;
  167787. }
  167788. cinfo->out_color_space = JCS_CMYK;
  167789. break;
  167790. default:
  167791. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167792. cinfo->out_color_space = JCS_UNKNOWN;
  167793. break;
  167794. }
  167795. /* Set defaults for other decompression parameters. */
  167796. cinfo->scale_num = 1; /* 1:1 scaling */
  167797. cinfo->scale_denom = 1;
  167798. cinfo->output_gamma = 1.0;
  167799. cinfo->buffered_image = FALSE;
  167800. cinfo->raw_data_out = FALSE;
  167801. cinfo->dct_method = JDCT_DEFAULT;
  167802. cinfo->do_fancy_upsampling = TRUE;
  167803. cinfo->do_block_smoothing = TRUE;
  167804. cinfo->quantize_colors = FALSE;
  167805. /* We set these in case application only sets quantize_colors. */
  167806. cinfo->dither_mode = JDITHER_FS;
  167807. #ifdef QUANT_2PASS_SUPPORTED
  167808. cinfo->two_pass_quantize = TRUE;
  167809. #else
  167810. cinfo->two_pass_quantize = FALSE;
  167811. #endif
  167812. cinfo->desired_number_of_colors = 256;
  167813. cinfo->colormap = NULL;
  167814. /* Initialize for no mode change in buffered-image mode. */
  167815. cinfo->enable_1pass_quant = FALSE;
  167816. cinfo->enable_external_quant = FALSE;
  167817. cinfo->enable_2pass_quant = FALSE;
  167818. }
  167819. /*
  167820. * Decompression startup: read start of JPEG datastream to see what's there.
  167821. * Need only initialize JPEG object and supply a data source before calling.
  167822. *
  167823. * This routine will read as far as the first SOS marker (ie, actual start of
  167824. * compressed data), and will save all tables and parameters in the JPEG
  167825. * object. It will also initialize the decompression parameters to default
  167826. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167827. * adjust the decompression parameters and then call jpeg_start_decompress.
  167828. * (Or, if the application only wanted to determine the image parameters,
  167829. * the data need not be decompressed. In that case, call jpeg_abort or
  167830. * jpeg_destroy to release any temporary space.)
  167831. * If an abbreviated (tables only) datastream is presented, the routine will
  167832. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167833. * re-use the JPEG object to read the abbreviated image datastream(s).
  167834. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167835. * The JPEG_SUSPENDED return code only occurs if the data source module
  167836. * requests suspension of the decompressor. In this case the application
  167837. * should load more source data and then re-call jpeg_read_header to resume
  167838. * processing.
  167839. * If a non-suspending data source is used and require_image is TRUE, then the
  167840. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167841. *
  167842. * This routine is now just a front end to jpeg_consume_input, with some
  167843. * extra error checking.
  167844. */
  167845. GLOBAL(int)
  167846. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167847. {
  167848. int retcode;
  167849. if (cinfo->global_state != DSTATE_START &&
  167850. cinfo->global_state != DSTATE_INHEADER)
  167851. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167852. retcode = jpeg_consume_input(cinfo);
  167853. switch (retcode) {
  167854. case JPEG_REACHED_SOS:
  167855. retcode = JPEG_HEADER_OK;
  167856. break;
  167857. case JPEG_REACHED_EOI:
  167858. if (require_image) /* Complain if application wanted an image */
  167859. ERREXIT(cinfo, JERR_NO_IMAGE);
  167860. /* Reset to start state; it would be safer to require the application to
  167861. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167862. * A side effect is to free any temporary memory (there shouldn't be any).
  167863. */
  167864. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167865. retcode = JPEG_HEADER_TABLES_ONLY;
  167866. break;
  167867. case JPEG_SUSPENDED:
  167868. /* no work */
  167869. break;
  167870. }
  167871. return retcode;
  167872. }
  167873. /*
  167874. * Consume data in advance of what the decompressor requires.
  167875. * This can be called at any time once the decompressor object has
  167876. * been created and a data source has been set up.
  167877. *
  167878. * This routine is essentially a state machine that handles a couple
  167879. * of critical state-transition actions, namely initial setup and
  167880. * transition from header scanning to ready-for-start_decompress.
  167881. * All the actual input is done via the input controller's consume_input
  167882. * method.
  167883. */
  167884. GLOBAL(int)
  167885. jpeg_consume_input (j_decompress_ptr cinfo)
  167886. {
  167887. int retcode = JPEG_SUSPENDED;
  167888. /* NB: every possible DSTATE value should be listed in this switch */
  167889. switch (cinfo->global_state) {
  167890. case DSTATE_START:
  167891. /* Start-of-datastream actions: reset appropriate modules */
  167892. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167893. /* Initialize application's data source module */
  167894. (*cinfo->src->init_source) (cinfo);
  167895. cinfo->global_state = DSTATE_INHEADER;
  167896. /*FALLTHROUGH*/
  167897. case DSTATE_INHEADER:
  167898. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167899. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167900. /* Set up default parameters based on header data */
  167901. default_decompress_parms(cinfo);
  167902. /* Set global state: ready for start_decompress */
  167903. cinfo->global_state = DSTATE_READY;
  167904. }
  167905. break;
  167906. case DSTATE_READY:
  167907. /* Can't advance past first SOS until start_decompress is called */
  167908. retcode = JPEG_REACHED_SOS;
  167909. break;
  167910. case DSTATE_PRELOAD:
  167911. case DSTATE_PRESCAN:
  167912. case DSTATE_SCANNING:
  167913. case DSTATE_RAW_OK:
  167914. case DSTATE_BUFIMAGE:
  167915. case DSTATE_BUFPOST:
  167916. case DSTATE_STOPPING:
  167917. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167918. break;
  167919. default:
  167920. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167921. }
  167922. return retcode;
  167923. }
  167924. /*
  167925. * Have we finished reading the input file?
  167926. */
  167927. GLOBAL(boolean)
  167928. jpeg_input_complete (j_decompress_ptr cinfo)
  167929. {
  167930. /* Check for valid jpeg object */
  167931. if (cinfo->global_state < DSTATE_START ||
  167932. cinfo->global_state > DSTATE_STOPPING)
  167933. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167934. return cinfo->inputctl->eoi_reached;
  167935. }
  167936. /*
  167937. * Is there more than one scan?
  167938. */
  167939. GLOBAL(boolean)
  167940. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167941. {
  167942. /* Only valid after jpeg_read_header completes */
  167943. if (cinfo->global_state < DSTATE_READY ||
  167944. cinfo->global_state > DSTATE_STOPPING)
  167945. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167946. return cinfo->inputctl->has_multiple_scans;
  167947. }
  167948. /*
  167949. * Finish JPEG decompression.
  167950. *
  167951. * This will normally just verify the file trailer and release temp storage.
  167952. *
  167953. * Returns FALSE if suspended. The return value need be inspected only if
  167954. * a suspending data source is used.
  167955. */
  167956. GLOBAL(boolean)
  167957. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167958. {
  167959. if ((cinfo->global_state == DSTATE_SCANNING ||
  167960. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167961. /* Terminate final pass of non-buffered mode */
  167962. if (cinfo->output_scanline < cinfo->output_height)
  167963. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167964. (*cinfo->master->finish_output_pass) (cinfo);
  167965. cinfo->global_state = DSTATE_STOPPING;
  167966. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167967. /* Finishing after a buffered-image operation */
  167968. cinfo->global_state = DSTATE_STOPPING;
  167969. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167970. /* STOPPING = repeat call after a suspension, anything else is error */
  167971. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167972. }
  167973. /* Read until EOI */
  167974. while (! cinfo->inputctl->eoi_reached) {
  167975. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167976. return FALSE; /* Suspend, come back later */
  167977. }
  167978. /* Do final cleanup */
  167979. (*cinfo->src->term_source) (cinfo);
  167980. /* We can use jpeg_abort to release memory and reset global_state */
  167981. jpeg_abort((j_common_ptr) cinfo);
  167982. return TRUE;
  167983. }
  167984. /*** End of inlined file: jdapimin.c ***/
  167985. /*** Start of inlined file: jdatasrc.c ***/
  167986. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167987. /*** Start of inlined file: jerror.h ***/
  167988. /*
  167989. * To define the enum list of message codes, include this file without
  167990. * defining macro JMESSAGE. To create a message string table, include it
  167991. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167992. */
  167993. #ifndef JMESSAGE
  167994. #ifndef JERROR_H
  167995. /* First time through, define the enum list */
  167996. #define JMAKE_ENUM_LIST
  167997. #else
  167998. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167999. #define JMESSAGE(code,string)
  168000. #endif /* JERROR_H */
  168001. #endif /* JMESSAGE */
  168002. #ifdef JMAKE_ENUM_LIST
  168003. typedef enum {
  168004. #define JMESSAGE(code,string) code ,
  168005. #endif /* JMAKE_ENUM_LIST */
  168006. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168007. /* For maintenance convenience, list is alphabetical by message code name */
  168008. JMESSAGE(JERR_ARITH_NOTIMPL,
  168009. "Sorry, there are legal restrictions on arithmetic coding")
  168010. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168011. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168012. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168013. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168014. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168015. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168016. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168017. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168018. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168019. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168020. JMESSAGE(JERR_BAD_LIB_VERSION,
  168021. "Wrong JPEG library version: library is %d, caller expects %d")
  168022. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168023. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168024. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168025. JMESSAGE(JERR_BAD_PROGRESSION,
  168026. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168027. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168028. "Invalid progressive parameters at scan script entry %d")
  168029. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168030. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168031. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168032. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168033. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168034. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168035. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168036. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168037. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168038. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168039. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168040. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168041. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168042. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168043. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168044. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168045. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168046. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168047. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168048. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168049. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168050. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168051. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168052. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168053. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168054. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168055. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168056. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168057. "Cannot transcode due to multiple use of quantization table %d")
  168058. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168059. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168060. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168061. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168062. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168063. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168064. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168065. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168066. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168067. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168068. JMESSAGE(JERR_QUANT_COMPONENTS,
  168069. "Cannot quantize more than %d color components")
  168070. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168071. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168072. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168073. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168074. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168075. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168076. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168077. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168078. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168079. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168080. JMESSAGE(JERR_TFILE_WRITE,
  168081. "Write failed on temporary file --- out of disk space?")
  168082. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168083. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168084. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168085. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168086. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168087. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168088. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168089. JMESSAGE(JMSG_VERSION, JVERSION)
  168090. JMESSAGE(JTRC_16BIT_TABLES,
  168091. "Caution: quantization tables are too coarse for baseline JPEG")
  168092. JMESSAGE(JTRC_ADOBE,
  168093. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168094. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168095. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168096. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168097. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168098. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168099. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168100. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168101. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168102. JMESSAGE(JTRC_EOI, "End Of Image")
  168103. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168104. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168105. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168106. "Warning: thumbnail image size does not match data length %u")
  168107. JMESSAGE(JTRC_JFIF_EXTENSION,
  168108. "JFIF extension marker: type 0x%02x, length %u")
  168109. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168110. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168111. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168112. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168113. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168114. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168115. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168116. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168117. JMESSAGE(JTRC_RST, "RST%d")
  168118. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168119. "Smoothing not supported with nonstandard sampling ratios")
  168120. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168121. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168122. JMESSAGE(JTRC_SOI, "Start of Image")
  168123. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168124. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168125. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168126. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168127. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168128. JMESSAGE(JTRC_THUMB_JPEG,
  168129. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168130. JMESSAGE(JTRC_THUMB_PALETTE,
  168131. "JFIF extension marker: palette thumbnail image, length %u")
  168132. JMESSAGE(JTRC_THUMB_RGB,
  168133. "JFIF extension marker: RGB thumbnail image, length %u")
  168134. JMESSAGE(JTRC_UNKNOWN_IDS,
  168135. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168136. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168137. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168138. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168139. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168140. "Inconsistent progression sequence for component %d coefficient %d")
  168141. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168142. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168143. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168144. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168145. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168146. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168147. JMESSAGE(JWRN_MUST_RESYNC,
  168148. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168149. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168150. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168151. #ifdef JMAKE_ENUM_LIST
  168152. JMSG_LASTMSGCODE
  168153. } J_MESSAGE_CODE;
  168154. #undef JMAKE_ENUM_LIST
  168155. #endif /* JMAKE_ENUM_LIST */
  168156. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168157. #undef JMESSAGE
  168158. #ifndef JERROR_H
  168159. #define JERROR_H
  168160. /* Macros to simplify using the error and trace message stuff */
  168161. /* The first parameter is either type of cinfo pointer */
  168162. /* Fatal errors (print message and exit) */
  168163. #define ERREXIT(cinfo,code) \
  168164. ((cinfo)->err->msg_code = (code), \
  168165. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168166. #define ERREXIT1(cinfo,code,p1) \
  168167. ((cinfo)->err->msg_code = (code), \
  168168. (cinfo)->err->msg_parm.i[0] = (p1), \
  168169. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168170. #define ERREXIT2(cinfo,code,p1,p2) \
  168171. ((cinfo)->err->msg_code = (code), \
  168172. (cinfo)->err->msg_parm.i[0] = (p1), \
  168173. (cinfo)->err->msg_parm.i[1] = (p2), \
  168174. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168175. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168176. ((cinfo)->err->msg_code = (code), \
  168177. (cinfo)->err->msg_parm.i[0] = (p1), \
  168178. (cinfo)->err->msg_parm.i[1] = (p2), \
  168179. (cinfo)->err->msg_parm.i[2] = (p3), \
  168180. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168181. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168182. ((cinfo)->err->msg_code = (code), \
  168183. (cinfo)->err->msg_parm.i[0] = (p1), \
  168184. (cinfo)->err->msg_parm.i[1] = (p2), \
  168185. (cinfo)->err->msg_parm.i[2] = (p3), \
  168186. (cinfo)->err->msg_parm.i[3] = (p4), \
  168187. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168188. #define ERREXITS(cinfo,code,str) \
  168189. ((cinfo)->err->msg_code = (code), \
  168190. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168191. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168192. #define MAKESTMT(stuff) do { stuff } while (0)
  168193. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168194. #define WARNMS(cinfo,code) \
  168195. ((cinfo)->err->msg_code = (code), \
  168196. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168197. #define WARNMS1(cinfo,code,p1) \
  168198. ((cinfo)->err->msg_code = (code), \
  168199. (cinfo)->err->msg_parm.i[0] = (p1), \
  168200. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168201. #define WARNMS2(cinfo,code,p1,p2) \
  168202. ((cinfo)->err->msg_code = (code), \
  168203. (cinfo)->err->msg_parm.i[0] = (p1), \
  168204. (cinfo)->err->msg_parm.i[1] = (p2), \
  168205. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168206. /* Informational/debugging messages */
  168207. #define TRACEMS(cinfo,lvl,code) \
  168208. ((cinfo)->err->msg_code = (code), \
  168209. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168210. #define TRACEMS1(cinfo,lvl,code,p1) \
  168211. ((cinfo)->err->msg_code = (code), \
  168212. (cinfo)->err->msg_parm.i[0] = (p1), \
  168213. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168214. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168215. ((cinfo)->err->msg_code = (code), \
  168216. (cinfo)->err->msg_parm.i[0] = (p1), \
  168217. (cinfo)->err->msg_parm.i[1] = (p2), \
  168218. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168219. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168220. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168221. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168222. (cinfo)->err->msg_code = (code); \
  168223. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168224. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168225. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168226. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168227. (cinfo)->err->msg_code = (code); \
  168228. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168229. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168230. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168231. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168232. _mp[4] = (p5); \
  168233. (cinfo)->err->msg_code = (code); \
  168234. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168235. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168236. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168237. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168238. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168239. (cinfo)->err->msg_code = (code); \
  168240. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168241. #define TRACEMSS(cinfo,lvl,code,str) \
  168242. ((cinfo)->err->msg_code = (code), \
  168243. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168244. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168245. #endif /* JERROR_H */
  168246. /*** End of inlined file: jerror.h ***/
  168247. /* Expanded data source object for stdio input */
  168248. typedef struct {
  168249. struct jpeg_source_mgr pub; /* public fields */
  168250. FILE * infile; /* source stream */
  168251. JOCTET * buffer; /* start of buffer */
  168252. boolean start_of_file; /* have we gotten any data yet? */
  168253. } my_source_mgr;
  168254. typedef my_source_mgr * my_src_ptr;
  168255. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168256. /*
  168257. * Initialize source --- called by jpeg_read_header
  168258. * before any data is actually read.
  168259. */
  168260. METHODDEF(void)
  168261. init_source (j_decompress_ptr cinfo)
  168262. {
  168263. my_src_ptr src = (my_src_ptr) cinfo->src;
  168264. /* We reset the empty-input-file flag for each image,
  168265. * but we don't clear the input buffer.
  168266. * This is correct behavior for reading a series of images from one source.
  168267. */
  168268. src->start_of_file = TRUE;
  168269. }
  168270. /*
  168271. * Fill the input buffer --- called whenever buffer is emptied.
  168272. *
  168273. * In typical applications, this should read fresh data into the buffer
  168274. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168275. * reset the pointer & count to the start of the buffer, and return TRUE
  168276. * indicating that the buffer has been reloaded. It is not necessary to
  168277. * fill the buffer entirely, only to obtain at least one more byte.
  168278. *
  168279. * There is no such thing as an EOF return. If the end of the file has been
  168280. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168281. * the buffer. In most cases, generating a warning message and inserting a
  168282. * fake EOI marker is the best course of action --- this will allow the
  168283. * decompressor to output however much of the image is there. However,
  168284. * the resulting error message is misleading if the real problem is an empty
  168285. * input file, so we handle that case specially.
  168286. *
  168287. * In applications that need to be able to suspend compression due to input
  168288. * not being available yet, a FALSE return indicates that no more data can be
  168289. * obtained right now, but more may be forthcoming later. In this situation,
  168290. * the decompressor will return to its caller (with an indication of the
  168291. * number of scanlines it has read, if any). The application should resume
  168292. * decompression after it has loaded more data into the input buffer. Note
  168293. * that there are substantial restrictions on the use of suspension --- see
  168294. * the documentation.
  168295. *
  168296. * When suspending, the decompressor will back up to a convenient restart point
  168297. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168298. * indicate where the restart point will be if the current call returns FALSE.
  168299. * Data beyond this point must be rescanned after resumption, so move it to
  168300. * the front of the buffer rather than discarding it.
  168301. */
  168302. METHODDEF(boolean)
  168303. fill_input_buffer (j_decompress_ptr cinfo)
  168304. {
  168305. my_src_ptr src = (my_src_ptr) cinfo->src;
  168306. size_t nbytes;
  168307. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168308. if (nbytes <= 0) {
  168309. if (src->start_of_file) /* Treat empty input file as fatal error */
  168310. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168311. WARNMS(cinfo, JWRN_JPEG_EOF);
  168312. /* Insert a fake EOI marker */
  168313. src->buffer[0] = (JOCTET) 0xFF;
  168314. src->buffer[1] = (JOCTET) JPEG_EOI;
  168315. nbytes = 2;
  168316. }
  168317. src->pub.next_input_byte = src->buffer;
  168318. src->pub.bytes_in_buffer = nbytes;
  168319. src->start_of_file = FALSE;
  168320. return TRUE;
  168321. }
  168322. /*
  168323. * Skip data --- used to skip over a potentially large amount of
  168324. * uninteresting data (such as an APPn marker).
  168325. *
  168326. * Writers of suspendable-input applications must note that skip_input_data
  168327. * is not granted the right to give a suspension return. If the skip extends
  168328. * beyond the data currently in the buffer, the buffer can be marked empty so
  168329. * that the next read will cause a fill_input_buffer call that can suspend.
  168330. * Arranging for additional bytes to be discarded before reloading the input
  168331. * buffer is the application writer's problem.
  168332. */
  168333. METHODDEF(void)
  168334. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168335. {
  168336. my_src_ptr src = (my_src_ptr) cinfo->src;
  168337. /* Just a dumb implementation for now. Could use fseek() except
  168338. * it doesn't work on pipes. Not clear that being smart is worth
  168339. * any trouble anyway --- large skips are infrequent.
  168340. */
  168341. if (num_bytes > 0) {
  168342. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168343. num_bytes -= (long) src->pub.bytes_in_buffer;
  168344. (void) fill_input_buffer(cinfo);
  168345. /* note we assume that fill_input_buffer will never return FALSE,
  168346. * so suspension need not be handled.
  168347. */
  168348. }
  168349. src->pub.next_input_byte += (size_t) num_bytes;
  168350. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168351. }
  168352. }
  168353. /*
  168354. * An additional method that can be provided by data source modules is the
  168355. * resync_to_restart method for error recovery in the presence of RST markers.
  168356. * For the moment, this source module just uses the default resync method
  168357. * provided by the JPEG library. That method assumes that no backtracking
  168358. * is possible.
  168359. */
  168360. /*
  168361. * Terminate source --- called by jpeg_finish_decompress
  168362. * after all data has been read. Often a no-op.
  168363. *
  168364. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168365. * application must deal with any cleanup that should happen even
  168366. * for error exit.
  168367. */
  168368. METHODDEF(void)
  168369. term_source (j_decompress_ptr)
  168370. {
  168371. /* no work necessary here */
  168372. }
  168373. /*
  168374. * Prepare for input from a stdio stream.
  168375. * The caller must have already opened the stream, and is responsible
  168376. * for closing it after finishing decompression.
  168377. */
  168378. GLOBAL(void)
  168379. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168380. {
  168381. my_src_ptr src;
  168382. /* The source object and input buffer are made permanent so that a series
  168383. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168384. * only before the first one. (If we discarded the buffer at the end of
  168385. * one image, we'd likely lose the start of the next one.)
  168386. * This makes it unsafe to use this manager and a different source
  168387. * manager serially with the same JPEG object. Caveat programmer.
  168388. */
  168389. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168390. cinfo->src = (struct jpeg_source_mgr *)
  168391. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168392. SIZEOF(my_source_mgr));
  168393. src = (my_src_ptr) cinfo->src;
  168394. src->buffer = (JOCTET *)
  168395. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168396. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168397. }
  168398. src = (my_src_ptr) cinfo->src;
  168399. src->pub.init_source = init_source;
  168400. src->pub.fill_input_buffer = fill_input_buffer;
  168401. src->pub.skip_input_data = skip_input_data;
  168402. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168403. src->pub.term_source = term_source;
  168404. src->infile = infile;
  168405. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168406. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168407. }
  168408. /*** End of inlined file: jdatasrc.c ***/
  168409. /*** Start of inlined file: jdcoefct.c ***/
  168410. #define JPEG_INTERNALS
  168411. /* Block smoothing is only applicable for progressive JPEG, so: */
  168412. #ifndef D_PROGRESSIVE_SUPPORTED
  168413. #undef BLOCK_SMOOTHING_SUPPORTED
  168414. #endif
  168415. /* Private buffer controller object */
  168416. typedef struct {
  168417. struct jpeg_d_coef_controller pub; /* public fields */
  168418. /* These variables keep track of the current location of the input side. */
  168419. /* cinfo->input_iMCU_row is also used for this. */
  168420. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168421. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168422. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168423. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168424. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168425. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168426. * and let the entropy decoder write into that workspace each time.
  168427. * (On 80x86, the workspace is FAR even though it's not really very big;
  168428. * this is to keep the module interfaces unchanged when a large coefficient
  168429. * buffer is necessary.)
  168430. * In multi-pass modes, this array points to the current MCU's blocks
  168431. * within the virtual arrays; it is used only by the input side.
  168432. */
  168433. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168434. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168435. /* In multi-pass modes, we need a virtual block array for each component. */
  168436. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168437. #endif
  168438. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168439. /* When doing block smoothing, we latch coefficient Al values here */
  168440. int * coef_bits_latch;
  168441. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168442. #endif
  168443. } my_coef_controller3;
  168444. typedef my_coef_controller3 * my_coef_ptr3;
  168445. /* Forward declarations */
  168446. METHODDEF(int) decompress_onepass
  168447. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168448. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168449. METHODDEF(int) decompress_data
  168450. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168451. #endif
  168452. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168453. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168454. METHODDEF(int) decompress_smooth_data
  168455. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168456. #endif
  168457. LOCAL(void)
  168458. start_iMCU_row3 (j_decompress_ptr cinfo)
  168459. /* Reset within-iMCU-row counters for a new row (input side) */
  168460. {
  168461. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168462. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168463. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168464. * But at the bottom of the image, process only what's left.
  168465. */
  168466. if (cinfo->comps_in_scan > 1) {
  168467. coef->MCU_rows_per_iMCU_row = 1;
  168468. } else {
  168469. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168470. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168471. else
  168472. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168473. }
  168474. coef->MCU_ctr = 0;
  168475. coef->MCU_vert_offset = 0;
  168476. }
  168477. /*
  168478. * Initialize for an input processing pass.
  168479. */
  168480. METHODDEF(void)
  168481. start_input_pass (j_decompress_ptr cinfo)
  168482. {
  168483. cinfo->input_iMCU_row = 0;
  168484. start_iMCU_row3(cinfo);
  168485. }
  168486. /*
  168487. * Initialize for an output processing pass.
  168488. */
  168489. METHODDEF(void)
  168490. start_output_pass (j_decompress_ptr cinfo)
  168491. {
  168492. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168493. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168494. /* If multipass, check to see whether to use block smoothing on this pass */
  168495. if (coef->pub.coef_arrays != NULL) {
  168496. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168497. coef->pub.decompress_data = decompress_smooth_data;
  168498. else
  168499. coef->pub.decompress_data = decompress_data;
  168500. }
  168501. #endif
  168502. cinfo->output_iMCU_row = 0;
  168503. }
  168504. /*
  168505. * Decompress and return some data in the single-pass case.
  168506. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168507. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168508. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168509. *
  168510. * NB: output_buf contains a plane for each component in image,
  168511. * which we index according to the component's SOF position.
  168512. */
  168513. METHODDEF(int)
  168514. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168515. {
  168516. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168517. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168518. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168519. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168520. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168521. JSAMPARRAY output_ptr;
  168522. JDIMENSION start_col, output_col;
  168523. jpeg_component_info *compptr;
  168524. inverse_DCT_method_ptr inverse_DCT;
  168525. /* Loop to process as much as one whole iMCU row */
  168526. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168527. yoffset++) {
  168528. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168529. MCU_col_num++) {
  168530. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168531. jzero_far((void FAR *) coef->MCU_buffer[0],
  168532. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168533. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168534. /* Suspension forced; update state counters and exit */
  168535. coef->MCU_vert_offset = yoffset;
  168536. coef->MCU_ctr = MCU_col_num;
  168537. return JPEG_SUSPENDED;
  168538. }
  168539. /* Determine where data should go in output_buf and do the IDCT thing.
  168540. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168541. * incremented past them!). Note the inner loop relies on having
  168542. * allocated the MCU_buffer[] blocks sequentially.
  168543. */
  168544. blkn = 0; /* index of current DCT block within MCU */
  168545. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168546. compptr = cinfo->cur_comp_info[ci];
  168547. /* Don't bother to IDCT an uninteresting component. */
  168548. if (! compptr->component_needed) {
  168549. blkn += compptr->MCU_blocks;
  168550. continue;
  168551. }
  168552. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168553. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168554. : compptr->last_col_width;
  168555. output_ptr = output_buf[compptr->component_index] +
  168556. yoffset * compptr->DCT_scaled_size;
  168557. start_col = MCU_col_num * compptr->MCU_sample_width;
  168558. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168559. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168560. yoffset+yindex < compptr->last_row_height) {
  168561. output_col = start_col;
  168562. for (xindex = 0; xindex < useful_width; xindex++) {
  168563. (*inverse_DCT) (cinfo, compptr,
  168564. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168565. output_ptr, output_col);
  168566. output_col += compptr->DCT_scaled_size;
  168567. }
  168568. }
  168569. blkn += compptr->MCU_width;
  168570. output_ptr += compptr->DCT_scaled_size;
  168571. }
  168572. }
  168573. }
  168574. /* Completed an MCU row, but perhaps not an iMCU row */
  168575. coef->MCU_ctr = 0;
  168576. }
  168577. /* Completed the iMCU row, advance counters for next one */
  168578. cinfo->output_iMCU_row++;
  168579. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168580. start_iMCU_row3(cinfo);
  168581. return JPEG_ROW_COMPLETED;
  168582. }
  168583. /* Completed the scan */
  168584. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168585. return JPEG_SCAN_COMPLETED;
  168586. }
  168587. /*
  168588. * Dummy consume-input routine for single-pass operation.
  168589. */
  168590. METHODDEF(int)
  168591. dummy_consume_data (j_decompress_ptr)
  168592. {
  168593. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168594. }
  168595. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168596. /*
  168597. * Consume input data and store it in the full-image coefficient buffer.
  168598. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168599. * ie, v_samp_factor block rows for each component in the scan.
  168600. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168601. */
  168602. METHODDEF(int)
  168603. consume_data (j_decompress_ptr cinfo)
  168604. {
  168605. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168606. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168607. int blkn, ci, xindex, yindex, yoffset;
  168608. JDIMENSION start_col;
  168609. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168610. JBLOCKROW buffer_ptr;
  168611. jpeg_component_info *compptr;
  168612. /* Align the virtual buffers for the components used in this scan. */
  168613. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168614. compptr = cinfo->cur_comp_info[ci];
  168615. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168616. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168617. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168618. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168619. /* Note: entropy decoder expects buffer to be zeroed,
  168620. * but this is handled automatically by the memory manager
  168621. * because we requested a pre-zeroed array.
  168622. */
  168623. }
  168624. /* Loop to process one whole iMCU row */
  168625. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168626. yoffset++) {
  168627. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168628. MCU_col_num++) {
  168629. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168630. blkn = 0; /* index of current DCT block within MCU */
  168631. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168632. compptr = cinfo->cur_comp_info[ci];
  168633. start_col = MCU_col_num * compptr->MCU_width;
  168634. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168635. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168636. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168637. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168638. }
  168639. }
  168640. }
  168641. /* Try to fetch the MCU. */
  168642. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168643. /* Suspension forced; update state counters and exit */
  168644. coef->MCU_vert_offset = yoffset;
  168645. coef->MCU_ctr = MCU_col_num;
  168646. return JPEG_SUSPENDED;
  168647. }
  168648. }
  168649. /* Completed an MCU row, but perhaps not an iMCU row */
  168650. coef->MCU_ctr = 0;
  168651. }
  168652. /* Completed the iMCU row, advance counters for next one */
  168653. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168654. start_iMCU_row3(cinfo);
  168655. return JPEG_ROW_COMPLETED;
  168656. }
  168657. /* Completed the scan */
  168658. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168659. return JPEG_SCAN_COMPLETED;
  168660. }
  168661. /*
  168662. * Decompress and return some data in the multi-pass case.
  168663. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168664. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168665. *
  168666. * NB: output_buf contains a plane for each component in image.
  168667. */
  168668. METHODDEF(int)
  168669. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168670. {
  168671. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168672. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168673. JDIMENSION block_num;
  168674. int ci, block_row, block_rows;
  168675. JBLOCKARRAY buffer;
  168676. JBLOCKROW buffer_ptr;
  168677. JSAMPARRAY output_ptr;
  168678. JDIMENSION output_col;
  168679. jpeg_component_info *compptr;
  168680. inverse_DCT_method_ptr inverse_DCT;
  168681. /* Force some input to be done if we are getting ahead of the input. */
  168682. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168683. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168684. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168685. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168686. return JPEG_SUSPENDED;
  168687. }
  168688. /* OK, output from the virtual arrays. */
  168689. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168690. ci++, compptr++) {
  168691. /* Don't bother to IDCT an uninteresting component. */
  168692. if (! compptr->component_needed)
  168693. continue;
  168694. /* Align the virtual buffer for this component. */
  168695. buffer = (*cinfo->mem->access_virt_barray)
  168696. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168697. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168698. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168699. /* Count non-dummy DCT block rows in this iMCU row. */
  168700. if (cinfo->output_iMCU_row < last_iMCU_row)
  168701. block_rows = compptr->v_samp_factor;
  168702. else {
  168703. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168704. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168705. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168706. }
  168707. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168708. output_ptr = output_buf[ci];
  168709. /* Loop over all DCT blocks to be processed. */
  168710. for (block_row = 0; block_row < block_rows; block_row++) {
  168711. buffer_ptr = buffer[block_row];
  168712. output_col = 0;
  168713. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168714. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168715. output_ptr, output_col);
  168716. buffer_ptr++;
  168717. output_col += compptr->DCT_scaled_size;
  168718. }
  168719. output_ptr += compptr->DCT_scaled_size;
  168720. }
  168721. }
  168722. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168723. return JPEG_ROW_COMPLETED;
  168724. return JPEG_SCAN_COMPLETED;
  168725. }
  168726. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168727. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168728. /*
  168729. * This code applies interblock smoothing as described by section K.8
  168730. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168731. * the DC values of a DCT block and its 8 neighboring blocks.
  168732. * We apply smoothing only for progressive JPEG decoding, and only if
  168733. * the coefficients it can estimate are not yet known to full precision.
  168734. */
  168735. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168736. #define Q01_POS 1
  168737. #define Q10_POS 8
  168738. #define Q20_POS 16
  168739. #define Q11_POS 9
  168740. #define Q02_POS 2
  168741. /*
  168742. * Determine whether block smoothing is applicable and safe.
  168743. * We also latch the current states of the coef_bits[] entries for the
  168744. * AC coefficients; otherwise, if the input side of the decompressor
  168745. * advances into a new scan, we might think the coefficients are known
  168746. * more accurately than they really are.
  168747. */
  168748. LOCAL(boolean)
  168749. smoothing_ok (j_decompress_ptr cinfo)
  168750. {
  168751. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168752. boolean smoothing_useful = FALSE;
  168753. int ci, coefi;
  168754. jpeg_component_info *compptr;
  168755. JQUANT_TBL * qtable;
  168756. int * coef_bits;
  168757. int * coef_bits_latch;
  168758. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168759. return FALSE;
  168760. /* Allocate latch area if not already done */
  168761. if (coef->coef_bits_latch == NULL)
  168762. coef->coef_bits_latch = (int *)
  168763. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168764. cinfo->num_components *
  168765. (SAVED_COEFS * SIZEOF(int)));
  168766. coef_bits_latch = coef->coef_bits_latch;
  168767. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168768. ci++, compptr++) {
  168769. /* All components' quantization values must already be latched. */
  168770. if ((qtable = compptr->quant_table) == NULL)
  168771. return FALSE;
  168772. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168773. if (qtable->quantval[0] == 0 ||
  168774. qtable->quantval[Q01_POS] == 0 ||
  168775. qtable->quantval[Q10_POS] == 0 ||
  168776. qtable->quantval[Q20_POS] == 0 ||
  168777. qtable->quantval[Q11_POS] == 0 ||
  168778. qtable->quantval[Q02_POS] == 0)
  168779. return FALSE;
  168780. /* DC values must be at least partly known for all components. */
  168781. coef_bits = cinfo->coef_bits[ci];
  168782. if (coef_bits[0] < 0)
  168783. return FALSE;
  168784. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168785. for (coefi = 1; coefi <= 5; coefi++) {
  168786. coef_bits_latch[coefi] = coef_bits[coefi];
  168787. if (coef_bits[coefi] != 0)
  168788. smoothing_useful = TRUE;
  168789. }
  168790. coef_bits_latch += SAVED_COEFS;
  168791. }
  168792. return smoothing_useful;
  168793. }
  168794. /*
  168795. * Variant of decompress_data for use when doing block smoothing.
  168796. */
  168797. METHODDEF(int)
  168798. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168799. {
  168800. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168801. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168802. JDIMENSION block_num, last_block_column;
  168803. int ci, block_row, block_rows, access_rows;
  168804. JBLOCKARRAY buffer;
  168805. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168806. JSAMPARRAY output_ptr;
  168807. JDIMENSION output_col;
  168808. jpeg_component_info *compptr;
  168809. inverse_DCT_method_ptr inverse_DCT;
  168810. boolean first_row, last_row;
  168811. JBLOCK workspace;
  168812. int *coef_bits;
  168813. JQUANT_TBL *quanttbl;
  168814. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168815. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168816. int Al, pred;
  168817. /* Force some input to be done if we are getting ahead of the input. */
  168818. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168819. ! cinfo->inputctl->eoi_reached) {
  168820. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168821. /* If input is working on current scan, we ordinarily want it to
  168822. * have completed the current row. But if input scan is DC,
  168823. * we want it to keep one row ahead so that next block row's DC
  168824. * values are up to date.
  168825. */
  168826. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168827. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168828. break;
  168829. }
  168830. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168831. return JPEG_SUSPENDED;
  168832. }
  168833. /* OK, output from the virtual arrays. */
  168834. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168835. ci++, compptr++) {
  168836. /* Don't bother to IDCT an uninteresting component. */
  168837. if (! compptr->component_needed)
  168838. continue;
  168839. /* Count non-dummy DCT block rows in this iMCU row. */
  168840. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168841. block_rows = compptr->v_samp_factor;
  168842. access_rows = block_rows * 2; /* this and next iMCU row */
  168843. last_row = FALSE;
  168844. } else {
  168845. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168846. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168847. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168848. access_rows = block_rows; /* this iMCU row only */
  168849. last_row = TRUE;
  168850. }
  168851. /* Align the virtual buffer for this component. */
  168852. if (cinfo->output_iMCU_row > 0) {
  168853. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168854. buffer = (*cinfo->mem->access_virt_barray)
  168855. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168856. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168857. (JDIMENSION) access_rows, FALSE);
  168858. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168859. first_row = FALSE;
  168860. } else {
  168861. buffer = (*cinfo->mem->access_virt_barray)
  168862. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168863. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168864. first_row = TRUE;
  168865. }
  168866. /* Fetch component-dependent info */
  168867. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168868. quanttbl = compptr->quant_table;
  168869. Q00 = quanttbl->quantval[0];
  168870. Q01 = quanttbl->quantval[Q01_POS];
  168871. Q10 = quanttbl->quantval[Q10_POS];
  168872. Q20 = quanttbl->quantval[Q20_POS];
  168873. Q11 = quanttbl->quantval[Q11_POS];
  168874. Q02 = quanttbl->quantval[Q02_POS];
  168875. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168876. output_ptr = output_buf[ci];
  168877. /* Loop over all DCT blocks to be processed. */
  168878. for (block_row = 0; block_row < block_rows; block_row++) {
  168879. buffer_ptr = buffer[block_row];
  168880. if (first_row && block_row == 0)
  168881. prev_block_row = buffer_ptr;
  168882. else
  168883. prev_block_row = buffer[block_row-1];
  168884. if (last_row && block_row == block_rows-1)
  168885. next_block_row = buffer_ptr;
  168886. else
  168887. next_block_row = buffer[block_row+1];
  168888. /* We fetch the surrounding DC values using a sliding-register approach.
  168889. * Initialize all nine here so as to do the right thing on narrow pics.
  168890. */
  168891. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168892. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168893. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168894. output_col = 0;
  168895. last_block_column = compptr->width_in_blocks - 1;
  168896. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168897. /* Fetch current DCT block into workspace so we can modify it. */
  168898. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168899. /* Update DC values */
  168900. if (block_num < last_block_column) {
  168901. DC3 = (int) prev_block_row[1][0];
  168902. DC6 = (int) buffer_ptr[1][0];
  168903. DC9 = (int) next_block_row[1][0];
  168904. }
  168905. /* Compute coefficient estimates per K.8.
  168906. * An estimate is applied only if coefficient is still zero,
  168907. * and is not known to be fully accurate.
  168908. */
  168909. /* AC01 */
  168910. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168911. num = 36 * Q00 * (DC4 - DC6);
  168912. if (num >= 0) {
  168913. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168914. if (Al > 0 && pred >= (1<<Al))
  168915. pred = (1<<Al)-1;
  168916. } else {
  168917. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168918. if (Al > 0 && pred >= (1<<Al))
  168919. pred = (1<<Al)-1;
  168920. pred = -pred;
  168921. }
  168922. workspace[1] = (JCOEF) pred;
  168923. }
  168924. /* AC10 */
  168925. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168926. num = 36 * Q00 * (DC2 - DC8);
  168927. if (num >= 0) {
  168928. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168929. if (Al > 0 && pred >= (1<<Al))
  168930. pred = (1<<Al)-1;
  168931. } else {
  168932. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168933. if (Al > 0 && pred >= (1<<Al))
  168934. pred = (1<<Al)-1;
  168935. pred = -pred;
  168936. }
  168937. workspace[8] = (JCOEF) pred;
  168938. }
  168939. /* AC20 */
  168940. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168941. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168942. if (num >= 0) {
  168943. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168944. if (Al > 0 && pred >= (1<<Al))
  168945. pred = (1<<Al)-1;
  168946. } else {
  168947. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168948. if (Al > 0 && pred >= (1<<Al))
  168949. pred = (1<<Al)-1;
  168950. pred = -pred;
  168951. }
  168952. workspace[16] = (JCOEF) pred;
  168953. }
  168954. /* AC11 */
  168955. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168956. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168957. if (num >= 0) {
  168958. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168959. if (Al > 0 && pred >= (1<<Al))
  168960. pred = (1<<Al)-1;
  168961. } else {
  168962. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168963. if (Al > 0 && pred >= (1<<Al))
  168964. pred = (1<<Al)-1;
  168965. pred = -pred;
  168966. }
  168967. workspace[9] = (JCOEF) pred;
  168968. }
  168969. /* AC02 */
  168970. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168971. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168972. if (num >= 0) {
  168973. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168974. if (Al > 0 && pred >= (1<<Al))
  168975. pred = (1<<Al)-1;
  168976. } else {
  168977. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168978. if (Al > 0 && pred >= (1<<Al))
  168979. pred = (1<<Al)-1;
  168980. pred = -pred;
  168981. }
  168982. workspace[2] = (JCOEF) pred;
  168983. }
  168984. /* OK, do the IDCT */
  168985. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168986. output_ptr, output_col);
  168987. /* Advance for next column */
  168988. DC1 = DC2; DC2 = DC3;
  168989. DC4 = DC5; DC5 = DC6;
  168990. DC7 = DC8; DC8 = DC9;
  168991. buffer_ptr++, prev_block_row++, next_block_row++;
  168992. output_col += compptr->DCT_scaled_size;
  168993. }
  168994. output_ptr += compptr->DCT_scaled_size;
  168995. }
  168996. }
  168997. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168998. return JPEG_ROW_COMPLETED;
  168999. return JPEG_SCAN_COMPLETED;
  169000. }
  169001. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169002. /*
  169003. * Initialize coefficient buffer controller.
  169004. */
  169005. GLOBAL(void)
  169006. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169007. {
  169008. my_coef_ptr3 coef;
  169009. coef = (my_coef_ptr3)
  169010. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169011. SIZEOF(my_coef_controller3));
  169012. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169013. coef->pub.start_input_pass = start_input_pass;
  169014. coef->pub.start_output_pass = start_output_pass;
  169015. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169016. coef->coef_bits_latch = NULL;
  169017. #endif
  169018. /* Create the coefficient buffer. */
  169019. if (need_full_buffer) {
  169020. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169021. /* Allocate a full-image virtual array for each component, */
  169022. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169023. /* Note we ask for a pre-zeroed array. */
  169024. int ci, access_rows;
  169025. jpeg_component_info *compptr;
  169026. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169027. ci++, compptr++) {
  169028. access_rows = compptr->v_samp_factor;
  169029. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169030. /* If block smoothing could be used, need a bigger window */
  169031. if (cinfo->progressive_mode)
  169032. access_rows *= 3;
  169033. #endif
  169034. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169035. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169036. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169037. (long) compptr->h_samp_factor),
  169038. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169039. (long) compptr->v_samp_factor),
  169040. (JDIMENSION) access_rows);
  169041. }
  169042. coef->pub.consume_data = consume_data;
  169043. coef->pub.decompress_data = decompress_data;
  169044. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169045. #else
  169046. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169047. #endif
  169048. } else {
  169049. /* We only need a single-MCU buffer. */
  169050. JBLOCKROW buffer;
  169051. int i;
  169052. buffer = (JBLOCKROW)
  169053. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169054. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169055. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169056. coef->MCU_buffer[i] = buffer + i;
  169057. }
  169058. coef->pub.consume_data = dummy_consume_data;
  169059. coef->pub.decompress_data = decompress_onepass;
  169060. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169061. }
  169062. }
  169063. /*** End of inlined file: jdcoefct.c ***/
  169064. #undef FIX
  169065. /*** Start of inlined file: jdcolor.c ***/
  169066. #define JPEG_INTERNALS
  169067. /* Private subobject */
  169068. typedef struct {
  169069. struct jpeg_color_deconverter pub; /* public fields */
  169070. /* Private state for YCC->RGB conversion */
  169071. int * Cr_r_tab; /* => table for Cr to R conversion */
  169072. int * Cb_b_tab; /* => table for Cb to B conversion */
  169073. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169074. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169075. } my_color_deconverter2;
  169076. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169077. /**************** YCbCr -> RGB conversion: most common case **************/
  169078. /*
  169079. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169080. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169081. * The conversion equations to be implemented are therefore
  169082. * R = Y + 1.40200 * Cr
  169083. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169084. * B = Y + 1.77200 * Cb
  169085. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169086. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169087. *
  169088. * To avoid floating-point arithmetic, we represent the fractional constants
  169089. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169090. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169091. * Notice that Y, being an integral input, does not contribute any fraction
  169092. * so it need not participate in the rounding.
  169093. *
  169094. * For even more speed, we avoid doing any multiplications in the inner loop
  169095. * by precalculating the constants times Cb and Cr for all possible values.
  169096. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169097. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169098. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169099. * colorspace anyway.
  169100. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169101. * values for the G calculation are left scaled up, since we must add them
  169102. * together before rounding.
  169103. */
  169104. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169105. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169106. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169107. /*
  169108. * Initialize tables for YCC->RGB colorspace conversion.
  169109. */
  169110. LOCAL(void)
  169111. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169112. {
  169113. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169114. int i;
  169115. INT32 x;
  169116. SHIFT_TEMPS
  169117. cconvert->Cr_r_tab = (int *)
  169118. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169119. (MAXJSAMPLE+1) * SIZEOF(int));
  169120. cconvert->Cb_b_tab = (int *)
  169121. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169122. (MAXJSAMPLE+1) * SIZEOF(int));
  169123. cconvert->Cr_g_tab = (INT32 *)
  169124. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169125. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169126. cconvert->Cb_g_tab = (INT32 *)
  169127. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169128. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169129. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169130. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169131. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169132. /* Cr=>R value is nearest int to 1.40200 * x */
  169133. cconvert->Cr_r_tab[i] = (int)
  169134. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169135. /* Cb=>B value is nearest int to 1.77200 * x */
  169136. cconvert->Cb_b_tab[i] = (int)
  169137. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169138. /* Cr=>G value is scaled-up -0.71414 * x */
  169139. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169140. /* Cb=>G value is scaled-up -0.34414 * x */
  169141. /* We also add in ONE_HALF so that need not do it in inner loop */
  169142. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169143. }
  169144. }
  169145. /*
  169146. * Convert some rows of samples to the output colorspace.
  169147. *
  169148. * Note that we change from noninterleaved, one-plane-per-component format
  169149. * to interleaved-pixel format. The output buffer is therefore three times
  169150. * as wide as the input buffer.
  169151. * A starting row offset is provided only for the input buffer. The caller
  169152. * can easily adjust the passed output_buf value to accommodate any row
  169153. * offset required on that side.
  169154. */
  169155. METHODDEF(void)
  169156. ycc_rgb_convert (j_decompress_ptr cinfo,
  169157. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169158. JSAMPARRAY output_buf, int num_rows)
  169159. {
  169160. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169161. register int y, cb, cr;
  169162. register JSAMPROW outptr;
  169163. register JSAMPROW inptr0, inptr1, inptr2;
  169164. register JDIMENSION col;
  169165. JDIMENSION num_cols = cinfo->output_width;
  169166. /* copy these pointers into registers if possible */
  169167. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169168. register int * Crrtab = cconvert->Cr_r_tab;
  169169. register int * Cbbtab = cconvert->Cb_b_tab;
  169170. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169171. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169172. SHIFT_TEMPS
  169173. while (--num_rows >= 0) {
  169174. inptr0 = input_buf[0][input_row];
  169175. inptr1 = input_buf[1][input_row];
  169176. inptr2 = input_buf[2][input_row];
  169177. input_row++;
  169178. outptr = *output_buf++;
  169179. for (col = 0; col < num_cols; col++) {
  169180. y = GETJSAMPLE(inptr0[col]);
  169181. cb = GETJSAMPLE(inptr1[col]);
  169182. cr = GETJSAMPLE(inptr2[col]);
  169183. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169184. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169185. outptr[RGB_GREEN] = range_limit[y +
  169186. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169187. SCALEBITS))];
  169188. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169189. outptr += RGB_PIXELSIZE;
  169190. }
  169191. }
  169192. }
  169193. /**************** Cases other than YCbCr -> RGB **************/
  169194. /*
  169195. * Color conversion for no colorspace change: just copy the data,
  169196. * converting from separate-planes to interleaved representation.
  169197. */
  169198. METHODDEF(void)
  169199. null_convert2 (j_decompress_ptr cinfo,
  169200. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169201. JSAMPARRAY output_buf, int num_rows)
  169202. {
  169203. register JSAMPROW inptr, outptr;
  169204. register JDIMENSION count;
  169205. register int num_components = cinfo->num_components;
  169206. JDIMENSION num_cols = cinfo->output_width;
  169207. int ci;
  169208. while (--num_rows >= 0) {
  169209. for (ci = 0; ci < num_components; ci++) {
  169210. inptr = input_buf[ci][input_row];
  169211. outptr = output_buf[0] + ci;
  169212. for (count = num_cols; count > 0; count--) {
  169213. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169214. outptr += num_components;
  169215. }
  169216. }
  169217. input_row++;
  169218. output_buf++;
  169219. }
  169220. }
  169221. /*
  169222. * Color conversion for grayscale: just copy the data.
  169223. * This also works for YCbCr -> grayscale conversion, in which
  169224. * we just copy the Y (luminance) component and ignore chrominance.
  169225. */
  169226. METHODDEF(void)
  169227. grayscale_convert2 (j_decompress_ptr cinfo,
  169228. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169229. JSAMPARRAY output_buf, int num_rows)
  169230. {
  169231. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169232. num_rows, cinfo->output_width);
  169233. }
  169234. /*
  169235. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169236. * This is provided to support applications that don't want to cope
  169237. * with grayscale as a separate case.
  169238. */
  169239. METHODDEF(void)
  169240. gray_rgb_convert (j_decompress_ptr cinfo,
  169241. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169242. JSAMPARRAY output_buf, int num_rows)
  169243. {
  169244. register JSAMPROW inptr, outptr;
  169245. register JDIMENSION col;
  169246. JDIMENSION num_cols = cinfo->output_width;
  169247. while (--num_rows >= 0) {
  169248. inptr = input_buf[0][input_row++];
  169249. outptr = *output_buf++;
  169250. for (col = 0; col < num_cols; col++) {
  169251. /* We can dispense with GETJSAMPLE() here */
  169252. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169253. outptr += RGB_PIXELSIZE;
  169254. }
  169255. }
  169256. }
  169257. /*
  169258. * Adobe-style YCCK->CMYK conversion.
  169259. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169260. * conversion as above, while passing K (black) unchanged.
  169261. * We assume build_ycc_rgb_table has been called.
  169262. */
  169263. METHODDEF(void)
  169264. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169265. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169266. JSAMPARRAY output_buf, int num_rows)
  169267. {
  169268. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169269. register int y, cb, cr;
  169270. register JSAMPROW outptr;
  169271. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169272. register JDIMENSION col;
  169273. JDIMENSION num_cols = cinfo->output_width;
  169274. /* copy these pointers into registers if possible */
  169275. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169276. register int * Crrtab = cconvert->Cr_r_tab;
  169277. register int * Cbbtab = cconvert->Cb_b_tab;
  169278. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169279. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169280. SHIFT_TEMPS
  169281. while (--num_rows >= 0) {
  169282. inptr0 = input_buf[0][input_row];
  169283. inptr1 = input_buf[1][input_row];
  169284. inptr2 = input_buf[2][input_row];
  169285. inptr3 = input_buf[3][input_row];
  169286. input_row++;
  169287. outptr = *output_buf++;
  169288. for (col = 0; col < num_cols; col++) {
  169289. y = GETJSAMPLE(inptr0[col]);
  169290. cb = GETJSAMPLE(inptr1[col]);
  169291. cr = GETJSAMPLE(inptr2[col]);
  169292. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169293. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169294. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169295. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169296. SCALEBITS)))];
  169297. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169298. /* K passes through unchanged */
  169299. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169300. outptr += 4;
  169301. }
  169302. }
  169303. }
  169304. /*
  169305. * Empty method for start_pass.
  169306. */
  169307. METHODDEF(void)
  169308. start_pass_dcolor (j_decompress_ptr)
  169309. {
  169310. /* no work needed */
  169311. }
  169312. /*
  169313. * Module initialization routine for output colorspace conversion.
  169314. */
  169315. GLOBAL(void)
  169316. jinit_color_deconverter (j_decompress_ptr cinfo)
  169317. {
  169318. my_cconvert_ptr2 cconvert;
  169319. int ci;
  169320. cconvert = (my_cconvert_ptr2)
  169321. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169322. SIZEOF(my_color_deconverter2));
  169323. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169324. cconvert->pub.start_pass = start_pass_dcolor;
  169325. /* Make sure num_components agrees with jpeg_color_space */
  169326. switch (cinfo->jpeg_color_space) {
  169327. case JCS_GRAYSCALE:
  169328. if (cinfo->num_components != 1)
  169329. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169330. break;
  169331. case JCS_RGB:
  169332. case JCS_YCbCr:
  169333. if (cinfo->num_components != 3)
  169334. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169335. break;
  169336. case JCS_CMYK:
  169337. case JCS_YCCK:
  169338. if (cinfo->num_components != 4)
  169339. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169340. break;
  169341. default: /* JCS_UNKNOWN can be anything */
  169342. if (cinfo->num_components < 1)
  169343. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169344. break;
  169345. }
  169346. /* Set out_color_components and conversion method based on requested space.
  169347. * Also clear the component_needed flags for any unused components,
  169348. * so that earlier pipeline stages can avoid useless computation.
  169349. */
  169350. switch (cinfo->out_color_space) {
  169351. case JCS_GRAYSCALE:
  169352. cinfo->out_color_components = 1;
  169353. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169354. cinfo->jpeg_color_space == JCS_YCbCr) {
  169355. cconvert->pub.color_convert = grayscale_convert2;
  169356. /* For color->grayscale conversion, only the Y (0) component is needed */
  169357. for (ci = 1; ci < cinfo->num_components; ci++)
  169358. cinfo->comp_info[ci].component_needed = FALSE;
  169359. } else
  169360. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169361. break;
  169362. case JCS_RGB:
  169363. cinfo->out_color_components = RGB_PIXELSIZE;
  169364. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169365. cconvert->pub.color_convert = ycc_rgb_convert;
  169366. build_ycc_rgb_table(cinfo);
  169367. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169368. cconvert->pub.color_convert = gray_rgb_convert;
  169369. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169370. cconvert->pub.color_convert = null_convert2;
  169371. } else
  169372. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169373. break;
  169374. case JCS_CMYK:
  169375. cinfo->out_color_components = 4;
  169376. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169377. cconvert->pub.color_convert = ycck_cmyk_convert;
  169378. build_ycc_rgb_table(cinfo);
  169379. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169380. cconvert->pub.color_convert = null_convert2;
  169381. } else
  169382. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169383. break;
  169384. default:
  169385. /* Permit null conversion to same output space */
  169386. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169387. cinfo->out_color_components = cinfo->num_components;
  169388. cconvert->pub.color_convert = null_convert2;
  169389. } else /* unsupported non-null conversion */
  169390. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169391. break;
  169392. }
  169393. if (cinfo->quantize_colors)
  169394. cinfo->output_components = 1; /* single colormapped output component */
  169395. else
  169396. cinfo->output_components = cinfo->out_color_components;
  169397. }
  169398. /*** End of inlined file: jdcolor.c ***/
  169399. #undef FIX
  169400. /*** Start of inlined file: jddctmgr.c ***/
  169401. #define JPEG_INTERNALS
  169402. /*
  169403. * The decompressor input side (jdinput.c) saves away the appropriate
  169404. * quantization table for each component at the start of the first scan
  169405. * involving that component. (This is necessary in order to correctly
  169406. * decode files that reuse Q-table slots.)
  169407. * When we are ready to make an output pass, the saved Q-table is converted
  169408. * to a multiplier table that will actually be used by the IDCT routine.
  169409. * The multiplier table contents are IDCT-method-dependent. To support
  169410. * application changes in IDCT method between scans, we can remake the
  169411. * multiplier tables if necessary.
  169412. * In buffered-image mode, the first output pass may occur before any data
  169413. * has been seen for some components, and thus before their Q-tables have
  169414. * been saved away. To handle this case, multiplier tables are preset
  169415. * to zeroes; the result of the IDCT will be a neutral gray level.
  169416. */
  169417. /* Private subobject for this module */
  169418. typedef struct {
  169419. struct jpeg_inverse_dct pub; /* public fields */
  169420. /* This array contains the IDCT method code that each multiplier table
  169421. * is currently set up for, or -1 if it's not yet set up.
  169422. * The actual multiplier tables are pointed to by dct_table in the
  169423. * per-component comp_info structures.
  169424. */
  169425. int cur_method[MAX_COMPONENTS];
  169426. } my_idct_controller;
  169427. typedef my_idct_controller * my_idct_ptr;
  169428. /* Allocated multiplier tables: big enough for any supported variant */
  169429. typedef union {
  169430. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169431. #ifdef DCT_IFAST_SUPPORTED
  169432. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169433. #endif
  169434. #ifdef DCT_FLOAT_SUPPORTED
  169435. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169436. #endif
  169437. } multiplier_table;
  169438. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169439. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169440. */
  169441. #ifdef DCT_ISLOW_SUPPORTED
  169442. #define PROVIDE_ISLOW_TABLES
  169443. #else
  169444. #ifdef IDCT_SCALING_SUPPORTED
  169445. #define PROVIDE_ISLOW_TABLES
  169446. #endif
  169447. #endif
  169448. /*
  169449. * Prepare for an output pass.
  169450. * Here we select the proper IDCT routine for each component and build
  169451. * a matching multiplier table.
  169452. */
  169453. METHODDEF(void)
  169454. start_pass (j_decompress_ptr cinfo)
  169455. {
  169456. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169457. int ci, i;
  169458. jpeg_component_info *compptr;
  169459. int method = 0;
  169460. inverse_DCT_method_ptr method_ptr = NULL;
  169461. JQUANT_TBL * qtbl;
  169462. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169463. ci++, compptr++) {
  169464. /* Select the proper IDCT routine for this component's scaling */
  169465. switch (compptr->DCT_scaled_size) {
  169466. #ifdef IDCT_SCALING_SUPPORTED
  169467. case 1:
  169468. method_ptr = jpeg_idct_1x1;
  169469. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169470. break;
  169471. case 2:
  169472. method_ptr = jpeg_idct_2x2;
  169473. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169474. break;
  169475. case 4:
  169476. method_ptr = jpeg_idct_4x4;
  169477. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169478. break;
  169479. #endif
  169480. case DCTSIZE:
  169481. switch (cinfo->dct_method) {
  169482. #ifdef DCT_ISLOW_SUPPORTED
  169483. case JDCT_ISLOW:
  169484. method_ptr = jpeg_idct_islow;
  169485. method = JDCT_ISLOW;
  169486. break;
  169487. #endif
  169488. #ifdef DCT_IFAST_SUPPORTED
  169489. case JDCT_IFAST:
  169490. method_ptr = jpeg_idct_ifast;
  169491. method = JDCT_IFAST;
  169492. break;
  169493. #endif
  169494. #ifdef DCT_FLOAT_SUPPORTED
  169495. case JDCT_FLOAT:
  169496. method_ptr = jpeg_idct_float;
  169497. method = JDCT_FLOAT;
  169498. break;
  169499. #endif
  169500. default:
  169501. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169502. break;
  169503. }
  169504. break;
  169505. default:
  169506. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169507. break;
  169508. }
  169509. idct->pub.inverse_DCT[ci] = method_ptr;
  169510. /* Create multiplier table from quant table.
  169511. * However, we can skip this if the component is uninteresting
  169512. * or if we already built the table. Also, if no quant table
  169513. * has yet been saved for the component, we leave the
  169514. * multiplier table all-zero; we'll be reading zeroes from the
  169515. * coefficient controller's buffer anyway.
  169516. */
  169517. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169518. continue;
  169519. qtbl = compptr->quant_table;
  169520. if (qtbl == NULL) /* happens if no data yet for component */
  169521. continue;
  169522. idct->cur_method[ci] = method;
  169523. switch (method) {
  169524. #ifdef PROVIDE_ISLOW_TABLES
  169525. case JDCT_ISLOW:
  169526. {
  169527. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169528. * coefficients, but are stored as ints to ensure access efficiency.
  169529. */
  169530. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169531. for (i = 0; i < DCTSIZE2; i++) {
  169532. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169533. }
  169534. }
  169535. break;
  169536. #endif
  169537. #ifdef DCT_IFAST_SUPPORTED
  169538. case JDCT_IFAST:
  169539. {
  169540. /* For AA&N IDCT method, multipliers are equal to quantization
  169541. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169542. * scalefactor[0] = 1
  169543. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169544. * For integer operation, the multiplier table is to be scaled by
  169545. * IFAST_SCALE_BITS.
  169546. */
  169547. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169548. #define CONST_BITS 14
  169549. static const INT16 aanscales[DCTSIZE2] = {
  169550. /* precomputed values scaled up by 14 bits */
  169551. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169552. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169553. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169554. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169555. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169556. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169557. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169558. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169559. };
  169560. SHIFT_TEMPS
  169561. for (i = 0; i < DCTSIZE2; i++) {
  169562. ifmtbl[i] = (IFAST_MULT_TYPE)
  169563. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169564. (INT32) aanscales[i]),
  169565. CONST_BITS-IFAST_SCALE_BITS);
  169566. }
  169567. }
  169568. break;
  169569. #endif
  169570. #ifdef DCT_FLOAT_SUPPORTED
  169571. case JDCT_FLOAT:
  169572. {
  169573. /* For float AA&N IDCT method, multipliers are equal to quantization
  169574. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169575. * scalefactor[0] = 1
  169576. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169577. */
  169578. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169579. int row, col;
  169580. static const double aanscalefactor[DCTSIZE] = {
  169581. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169582. 1.0, 0.785694958, 0.541196100, 0.275899379
  169583. };
  169584. i = 0;
  169585. for (row = 0; row < DCTSIZE; row++) {
  169586. for (col = 0; col < DCTSIZE; col++) {
  169587. fmtbl[i] = (FLOAT_MULT_TYPE)
  169588. ((double) qtbl->quantval[i] *
  169589. aanscalefactor[row] * aanscalefactor[col]);
  169590. i++;
  169591. }
  169592. }
  169593. }
  169594. break;
  169595. #endif
  169596. default:
  169597. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169598. break;
  169599. }
  169600. }
  169601. }
  169602. /*
  169603. * Initialize IDCT manager.
  169604. */
  169605. GLOBAL(void)
  169606. jinit_inverse_dct (j_decompress_ptr cinfo)
  169607. {
  169608. my_idct_ptr idct;
  169609. int ci;
  169610. jpeg_component_info *compptr;
  169611. idct = (my_idct_ptr)
  169612. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169613. SIZEOF(my_idct_controller));
  169614. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169615. idct->pub.start_pass = start_pass;
  169616. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169617. ci++, compptr++) {
  169618. /* Allocate and pre-zero a multiplier table for each component */
  169619. compptr->dct_table =
  169620. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169621. SIZEOF(multiplier_table));
  169622. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169623. /* Mark multiplier table not yet set up for any method */
  169624. idct->cur_method[ci] = -1;
  169625. }
  169626. }
  169627. /*** End of inlined file: jddctmgr.c ***/
  169628. #undef CONST_BITS
  169629. #undef ASSIGN_STATE
  169630. /*** Start of inlined file: jdhuff.c ***/
  169631. #define JPEG_INTERNALS
  169632. /*** Start of inlined file: jdhuff.h ***/
  169633. /* Short forms of external names for systems with brain-damaged linkers. */
  169634. #ifndef __jdhuff_h__
  169635. #define __jdhuff_h__
  169636. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169637. #define jpeg_make_d_derived_tbl jMkDDerived
  169638. #define jpeg_fill_bit_buffer jFilBitBuf
  169639. #define jpeg_huff_decode jHufDecode
  169640. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169641. /* Derived data constructed for each Huffman table */
  169642. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169643. typedef struct {
  169644. /* Basic tables: (element [0] of each array is unused) */
  169645. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169646. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169647. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169648. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169649. * the smallest code of length k; so given a code of length k, the
  169650. * corresponding symbol is huffval[code + valoffset[k]]
  169651. */
  169652. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169653. JHUFF_TBL *pub;
  169654. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169655. * the input data stream. If the next Huffman code is no more
  169656. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169657. * the corresponding symbol directly from these tables.
  169658. */
  169659. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169660. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169661. } d_derived_tbl;
  169662. /* Expand a Huffman table definition into the derived format */
  169663. EXTERN(void) jpeg_make_d_derived_tbl
  169664. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169665. d_derived_tbl ** pdtbl));
  169666. /*
  169667. * Fetching the next N bits from the input stream is a time-critical operation
  169668. * for the Huffman decoders. We implement it with a combination of inline
  169669. * macros and out-of-line subroutines. Note that N (the number of bits
  169670. * demanded at one time) never exceeds 15 for JPEG use.
  169671. *
  169672. * We read source bytes into get_buffer and dole out bits as needed.
  169673. * If get_buffer already contains enough bits, they are fetched in-line
  169674. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169675. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169676. * as full as possible (not just to the number of bits needed; this
  169677. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169678. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169679. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169680. * at least the requested number of bits --- dummy zeroes are inserted if
  169681. * necessary.
  169682. */
  169683. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169684. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169685. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169686. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169687. * appropriately should be a win. Unfortunately we can't define the size
  169688. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169689. * because not all machines measure sizeof in 8-bit bytes.
  169690. */
  169691. typedef struct { /* Bitreading state saved across MCUs */
  169692. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169693. int bits_left; /* # of unused bits in it */
  169694. } bitread_perm_state;
  169695. typedef struct { /* Bitreading working state within an MCU */
  169696. /* Current data source location */
  169697. /* We need a copy, rather than munging the original, in case of suspension */
  169698. const JOCTET * next_input_byte; /* => next byte to read from source */
  169699. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169700. /* Bit input buffer --- note these values are kept in register variables,
  169701. * not in this struct, inside the inner loops.
  169702. */
  169703. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169704. int bits_left; /* # of unused bits in it */
  169705. /* Pointer needed by jpeg_fill_bit_buffer. */
  169706. j_decompress_ptr cinfo; /* back link to decompress master record */
  169707. } bitread_working_state;
  169708. /* Macros to declare and load/save bitread local variables. */
  169709. #define BITREAD_STATE_VARS \
  169710. register bit_buf_type get_buffer; \
  169711. register int bits_left; \
  169712. bitread_working_state br_state
  169713. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169714. br_state.cinfo = cinfop; \
  169715. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169716. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169717. get_buffer = permstate.get_buffer; \
  169718. bits_left = permstate.bits_left;
  169719. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169720. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169721. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169722. permstate.get_buffer = get_buffer; \
  169723. permstate.bits_left = bits_left
  169724. /*
  169725. * These macros provide the in-line portion of bit fetching.
  169726. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169727. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169728. * The variables get_buffer and bits_left are assumed to be locals,
  169729. * but the state struct might not be (jpeg_huff_decode needs this).
  169730. * CHECK_BIT_BUFFER(state,n,action);
  169731. * Ensure there are N bits in get_buffer; if suspend, take action.
  169732. * val = GET_BITS(n);
  169733. * Fetch next N bits.
  169734. * val = PEEK_BITS(n);
  169735. * Fetch next N bits without removing them from the buffer.
  169736. * DROP_BITS(n);
  169737. * Discard next N bits.
  169738. * The value N should be a simple variable, not an expression, because it
  169739. * is evaluated multiple times.
  169740. */
  169741. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169742. { if (bits_left < (nbits)) { \
  169743. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169744. { action; } \
  169745. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169746. #define GET_BITS(nbits) \
  169747. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169748. #define PEEK_BITS(nbits) \
  169749. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169750. #define DROP_BITS(nbits) \
  169751. (bits_left -= (nbits))
  169752. /* Load up the bit buffer to a depth of at least nbits */
  169753. EXTERN(boolean) jpeg_fill_bit_buffer
  169754. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169755. register int bits_left, int nbits));
  169756. /*
  169757. * Code for extracting next Huffman-coded symbol from input bit stream.
  169758. * Again, this is time-critical and we make the main paths be macros.
  169759. *
  169760. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169761. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169762. * or fewer bits long. The few overlength codes are handled with a loop,
  169763. * which need not be inline code.
  169764. *
  169765. * Notes about the HUFF_DECODE macro:
  169766. * 1. Near the end of the data segment, we may fail to get enough bits
  169767. * for a lookahead. In that case, we do it the hard way.
  169768. * 2. If the lookahead table contains no entry, the next code must be
  169769. * more than HUFF_LOOKAHEAD bits long.
  169770. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169771. */
  169772. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169773. { register int nb, look; \
  169774. if (bits_left < HUFF_LOOKAHEAD) { \
  169775. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169776. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169777. if (bits_left < HUFF_LOOKAHEAD) { \
  169778. nb = 1; goto slowlabel; \
  169779. } \
  169780. } \
  169781. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169782. if ((nb = htbl->look_nbits[look]) != 0) { \
  169783. DROP_BITS(nb); \
  169784. result = htbl->look_sym[look]; \
  169785. } else { \
  169786. nb = HUFF_LOOKAHEAD+1; \
  169787. slowlabel: \
  169788. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169789. { failaction; } \
  169790. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169791. } \
  169792. }
  169793. /* Out-of-line case for Huffman code fetching */
  169794. EXTERN(int) jpeg_huff_decode
  169795. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169796. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169797. #endif
  169798. /*** End of inlined file: jdhuff.h ***/
  169799. /* Declarations shared with jdphuff.c */
  169800. /*
  169801. * Expanded entropy decoder object for Huffman decoding.
  169802. *
  169803. * The savable_state subrecord contains fields that change within an MCU,
  169804. * but must not be updated permanently until we complete the MCU.
  169805. */
  169806. typedef struct {
  169807. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169808. } savable_state2;
  169809. /* This macro is to work around compilers with missing or broken
  169810. * structure assignment. You'll need to fix this code if you have
  169811. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169812. */
  169813. #ifndef NO_STRUCT_ASSIGN
  169814. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169815. #else
  169816. #if MAX_COMPS_IN_SCAN == 4
  169817. #define ASSIGN_STATE(dest,src) \
  169818. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169819. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169820. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169821. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169822. #endif
  169823. #endif
  169824. typedef struct {
  169825. struct jpeg_entropy_decoder pub; /* public fields */
  169826. /* These fields are loaded into local variables at start of each MCU.
  169827. * In case of suspension, we exit WITHOUT updating them.
  169828. */
  169829. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169830. savable_state2 saved; /* Other state at start of MCU */
  169831. /* These fields are NOT loaded into local working state. */
  169832. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169833. /* Pointers to derived tables (these workspaces have image lifespan) */
  169834. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169835. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169836. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169837. /* Pointers to derived tables to be used for each block within an MCU */
  169838. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169839. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169840. /* Whether we care about the DC and AC coefficient values for each block */
  169841. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169842. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169843. } huff_entropy_decoder2;
  169844. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169845. /*
  169846. * Initialize for a Huffman-compressed scan.
  169847. */
  169848. METHODDEF(void)
  169849. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169850. {
  169851. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169852. int ci, blkn, dctbl, actbl;
  169853. jpeg_component_info * compptr;
  169854. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169855. * This ought to be an error condition, but we make it a warning because
  169856. * there are some baseline files out there with all zeroes in these bytes.
  169857. */
  169858. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169859. cinfo->Ah != 0 || cinfo->Al != 0)
  169860. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169861. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169862. compptr = cinfo->cur_comp_info[ci];
  169863. dctbl = compptr->dc_tbl_no;
  169864. actbl = compptr->ac_tbl_no;
  169865. /* Compute derived values for Huffman tables */
  169866. /* We may do this more than once for a table, but it's not expensive */
  169867. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169868. & entropy->dc_derived_tbls[dctbl]);
  169869. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169870. & entropy->ac_derived_tbls[actbl]);
  169871. /* Initialize DC predictions to 0 */
  169872. entropy->saved.last_dc_val[ci] = 0;
  169873. }
  169874. /* Precalculate decoding info for each block in an MCU of this scan */
  169875. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169876. ci = cinfo->MCU_membership[blkn];
  169877. compptr = cinfo->cur_comp_info[ci];
  169878. /* Precalculate which table to use for each block */
  169879. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169880. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169881. /* Decide whether we really care about the coefficient values */
  169882. if (compptr->component_needed) {
  169883. entropy->dc_needed[blkn] = TRUE;
  169884. /* we don't need the ACs if producing a 1/8th-size image */
  169885. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169886. } else {
  169887. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169888. }
  169889. }
  169890. /* Initialize bitread state variables */
  169891. entropy->bitstate.bits_left = 0;
  169892. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169893. entropy->pub.insufficient_data = FALSE;
  169894. /* Initialize restart counter */
  169895. entropy->restarts_to_go = cinfo->restart_interval;
  169896. }
  169897. /*
  169898. * Compute the derived values for a Huffman table.
  169899. * This routine also performs some validation checks on the table.
  169900. *
  169901. * Note this is also used by jdphuff.c.
  169902. */
  169903. GLOBAL(void)
  169904. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169905. d_derived_tbl ** pdtbl)
  169906. {
  169907. JHUFF_TBL *htbl;
  169908. d_derived_tbl *dtbl;
  169909. int p, i, l, si, numsymbols;
  169910. int lookbits, ctr;
  169911. char huffsize[257];
  169912. unsigned int huffcode[257];
  169913. unsigned int code;
  169914. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169915. * paralleling the order of the symbols themselves in htbl->huffval[].
  169916. */
  169917. /* Find the input Huffman table */
  169918. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169919. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169920. htbl =
  169921. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169922. if (htbl == NULL)
  169923. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169924. /* Allocate a workspace if we haven't already done so. */
  169925. if (*pdtbl == NULL)
  169926. *pdtbl = (d_derived_tbl *)
  169927. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169928. SIZEOF(d_derived_tbl));
  169929. dtbl = *pdtbl;
  169930. dtbl->pub = htbl; /* fill in back link */
  169931. /* Figure C.1: make table of Huffman code length for each symbol */
  169932. p = 0;
  169933. for (l = 1; l <= 16; l++) {
  169934. i = (int) htbl->bits[l];
  169935. if (i < 0 || p + i > 256) /* protect against table overrun */
  169936. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169937. while (i--)
  169938. huffsize[p++] = (char) l;
  169939. }
  169940. huffsize[p] = 0;
  169941. numsymbols = p;
  169942. /* Figure C.2: generate the codes themselves */
  169943. /* We also validate that the counts represent a legal Huffman code tree. */
  169944. code = 0;
  169945. si = huffsize[0];
  169946. p = 0;
  169947. while (huffsize[p]) {
  169948. while (((int) huffsize[p]) == si) {
  169949. huffcode[p++] = code;
  169950. code++;
  169951. }
  169952. /* code is now 1 more than the last code used for codelength si; but
  169953. * it must still fit in si bits, since no code is allowed to be all ones.
  169954. */
  169955. if (((INT32) code) >= (((INT32) 1) << si))
  169956. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169957. code <<= 1;
  169958. si++;
  169959. }
  169960. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169961. p = 0;
  169962. for (l = 1; l <= 16; l++) {
  169963. if (htbl->bits[l]) {
  169964. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169965. * minus the minimum code of length l
  169966. */
  169967. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169968. p += htbl->bits[l];
  169969. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169970. } else {
  169971. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169972. }
  169973. }
  169974. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169975. /* Compute lookahead tables to speed up decoding.
  169976. * First we set all the table entries to 0, indicating "too long";
  169977. * then we iterate through the Huffman codes that are short enough and
  169978. * fill in all the entries that correspond to bit sequences starting
  169979. * with that code.
  169980. */
  169981. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169982. p = 0;
  169983. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169984. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169985. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169986. /* Generate left-justified code followed by all possible bit sequences */
  169987. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169988. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169989. dtbl->look_nbits[lookbits] = l;
  169990. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169991. lookbits++;
  169992. }
  169993. }
  169994. }
  169995. /* Validate symbols as being reasonable.
  169996. * For AC tables, we make no check, but accept all byte values 0..255.
  169997. * For DC tables, we require the symbols to be in range 0..15.
  169998. * (Tighter bounds could be applied depending on the data depth and mode,
  169999. * but this is sufficient to ensure safe decoding.)
  170000. */
  170001. if (isDC) {
  170002. for (i = 0; i < numsymbols; i++) {
  170003. int sym = htbl->huffval[i];
  170004. if (sym < 0 || sym > 15)
  170005. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170006. }
  170007. }
  170008. }
  170009. /*
  170010. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170011. * See jdhuff.h for info about usage.
  170012. * Note: current values of get_buffer and bits_left are passed as parameters,
  170013. * but are returned in the corresponding fields of the state struct.
  170014. *
  170015. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170016. * of get_buffer to be used. (On machines with wider words, an even larger
  170017. * buffer could be used.) However, on some machines 32-bit shifts are
  170018. * quite slow and take time proportional to the number of places shifted.
  170019. * (This is true with most PC compilers, for instance.) In this case it may
  170020. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170021. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170022. */
  170023. #ifdef SLOW_SHIFT_32
  170024. #define MIN_GET_BITS 15 /* minimum allowable value */
  170025. #else
  170026. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170027. #endif
  170028. GLOBAL(boolean)
  170029. jpeg_fill_bit_buffer (bitread_working_state * state,
  170030. register bit_buf_type get_buffer, register int bits_left,
  170031. int nbits)
  170032. /* Load up the bit buffer to a depth of at least nbits */
  170033. {
  170034. /* Copy heavily used state fields into locals (hopefully registers) */
  170035. register const JOCTET * next_input_byte = state->next_input_byte;
  170036. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170037. j_decompress_ptr cinfo = state->cinfo;
  170038. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170039. /* (It is assumed that no request will be for more than that many bits.) */
  170040. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170041. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170042. while (bits_left < MIN_GET_BITS) {
  170043. register int c;
  170044. /* Attempt to read a byte */
  170045. if (bytes_in_buffer == 0) {
  170046. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170047. return FALSE;
  170048. next_input_byte = cinfo->src->next_input_byte;
  170049. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170050. }
  170051. bytes_in_buffer--;
  170052. c = GETJOCTET(*next_input_byte++);
  170053. /* If it's 0xFF, check and discard stuffed zero byte */
  170054. if (c == 0xFF) {
  170055. /* Loop here to discard any padding FF's on terminating marker,
  170056. * so that we can save a valid unread_marker value. NOTE: we will
  170057. * accept multiple FF's followed by a 0 as meaning a single FF data
  170058. * byte. This data pattern is not valid according to the standard.
  170059. */
  170060. do {
  170061. if (bytes_in_buffer == 0) {
  170062. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170063. return FALSE;
  170064. next_input_byte = cinfo->src->next_input_byte;
  170065. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170066. }
  170067. bytes_in_buffer--;
  170068. c = GETJOCTET(*next_input_byte++);
  170069. } while (c == 0xFF);
  170070. if (c == 0) {
  170071. /* Found FF/00, which represents an FF data byte */
  170072. c = 0xFF;
  170073. } else {
  170074. /* Oops, it's actually a marker indicating end of compressed data.
  170075. * Save the marker code for later use.
  170076. * Fine point: it might appear that we should save the marker into
  170077. * bitread working state, not straight into permanent state. But
  170078. * once we have hit a marker, we cannot need to suspend within the
  170079. * current MCU, because we will read no more bytes from the data
  170080. * source. So it is OK to update permanent state right away.
  170081. */
  170082. cinfo->unread_marker = c;
  170083. /* See if we need to insert some fake zero bits. */
  170084. goto no_more_bytes;
  170085. }
  170086. }
  170087. /* OK, load c into get_buffer */
  170088. get_buffer = (get_buffer << 8) | c;
  170089. bits_left += 8;
  170090. } /* end while */
  170091. } else {
  170092. no_more_bytes:
  170093. /* We get here if we've read the marker that terminates the compressed
  170094. * data segment. There should be enough bits in the buffer register
  170095. * to satisfy the request; if so, no problem.
  170096. */
  170097. if (nbits > bits_left) {
  170098. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170099. * the data stream, so that we can produce some kind of image.
  170100. * We use a nonvolatile flag to ensure that only one warning message
  170101. * appears per data segment.
  170102. */
  170103. if (! cinfo->entropy->insufficient_data) {
  170104. WARNMS(cinfo, JWRN_HIT_MARKER);
  170105. cinfo->entropy->insufficient_data = TRUE;
  170106. }
  170107. /* Fill the buffer with zero bits */
  170108. get_buffer <<= MIN_GET_BITS - bits_left;
  170109. bits_left = MIN_GET_BITS;
  170110. }
  170111. }
  170112. /* Unload the local registers */
  170113. state->next_input_byte = next_input_byte;
  170114. state->bytes_in_buffer = bytes_in_buffer;
  170115. state->get_buffer = get_buffer;
  170116. state->bits_left = bits_left;
  170117. return TRUE;
  170118. }
  170119. /*
  170120. * Out-of-line code for Huffman code decoding.
  170121. * See jdhuff.h for info about usage.
  170122. */
  170123. GLOBAL(int)
  170124. jpeg_huff_decode (bitread_working_state * state,
  170125. register bit_buf_type get_buffer, register int bits_left,
  170126. d_derived_tbl * htbl, int min_bits)
  170127. {
  170128. register int l = min_bits;
  170129. register INT32 code;
  170130. /* HUFF_DECODE has determined that the code is at least min_bits */
  170131. /* bits long, so fetch that many bits in one swoop. */
  170132. CHECK_BIT_BUFFER(*state, l, return -1);
  170133. code = GET_BITS(l);
  170134. /* Collect the rest of the Huffman code one bit at a time. */
  170135. /* This is per Figure F.16 in the JPEG spec. */
  170136. while (code > htbl->maxcode[l]) {
  170137. code <<= 1;
  170138. CHECK_BIT_BUFFER(*state, 1, return -1);
  170139. code |= GET_BITS(1);
  170140. l++;
  170141. }
  170142. /* Unload the local registers */
  170143. state->get_buffer = get_buffer;
  170144. state->bits_left = bits_left;
  170145. /* With garbage input we may reach the sentinel value l = 17. */
  170146. if (l > 16) {
  170147. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170148. return 0; /* fake a zero as the safest result */
  170149. }
  170150. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170151. }
  170152. /*
  170153. * Check for a restart marker & resynchronize decoder.
  170154. * Returns FALSE if must suspend.
  170155. */
  170156. LOCAL(boolean)
  170157. process_restart (j_decompress_ptr cinfo)
  170158. {
  170159. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170160. int ci;
  170161. /* Throw away any unused bits remaining in bit buffer; */
  170162. /* include any full bytes in next_marker's count of discarded bytes */
  170163. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170164. entropy->bitstate.bits_left = 0;
  170165. /* Advance past the RSTn marker */
  170166. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170167. return FALSE;
  170168. /* Re-initialize DC predictions to 0 */
  170169. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170170. entropy->saved.last_dc_val[ci] = 0;
  170171. /* Reset restart counter */
  170172. entropy->restarts_to_go = cinfo->restart_interval;
  170173. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170174. * against a marker. In that case we will end up treating the next data
  170175. * segment as empty, and we can avoid producing bogus output pixels by
  170176. * leaving the flag set.
  170177. */
  170178. if (cinfo->unread_marker == 0)
  170179. entropy->pub.insufficient_data = FALSE;
  170180. return TRUE;
  170181. }
  170182. /*
  170183. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170184. * The coefficients are reordered from zigzag order into natural array order,
  170185. * but are not dequantized.
  170186. *
  170187. * The i'th block of the MCU is stored into the block pointed to by
  170188. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170189. * (Wholesale zeroing is usually a little faster than retail...)
  170190. *
  170191. * Returns FALSE if data source requested suspension. In that case no
  170192. * changes have been made to permanent state. (Exception: some output
  170193. * coefficients may already have been assigned. This is harmless for
  170194. * this module, since we'll just re-assign them on the next call.)
  170195. */
  170196. METHODDEF(boolean)
  170197. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170198. {
  170199. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170200. int blkn;
  170201. BITREAD_STATE_VARS;
  170202. savable_state2 state;
  170203. /* Process restart marker if needed; may have to suspend */
  170204. if (cinfo->restart_interval) {
  170205. if (entropy->restarts_to_go == 0)
  170206. if (! process_restart(cinfo))
  170207. return FALSE;
  170208. }
  170209. /* If we've run out of data, just leave the MCU set to zeroes.
  170210. * This way, we return uniform gray for the remainder of the segment.
  170211. */
  170212. if (! entropy->pub.insufficient_data) {
  170213. /* Load up working state */
  170214. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170215. ASSIGN_STATE(state, entropy->saved);
  170216. /* Outer loop handles each block in the MCU */
  170217. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170218. JBLOCKROW block = MCU_data[blkn];
  170219. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170220. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170221. register int s, k, r;
  170222. /* Decode a single block's worth of coefficients */
  170223. /* Section F.2.2.1: decode the DC coefficient difference */
  170224. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170225. if (s) {
  170226. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170227. r = GET_BITS(s);
  170228. s = HUFF_EXTEND(r, s);
  170229. }
  170230. if (entropy->dc_needed[blkn]) {
  170231. /* Convert DC difference to actual value, update last_dc_val */
  170232. int ci = cinfo->MCU_membership[blkn];
  170233. s += state.last_dc_val[ci];
  170234. state.last_dc_val[ci] = s;
  170235. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170236. (*block)[0] = (JCOEF) s;
  170237. }
  170238. if (entropy->ac_needed[blkn]) {
  170239. /* Section F.2.2.2: decode the AC coefficients */
  170240. /* Since zeroes are skipped, output area must be cleared beforehand */
  170241. for (k = 1; k < DCTSIZE2; k++) {
  170242. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170243. r = s >> 4;
  170244. s &= 15;
  170245. if (s) {
  170246. k += r;
  170247. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170248. r = GET_BITS(s);
  170249. s = HUFF_EXTEND(r, s);
  170250. /* Output coefficient in natural (dezigzagged) order.
  170251. * Note: the extra entries in jpeg_natural_order[] will save us
  170252. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170253. */
  170254. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170255. } else {
  170256. if (r != 15)
  170257. break;
  170258. k += 15;
  170259. }
  170260. }
  170261. } else {
  170262. /* Section F.2.2.2: decode the AC coefficients */
  170263. /* In this path we just discard the values */
  170264. for (k = 1; k < DCTSIZE2; k++) {
  170265. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170266. r = s >> 4;
  170267. s &= 15;
  170268. if (s) {
  170269. k += r;
  170270. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170271. DROP_BITS(s);
  170272. } else {
  170273. if (r != 15)
  170274. break;
  170275. k += 15;
  170276. }
  170277. }
  170278. }
  170279. }
  170280. /* Completed MCU, so update state */
  170281. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170282. ASSIGN_STATE(entropy->saved, state);
  170283. }
  170284. /* Account for restart interval (no-op if not using restarts) */
  170285. entropy->restarts_to_go--;
  170286. return TRUE;
  170287. }
  170288. /*
  170289. * Module initialization routine for Huffman entropy decoding.
  170290. */
  170291. GLOBAL(void)
  170292. jinit_huff_decoder (j_decompress_ptr cinfo)
  170293. {
  170294. huff_entropy_ptr2 entropy;
  170295. int i;
  170296. entropy = (huff_entropy_ptr2)
  170297. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170298. SIZEOF(huff_entropy_decoder2));
  170299. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170300. entropy->pub.start_pass = start_pass_huff_decoder;
  170301. entropy->pub.decode_mcu = decode_mcu;
  170302. /* Mark tables unallocated */
  170303. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170304. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170305. }
  170306. }
  170307. /*** End of inlined file: jdhuff.c ***/
  170308. /*** Start of inlined file: jdinput.c ***/
  170309. #define JPEG_INTERNALS
  170310. /* Private state */
  170311. typedef struct {
  170312. struct jpeg_input_controller pub; /* public fields */
  170313. boolean inheaders; /* TRUE until first SOS is reached */
  170314. } my_input_controller;
  170315. typedef my_input_controller * my_inputctl_ptr;
  170316. /* Forward declarations */
  170317. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170318. /*
  170319. * Routines to calculate various quantities related to the size of the image.
  170320. */
  170321. LOCAL(void)
  170322. initial_setup2 (j_decompress_ptr cinfo)
  170323. /* Called once, when first SOS marker is reached */
  170324. {
  170325. int ci;
  170326. jpeg_component_info *compptr;
  170327. /* Make sure image isn't bigger than I can handle */
  170328. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170329. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170330. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170331. /* For now, precision must match compiled-in value... */
  170332. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170333. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170334. /* Check that number of components won't exceed internal array sizes */
  170335. if (cinfo->num_components > MAX_COMPONENTS)
  170336. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170337. MAX_COMPONENTS);
  170338. /* Compute maximum sampling factors; check factor validity */
  170339. cinfo->max_h_samp_factor = 1;
  170340. cinfo->max_v_samp_factor = 1;
  170341. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170342. ci++, compptr++) {
  170343. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170344. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170345. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170346. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170347. compptr->h_samp_factor);
  170348. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170349. compptr->v_samp_factor);
  170350. }
  170351. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170352. * In the full decompressor, this will be overridden by jdmaster.c;
  170353. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170354. */
  170355. cinfo->min_DCT_scaled_size = DCTSIZE;
  170356. /* Compute dimensions of components */
  170357. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170358. ci++, compptr++) {
  170359. compptr->DCT_scaled_size = DCTSIZE;
  170360. /* Size in DCT blocks */
  170361. compptr->width_in_blocks = (JDIMENSION)
  170362. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170363. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170364. compptr->height_in_blocks = (JDIMENSION)
  170365. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170366. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170367. /* downsampled_width and downsampled_height will also be overridden by
  170368. * jdmaster.c if we are doing full decompression. The transcoder library
  170369. * doesn't use these values, but the calling application might.
  170370. */
  170371. /* Size in samples */
  170372. compptr->downsampled_width = (JDIMENSION)
  170373. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170374. (long) cinfo->max_h_samp_factor);
  170375. compptr->downsampled_height = (JDIMENSION)
  170376. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170377. (long) cinfo->max_v_samp_factor);
  170378. /* Mark component needed, until color conversion says otherwise */
  170379. compptr->component_needed = TRUE;
  170380. /* Mark no quantization table yet saved for component */
  170381. compptr->quant_table = NULL;
  170382. }
  170383. /* Compute number of fully interleaved MCU rows. */
  170384. cinfo->total_iMCU_rows = (JDIMENSION)
  170385. jdiv_round_up((long) cinfo->image_height,
  170386. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170387. /* Decide whether file contains multiple scans */
  170388. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170389. cinfo->inputctl->has_multiple_scans = TRUE;
  170390. else
  170391. cinfo->inputctl->has_multiple_scans = FALSE;
  170392. }
  170393. LOCAL(void)
  170394. per_scan_setup2 (j_decompress_ptr cinfo)
  170395. /* Do computations that are needed before processing a JPEG scan */
  170396. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170397. {
  170398. int ci, mcublks, tmp;
  170399. jpeg_component_info *compptr;
  170400. if (cinfo->comps_in_scan == 1) {
  170401. /* Noninterleaved (single-component) scan */
  170402. compptr = cinfo->cur_comp_info[0];
  170403. /* Overall image size in MCUs */
  170404. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170405. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170406. /* For noninterleaved scan, always one block per MCU */
  170407. compptr->MCU_width = 1;
  170408. compptr->MCU_height = 1;
  170409. compptr->MCU_blocks = 1;
  170410. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170411. compptr->last_col_width = 1;
  170412. /* For noninterleaved scans, it is convenient to define last_row_height
  170413. * as the number of block rows present in the last iMCU row.
  170414. */
  170415. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170416. if (tmp == 0) tmp = compptr->v_samp_factor;
  170417. compptr->last_row_height = tmp;
  170418. /* Prepare array describing MCU composition */
  170419. cinfo->blocks_in_MCU = 1;
  170420. cinfo->MCU_membership[0] = 0;
  170421. } else {
  170422. /* Interleaved (multi-component) scan */
  170423. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170424. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170425. MAX_COMPS_IN_SCAN);
  170426. /* Overall image size in MCUs */
  170427. cinfo->MCUs_per_row = (JDIMENSION)
  170428. jdiv_round_up((long) cinfo->image_width,
  170429. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170430. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170431. jdiv_round_up((long) cinfo->image_height,
  170432. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170433. cinfo->blocks_in_MCU = 0;
  170434. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170435. compptr = cinfo->cur_comp_info[ci];
  170436. /* Sampling factors give # of blocks of component in each MCU */
  170437. compptr->MCU_width = compptr->h_samp_factor;
  170438. compptr->MCU_height = compptr->v_samp_factor;
  170439. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170440. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170441. /* Figure number of non-dummy blocks in last MCU column & row */
  170442. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170443. if (tmp == 0) tmp = compptr->MCU_width;
  170444. compptr->last_col_width = tmp;
  170445. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170446. if (tmp == 0) tmp = compptr->MCU_height;
  170447. compptr->last_row_height = tmp;
  170448. /* Prepare array describing MCU composition */
  170449. mcublks = compptr->MCU_blocks;
  170450. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170451. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170452. while (mcublks-- > 0) {
  170453. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170454. }
  170455. }
  170456. }
  170457. }
  170458. /*
  170459. * Save away a copy of the Q-table referenced by each component present
  170460. * in the current scan, unless already saved during a prior scan.
  170461. *
  170462. * In a multiple-scan JPEG file, the encoder could assign different components
  170463. * the same Q-table slot number, but change table definitions between scans
  170464. * so that each component uses a different Q-table. (The IJG encoder is not
  170465. * currently capable of doing this, but other encoders might.) Since we want
  170466. * to be able to dequantize all the components at the end of the file, this
  170467. * means that we have to save away the table actually used for each component.
  170468. * We do this by copying the table at the start of the first scan containing
  170469. * the component.
  170470. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170471. * slot between scans of a component using that slot. If the encoder does so
  170472. * anyway, this decoder will simply use the Q-table values that were current
  170473. * at the start of the first scan for the component.
  170474. *
  170475. * The decompressor output side looks only at the saved quant tables,
  170476. * not at the current Q-table slots.
  170477. */
  170478. LOCAL(void)
  170479. latch_quant_tables (j_decompress_ptr cinfo)
  170480. {
  170481. int ci, qtblno;
  170482. jpeg_component_info *compptr;
  170483. JQUANT_TBL * qtbl;
  170484. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170485. compptr = cinfo->cur_comp_info[ci];
  170486. /* No work if we already saved Q-table for this component */
  170487. if (compptr->quant_table != NULL)
  170488. continue;
  170489. /* Make sure specified quantization table is present */
  170490. qtblno = compptr->quant_tbl_no;
  170491. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170492. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170493. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170494. /* OK, save away the quantization table */
  170495. qtbl = (JQUANT_TBL *)
  170496. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170497. SIZEOF(JQUANT_TBL));
  170498. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170499. compptr->quant_table = qtbl;
  170500. }
  170501. }
  170502. /*
  170503. * Initialize the input modules to read a scan of compressed data.
  170504. * The first call to this is done by jdmaster.c after initializing
  170505. * the entire decompressor (during jpeg_start_decompress).
  170506. * Subsequent calls come from consume_markers, below.
  170507. */
  170508. METHODDEF(void)
  170509. start_input_pass2 (j_decompress_ptr cinfo)
  170510. {
  170511. per_scan_setup2(cinfo);
  170512. latch_quant_tables(cinfo);
  170513. (*cinfo->entropy->start_pass) (cinfo);
  170514. (*cinfo->coef->start_input_pass) (cinfo);
  170515. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170516. }
  170517. /*
  170518. * Finish up after inputting a compressed-data scan.
  170519. * This is called by the coefficient controller after it's read all
  170520. * the expected data of the scan.
  170521. */
  170522. METHODDEF(void)
  170523. finish_input_pass (j_decompress_ptr cinfo)
  170524. {
  170525. cinfo->inputctl->consume_input = consume_markers;
  170526. }
  170527. /*
  170528. * Read JPEG markers before, between, or after compressed-data scans.
  170529. * Change state as necessary when a new scan is reached.
  170530. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170531. *
  170532. * The consume_input method pointer points either here or to the
  170533. * coefficient controller's consume_data routine, depending on whether
  170534. * we are reading a compressed data segment or inter-segment markers.
  170535. */
  170536. METHODDEF(int)
  170537. consume_markers (j_decompress_ptr cinfo)
  170538. {
  170539. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170540. int val;
  170541. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170542. return JPEG_REACHED_EOI;
  170543. val = (*cinfo->marker->read_markers) (cinfo);
  170544. switch (val) {
  170545. case JPEG_REACHED_SOS: /* Found SOS */
  170546. if (inputctl->inheaders) { /* 1st SOS */
  170547. initial_setup2(cinfo);
  170548. inputctl->inheaders = FALSE;
  170549. /* Note: start_input_pass must be called by jdmaster.c
  170550. * before any more input can be consumed. jdapimin.c is
  170551. * responsible for enforcing this sequencing.
  170552. */
  170553. } else { /* 2nd or later SOS marker */
  170554. if (! inputctl->pub.has_multiple_scans)
  170555. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170556. start_input_pass2(cinfo);
  170557. }
  170558. break;
  170559. case JPEG_REACHED_EOI: /* Found EOI */
  170560. inputctl->pub.eoi_reached = TRUE;
  170561. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170562. if (cinfo->marker->saw_SOF)
  170563. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170564. } else {
  170565. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170566. * if user set output_scan_number larger than number of scans.
  170567. */
  170568. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170569. cinfo->output_scan_number = cinfo->input_scan_number;
  170570. }
  170571. break;
  170572. case JPEG_SUSPENDED:
  170573. break;
  170574. }
  170575. return val;
  170576. }
  170577. /*
  170578. * Reset state to begin a fresh datastream.
  170579. */
  170580. METHODDEF(void)
  170581. reset_input_controller (j_decompress_ptr cinfo)
  170582. {
  170583. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170584. inputctl->pub.consume_input = consume_markers;
  170585. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170586. inputctl->pub.eoi_reached = FALSE;
  170587. inputctl->inheaders = TRUE;
  170588. /* Reset other modules */
  170589. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170590. (*cinfo->marker->reset_marker_reader) (cinfo);
  170591. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170592. cinfo->coef_bits = NULL;
  170593. }
  170594. /*
  170595. * Initialize the input controller module.
  170596. * This is called only once, when the decompression object is created.
  170597. */
  170598. GLOBAL(void)
  170599. jinit_input_controller (j_decompress_ptr cinfo)
  170600. {
  170601. my_inputctl_ptr inputctl;
  170602. /* Create subobject in permanent pool */
  170603. inputctl = (my_inputctl_ptr)
  170604. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170605. SIZEOF(my_input_controller));
  170606. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170607. /* Initialize method pointers */
  170608. inputctl->pub.consume_input = consume_markers;
  170609. inputctl->pub.reset_input_controller = reset_input_controller;
  170610. inputctl->pub.start_input_pass = start_input_pass2;
  170611. inputctl->pub.finish_input_pass = finish_input_pass;
  170612. /* Initialize state: can't use reset_input_controller since we don't
  170613. * want to try to reset other modules yet.
  170614. */
  170615. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170616. inputctl->pub.eoi_reached = FALSE;
  170617. inputctl->inheaders = TRUE;
  170618. }
  170619. /*** End of inlined file: jdinput.c ***/
  170620. /*** Start of inlined file: jdmainct.c ***/
  170621. #define JPEG_INTERNALS
  170622. /*
  170623. * In the current system design, the main buffer need never be a full-image
  170624. * buffer; any full-height buffers will be found inside the coefficient or
  170625. * postprocessing controllers. Nonetheless, the main controller is not
  170626. * trivial. Its responsibility is to provide context rows for upsampling/
  170627. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170628. *
  170629. * Postprocessor input data is counted in "row groups". A row group
  170630. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170631. * sample rows of each component. (We require DCT_scaled_size values to be
  170632. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170633. * values will likely be powers of two, so we actually have the stronger
  170634. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170635. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170636. * row group (times any additional scale factor that the upsampler is
  170637. * applying).
  170638. *
  170639. * The coefficient controller will deliver data to us one iMCU row at a time;
  170640. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170641. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170642. * to one row of MCUs when the image is fully interleaved.) Note that the
  170643. * number of sample rows varies across components, but the number of row
  170644. * groups does not. Some garbage sample rows may be included in the last iMCU
  170645. * row at the bottom of the image.
  170646. *
  170647. * Depending on the vertical scaling algorithm used, the upsampler may need
  170648. * access to the sample row(s) above and below its current input row group.
  170649. * The upsampler is required to set need_context_rows TRUE at global selection
  170650. * time if so. When need_context_rows is FALSE, this controller can simply
  170651. * obtain one iMCU row at a time from the coefficient controller and dole it
  170652. * out as row groups to the postprocessor.
  170653. *
  170654. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170655. * passed to postprocessing contains at least one row group's worth of samples
  170656. * above and below the row group(s) being processed. Note that the context
  170657. * rows "above" the first passed row group appear at negative row offsets in
  170658. * the passed buffer. At the top and bottom of the image, the required
  170659. * context rows are manufactured by duplicating the first or last real sample
  170660. * row; this avoids having special cases in the upsampling inner loops.
  170661. *
  170662. * The amount of context is fixed at one row group just because that's a
  170663. * convenient number for this controller to work with. The existing
  170664. * upsamplers really only need one sample row of context. An upsampler
  170665. * supporting arbitrary output rescaling might wish for more than one row
  170666. * group of context when shrinking the image; tough, we don't handle that.
  170667. * (This is justified by the assumption that downsizing will be handled mostly
  170668. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170669. * the upsample step needn't be much less than one.)
  170670. *
  170671. * To provide the desired context, we have to retain the last two row groups
  170672. * of one iMCU row while reading in the next iMCU row. (The last row group
  170673. * can't be processed until we have another row group for its below-context,
  170674. * and so we have to save the next-to-last group too for its above-context.)
  170675. * We could do this most simply by copying data around in our buffer, but
  170676. * that'd be very slow. We can avoid copying any data by creating a rather
  170677. * strange pointer structure. Here's how it works. We allocate a workspace
  170678. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170679. * of row groups per iMCU row). We create two sets of redundant pointers to
  170680. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170681. * pointer lists look like this:
  170682. * M+1 M-1
  170683. * master pointer --> 0 master pointer --> 0
  170684. * 1 1
  170685. * ... ...
  170686. * M-3 M-3
  170687. * M-2 M
  170688. * M-1 M+1
  170689. * M M-2
  170690. * M+1 M-1
  170691. * 0 0
  170692. * We read alternate iMCU rows using each master pointer; thus the last two
  170693. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170694. * The pointer lists are set up so that the required context rows appear to
  170695. * be adjacent to the proper places when we pass the pointer lists to the
  170696. * upsampler.
  170697. *
  170698. * The above pictures describe the normal state of the pointer lists.
  170699. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170700. * the first or last sample row as necessary (this is cheaper than copying
  170701. * sample rows around).
  170702. *
  170703. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170704. * situation each iMCU row provides only one row group so the buffering logic
  170705. * must be different (eg, we must read two iMCU rows before we can emit the
  170706. * first row group). For now, we simply do not support providing context
  170707. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170708. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170709. * want it quick and dirty, so a context-free upsampler is sufficient.
  170710. */
  170711. /* Private buffer controller object */
  170712. typedef struct {
  170713. struct jpeg_d_main_controller pub; /* public fields */
  170714. /* Pointer to allocated workspace (M or M+2 row groups). */
  170715. JSAMPARRAY buffer[MAX_COMPONENTS];
  170716. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170717. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170718. /* Remaining fields are only used in the context case. */
  170719. /* These are the master pointers to the funny-order pointer lists. */
  170720. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170721. int whichptr; /* indicates which pointer set is now in use */
  170722. int context_state; /* process_data state machine status */
  170723. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170724. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170725. } my_main_controller4;
  170726. typedef my_main_controller4 * my_main_ptr4;
  170727. /* context_state values: */
  170728. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170729. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170730. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170731. /* Forward declarations */
  170732. METHODDEF(void) process_data_simple_main2
  170733. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170734. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170735. METHODDEF(void) process_data_context_main
  170736. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170737. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170738. #ifdef QUANT_2PASS_SUPPORTED
  170739. METHODDEF(void) process_data_crank_post
  170740. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170741. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170742. #endif
  170743. LOCAL(void)
  170744. alloc_funny_pointers (j_decompress_ptr cinfo)
  170745. /* Allocate space for the funny pointer lists.
  170746. * This is done only once, not once per pass.
  170747. */
  170748. {
  170749. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170750. int ci, rgroup;
  170751. int M = cinfo->min_DCT_scaled_size;
  170752. jpeg_component_info *compptr;
  170753. JSAMPARRAY xbuf;
  170754. /* Get top-level space for component array pointers.
  170755. * We alloc both arrays with one call to save a few cycles.
  170756. */
  170757. main_->xbuffer[0] = (JSAMPIMAGE)
  170758. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170759. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170760. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170761. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170762. ci++, compptr++) {
  170763. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170764. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170765. /* Get space for pointer lists --- M+4 row groups in each list.
  170766. * We alloc both pointer lists with one call to save a few cycles.
  170767. */
  170768. xbuf = (JSAMPARRAY)
  170769. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170770. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170771. xbuf += rgroup; /* want one row group at negative offsets */
  170772. main_->xbuffer[0][ci] = xbuf;
  170773. xbuf += rgroup * (M + 4);
  170774. main_->xbuffer[1][ci] = xbuf;
  170775. }
  170776. }
  170777. LOCAL(void)
  170778. make_funny_pointers (j_decompress_ptr cinfo)
  170779. /* Create the funny pointer lists discussed in the comments above.
  170780. * The actual workspace is already allocated (in main->buffer),
  170781. * and the space for the pointer lists is allocated too.
  170782. * This routine just fills in the curiously ordered lists.
  170783. * This will be repeated at the beginning of each pass.
  170784. */
  170785. {
  170786. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170787. int ci, i, rgroup;
  170788. int M = cinfo->min_DCT_scaled_size;
  170789. jpeg_component_info *compptr;
  170790. JSAMPARRAY buf, xbuf0, xbuf1;
  170791. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170792. ci++, compptr++) {
  170793. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170794. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170795. xbuf0 = main_->xbuffer[0][ci];
  170796. xbuf1 = main_->xbuffer[1][ci];
  170797. /* First copy the workspace pointers as-is */
  170798. buf = main_->buffer[ci];
  170799. for (i = 0; i < rgroup * (M + 2); i++) {
  170800. xbuf0[i] = xbuf1[i] = buf[i];
  170801. }
  170802. /* In the second list, put the last four row groups in swapped order */
  170803. for (i = 0; i < rgroup * 2; i++) {
  170804. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170805. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170806. }
  170807. /* The wraparound pointers at top and bottom will be filled later
  170808. * (see set_wraparound_pointers, below). Initially we want the "above"
  170809. * pointers to duplicate the first actual data line. This only needs
  170810. * to happen in xbuffer[0].
  170811. */
  170812. for (i = 0; i < rgroup; i++) {
  170813. xbuf0[i - rgroup] = xbuf0[0];
  170814. }
  170815. }
  170816. }
  170817. LOCAL(void)
  170818. set_wraparound_pointers (j_decompress_ptr cinfo)
  170819. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170820. * This changes the pointer list state from top-of-image to the normal state.
  170821. */
  170822. {
  170823. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170824. int ci, i, rgroup;
  170825. int M = cinfo->min_DCT_scaled_size;
  170826. jpeg_component_info *compptr;
  170827. JSAMPARRAY xbuf0, xbuf1;
  170828. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170829. ci++, compptr++) {
  170830. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170831. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170832. xbuf0 = main_->xbuffer[0][ci];
  170833. xbuf1 = main_->xbuffer[1][ci];
  170834. for (i = 0; i < rgroup; i++) {
  170835. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170836. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170837. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170838. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170839. }
  170840. }
  170841. }
  170842. LOCAL(void)
  170843. set_bottom_pointers (j_decompress_ptr cinfo)
  170844. /* Change the pointer lists to duplicate the last sample row at the bottom
  170845. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170846. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170847. */
  170848. {
  170849. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170850. int ci, i, rgroup, iMCUheight, rows_left;
  170851. jpeg_component_info *compptr;
  170852. JSAMPARRAY xbuf;
  170853. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170854. ci++, compptr++) {
  170855. /* Count sample rows in one iMCU row and in one row group */
  170856. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170857. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170858. /* Count nondummy sample rows remaining for this component */
  170859. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170860. if (rows_left == 0) rows_left = iMCUheight;
  170861. /* Count nondummy row groups. Should get same answer for each component,
  170862. * so we need only do it once.
  170863. */
  170864. if (ci == 0) {
  170865. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170866. }
  170867. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170868. * last partial rowgroup and ensures at least one full rowgroup of context.
  170869. */
  170870. xbuf = main_->xbuffer[main_->whichptr][ci];
  170871. for (i = 0; i < rgroup * 2; i++) {
  170872. xbuf[rows_left + i] = xbuf[rows_left-1];
  170873. }
  170874. }
  170875. }
  170876. /*
  170877. * Initialize for a processing pass.
  170878. */
  170879. METHODDEF(void)
  170880. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170881. {
  170882. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170883. switch (pass_mode) {
  170884. case JBUF_PASS_THRU:
  170885. if (cinfo->upsample->need_context_rows) {
  170886. main_->pub.process_data = process_data_context_main;
  170887. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170888. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170889. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170890. main_->iMCU_row_ctr = 0;
  170891. } else {
  170892. /* Simple case with no context needed */
  170893. main_->pub.process_data = process_data_simple_main2;
  170894. }
  170895. main_->buffer_full = FALSE; /* Mark buffer empty */
  170896. main_->rowgroup_ctr = 0;
  170897. break;
  170898. #ifdef QUANT_2PASS_SUPPORTED
  170899. case JBUF_CRANK_DEST:
  170900. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170901. main_->pub.process_data = process_data_crank_post;
  170902. break;
  170903. #endif
  170904. default:
  170905. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170906. break;
  170907. }
  170908. }
  170909. /*
  170910. * Process some data.
  170911. * This handles the simple case where no context is required.
  170912. */
  170913. METHODDEF(void)
  170914. process_data_simple_main2 (j_decompress_ptr cinfo,
  170915. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170916. JDIMENSION out_rows_avail)
  170917. {
  170918. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170919. JDIMENSION rowgroups_avail;
  170920. /* Read input data if we haven't filled the main buffer yet */
  170921. if (! main_->buffer_full) {
  170922. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170923. return; /* suspension forced, can do nothing more */
  170924. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170925. }
  170926. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170927. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170928. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170929. * to the postprocessor. The postprocessor has to check for bottom
  170930. * of image anyway (at row resolution), so no point in us doing it too.
  170931. */
  170932. /* Feed the postprocessor */
  170933. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170934. &main_->rowgroup_ctr, rowgroups_avail,
  170935. output_buf, out_row_ctr, out_rows_avail);
  170936. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170937. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170938. main_->buffer_full = FALSE;
  170939. main_->rowgroup_ctr = 0;
  170940. }
  170941. }
  170942. /*
  170943. * Process some data.
  170944. * This handles the case where context rows must be provided.
  170945. */
  170946. METHODDEF(void)
  170947. process_data_context_main (j_decompress_ptr cinfo,
  170948. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170949. JDIMENSION out_rows_avail)
  170950. {
  170951. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170952. /* Read input data if we haven't filled the main buffer yet */
  170953. if (! main_->buffer_full) {
  170954. if (! (*cinfo->coef->decompress_data) (cinfo,
  170955. main_->xbuffer[main_->whichptr]))
  170956. return; /* suspension forced, can do nothing more */
  170957. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170958. main_->iMCU_row_ctr++; /* count rows received */
  170959. }
  170960. /* Postprocessor typically will not swallow all the input data it is handed
  170961. * in one call (due to filling the output buffer first). Must be prepared
  170962. * to exit and restart. This switch lets us keep track of how far we got.
  170963. * Note that each case falls through to the next on successful completion.
  170964. */
  170965. switch (main_->context_state) {
  170966. case CTX_POSTPONED_ROW:
  170967. /* Call postprocessor using previously set pointers for postponed row */
  170968. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170969. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170970. output_buf, out_row_ctr, out_rows_avail);
  170971. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170972. return; /* Need to suspend */
  170973. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170974. if (*out_row_ctr >= out_rows_avail)
  170975. return; /* Postprocessor exactly filled output buf */
  170976. /*FALLTHROUGH*/
  170977. case CTX_PREPARE_FOR_IMCU:
  170978. /* Prepare to process first M-1 row groups of this iMCU row */
  170979. main_->rowgroup_ctr = 0;
  170980. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170981. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170982. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170983. */
  170984. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170985. set_bottom_pointers(cinfo);
  170986. main_->context_state = CTX_PROCESS_IMCU;
  170987. /*FALLTHROUGH*/
  170988. case CTX_PROCESS_IMCU:
  170989. /* Call postprocessor using previously set pointers */
  170990. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170991. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170992. output_buf, out_row_ctr, out_rows_avail);
  170993. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170994. return; /* Need to suspend */
  170995. /* After the first iMCU, change wraparound pointers to normal state */
  170996. if (main_->iMCU_row_ctr == 1)
  170997. set_wraparound_pointers(cinfo);
  170998. /* Prepare to load new iMCU row using other xbuffer list */
  170999. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171000. main_->buffer_full = FALSE;
  171001. /* Still need to process last row group of this iMCU row, */
  171002. /* which is saved at index M+1 of the other xbuffer */
  171003. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171004. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171005. main_->context_state = CTX_POSTPONED_ROW;
  171006. }
  171007. }
  171008. /*
  171009. * Process some data.
  171010. * Final pass of two-pass quantization: just call the postprocessor.
  171011. * Source data will be the postprocessor controller's internal buffer.
  171012. */
  171013. #ifdef QUANT_2PASS_SUPPORTED
  171014. METHODDEF(void)
  171015. process_data_crank_post (j_decompress_ptr cinfo,
  171016. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171017. JDIMENSION out_rows_avail)
  171018. {
  171019. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171020. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171021. output_buf, out_row_ctr, out_rows_avail);
  171022. }
  171023. #endif /* QUANT_2PASS_SUPPORTED */
  171024. /*
  171025. * Initialize main buffer controller.
  171026. */
  171027. GLOBAL(void)
  171028. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171029. {
  171030. my_main_ptr4 main_;
  171031. int ci, rgroup, ngroups;
  171032. jpeg_component_info *compptr;
  171033. main_ = (my_main_ptr4)
  171034. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171035. SIZEOF(my_main_controller4));
  171036. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171037. main_->pub.start_pass = start_pass_main2;
  171038. if (need_full_buffer) /* shouldn't happen */
  171039. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171040. /* Allocate the workspace.
  171041. * ngroups is the number of row groups we need.
  171042. */
  171043. if (cinfo->upsample->need_context_rows) {
  171044. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171045. ERREXIT(cinfo, JERR_NOTIMPL);
  171046. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171047. ngroups = cinfo->min_DCT_scaled_size + 2;
  171048. } else {
  171049. ngroups = cinfo->min_DCT_scaled_size;
  171050. }
  171051. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171052. ci++, compptr++) {
  171053. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171054. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171055. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171056. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171057. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171058. (JDIMENSION) (rgroup * ngroups));
  171059. }
  171060. }
  171061. /*** End of inlined file: jdmainct.c ***/
  171062. /*** Start of inlined file: jdmarker.c ***/
  171063. #define JPEG_INTERNALS
  171064. /* Private state */
  171065. typedef struct {
  171066. struct jpeg_marker_reader pub; /* public fields */
  171067. /* Application-overridable marker processing methods */
  171068. jpeg_marker_parser_method process_COM;
  171069. jpeg_marker_parser_method process_APPn[16];
  171070. /* Limit on marker data length to save for each marker type */
  171071. unsigned int length_limit_COM;
  171072. unsigned int length_limit_APPn[16];
  171073. /* Status of COM/APPn marker saving */
  171074. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171075. unsigned int bytes_read; /* data bytes read so far in marker */
  171076. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171077. } my_marker_reader;
  171078. typedef my_marker_reader * my_marker_ptr2;
  171079. /*
  171080. * Macros for fetching data from the data source module.
  171081. *
  171082. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171083. * the current restart point; we update them only when we have reached a
  171084. * suitable place to restart if a suspension occurs.
  171085. */
  171086. /* Declare and initialize local copies of input pointer/count */
  171087. #define INPUT_VARS(cinfo) \
  171088. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171089. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171090. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171091. /* Unload the local copies --- do this only at a restart boundary */
  171092. #define INPUT_SYNC(cinfo) \
  171093. ( datasrc->next_input_byte = next_input_byte, \
  171094. datasrc->bytes_in_buffer = bytes_in_buffer )
  171095. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171096. #define INPUT_RELOAD(cinfo) \
  171097. ( next_input_byte = datasrc->next_input_byte, \
  171098. bytes_in_buffer = datasrc->bytes_in_buffer )
  171099. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171100. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171101. * but we must reload the local copies after a successful fill.
  171102. */
  171103. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171104. if (bytes_in_buffer == 0) { \
  171105. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171106. { action; } \
  171107. INPUT_RELOAD(cinfo); \
  171108. }
  171109. /* Read a byte into variable V.
  171110. * If must suspend, take the specified action (typically "return FALSE").
  171111. */
  171112. #define INPUT_BYTE(cinfo,V,action) \
  171113. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171114. bytes_in_buffer--; \
  171115. V = GETJOCTET(*next_input_byte++); )
  171116. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171117. * V should be declared unsigned int or perhaps INT32.
  171118. */
  171119. #define INPUT_2BYTES(cinfo,V,action) \
  171120. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171121. bytes_in_buffer--; \
  171122. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171123. MAKE_BYTE_AVAIL(cinfo,action); \
  171124. bytes_in_buffer--; \
  171125. V += GETJOCTET(*next_input_byte++); )
  171126. /*
  171127. * Routines to process JPEG markers.
  171128. *
  171129. * Entry condition: JPEG marker itself has been read and its code saved
  171130. * in cinfo->unread_marker; input restart point is just after the marker.
  171131. *
  171132. * Exit: if return TRUE, have read and processed any parameters, and have
  171133. * updated the restart point to point after the parameters.
  171134. * If return FALSE, was forced to suspend before reaching end of
  171135. * marker parameters; restart point has not been moved. Same routine
  171136. * will be called again after application supplies more input data.
  171137. *
  171138. * This approach to suspension assumes that all of a marker's parameters
  171139. * can fit into a single input bufferload. This should hold for "normal"
  171140. * markers. Some COM/APPn markers might have large parameter segments
  171141. * that might not fit. If we are simply dropping such a marker, we use
  171142. * skip_input_data to get past it, and thereby put the problem on the
  171143. * source manager's shoulders. If we are saving the marker's contents
  171144. * into memory, we use a slightly different convention: when forced to
  171145. * suspend, the marker processor updates the restart point to the end of
  171146. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171147. * On resumption, cinfo->unread_marker still contains the marker code,
  171148. * but the data source will point to the next chunk of marker data.
  171149. * The marker processor must retain internal state to deal with this.
  171150. *
  171151. * Note that we don't bother to avoid duplicate trace messages if a
  171152. * suspension occurs within marker parameters. Other side effects
  171153. * require more care.
  171154. */
  171155. LOCAL(boolean)
  171156. get_soi (j_decompress_ptr cinfo)
  171157. /* Process an SOI marker */
  171158. {
  171159. int i;
  171160. TRACEMS(cinfo, 1, JTRC_SOI);
  171161. if (cinfo->marker->saw_SOI)
  171162. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171163. /* Reset all parameters that are defined to be reset by SOI */
  171164. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171165. cinfo->arith_dc_L[i] = 0;
  171166. cinfo->arith_dc_U[i] = 1;
  171167. cinfo->arith_ac_K[i] = 5;
  171168. }
  171169. cinfo->restart_interval = 0;
  171170. /* Set initial assumptions for colorspace etc */
  171171. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171172. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171173. cinfo->saw_JFIF_marker = FALSE;
  171174. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171175. cinfo->JFIF_minor_version = 1;
  171176. cinfo->density_unit = 0;
  171177. cinfo->X_density = 1;
  171178. cinfo->Y_density = 1;
  171179. cinfo->saw_Adobe_marker = FALSE;
  171180. cinfo->Adobe_transform = 0;
  171181. cinfo->marker->saw_SOI = TRUE;
  171182. return TRUE;
  171183. }
  171184. LOCAL(boolean)
  171185. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171186. /* Process a SOFn marker */
  171187. {
  171188. INT32 length;
  171189. int c, ci;
  171190. jpeg_component_info * compptr;
  171191. INPUT_VARS(cinfo);
  171192. cinfo->progressive_mode = is_prog;
  171193. cinfo->arith_code = is_arith;
  171194. INPUT_2BYTES(cinfo, length, return FALSE);
  171195. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171196. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171197. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171198. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171199. length -= 8;
  171200. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171201. (int) cinfo->image_width, (int) cinfo->image_height,
  171202. cinfo->num_components);
  171203. if (cinfo->marker->saw_SOF)
  171204. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171205. /* We don't support files in which the image height is initially specified */
  171206. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171207. /* might as well have a general sanity check. */
  171208. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171209. || cinfo->num_components <= 0)
  171210. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171211. if (length != (cinfo->num_components * 3))
  171212. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171213. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171214. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171215. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171216. cinfo->num_components * SIZEOF(jpeg_component_info));
  171217. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171218. ci++, compptr++) {
  171219. compptr->component_index = ci;
  171220. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171221. INPUT_BYTE(cinfo, c, return FALSE);
  171222. compptr->h_samp_factor = (c >> 4) & 15;
  171223. compptr->v_samp_factor = (c ) & 15;
  171224. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171225. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171226. compptr->component_id, compptr->h_samp_factor,
  171227. compptr->v_samp_factor, compptr->quant_tbl_no);
  171228. }
  171229. cinfo->marker->saw_SOF = TRUE;
  171230. INPUT_SYNC(cinfo);
  171231. return TRUE;
  171232. }
  171233. LOCAL(boolean)
  171234. get_sos (j_decompress_ptr cinfo)
  171235. /* Process a SOS marker */
  171236. {
  171237. INT32 length;
  171238. int i, ci, n, c, cc;
  171239. jpeg_component_info * compptr;
  171240. INPUT_VARS(cinfo);
  171241. if (! cinfo->marker->saw_SOF)
  171242. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171243. INPUT_2BYTES(cinfo, length, return FALSE);
  171244. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171245. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171246. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171247. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171248. cinfo->comps_in_scan = n;
  171249. /* Collect the component-spec parameters */
  171250. for (i = 0; i < n; i++) {
  171251. INPUT_BYTE(cinfo, cc, return FALSE);
  171252. INPUT_BYTE(cinfo, c, return FALSE);
  171253. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171254. ci++, compptr++) {
  171255. if (cc == compptr->component_id)
  171256. goto id_found;
  171257. }
  171258. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171259. id_found:
  171260. cinfo->cur_comp_info[i] = compptr;
  171261. compptr->dc_tbl_no = (c >> 4) & 15;
  171262. compptr->ac_tbl_no = (c ) & 15;
  171263. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171264. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171265. }
  171266. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171267. INPUT_BYTE(cinfo, c, return FALSE);
  171268. cinfo->Ss = c;
  171269. INPUT_BYTE(cinfo, c, return FALSE);
  171270. cinfo->Se = c;
  171271. INPUT_BYTE(cinfo, c, return FALSE);
  171272. cinfo->Ah = (c >> 4) & 15;
  171273. cinfo->Al = (c ) & 15;
  171274. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171275. cinfo->Ah, cinfo->Al);
  171276. /* Prepare to scan data & restart markers */
  171277. cinfo->marker->next_restart_num = 0;
  171278. /* Count another SOS marker */
  171279. cinfo->input_scan_number++;
  171280. INPUT_SYNC(cinfo);
  171281. return TRUE;
  171282. }
  171283. #ifdef D_ARITH_CODING_SUPPORTED
  171284. LOCAL(boolean)
  171285. get_dac (j_decompress_ptr cinfo)
  171286. /* Process a DAC marker */
  171287. {
  171288. INT32 length;
  171289. int index, val;
  171290. INPUT_VARS(cinfo);
  171291. INPUT_2BYTES(cinfo, length, return FALSE);
  171292. length -= 2;
  171293. while (length > 0) {
  171294. INPUT_BYTE(cinfo, index, return FALSE);
  171295. INPUT_BYTE(cinfo, val, return FALSE);
  171296. length -= 2;
  171297. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171298. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171299. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171300. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171301. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171302. } else { /* define DC table */
  171303. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171304. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171305. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171306. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171307. }
  171308. }
  171309. if (length != 0)
  171310. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171311. INPUT_SYNC(cinfo);
  171312. return TRUE;
  171313. }
  171314. #else /* ! D_ARITH_CODING_SUPPORTED */
  171315. #define get_dac(cinfo) skip_variable(cinfo)
  171316. #endif /* D_ARITH_CODING_SUPPORTED */
  171317. LOCAL(boolean)
  171318. get_dht (j_decompress_ptr cinfo)
  171319. /* Process a DHT marker */
  171320. {
  171321. INT32 length;
  171322. UINT8 bits[17];
  171323. UINT8 huffval[256];
  171324. int i, index, count;
  171325. JHUFF_TBL **htblptr;
  171326. INPUT_VARS(cinfo);
  171327. INPUT_2BYTES(cinfo, length, return FALSE);
  171328. length -= 2;
  171329. while (length > 16) {
  171330. INPUT_BYTE(cinfo, index, return FALSE);
  171331. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171332. bits[0] = 0;
  171333. count = 0;
  171334. for (i = 1; i <= 16; i++) {
  171335. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171336. count += bits[i];
  171337. }
  171338. length -= 1 + 16;
  171339. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171340. bits[1], bits[2], bits[3], bits[4],
  171341. bits[5], bits[6], bits[7], bits[8]);
  171342. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171343. bits[9], bits[10], bits[11], bits[12],
  171344. bits[13], bits[14], bits[15], bits[16]);
  171345. /* Here we just do minimal validation of the counts to avoid walking
  171346. * off the end of our table space. jdhuff.c will check more carefully.
  171347. */
  171348. if (count > 256 || ((INT32) count) > length)
  171349. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171350. for (i = 0; i < count; i++)
  171351. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171352. length -= count;
  171353. if (index & 0x10) { /* AC table definition */
  171354. index -= 0x10;
  171355. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171356. } else { /* DC table definition */
  171357. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171358. }
  171359. if (index < 0 || index >= NUM_HUFF_TBLS)
  171360. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171361. if (*htblptr == NULL)
  171362. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171363. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171364. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171365. }
  171366. if (length != 0)
  171367. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171368. INPUT_SYNC(cinfo);
  171369. return TRUE;
  171370. }
  171371. LOCAL(boolean)
  171372. get_dqt (j_decompress_ptr cinfo)
  171373. /* Process a DQT marker */
  171374. {
  171375. INT32 length;
  171376. int n, i, prec;
  171377. unsigned int tmp;
  171378. JQUANT_TBL *quant_ptr;
  171379. INPUT_VARS(cinfo);
  171380. INPUT_2BYTES(cinfo, length, return FALSE);
  171381. length -= 2;
  171382. while (length > 0) {
  171383. INPUT_BYTE(cinfo, n, return FALSE);
  171384. prec = n >> 4;
  171385. n &= 0x0F;
  171386. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171387. if (n >= NUM_QUANT_TBLS)
  171388. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171389. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171390. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171391. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171392. for (i = 0; i < DCTSIZE2; i++) {
  171393. if (prec)
  171394. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171395. else
  171396. INPUT_BYTE(cinfo, tmp, return FALSE);
  171397. /* We convert the zigzag-order table to natural array order. */
  171398. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171399. }
  171400. if (cinfo->err->trace_level >= 2) {
  171401. for (i = 0; i < DCTSIZE2; i += 8) {
  171402. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171403. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171404. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171405. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171406. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171407. }
  171408. }
  171409. length -= DCTSIZE2+1;
  171410. if (prec) length -= DCTSIZE2;
  171411. }
  171412. if (length != 0)
  171413. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171414. INPUT_SYNC(cinfo);
  171415. return TRUE;
  171416. }
  171417. LOCAL(boolean)
  171418. get_dri (j_decompress_ptr cinfo)
  171419. /* Process a DRI marker */
  171420. {
  171421. INT32 length;
  171422. unsigned int tmp;
  171423. INPUT_VARS(cinfo);
  171424. INPUT_2BYTES(cinfo, length, return FALSE);
  171425. if (length != 4)
  171426. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171427. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171428. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171429. cinfo->restart_interval = tmp;
  171430. INPUT_SYNC(cinfo);
  171431. return TRUE;
  171432. }
  171433. /*
  171434. * Routines for processing APPn and COM markers.
  171435. * These are either saved in memory or discarded, per application request.
  171436. * APP0 and APP14 are specially checked to see if they are
  171437. * JFIF and Adobe markers, respectively.
  171438. */
  171439. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171440. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171441. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171442. LOCAL(void)
  171443. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171444. unsigned int datalen, INT32 remaining)
  171445. /* Examine first few bytes from an APP0.
  171446. * Take appropriate action if it is a JFIF marker.
  171447. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171448. */
  171449. {
  171450. INT32 totallen = (INT32) datalen + remaining;
  171451. if (datalen >= APP0_DATA_LEN &&
  171452. GETJOCTET(data[0]) == 0x4A &&
  171453. GETJOCTET(data[1]) == 0x46 &&
  171454. GETJOCTET(data[2]) == 0x49 &&
  171455. GETJOCTET(data[3]) == 0x46 &&
  171456. GETJOCTET(data[4]) == 0) {
  171457. /* Found JFIF APP0 marker: save info */
  171458. cinfo->saw_JFIF_marker = TRUE;
  171459. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171460. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171461. cinfo->density_unit = GETJOCTET(data[7]);
  171462. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171463. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171464. /* Check version.
  171465. * Major version must be 1, anything else signals an incompatible change.
  171466. * (We used to treat this as an error, but now it's a nonfatal warning,
  171467. * because some bozo at Hijaak couldn't read the spec.)
  171468. * Minor version should be 0..2, but process anyway if newer.
  171469. */
  171470. if (cinfo->JFIF_major_version != 1)
  171471. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171472. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171473. /* Generate trace messages */
  171474. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171475. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171476. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171477. /* Validate thumbnail dimensions and issue appropriate messages */
  171478. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171479. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171480. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171481. totallen -= APP0_DATA_LEN;
  171482. if (totallen !=
  171483. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171484. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171485. } else if (datalen >= 6 &&
  171486. GETJOCTET(data[0]) == 0x4A &&
  171487. GETJOCTET(data[1]) == 0x46 &&
  171488. GETJOCTET(data[2]) == 0x58 &&
  171489. GETJOCTET(data[3]) == 0x58 &&
  171490. GETJOCTET(data[4]) == 0) {
  171491. /* Found JFIF "JFXX" extension APP0 marker */
  171492. /* The library doesn't actually do anything with these,
  171493. * but we try to produce a helpful trace message.
  171494. */
  171495. switch (GETJOCTET(data[5])) {
  171496. case 0x10:
  171497. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171498. break;
  171499. case 0x11:
  171500. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171501. break;
  171502. case 0x13:
  171503. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171504. break;
  171505. default:
  171506. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171507. GETJOCTET(data[5]), (int) totallen);
  171508. break;
  171509. }
  171510. } else {
  171511. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171512. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171513. }
  171514. }
  171515. LOCAL(void)
  171516. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171517. unsigned int datalen, INT32 remaining)
  171518. /* Examine first few bytes from an APP14.
  171519. * Take appropriate action if it is an Adobe marker.
  171520. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171521. */
  171522. {
  171523. unsigned int version, flags0, flags1, transform;
  171524. if (datalen >= APP14_DATA_LEN &&
  171525. GETJOCTET(data[0]) == 0x41 &&
  171526. GETJOCTET(data[1]) == 0x64 &&
  171527. GETJOCTET(data[2]) == 0x6F &&
  171528. GETJOCTET(data[3]) == 0x62 &&
  171529. GETJOCTET(data[4]) == 0x65) {
  171530. /* Found Adobe APP14 marker */
  171531. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171532. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171533. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171534. transform = GETJOCTET(data[11]);
  171535. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171536. cinfo->saw_Adobe_marker = TRUE;
  171537. cinfo->Adobe_transform = (UINT8) transform;
  171538. } else {
  171539. /* Start of APP14 does not match "Adobe", or too short */
  171540. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171541. }
  171542. }
  171543. METHODDEF(boolean)
  171544. get_interesting_appn (j_decompress_ptr cinfo)
  171545. /* Process an APP0 or APP14 marker without saving it */
  171546. {
  171547. INT32 length;
  171548. JOCTET b[APPN_DATA_LEN];
  171549. unsigned int i, numtoread;
  171550. INPUT_VARS(cinfo);
  171551. INPUT_2BYTES(cinfo, length, return FALSE);
  171552. length -= 2;
  171553. /* get the interesting part of the marker data */
  171554. if (length >= APPN_DATA_LEN)
  171555. numtoread = APPN_DATA_LEN;
  171556. else if (length > 0)
  171557. numtoread = (unsigned int) length;
  171558. else
  171559. numtoread = 0;
  171560. for (i = 0; i < numtoread; i++)
  171561. INPUT_BYTE(cinfo, b[i], return FALSE);
  171562. length -= numtoread;
  171563. /* process it */
  171564. switch (cinfo->unread_marker) {
  171565. case M_APP0:
  171566. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171567. break;
  171568. case M_APP14:
  171569. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171570. break;
  171571. default:
  171572. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171573. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171574. break;
  171575. }
  171576. /* skip any remaining data -- could be lots */
  171577. INPUT_SYNC(cinfo);
  171578. if (length > 0)
  171579. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171580. return TRUE;
  171581. }
  171582. #ifdef SAVE_MARKERS_SUPPORTED
  171583. METHODDEF(boolean)
  171584. save_marker (j_decompress_ptr cinfo)
  171585. /* Save an APPn or COM marker into the marker list */
  171586. {
  171587. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171588. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171589. unsigned int bytes_read, data_length;
  171590. JOCTET FAR * data;
  171591. INT32 length = 0;
  171592. INPUT_VARS(cinfo);
  171593. if (cur_marker == NULL) {
  171594. /* begin reading a marker */
  171595. INPUT_2BYTES(cinfo, length, return FALSE);
  171596. length -= 2;
  171597. if (length >= 0) { /* watch out for bogus length word */
  171598. /* figure out how much we want to save */
  171599. unsigned int limit;
  171600. if (cinfo->unread_marker == (int) M_COM)
  171601. limit = marker->length_limit_COM;
  171602. else
  171603. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171604. if ((unsigned int) length < limit)
  171605. limit = (unsigned int) length;
  171606. /* allocate and initialize the marker item */
  171607. cur_marker = (jpeg_saved_marker_ptr)
  171608. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171609. SIZEOF(struct jpeg_marker_struct) + limit);
  171610. cur_marker->next = NULL;
  171611. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171612. cur_marker->original_length = (unsigned int) length;
  171613. cur_marker->data_length = limit;
  171614. /* data area is just beyond the jpeg_marker_struct */
  171615. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171616. marker->cur_marker = cur_marker;
  171617. marker->bytes_read = 0;
  171618. bytes_read = 0;
  171619. data_length = limit;
  171620. } else {
  171621. /* deal with bogus length word */
  171622. bytes_read = data_length = 0;
  171623. data = NULL;
  171624. }
  171625. } else {
  171626. /* resume reading a marker */
  171627. bytes_read = marker->bytes_read;
  171628. data_length = cur_marker->data_length;
  171629. data = cur_marker->data + bytes_read;
  171630. }
  171631. while (bytes_read < data_length) {
  171632. INPUT_SYNC(cinfo); /* move the restart point to here */
  171633. marker->bytes_read = bytes_read;
  171634. /* If there's not at least one byte in buffer, suspend */
  171635. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171636. /* Copy bytes with reasonable rapidity */
  171637. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171638. *data++ = *next_input_byte++;
  171639. bytes_in_buffer--;
  171640. bytes_read++;
  171641. }
  171642. }
  171643. /* Done reading what we want to read */
  171644. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171645. /* Add new marker to end of list */
  171646. if (cinfo->marker_list == NULL) {
  171647. cinfo->marker_list = cur_marker;
  171648. } else {
  171649. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171650. while (prev->next != NULL)
  171651. prev = prev->next;
  171652. prev->next = cur_marker;
  171653. }
  171654. /* Reset pointer & calc remaining data length */
  171655. data = cur_marker->data;
  171656. length = cur_marker->original_length - data_length;
  171657. }
  171658. /* Reset to initial state for next marker */
  171659. marker->cur_marker = NULL;
  171660. /* Process the marker if interesting; else just make a generic trace msg */
  171661. switch (cinfo->unread_marker) {
  171662. case M_APP0:
  171663. examine_app0(cinfo, data, data_length, length);
  171664. break;
  171665. case M_APP14:
  171666. examine_app14(cinfo, data, data_length, length);
  171667. break;
  171668. default:
  171669. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171670. (int) (data_length + length));
  171671. break;
  171672. }
  171673. /* skip any remaining data -- could be lots */
  171674. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171675. if (length > 0)
  171676. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171677. return TRUE;
  171678. }
  171679. #endif /* SAVE_MARKERS_SUPPORTED */
  171680. METHODDEF(boolean)
  171681. skip_variable (j_decompress_ptr cinfo)
  171682. /* Skip over an unknown or uninteresting variable-length marker */
  171683. {
  171684. INT32 length;
  171685. INPUT_VARS(cinfo);
  171686. INPUT_2BYTES(cinfo, length, return FALSE);
  171687. length -= 2;
  171688. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171689. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171690. if (length > 0)
  171691. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171692. return TRUE;
  171693. }
  171694. /*
  171695. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171696. * Returns FALSE if had to suspend before reaching a marker;
  171697. * in that case cinfo->unread_marker is unchanged.
  171698. *
  171699. * Note that the result might not be a valid marker code,
  171700. * but it will never be 0 or FF.
  171701. */
  171702. LOCAL(boolean)
  171703. next_marker (j_decompress_ptr cinfo)
  171704. {
  171705. int c;
  171706. INPUT_VARS(cinfo);
  171707. for (;;) {
  171708. INPUT_BYTE(cinfo, c, return FALSE);
  171709. /* Skip any non-FF bytes.
  171710. * This may look a bit inefficient, but it will not occur in a valid file.
  171711. * We sync after each discarded byte so that a suspending data source
  171712. * can discard the byte from its buffer.
  171713. */
  171714. while (c != 0xFF) {
  171715. cinfo->marker->discarded_bytes++;
  171716. INPUT_SYNC(cinfo);
  171717. INPUT_BYTE(cinfo, c, return FALSE);
  171718. }
  171719. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171720. * pad bytes, so don't count them in discarded_bytes. We assume there
  171721. * will not be so many consecutive FF bytes as to overflow a suspending
  171722. * data source's input buffer.
  171723. */
  171724. do {
  171725. INPUT_BYTE(cinfo, c, return FALSE);
  171726. } while (c == 0xFF);
  171727. if (c != 0)
  171728. break; /* found a valid marker, exit loop */
  171729. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171730. * Discard it and loop back to try again.
  171731. */
  171732. cinfo->marker->discarded_bytes += 2;
  171733. INPUT_SYNC(cinfo);
  171734. }
  171735. if (cinfo->marker->discarded_bytes != 0) {
  171736. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171737. cinfo->marker->discarded_bytes = 0;
  171738. }
  171739. cinfo->unread_marker = c;
  171740. INPUT_SYNC(cinfo);
  171741. return TRUE;
  171742. }
  171743. LOCAL(boolean)
  171744. first_marker (j_decompress_ptr cinfo)
  171745. /* Like next_marker, but used to obtain the initial SOI marker. */
  171746. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171747. * we might well scan an entire input file before realizing it ain't JPEG.
  171748. * If an application wants to process non-JFIF files, it must seek to the
  171749. * SOI before calling the JPEG library.
  171750. */
  171751. {
  171752. int c, c2;
  171753. INPUT_VARS(cinfo);
  171754. INPUT_BYTE(cinfo, c, return FALSE);
  171755. INPUT_BYTE(cinfo, c2, return FALSE);
  171756. if (c != 0xFF || c2 != (int) M_SOI)
  171757. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171758. cinfo->unread_marker = c2;
  171759. INPUT_SYNC(cinfo);
  171760. return TRUE;
  171761. }
  171762. /*
  171763. * Read markers until SOS or EOI.
  171764. *
  171765. * Returns same codes as are defined for jpeg_consume_input:
  171766. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171767. */
  171768. METHODDEF(int)
  171769. read_markers (j_decompress_ptr cinfo)
  171770. {
  171771. /* Outer loop repeats once for each marker. */
  171772. for (;;) {
  171773. /* Collect the marker proper, unless we already did. */
  171774. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171775. if (cinfo->unread_marker == 0) {
  171776. if (! cinfo->marker->saw_SOI) {
  171777. if (! first_marker(cinfo))
  171778. return JPEG_SUSPENDED;
  171779. } else {
  171780. if (! next_marker(cinfo))
  171781. return JPEG_SUSPENDED;
  171782. }
  171783. }
  171784. /* At this point cinfo->unread_marker contains the marker code and the
  171785. * input point is just past the marker proper, but before any parameters.
  171786. * A suspension will cause us to return with this state still true.
  171787. */
  171788. switch (cinfo->unread_marker) {
  171789. case M_SOI:
  171790. if (! get_soi(cinfo))
  171791. return JPEG_SUSPENDED;
  171792. break;
  171793. case M_SOF0: /* Baseline */
  171794. case M_SOF1: /* Extended sequential, Huffman */
  171795. if (! get_sof(cinfo, FALSE, FALSE))
  171796. return JPEG_SUSPENDED;
  171797. break;
  171798. case M_SOF2: /* Progressive, Huffman */
  171799. if (! get_sof(cinfo, TRUE, FALSE))
  171800. return JPEG_SUSPENDED;
  171801. break;
  171802. case M_SOF9: /* Extended sequential, arithmetic */
  171803. if (! get_sof(cinfo, FALSE, TRUE))
  171804. return JPEG_SUSPENDED;
  171805. break;
  171806. case M_SOF10: /* Progressive, arithmetic */
  171807. if (! get_sof(cinfo, TRUE, TRUE))
  171808. return JPEG_SUSPENDED;
  171809. break;
  171810. /* Currently unsupported SOFn types */
  171811. case M_SOF3: /* Lossless, Huffman */
  171812. case M_SOF5: /* Differential sequential, Huffman */
  171813. case M_SOF6: /* Differential progressive, Huffman */
  171814. case M_SOF7: /* Differential lossless, Huffman */
  171815. case M_JPG: /* Reserved for JPEG extensions */
  171816. case M_SOF11: /* Lossless, arithmetic */
  171817. case M_SOF13: /* Differential sequential, arithmetic */
  171818. case M_SOF14: /* Differential progressive, arithmetic */
  171819. case M_SOF15: /* Differential lossless, arithmetic */
  171820. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171821. break;
  171822. case M_SOS:
  171823. if (! get_sos(cinfo))
  171824. return JPEG_SUSPENDED;
  171825. cinfo->unread_marker = 0; /* processed the marker */
  171826. return JPEG_REACHED_SOS;
  171827. case M_EOI:
  171828. TRACEMS(cinfo, 1, JTRC_EOI);
  171829. cinfo->unread_marker = 0; /* processed the marker */
  171830. return JPEG_REACHED_EOI;
  171831. case M_DAC:
  171832. if (! get_dac(cinfo))
  171833. return JPEG_SUSPENDED;
  171834. break;
  171835. case M_DHT:
  171836. if (! get_dht(cinfo))
  171837. return JPEG_SUSPENDED;
  171838. break;
  171839. case M_DQT:
  171840. if (! get_dqt(cinfo))
  171841. return JPEG_SUSPENDED;
  171842. break;
  171843. case M_DRI:
  171844. if (! get_dri(cinfo))
  171845. return JPEG_SUSPENDED;
  171846. break;
  171847. case M_APP0:
  171848. case M_APP1:
  171849. case M_APP2:
  171850. case M_APP3:
  171851. case M_APP4:
  171852. case M_APP5:
  171853. case M_APP6:
  171854. case M_APP7:
  171855. case M_APP8:
  171856. case M_APP9:
  171857. case M_APP10:
  171858. case M_APP11:
  171859. case M_APP12:
  171860. case M_APP13:
  171861. case M_APP14:
  171862. case M_APP15:
  171863. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171864. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171865. return JPEG_SUSPENDED;
  171866. break;
  171867. case M_COM:
  171868. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171869. return JPEG_SUSPENDED;
  171870. break;
  171871. case M_RST0: /* these are all parameterless */
  171872. case M_RST1:
  171873. case M_RST2:
  171874. case M_RST3:
  171875. case M_RST4:
  171876. case M_RST5:
  171877. case M_RST6:
  171878. case M_RST7:
  171879. case M_TEM:
  171880. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171881. break;
  171882. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171883. if (! skip_variable(cinfo))
  171884. return JPEG_SUSPENDED;
  171885. break;
  171886. default: /* must be DHP, EXP, JPGn, or RESn */
  171887. /* For now, we treat the reserved markers as fatal errors since they are
  171888. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171889. * Once the JPEG 3 version-number marker is well defined, this code
  171890. * ought to change!
  171891. */
  171892. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171893. break;
  171894. }
  171895. /* Successfully processed marker, so reset state variable */
  171896. cinfo->unread_marker = 0;
  171897. } /* end loop */
  171898. }
  171899. /*
  171900. * Read a restart marker, which is expected to appear next in the datastream;
  171901. * if the marker is not there, take appropriate recovery action.
  171902. * Returns FALSE if suspension is required.
  171903. *
  171904. * This is called by the entropy decoder after it has read an appropriate
  171905. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171906. * has already read a marker from the data source. Under normal conditions
  171907. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171908. * it holds a marker which the decoder will be unable to read past.
  171909. */
  171910. METHODDEF(boolean)
  171911. read_restart_marker (j_decompress_ptr cinfo)
  171912. {
  171913. /* Obtain a marker unless we already did. */
  171914. /* Note that next_marker will complain if it skips any data. */
  171915. if (cinfo->unread_marker == 0) {
  171916. if (! next_marker(cinfo))
  171917. return FALSE;
  171918. }
  171919. if (cinfo->unread_marker ==
  171920. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171921. /* Normal case --- swallow the marker and let entropy decoder continue */
  171922. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171923. cinfo->unread_marker = 0;
  171924. } else {
  171925. /* Uh-oh, the restart markers have been messed up. */
  171926. /* Let the data source manager determine how to resync. */
  171927. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171928. cinfo->marker->next_restart_num))
  171929. return FALSE;
  171930. }
  171931. /* Update next-restart state */
  171932. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171933. return TRUE;
  171934. }
  171935. /*
  171936. * This is the default resync_to_restart method for data source managers
  171937. * to use if they don't have any better approach. Some data source managers
  171938. * may be able to back up, or may have additional knowledge about the data
  171939. * which permits a more intelligent recovery strategy; such managers would
  171940. * presumably supply their own resync method.
  171941. *
  171942. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171943. * the restart marker it was expecting. (This code is *not* used unless
  171944. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171945. * the marker code actually found (might be anything, except 0 or FF).
  171946. * The desired restart marker number (0..7) is passed as a parameter.
  171947. * This routine is supposed to apply whatever error recovery strategy seems
  171948. * appropriate in order to position the input stream to the next data segment.
  171949. * Note that cinfo->unread_marker is treated as a marker appearing before
  171950. * the current data-source input point; usually it should be reset to zero
  171951. * before returning.
  171952. * Returns FALSE if suspension is required.
  171953. *
  171954. * This implementation is substantially constrained by wanting to treat the
  171955. * input as a data stream; this means we can't back up. Therefore, we have
  171956. * only the following actions to work with:
  171957. * 1. Simply discard the marker and let the entropy decoder resume at next
  171958. * byte of file.
  171959. * 2. Read forward until we find another marker, discarding intervening
  171960. * data. (In theory we could look ahead within the current bufferload,
  171961. * without having to discard data if we don't find the desired marker.
  171962. * This idea is not implemented here, in part because it makes behavior
  171963. * dependent on buffer size and chance buffer-boundary positions.)
  171964. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171965. * This will cause the entropy decoder to process an empty data segment,
  171966. * inserting dummy zeroes, and then we will reprocess the marker.
  171967. *
  171968. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171969. * appropriate if the found marker is a future restart marker (indicating
  171970. * that we have missed the desired restart marker, probably because it got
  171971. * corrupted).
  171972. * We apply #2 or #3 if the found marker is a restart marker no more than
  171973. * two counts behind or ahead of the expected one. We also apply #2 if the
  171974. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171975. * If the found marker is a restart marker more than 2 counts away, we do #1
  171976. * (too much risk that the marker is erroneous; with luck we will be able to
  171977. * resync at some future point).
  171978. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171979. * overrunning the end of a scan. An implementation limited to single-scan
  171980. * files might find it better to apply #2 for markers other than EOI, since
  171981. * any other marker would have to be bogus data in that case.
  171982. */
  171983. GLOBAL(boolean)
  171984. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171985. {
  171986. int marker = cinfo->unread_marker;
  171987. int action = 1;
  171988. /* Always put up a warning. */
  171989. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171990. /* Outer loop handles repeated decision after scanning forward. */
  171991. for (;;) {
  171992. if (marker < (int) M_SOF0)
  171993. action = 2; /* invalid marker */
  171994. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171995. action = 3; /* valid non-restart marker */
  171996. else {
  171997. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171998. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171999. action = 3; /* one of the next two expected restarts */
  172000. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172001. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172002. action = 2; /* a prior restart, so advance */
  172003. else
  172004. action = 1; /* desired restart or too far away */
  172005. }
  172006. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172007. switch (action) {
  172008. case 1:
  172009. /* Discard marker and let entropy decoder resume processing. */
  172010. cinfo->unread_marker = 0;
  172011. return TRUE;
  172012. case 2:
  172013. /* Scan to the next marker, and repeat the decision loop. */
  172014. if (! next_marker(cinfo))
  172015. return FALSE;
  172016. marker = cinfo->unread_marker;
  172017. break;
  172018. case 3:
  172019. /* Return without advancing past this marker. */
  172020. /* Entropy decoder will be forced to process an empty segment. */
  172021. return TRUE;
  172022. }
  172023. } /* end loop */
  172024. }
  172025. /*
  172026. * Reset marker processing state to begin a fresh datastream.
  172027. */
  172028. METHODDEF(void)
  172029. reset_marker_reader (j_decompress_ptr cinfo)
  172030. {
  172031. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172032. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172033. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172034. cinfo->unread_marker = 0; /* no pending marker */
  172035. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172036. marker->pub.saw_SOF = FALSE;
  172037. marker->pub.discarded_bytes = 0;
  172038. marker->cur_marker = NULL;
  172039. }
  172040. /*
  172041. * Initialize the marker reader module.
  172042. * This is called only once, when the decompression object is created.
  172043. */
  172044. GLOBAL(void)
  172045. jinit_marker_reader (j_decompress_ptr cinfo)
  172046. {
  172047. my_marker_ptr2 marker;
  172048. int i;
  172049. /* Create subobject in permanent pool */
  172050. marker = (my_marker_ptr2)
  172051. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172052. SIZEOF(my_marker_reader));
  172053. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172054. /* Initialize public method pointers */
  172055. marker->pub.reset_marker_reader = reset_marker_reader;
  172056. marker->pub.read_markers = read_markers;
  172057. marker->pub.read_restart_marker = read_restart_marker;
  172058. /* Initialize COM/APPn processing.
  172059. * By default, we examine and then discard APP0 and APP14,
  172060. * but simply discard COM and all other APPn.
  172061. */
  172062. marker->process_COM = skip_variable;
  172063. marker->length_limit_COM = 0;
  172064. for (i = 0; i < 16; i++) {
  172065. marker->process_APPn[i] = skip_variable;
  172066. marker->length_limit_APPn[i] = 0;
  172067. }
  172068. marker->process_APPn[0] = get_interesting_appn;
  172069. marker->process_APPn[14] = get_interesting_appn;
  172070. /* Reset marker processing state */
  172071. reset_marker_reader(cinfo);
  172072. }
  172073. /*
  172074. * Control saving of COM and APPn markers into marker_list.
  172075. */
  172076. #ifdef SAVE_MARKERS_SUPPORTED
  172077. GLOBAL(void)
  172078. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172079. unsigned int length_limit)
  172080. {
  172081. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172082. long maxlength;
  172083. jpeg_marker_parser_method processor;
  172084. /* Length limit mustn't be larger than what we can allocate
  172085. * (should only be a concern in a 16-bit environment).
  172086. */
  172087. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172088. if (((long) length_limit) > maxlength)
  172089. length_limit = (unsigned int) maxlength;
  172090. /* Choose processor routine to use.
  172091. * APP0/APP14 have special requirements.
  172092. */
  172093. if (length_limit) {
  172094. processor = save_marker;
  172095. /* If saving APP0/APP14, save at least enough for our internal use. */
  172096. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172097. length_limit = APP0_DATA_LEN;
  172098. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172099. length_limit = APP14_DATA_LEN;
  172100. } else {
  172101. processor = skip_variable;
  172102. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172103. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172104. processor = get_interesting_appn;
  172105. }
  172106. if (marker_code == (int) M_COM) {
  172107. marker->process_COM = processor;
  172108. marker->length_limit_COM = length_limit;
  172109. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172110. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172111. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172112. } else
  172113. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172114. }
  172115. #endif /* SAVE_MARKERS_SUPPORTED */
  172116. /*
  172117. * Install a special processing method for COM or APPn markers.
  172118. */
  172119. GLOBAL(void)
  172120. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172121. jpeg_marker_parser_method routine)
  172122. {
  172123. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172124. if (marker_code == (int) M_COM)
  172125. marker->process_COM = routine;
  172126. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172127. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172128. else
  172129. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172130. }
  172131. /*** End of inlined file: jdmarker.c ***/
  172132. /*** Start of inlined file: jdmaster.c ***/
  172133. #define JPEG_INTERNALS
  172134. /* Private state */
  172135. typedef struct {
  172136. struct jpeg_decomp_master pub; /* public fields */
  172137. int pass_number; /* # of passes completed */
  172138. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172139. /* Saved references to initialized quantizer modules,
  172140. * in case we need to switch modes.
  172141. */
  172142. struct jpeg_color_quantizer * quantizer_1pass;
  172143. struct jpeg_color_quantizer * quantizer_2pass;
  172144. } my_decomp_master;
  172145. typedef my_decomp_master * my_master_ptr6;
  172146. /*
  172147. * Determine whether merged upsample/color conversion should be used.
  172148. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172149. */
  172150. LOCAL(boolean)
  172151. use_merged_upsample (j_decompress_ptr cinfo)
  172152. {
  172153. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172154. /* Merging is the equivalent of plain box-filter upsampling */
  172155. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172156. return FALSE;
  172157. /* jdmerge.c only supports YCC=>RGB color conversion */
  172158. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172159. cinfo->out_color_space != JCS_RGB ||
  172160. cinfo->out_color_components != RGB_PIXELSIZE)
  172161. return FALSE;
  172162. /* and it only handles 2h1v or 2h2v sampling ratios */
  172163. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172164. cinfo->comp_info[1].h_samp_factor != 1 ||
  172165. cinfo->comp_info[2].h_samp_factor != 1 ||
  172166. cinfo->comp_info[0].v_samp_factor > 2 ||
  172167. cinfo->comp_info[1].v_samp_factor != 1 ||
  172168. cinfo->comp_info[2].v_samp_factor != 1)
  172169. return FALSE;
  172170. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172171. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172172. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172173. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172174. return FALSE;
  172175. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172176. return TRUE; /* by golly, it'll work... */
  172177. #else
  172178. return FALSE;
  172179. #endif
  172180. }
  172181. /*
  172182. * Compute output image dimensions and related values.
  172183. * NOTE: this is exported for possible use by application.
  172184. * Hence it mustn't do anything that can't be done twice.
  172185. * Also note that it may be called before the master module is initialized!
  172186. */
  172187. GLOBAL(void)
  172188. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172189. /* Do computations that are needed before master selection phase */
  172190. {
  172191. #ifdef IDCT_SCALING_SUPPORTED
  172192. int ci;
  172193. jpeg_component_info *compptr;
  172194. #endif
  172195. /* Prevent application from calling me at wrong times */
  172196. if (cinfo->global_state != DSTATE_READY)
  172197. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172198. #ifdef IDCT_SCALING_SUPPORTED
  172199. /* Compute actual output image dimensions and DCT scaling choices. */
  172200. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172201. /* Provide 1/8 scaling */
  172202. cinfo->output_width = (JDIMENSION)
  172203. jdiv_round_up((long) cinfo->image_width, 8L);
  172204. cinfo->output_height = (JDIMENSION)
  172205. jdiv_round_up((long) cinfo->image_height, 8L);
  172206. cinfo->min_DCT_scaled_size = 1;
  172207. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172208. /* Provide 1/4 scaling */
  172209. cinfo->output_width = (JDIMENSION)
  172210. jdiv_round_up((long) cinfo->image_width, 4L);
  172211. cinfo->output_height = (JDIMENSION)
  172212. jdiv_round_up((long) cinfo->image_height, 4L);
  172213. cinfo->min_DCT_scaled_size = 2;
  172214. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172215. /* Provide 1/2 scaling */
  172216. cinfo->output_width = (JDIMENSION)
  172217. jdiv_round_up((long) cinfo->image_width, 2L);
  172218. cinfo->output_height = (JDIMENSION)
  172219. jdiv_round_up((long) cinfo->image_height, 2L);
  172220. cinfo->min_DCT_scaled_size = 4;
  172221. } else {
  172222. /* Provide 1/1 scaling */
  172223. cinfo->output_width = cinfo->image_width;
  172224. cinfo->output_height = cinfo->image_height;
  172225. cinfo->min_DCT_scaled_size = DCTSIZE;
  172226. }
  172227. /* In selecting the actual DCT scaling for each component, we try to
  172228. * scale up the chroma components via IDCT scaling rather than upsampling.
  172229. * This saves time if the upsampler gets to use 1:1 scaling.
  172230. * Note this code assumes that the supported DCT scalings are powers of 2.
  172231. */
  172232. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172233. ci++, compptr++) {
  172234. int ssize = cinfo->min_DCT_scaled_size;
  172235. while (ssize < DCTSIZE &&
  172236. (compptr->h_samp_factor * ssize * 2 <=
  172237. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172238. (compptr->v_samp_factor * ssize * 2 <=
  172239. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172240. ssize = ssize * 2;
  172241. }
  172242. compptr->DCT_scaled_size = ssize;
  172243. }
  172244. /* Recompute downsampled dimensions of components;
  172245. * application needs to know these if using raw downsampled data.
  172246. */
  172247. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172248. ci++, compptr++) {
  172249. /* Size in samples, after IDCT scaling */
  172250. compptr->downsampled_width = (JDIMENSION)
  172251. jdiv_round_up((long) cinfo->image_width *
  172252. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172253. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172254. compptr->downsampled_height = (JDIMENSION)
  172255. jdiv_round_up((long) cinfo->image_height *
  172256. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172257. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172258. }
  172259. #else /* !IDCT_SCALING_SUPPORTED */
  172260. /* Hardwire it to "no scaling" */
  172261. cinfo->output_width = cinfo->image_width;
  172262. cinfo->output_height = cinfo->image_height;
  172263. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172264. * and has computed unscaled downsampled_width and downsampled_height.
  172265. */
  172266. #endif /* IDCT_SCALING_SUPPORTED */
  172267. /* Report number of components in selected colorspace. */
  172268. /* Probably this should be in the color conversion module... */
  172269. switch (cinfo->out_color_space) {
  172270. case JCS_GRAYSCALE:
  172271. cinfo->out_color_components = 1;
  172272. break;
  172273. case JCS_RGB:
  172274. #if RGB_PIXELSIZE != 3
  172275. cinfo->out_color_components = RGB_PIXELSIZE;
  172276. break;
  172277. #endif /* else share code with YCbCr */
  172278. case JCS_YCbCr:
  172279. cinfo->out_color_components = 3;
  172280. break;
  172281. case JCS_CMYK:
  172282. case JCS_YCCK:
  172283. cinfo->out_color_components = 4;
  172284. break;
  172285. default: /* else must be same colorspace as in file */
  172286. cinfo->out_color_components = cinfo->num_components;
  172287. break;
  172288. }
  172289. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172290. cinfo->out_color_components);
  172291. /* See if upsampler will want to emit more than one row at a time */
  172292. if (use_merged_upsample(cinfo))
  172293. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172294. else
  172295. cinfo->rec_outbuf_height = 1;
  172296. }
  172297. /*
  172298. * Several decompression processes need to range-limit values to the range
  172299. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172300. * due to noise introduced by quantization, roundoff error, etc. These
  172301. * processes are inner loops and need to be as fast as possible. On most
  172302. * machines, particularly CPUs with pipelines or instruction prefetch,
  172303. * a (subscript-check-less) C table lookup
  172304. * x = sample_range_limit[x];
  172305. * is faster than explicit tests
  172306. * if (x < 0) x = 0;
  172307. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172308. * These processes all use a common table prepared by the routine below.
  172309. *
  172310. * For most steps we can mathematically guarantee that the initial value
  172311. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172312. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172313. * limiting step (just after the IDCT), a wildly out-of-range value is
  172314. * possible if the input data is corrupt. To avoid any chance of indexing
  172315. * off the end of memory and getting a bad-pointer trap, we perform the
  172316. * post-IDCT limiting thus:
  172317. * x = range_limit[x & MASK];
  172318. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172319. * samples. Under normal circumstances this is more than enough range and
  172320. * a correct output will be generated; with bogus input data the mask will
  172321. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172322. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172323. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172324. * So the post-IDCT limiting table ends up looking like this:
  172325. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172326. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172327. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172328. * 0,1,...,CENTERJSAMPLE-1
  172329. * Negative inputs select values from the upper half of the table after
  172330. * masking.
  172331. *
  172332. * We can save some space by overlapping the start of the post-IDCT table
  172333. * with the simpler range limiting table. The post-IDCT table begins at
  172334. * sample_range_limit + CENTERJSAMPLE.
  172335. *
  172336. * Note that the table is allocated in near data space on PCs; it's small
  172337. * enough and used often enough to justify this.
  172338. */
  172339. LOCAL(void)
  172340. prepare_range_limit_table (j_decompress_ptr cinfo)
  172341. /* Allocate and fill in the sample_range_limit table */
  172342. {
  172343. JSAMPLE * table;
  172344. int i;
  172345. table = (JSAMPLE *)
  172346. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172347. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172348. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172349. cinfo->sample_range_limit = table;
  172350. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172351. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172352. /* Main part of "simple" table: limit[x] = x */
  172353. for (i = 0; i <= MAXJSAMPLE; i++)
  172354. table[i] = (JSAMPLE) i;
  172355. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172356. /* End of simple table, rest of first half of post-IDCT table */
  172357. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172358. table[i] = MAXJSAMPLE;
  172359. /* Second half of post-IDCT table */
  172360. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172361. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172362. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172363. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172364. }
  172365. /*
  172366. * Master selection of decompression modules.
  172367. * This is done once at jpeg_start_decompress time. We determine
  172368. * which modules will be used and give them appropriate initialization calls.
  172369. * We also initialize the decompressor input side to begin consuming data.
  172370. *
  172371. * Since jpeg_read_header has finished, we know what is in the SOF
  172372. * and (first) SOS markers. We also have all the application parameter
  172373. * settings.
  172374. */
  172375. LOCAL(void)
  172376. master_selection (j_decompress_ptr cinfo)
  172377. {
  172378. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172379. boolean use_c_buffer;
  172380. long samplesperrow;
  172381. JDIMENSION jd_samplesperrow;
  172382. /* Initialize dimensions and other stuff */
  172383. jpeg_calc_output_dimensions(cinfo);
  172384. prepare_range_limit_table(cinfo);
  172385. /* Width of an output scanline must be representable as JDIMENSION. */
  172386. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172387. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172388. if ((long) jd_samplesperrow != samplesperrow)
  172389. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172390. /* Initialize my private state */
  172391. master->pass_number = 0;
  172392. master->using_merged_upsample = use_merged_upsample(cinfo);
  172393. /* Color quantizer selection */
  172394. master->quantizer_1pass = NULL;
  172395. master->quantizer_2pass = NULL;
  172396. /* No mode changes if not using buffered-image mode. */
  172397. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172398. cinfo->enable_1pass_quant = FALSE;
  172399. cinfo->enable_external_quant = FALSE;
  172400. cinfo->enable_2pass_quant = FALSE;
  172401. }
  172402. if (cinfo->quantize_colors) {
  172403. if (cinfo->raw_data_out)
  172404. ERREXIT(cinfo, JERR_NOTIMPL);
  172405. /* 2-pass quantizer only works in 3-component color space. */
  172406. if (cinfo->out_color_components != 3) {
  172407. cinfo->enable_1pass_quant = TRUE;
  172408. cinfo->enable_external_quant = FALSE;
  172409. cinfo->enable_2pass_quant = FALSE;
  172410. cinfo->colormap = NULL;
  172411. } else if (cinfo->colormap != NULL) {
  172412. cinfo->enable_external_quant = TRUE;
  172413. } else if (cinfo->two_pass_quantize) {
  172414. cinfo->enable_2pass_quant = TRUE;
  172415. } else {
  172416. cinfo->enable_1pass_quant = TRUE;
  172417. }
  172418. if (cinfo->enable_1pass_quant) {
  172419. #ifdef QUANT_1PASS_SUPPORTED
  172420. jinit_1pass_quantizer(cinfo);
  172421. master->quantizer_1pass = cinfo->cquantize;
  172422. #else
  172423. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172424. #endif
  172425. }
  172426. /* We use the 2-pass code to map to external colormaps. */
  172427. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172428. #ifdef QUANT_2PASS_SUPPORTED
  172429. jinit_2pass_quantizer(cinfo);
  172430. master->quantizer_2pass = cinfo->cquantize;
  172431. #else
  172432. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172433. #endif
  172434. }
  172435. /* If both quantizers are initialized, the 2-pass one is left active;
  172436. * this is necessary for starting with quantization to an external map.
  172437. */
  172438. }
  172439. /* Post-processing: in particular, color conversion first */
  172440. if (! cinfo->raw_data_out) {
  172441. if (master->using_merged_upsample) {
  172442. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172443. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172444. #else
  172445. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172446. #endif
  172447. } else {
  172448. jinit_color_deconverter(cinfo);
  172449. jinit_upsampler(cinfo);
  172450. }
  172451. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172452. }
  172453. /* Inverse DCT */
  172454. jinit_inverse_dct(cinfo);
  172455. /* Entropy decoding: either Huffman or arithmetic coding. */
  172456. if (cinfo->arith_code) {
  172457. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172458. } else {
  172459. if (cinfo->progressive_mode) {
  172460. #ifdef D_PROGRESSIVE_SUPPORTED
  172461. jinit_phuff_decoder(cinfo);
  172462. #else
  172463. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172464. #endif
  172465. } else
  172466. jinit_huff_decoder(cinfo);
  172467. }
  172468. /* Initialize principal buffer controllers. */
  172469. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172470. jinit_d_coef_controller(cinfo, use_c_buffer);
  172471. if (! cinfo->raw_data_out)
  172472. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172473. /* We can now tell the memory manager to allocate virtual arrays. */
  172474. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172475. /* Initialize input side of decompressor to consume first scan. */
  172476. (*cinfo->inputctl->start_input_pass) (cinfo);
  172477. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172478. /* If jpeg_start_decompress will read the whole file, initialize
  172479. * progress monitoring appropriately. The input step is counted
  172480. * as one pass.
  172481. */
  172482. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172483. cinfo->inputctl->has_multiple_scans) {
  172484. int nscans;
  172485. /* Estimate number of scans to set pass_limit. */
  172486. if (cinfo->progressive_mode) {
  172487. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172488. nscans = 2 + 3 * cinfo->num_components;
  172489. } else {
  172490. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172491. nscans = cinfo->num_components;
  172492. }
  172493. cinfo->progress->pass_counter = 0L;
  172494. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172495. cinfo->progress->completed_passes = 0;
  172496. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172497. /* Count the input pass as done */
  172498. master->pass_number++;
  172499. }
  172500. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172501. }
  172502. /*
  172503. * Per-pass setup.
  172504. * This is called at the beginning of each output pass. We determine which
  172505. * modules will be active during this pass and give them appropriate
  172506. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172507. * is a "real" output pass or a dummy pass for color quantization.
  172508. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172509. */
  172510. METHODDEF(void)
  172511. prepare_for_output_pass (j_decompress_ptr cinfo)
  172512. {
  172513. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172514. if (master->pub.is_dummy_pass) {
  172515. #ifdef QUANT_2PASS_SUPPORTED
  172516. /* Final pass of 2-pass quantization */
  172517. master->pub.is_dummy_pass = FALSE;
  172518. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172519. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172520. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172521. #else
  172522. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172523. #endif /* QUANT_2PASS_SUPPORTED */
  172524. } else {
  172525. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172526. /* Select new quantization method */
  172527. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172528. cinfo->cquantize = master->quantizer_2pass;
  172529. master->pub.is_dummy_pass = TRUE;
  172530. } else if (cinfo->enable_1pass_quant) {
  172531. cinfo->cquantize = master->quantizer_1pass;
  172532. } else {
  172533. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172534. }
  172535. }
  172536. (*cinfo->idct->start_pass) (cinfo);
  172537. (*cinfo->coef->start_output_pass) (cinfo);
  172538. if (! cinfo->raw_data_out) {
  172539. if (! master->using_merged_upsample)
  172540. (*cinfo->cconvert->start_pass) (cinfo);
  172541. (*cinfo->upsample->start_pass) (cinfo);
  172542. if (cinfo->quantize_colors)
  172543. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172544. (*cinfo->post->start_pass) (cinfo,
  172545. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172546. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172547. }
  172548. }
  172549. /* Set up progress monitor's pass info if present */
  172550. if (cinfo->progress != NULL) {
  172551. cinfo->progress->completed_passes = master->pass_number;
  172552. cinfo->progress->total_passes = master->pass_number +
  172553. (master->pub.is_dummy_pass ? 2 : 1);
  172554. /* In buffered-image mode, we assume one more output pass if EOI not
  172555. * yet reached, but no more passes if EOI has been reached.
  172556. */
  172557. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172558. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172559. }
  172560. }
  172561. }
  172562. /*
  172563. * Finish up at end of an output pass.
  172564. */
  172565. METHODDEF(void)
  172566. finish_output_pass (j_decompress_ptr cinfo)
  172567. {
  172568. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172569. if (cinfo->quantize_colors)
  172570. (*cinfo->cquantize->finish_pass) (cinfo);
  172571. master->pass_number++;
  172572. }
  172573. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172574. /*
  172575. * Switch to a new external colormap between output passes.
  172576. */
  172577. GLOBAL(void)
  172578. jpeg_new_colormap (j_decompress_ptr cinfo)
  172579. {
  172580. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172581. /* Prevent application from calling me at wrong times */
  172582. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172583. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172584. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172585. cinfo->colormap != NULL) {
  172586. /* Select 2-pass quantizer for external colormap use */
  172587. cinfo->cquantize = master->quantizer_2pass;
  172588. /* Notify quantizer of colormap change */
  172589. (*cinfo->cquantize->new_color_map) (cinfo);
  172590. master->pub.is_dummy_pass = FALSE; /* just in case */
  172591. } else
  172592. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172593. }
  172594. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172595. /*
  172596. * Initialize master decompression control and select active modules.
  172597. * This is performed at the start of jpeg_start_decompress.
  172598. */
  172599. GLOBAL(void)
  172600. jinit_master_decompress (j_decompress_ptr cinfo)
  172601. {
  172602. my_master_ptr6 master;
  172603. master = (my_master_ptr6)
  172604. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172605. SIZEOF(my_decomp_master));
  172606. cinfo->master = (struct jpeg_decomp_master *) master;
  172607. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172608. master->pub.finish_output_pass = finish_output_pass;
  172609. master->pub.is_dummy_pass = FALSE;
  172610. master_selection(cinfo);
  172611. }
  172612. /*** End of inlined file: jdmaster.c ***/
  172613. #undef FIX
  172614. /*** Start of inlined file: jdmerge.c ***/
  172615. #define JPEG_INTERNALS
  172616. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172617. /* Private subobject */
  172618. typedef struct {
  172619. struct jpeg_upsampler pub; /* public fields */
  172620. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172621. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172622. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172623. JSAMPARRAY output_buf));
  172624. /* Private state for YCC->RGB conversion */
  172625. int * Cr_r_tab; /* => table for Cr to R conversion */
  172626. int * Cb_b_tab; /* => table for Cb to B conversion */
  172627. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172628. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172629. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172630. * We need a "spare" row buffer to hold the second output row if the
  172631. * application provides just a one-row buffer; we also use the spare
  172632. * to discard the dummy last row if the image height is odd.
  172633. */
  172634. JSAMPROW spare_row;
  172635. boolean spare_full; /* T if spare buffer is occupied */
  172636. JDIMENSION out_row_width; /* samples per output row */
  172637. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172638. } my_upsampler;
  172639. typedef my_upsampler * my_upsample_ptr;
  172640. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172641. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172642. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172643. /*
  172644. * Initialize tables for YCC->RGB colorspace conversion.
  172645. * This is taken directly from jdcolor.c; see that file for more info.
  172646. */
  172647. LOCAL(void)
  172648. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172649. {
  172650. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172651. int i;
  172652. INT32 x;
  172653. SHIFT_TEMPS
  172654. upsample->Cr_r_tab = (int *)
  172655. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172656. (MAXJSAMPLE+1) * SIZEOF(int));
  172657. upsample->Cb_b_tab = (int *)
  172658. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172659. (MAXJSAMPLE+1) * SIZEOF(int));
  172660. upsample->Cr_g_tab = (INT32 *)
  172661. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172662. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172663. upsample->Cb_g_tab = (INT32 *)
  172664. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172665. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172666. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172667. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172668. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172669. /* Cr=>R value is nearest int to 1.40200 * x */
  172670. upsample->Cr_r_tab[i] = (int)
  172671. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172672. /* Cb=>B value is nearest int to 1.77200 * x */
  172673. upsample->Cb_b_tab[i] = (int)
  172674. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172675. /* Cr=>G value is scaled-up -0.71414 * x */
  172676. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172677. /* Cb=>G value is scaled-up -0.34414 * x */
  172678. /* We also add in ONE_HALF so that need not do it in inner loop */
  172679. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172680. }
  172681. }
  172682. /*
  172683. * Initialize for an upsampling pass.
  172684. */
  172685. METHODDEF(void)
  172686. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172687. {
  172688. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172689. /* Mark the spare buffer empty */
  172690. upsample->spare_full = FALSE;
  172691. /* Initialize total-height counter for detecting bottom of image */
  172692. upsample->rows_to_go = cinfo->output_height;
  172693. }
  172694. /*
  172695. * Control routine to do upsampling (and color conversion).
  172696. *
  172697. * The control routine just handles the row buffering considerations.
  172698. */
  172699. METHODDEF(void)
  172700. merged_2v_upsample (j_decompress_ptr cinfo,
  172701. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172702. JDIMENSION,
  172703. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172704. JDIMENSION out_rows_avail)
  172705. /* 2:1 vertical sampling case: may need a spare row. */
  172706. {
  172707. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172708. JSAMPROW work_ptrs[2];
  172709. JDIMENSION num_rows; /* number of rows returned to caller */
  172710. if (upsample->spare_full) {
  172711. /* If we have a spare row saved from a previous cycle, just return it. */
  172712. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172713. 1, upsample->out_row_width);
  172714. num_rows = 1;
  172715. upsample->spare_full = FALSE;
  172716. } else {
  172717. /* Figure number of rows to return to caller. */
  172718. num_rows = 2;
  172719. /* Not more than the distance to the end of the image. */
  172720. if (num_rows > upsample->rows_to_go)
  172721. num_rows = upsample->rows_to_go;
  172722. /* And not more than what the client can accept: */
  172723. out_rows_avail -= *out_row_ctr;
  172724. if (num_rows > out_rows_avail)
  172725. num_rows = out_rows_avail;
  172726. /* Create output pointer array for upsampler. */
  172727. work_ptrs[0] = output_buf[*out_row_ctr];
  172728. if (num_rows > 1) {
  172729. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172730. } else {
  172731. work_ptrs[1] = upsample->spare_row;
  172732. upsample->spare_full = TRUE;
  172733. }
  172734. /* Now do the upsampling. */
  172735. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172736. }
  172737. /* Adjust counts */
  172738. *out_row_ctr += num_rows;
  172739. upsample->rows_to_go -= num_rows;
  172740. /* When the buffer is emptied, declare this input row group consumed */
  172741. if (! upsample->spare_full)
  172742. (*in_row_group_ctr)++;
  172743. }
  172744. METHODDEF(void)
  172745. merged_1v_upsample (j_decompress_ptr cinfo,
  172746. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172747. JDIMENSION,
  172748. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172749. JDIMENSION)
  172750. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172751. {
  172752. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172753. /* Just do the upsampling. */
  172754. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172755. output_buf + *out_row_ctr);
  172756. /* Adjust counts */
  172757. (*out_row_ctr)++;
  172758. (*in_row_group_ctr)++;
  172759. }
  172760. /*
  172761. * These are the routines invoked by the control routines to do
  172762. * the actual upsampling/conversion. One row group is processed per call.
  172763. *
  172764. * Note: since we may be writing directly into application-supplied buffers,
  172765. * we have to be honest about the output width; we can't assume the buffer
  172766. * has been rounded up to an even width.
  172767. */
  172768. /*
  172769. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172770. */
  172771. METHODDEF(void)
  172772. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172773. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172774. JSAMPARRAY output_buf)
  172775. {
  172776. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172777. register int y, cred, cgreen, cblue;
  172778. int cb, cr;
  172779. register JSAMPROW outptr;
  172780. JSAMPROW inptr0, inptr1, inptr2;
  172781. JDIMENSION col;
  172782. /* copy these pointers into registers if possible */
  172783. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172784. int * Crrtab = upsample->Cr_r_tab;
  172785. int * Cbbtab = upsample->Cb_b_tab;
  172786. INT32 * Crgtab = upsample->Cr_g_tab;
  172787. INT32 * Cbgtab = upsample->Cb_g_tab;
  172788. SHIFT_TEMPS
  172789. inptr0 = input_buf[0][in_row_group_ctr];
  172790. inptr1 = input_buf[1][in_row_group_ctr];
  172791. inptr2 = input_buf[2][in_row_group_ctr];
  172792. outptr = output_buf[0];
  172793. /* Loop for each pair of output pixels */
  172794. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172795. /* Do the chroma part of the calculation */
  172796. cb = GETJSAMPLE(*inptr1++);
  172797. cr = GETJSAMPLE(*inptr2++);
  172798. cred = Crrtab[cr];
  172799. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172800. cblue = Cbbtab[cb];
  172801. /* Fetch 2 Y values and emit 2 pixels */
  172802. y = GETJSAMPLE(*inptr0++);
  172803. outptr[RGB_RED] = range_limit[y + cred];
  172804. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172805. outptr[RGB_BLUE] = range_limit[y + cblue];
  172806. outptr += RGB_PIXELSIZE;
  172807. y = GETJSAMPLE(*inptr0++);
  172808. outptr[RGB_RED] = range_limit[y + cred];
  172809. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172810. outptr[RGB_BLUE] = range_limit[y + cblue];
  172811. outptr += RGB_PIXELSIZE;
  172812. }
  172813. /* If image width is odd, do the last output column separately */
  172814. if (cinfo->output_width & 1) {
  172815. cb = GETJSAMPLE(*inptr1);
  172816. cr = GETJSAMPLE(*inptr2);
  172817. cred = Crrtab[cr];
  172818. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172819. cblue = Cbbtab[cb];
  172820. y = GETJSAMPLE(*inptr0);
  172821. outptr[RGB_RED] = range_limit[y + cred];
  172822. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172823. outptr[RGB_BLUE] = range_limit[y + cblue];
  172824. }
  172825. }
  172826. /*
  172827. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172828. */
  172829. METHODDEF(void)
  172830. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172831. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172832. JSAMPARRAY output_buf)
  172833. {
  172834. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172835. register int y, cred, cgreen, cblue;
  172836. int cb, cr;
  172837. register JSAMPROW outptr0, outptr1;
  172838. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172839. JDIMENSION col;
  172840. /* copy these pointers into registers if possible */
  172841. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172842. int * Crrtab = upsample->Cr_r_tab;
  172843. int * Cbbtab = upsample->Cb_b_tab;
  172844. INT32 * Crgtab = upsample->Cr_g_tab;
  172845. INT32 * Cbgtab = upsample->Cb_g_tab;
  172846. SHIFT_TEMPS
  172847. inptr00 = input_buf[0][in_row_group_ctr*2];
  172848. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172849. inptr1 = input_buf[1][in_row_group_ctr];
  172850. inptr2 = input_buf[2][in_row_group_ctr];
  172851. outptr0 = output_buf[0];
  172852. outptr1 = output_buf[1];
  172853. /* Loop for each group of output pixels */
  172854. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172855. /* Do the chroma part of the calculation */
  172856. cb = GETJSAMPLE(*inptr1++);
  172857. cr = GETJSAMPLE(*inptr2++);
  172858. cred = Crrtab[cr];
  172859. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172860. cblue = Cbbtab[cb];
  172861. /* Fetch 4 Y values and emit 4 pixels */
  172862. y = GETJSAMPLE(*inptr00++);
  172863. outptr0[RGB_RED] = range_limit[y + cred];
  172864. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172865. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172866. outptr0 += RGB_PIXELSIZE;
  172867. y = GETJSAMPLE(*inptr00++);
  172868. outptr0[RGB_RED] = range_limit[y + cred];
  172869. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172870. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172871. outptr0 += RGB_PIXELSIZE;
  172872. y = GETJSAMPLE(*inptr01++);
  172873. outptr1[RGB_RED] = range_limit[y + cred];
  172874. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172875. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172876. outptr1 += RGB_PIXELSIZE;
  172877. y = GETJSAMPLE(*inptr01++);
  172878. outptr1[RGB_RED] = range_limit[y + cred];
  172879. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172880. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172881. outptr1 += RGB_PIXELSIZE;
  172882. }
  172883. /* If image width is odd, do the last output column separately */
  172884. if (cinfo->output_width & 1) {
  172885. cb = GETJSAMPLE(*inptr1);
  172886. cr = GETJSAMPLE(*inptr2);
  172887. cred = Crrtab[cr];
  172888. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172889. cblue = Cbbtab[cb];
  172890. y = GETJSAMPLE(*inptr00);
  172891. outptr0[RGB_RED] = range_limit[y + cred];
  172892. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172893. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172894. y = GETJSAMPLE(*inptr01);
  172895. outptr1[RGB_RED] = range_limit[y + cred];
  172896. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172897. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172898. }
  172899. }
  172900. /*
  172901. * Module initialization routine for merged upsampling/color conversion.
  172902. *
  172903. * NB: this is called under the conditions determined by use_merged_upsample()
  172904. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172905. * of this module; no safety checks are made here.
  172906. */
  172907. GLOBAL(void)
  172908. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172909. {
  172910. my_upsample_ptr upsample;
  172911. upsample = (my_upsample_ptr)
  172912. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172913. SIZEOF(my_upsampler));
  172914. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172915. upsample->pub.start_pass = start_pass_merged_upsample;
  172916. upsample->pub.need_context_rows = FALSE;
  172917. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172918. if (cinfo->max_v_samp_factor == 2) {
  172919. upsample->pub.upsample = merged_2v_upsample;
  172920. upsample->upmethod = h2v2_merged_upsample;
  172921. /* Allocate a spare row buffer */
  172922. upsample->spare_row = (JSAMPROW)
  172923. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172924. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172925. } else {
  172926. upsample->pub.upsample = merged_1v_upsample;
  172927. upsample->upmethod = h2v1_merged_upsample;
  172928. /* No spare row needed */
  172929. upsample->spare_row = NULL;
  172930. }
  172931. build_ycc_rgb_table2(cinfo);
  172932. }
  172933. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172934. /*** End of inlined file: jdmerge.c ***/
  172935. #undef ASSIGN_STATE
  172936. /*** Start of inlined file: jdphuff.c ***/
  172937. #define JPEG_INTERNALS
  172938. #ifdef D_PROGRESSIVE_SUPPORTED
  172939. /*
  172940. * Expanded entropy decoder object for progressive Huffman decoding.
  172941. *
  172942. * The savable_state subrecord contains fields that change within an MCU,
  172943. * but must not be updated permanently until we complete the MCU.
  172944. */
  172945. typedef struct {
  172946. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172947. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172948. } savable_state3;
  172949. /* This macro is to work around compilers with missing or broken
  172950. * structure assignment. You'll need to fix this code if you have
  172951. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172952. */
  172953. #ifndef NO_STRUCT_ASSIGN
  172954. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172955. #else
  172956. #if MAX_COMPS_IN_SCAN == 4
  172957. #define ASSIGN_STATE(dest,src) \
  172958. ((dest).EOBRUN = (src).EOBRUN, \
  172959. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172960. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172961. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172962. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172963. #endif
  172964. #endif
  172965. typedef struct {
  172966. struct jpeg_entropy_decoder pub; /* public fields */
  172967. /* These fields are loaded into local variables at start of each MCU.
  172968. * In case of suspension, we exit WITHOUT updating them.
  172969. */
  172970. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172971. savable_state3 saved; /* Other state at start of MCU */
  172972. /* These fields are NOT loaded into local working state. */
  172973. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172974. /* Pointers to derived tables (these workspaces have image lifespan) */
  172975. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172976. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172977. } phuff_entropy_decoder;
  172978. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172979. /* Forward declarations */
  172980. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172981. JBLOCKROW *MCU_data));
  172982. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172983. JBLOCKROW *MCU_data));
  172984. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172985. JBLOCKROW *MCU_data));
  172986. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172987. JBLOCKROW *MCU_data));
  172988. /*
  172989. * Initialize for a Huffman-compressed scan.
  172990. */
  172991. METHODDEF(void)
  172992. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172993. {
  172994. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172995. boolean is_DC_band, bad;
  172996. int ci, coefi, tbl;
  172997. int *coef_bit_ptr;
  172998. jpeg_component_info * compptr;
  172999. is_DC_band = (cinfo->Ss == 0);
  173000. /* Validate scan parameters */
  173001. bad = FALSE;
  173002. if (is_DC_band) {
  173003. if (cinfo->Se != 0)
  173004. bad = TRUE;
  173005. } else {
  173006. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173007. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173008. bad = TRUE;
  173009. /* AC scans may have only one component */
  173010. if (cinfo->comps_in_scan != 1)
  173011. bad = TRUE;
  173012. }
  173013. if (cinfo->Ah != 0) {
  173014. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173015. if (cinfo->Al != cinfo->Ah-1)
  173016. bad = TRUE;
  173017. }
  173018. if (cinfo->Al > 13) /* need not check for < 0 */
  173019. bad = TRUE;
  173020. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173021. * but the spec doesn't say so, and we try to be liberal about what we
  173022. * accept. Note: large Al values could result in out-of-range DC
  173023. * coefficients during early scans, leading to bizarre displays due to
  173024. * overflows in the IDCT math. But we won't crash.
  173025. */
  173026. if (bad)
  173027. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173028. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173029. /* Update progression status, and verify that scan order is legal.
  173030. * Note that inter-scan inconsistencies are treated as warnings
  173031. * not fatal errors ... not clear if this is right way to behave.
  173032. */
  173033. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173034. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173035. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173036. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173037. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173038. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173039. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173040. if (cinfo->Ah != expected)
  173041. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173042. coef_bit_ptr[coefi] = cinfo->Al;
  173043. }
  173044. }
  173045. /* Select MCU decoding routine */
  173046. if (cinfo->Ah == 0) {
  173047. if (is_DC_band)
  173048. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173049. else
  173050. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173051. } else {
  173052. if (is_DC_band)
  173053. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173054. else
  173055. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173056. }
  173057. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173058. compptr = cinfo->cur_comp_info[ci];
  173059. /* Make sure requested tables are present, and compute derived tables.
  173060. * We may build same derived table more than once, but it's not expensive.
  173061. */
  173062. if (is_DC_band) {
  173063. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173064. tbl = compptr->dc_tbl_no;
  173065. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173066. & entropy->derived_tbls[tbl]);
  173067. }
  173068. } else {
  173069. tbl = compptr->ac_tbl_no;
  173070. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173071. & entropy->derived_tbls[tbl]);
  173072. /* remember the single active table */
  173073. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173074. }
  173075. /* Initialize DC predictions to 0 */
  173076. entropy->saved.last_dc_val[ci] = 0;
  173077. }
  173078. /* Initialize bitread state variables */
  173079. entropy->bitstate.bits_left = 0;
  173080. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173081. entropy->pub.insufficient_data = FALSE;
  173082. /* Initialize private state variables */
  173083. entropy->saved.EOBRUN = 0;
  173084. /* Initialize restart counter */
  173085. entropy->restarts_to_go = cinfo->restart_interval;
  173086. }
  173087. /*
  173088. * Check for a restart marker & resynchronize decoder.
  173089. * Returns FALSE if must suspend.
  173090. */
  173091. LOCAL(boolean)
  173092. process_restartp (j_decompress_ptr cinfo)
  173093. {
  173094. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173095. int ci;
  173096. /* Throw away any unused bits remaining in bit buffer; */
  173097. /* include any full bytes in next_marker's count of discarded bytes */
  173098. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173099. entropy->bitstate.bits_left = 0;
  173100. /* Advance past the RSTn marker */
  173101. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173102. return FALSE;
  173103. /* Re-initialize DC predictions to 0 */
  173104. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173105. entropy->saved.last_dc_val[ci] = 0;
  173106. /* Re-init EOB run count, too */
  173107. entropy->saved.EOBRUN = 0;
  173108. /* Reset restart counter */
  173109. entropy->restarts_to_go = cinfo->restart_interval;
  173110. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173111. * against a marker. In that case we will end up treating the next data
  173112. * segment as empty, and we can avoid producing bogus output pixels by
  173113. * leaving the flag set.
  173114. */
  173115. if (cinfo->unread_marker == 0)
  173116. entropy->pub.insufficient_data = FALSE;
  173117. return TRUE;
  173118. }
  173119. /*
  173120. * Huffman MCU decoding.
  173121. * Each of these routines decodes and returns one MCU's worth of
  173122. * Huffman-compressed coefficients.
  173123. * The coefficients are reordered from zigzag order into natural array order,
  173124. * but are not dequantized.
  173125. *
  173126. * The i'th block of the MCU is stored into the block pointed to by
  173127. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173128. *
  173129. * We return FALSE if data source requested suspension. In that case no
  173130. * changes have been made to permanent state. (Exception: some output
  173131. * coefficients may already have been assigned. This is harmless for
  173132. * spectral selection, since we'll just re-assign them on the next call.
  173133. * Successive approximation AC refinement has to be more careful, however.)
  173134. */
  173135. /*
  173136. * MCU decoding for DC initial scan (either spectral selection,
  173137. * or first pass of successive approximation).
  173138. */
  173139. METHODDEF(boolean)
  173140. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173141. {
  173142. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173143. int Al = cinfo->Al;
  173144. register int s, r;
  173145. int blkn, ci;
  173146. JBLOCKROW block;
  173147. BITREAD_STATE_VARS;
  173148. savable_state3 state;
  173149. d_derived_tbl * tbl;
  173150. jpeg_component_info * compptr;
  173151. /* Process restart marker if needed; may have to suspend */
  173152. if (cinfo->restart_interval) {
  173153. if (entropy->restarts_to_go == 0)
  173154. if (! process_restartp(cinfo))
  173155. return FALSE;
  173156. }
  173157. /* If we've run out of data, just leave the MCU set to zeroes.
  173158. * This way, we return uniform gray for the remainder of the segment.
  173159. */
  173160. if (! entropy->pub.insufficient_data) {
  173161. /* Load up working state */
  173162. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173163. ASSIGN_STATE(state, entropy->saved);
  173164. /* Outer loop handles each block in the MCU */
  173165. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173166. block = MCU_data[blkn];
  173167. ci = cinfo->MCU_membership[blkn];
  173168. compptr = cinfo->cur_comp_info[ci];
  173169. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173170. /* Decode a single block's worth of coefficients */
  173171. /* Section F.2.2.1: decode the DC coefficient difference */
  173172. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173173. if (s) {
  173174. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173175. r = GET_BITS(s);
  173176. s = HUFF_EXTEND(r, s);
  173177. }
  173178. /* Convert DC difference to actual value, update last_dc_val */
  173179. s += state.last_dc_val[ci];
  173180. state.last_dc_val[ci] = s;
  173181. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173182. (*block)[0] = (JCOEF) (s << Al);
  173183. }
  173184. /* Completed MCU, so update state */
  173185. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173186. ASSIGN_STATE(entropy->saved, state);
  173187. }
  173188. /* Account for restart interval (no-op if not using restarts) */
  173189. entropy->restarts_to_go--;
  173190. return TRUE;
  173191. }
  173192. /*
  173193. * MCU decoding for AC initial scan (either spectral selection,
  173194. * or first pass of successive approximation).
  173195. */
  173196. METHODDEF(boolean)
  173197. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173198. {
  173199. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173200. int Se = cinfo->Se;
  173201. int Al = cinfo->Al;
  173202. register int s, k, r;
  173203. unsigned int EOBRUN;
  173204. JBLOCKROW block;
  173205. BITREAD_STATE_VARS;
  173206. d_derived_tbl * tbl;
  173207. /* Process restart marker if needed; may have to suspend */
  173208. if (cinfo->restart_interval) {
  173209. if (entropy->restarts_to_go == 0)
  173210. if (! process_restartp(cinfo))
  173211. return FALSE;
  173212. }
  173213. /* If we've run out of data, just leave the MCU set to zeroes.
  173214. * This way, we return uniform gray for the remainder of the segment.
  173215. */
  173216. if (! entropy->pub.insufficient_data) {
  173217. /* Load up working state.
  173218. * We can avoid loading/saving bitread state if in an EOB run.
  173219. */
  173220. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173221. /* There is always only one block per MCU */
  173222. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173223. EOBRUN--; /* ...process it now (we do nothing) */
  173224. else {
  173225. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173226. block = MCU_data[0];
  173227. tbl = entropy->ac_derived_tbl;
  173228. for (k = cinfo->Ss; k <= Se; k++) {
  173229. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173230. r = s >> 4;
  173231. s &= 15;
  173232. if (s) {
  173233. k += r;
  173234. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173235. r = GET_BITS(s);
  173236. s = HUFF_EXTEND(r, s);
  173237. /* Scale and output coefficient in natural (dezigzagged) order */
  173238. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173239. } else {
  173240. if (r == 15) { /* ZRL */
  173241. k += 15; /* skip 15 zeroes in band */
  173242. } else { /* EOBr, run length is 2^r + appended bits */
  173243. EOBRUN = 1 << r;
  173244. if (r) { /* EOBr, r > 0 */
  173245. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173246. r = GET_BITS(r);
  173247. EOBRUN += r;
  173248. }
  173249. EOBRUN--; /* this band is processed at this moment */
  173250. break; /* force end-of-band */
  173251. }
  173252. }
  173253. }
  173254. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173255. }
  173256. /* Completed MCU, so update state */
  173257. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173258. }
  173259. /* Account for restart interval (no-op if not using restarts) */
  173260. entropy->restarts_to_go--;
  173261. return TRUE;
  173262. }
  173263. /*
  173264. * MCU decoding for DC successive approximation refinement scan.
  173265. * Note: we assume such scans can be multi-component, although the spec
  173266. * is not very clear on the point.
  173267. */
  173268. METHODDEF(boolean)
  173269. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173270. {
  173271. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173272. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173273. int blkn;
  173274. JBLOCKROW block;
  173275. BITREAD_STATE_VARS;
  173276. /* Process restart marker if needed; may have to suspend */
  173277. if (cinfo->restart_interval) {
  173278. if (entropy->restarts_to_go == 0)
  173279. if (! process_restartp(cinfo))
  173280. return FALSE;
  173281. }
  173282. /* Not worth the cycles to check insufficient_data here,
  173283. * since we will not change the data anyway if we read zeroes.
  173284. */
  173285. /* Load up working state */
  173286. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173287. /* Outer loop handles each block in the MCU */
  173288. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173289. block = MCU_data[blkn];
  173290. /* Encoded data is simply the next bit of the two's-complement DC value */
  173291. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173292. if (GET_BITS(1))
  173293. (*block)[0] |= p1;
  173294. /* Note: since we use |=, repeating the assignment later is safe */
  173295. }
  173296. /* Completed MCU, so update state */
  173297. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173298. /* Account for restart interval (no-op if not using restarts) */
  173299. entropy->restarts_to_go--;
  173300. return TRUE;
  173301. }
  173302. /*
  173303. * MCU decoding for AC successive approximation refinement scan.
  173304. */
  173305. METHODDEF(boolean)
  173306. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173307. {
  173308. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173309. int Se = cinfo->Se;
  173310. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173311. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173312. register int s, k, r;
  173313. unsigned int EOBRUN;
  173314. JBLOCKROW block;
  173315. JCOEFPTR thiscoef;
  173316. BITREAD_STATE_VARS;
  173317. d_derived_tbl * tbl;
  173318. int num_newnz;
  173319. int newnz_pos[DCTSIZE2];
  173320. /* Process restart marker if needed; may have to suspend */
  173321. if (cinfo->restart_interval) {
  173322. if (entropy->restarts_to_go == 0)
  173323. if (! process_restartp(cinfo))
  173324. return FALSE;
  173325. }
  173326. /* If we've run out of data, don't modify the MCU.
  173327. */
  173328. if (! entropy->pub.insufficient_data) {
  173329. /* Load up working state */
  173330. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173331. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173332. /* There is always only one block per MCU */
  173333. block = MCU_data[0];
  173334. tbl = entropy->ac_derived_tbl;
  173335. /* If we are forced to suspend, we must undo the assignments to any newly
  173336. * nonzero coefficients in the block, because otherwise we'd get confused
  173337. * next time about which coefficients were already nonzero.
  173338. * But we need not undo addition of bits to already-nonzero coefficients;
  173339. * instead, we can test the current bit to see if we already did it.
  173340. */
  173341. num_newnz = 0;
  173342. /* initialize coefficient loop counter to start of band */
  173343. k = cinfo->Ss;
  173344. if (EOBRUN == 0) {
  173345. for (; k <= Se; k++) {
  173346. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173347. r = s >> 4;
  173348. s &= 15;
  173349. if (s) {
  173350. if (s != 1) /* size of new coef should always be 1 */
  173351. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173352. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173353. if (GET_BITS(1))
  173354. s = p1; /* newly nonzero coef is positive */
  173355. else
  173356. s = m1; /* newly nonzero coef is negative */
  173357. } else {
  173358. if (r != 15) {
  173359. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173360. if (r) {
  173361. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173362. r = GET_BITS(r);
  173363. EOBRUN += r;
  173364. }
  173365. break; /* rest of block is handled by EOB logic */
  173366. }
  173367. /* note s = 0 for processing ZRL */
  173368. }
  173369. /* Advance over already-nonzero coefs and r still-zero coefs,
  173370. * appending correction bits to the nonzeroes. A correction bit is 1
  173371. * if the absolute value of the coefficient must be increased.
  173372. */
  173373. do {
  173374. thiscoef = *block + jpeg_natural_order[k];
  173375. if (*thiscoef != 0) {
  173376. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173377. if (GET_BITS(1)) {
  173378. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173379. if (*thiscoef >= 0)
  173380. *thiscoef += p1;
  173381. else
  173382. *thiscoef += m1;
  173383. }
  173384. }
  173385. } else {
  173386. if (--r < 0)
  173387. break; /* reached target zero coefficient */
  173388. }
  173389. k++;
  173390. } while (k <= Se);
  173391. if (s) {
  173392. int pos = jpeg_natural_order[k];
  173393. /* Output newly nonzero coefficient */
  173394. (*block)[pos] = (JCOEF) s;
  173395. /* Remember its position in case we have to suspend */
  173396. newnz_pos[num_newnz++] = pos;
  173397. }
  173398. }
  173399. }
  173400. if (EOBRUN > 0) {
  173401. /* Scan any remaining coefficient positions after the end-of-band
  173402. * (the last newly nonzero coefficient, if any). Append a correction
  173403. * bit to each already-nonzero coefficient. A correction bit is 1
  173404. * if the absolute value of the coefficient must be increased.
  173405. */
  173406. for (; k <= Se; k++) {
  173407. thiscoef = *block + jpeg_natural_order[k];
  173408. if (*thiscoef != 0) {
  173409. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173410. if (GET_BITS(1)) {
  173411. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173412. if (*thiscoef >= 0)
  173413. *thiscoef += p1;
  173414. else
  173415. *thiscoef += m1;
  173416. }
  173417. }
  173418. }
  173419. }
  173420. /* Count one block completed in EOB run */
  173421. EOBRUN--;
  173422. }
  173423. /* Completed MCU, so update state */
  173424. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173425. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173426. }
  173427. /* Account for restart interval (no-op if not using restarts) */
  173428. entropy->restarts_to_go--;
  173429. return TRUE;
  173430. undoit:
  173431. /* Re-zero any output coefficients that we made newly nonzero */
  173432. while (num_newnz > 0)
  173433. (*block)[newnz_pos[--num_newnz]] = 0;
  173434. return FALSE;
  173435. }
  173436. /*
  173437. * Module initialization routine for progressive Huffman entropy decoding.
  173438. */
  173439. GLOBAL(void)
  173440. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173441. {
  173442. phuff_entropy_ptr2 entropy;
  173443. int *coef_bit_ptr;
  173444. int ci, i;
  173445. entropy = (phuff_entropy_ptr2)
  173446. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173447. SIZEOF(phuff_entropy_decoder));
  173448. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173449. entropy->pub.start_pass = start_pass_phuff_decoder;
  173450. /* Mark derived tables unallocated */
  173451. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173452. entropy->derived_tbls[i] = NULL;
  173453. }
  173454. /* Create progression status table */
  173455. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173456. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173457. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173458. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173459. for (ci = 0; ci < cinfo->num_components; ci++)
  173460. for (i = 0; i < DCTSIZE2; i++)
  173461. *coef_bit_ptr++ = -1;
  173462. }
  173463. #endif /* D_PROGRESSIVE_SUPPORTED */
  173464. /*** End of inlined file: jdphuff.c ***/
  173465. /*** Start of inlined file: jdpostct.c ***/
  173466. #define JPEG_INTERNALS
  173467. /* Private buffer controller object */
  173468. typedef struct {
  173469. struct jpeg_d_post_controller pub; /* public fields */
  173470. /* Color quantization source buffer: this holds output data from
  173471. * the upsample/color conversion step to be passed to the quantizer.
  173472. * For two-pass color quantization, we need a full-image buffer;
  173473. * for one-pass operation, a strip buffer is sufficient.
  173474. */
  173475. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173476. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173477. JDIMENSION strip_height; /* buffer size in rows */
  173478. /* for two-pass mode only: */
  173479. JDIMENSION starting_row; /* row # of first row in current strip */
  173480. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173481. } my_post_controller;
  173482. typedef my_post_controller * my_post_ptr;
  173483. /* Forward declarations */
  173484. METHODDEF(void) post_process_1pass
  173485. JPP((j_decompress_ptr cinfo,
  173486. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173487. JDIMENSION in_row_groups_avail,
  173488. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173489. JDIMENSION out_rows_avail));
  173490. #ifdef QUANT_2PASS_SUPPORTED
  173491. METHODDEF(void) post_process_prepass
  173492. JPP((j_decompress_ptr cinfo,
  173493. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173494. JDIMENSION in_row_groups_avail,
  173495. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173496. JDIMENSION out_rows_avail));
  173497. METHODDEF(void) post_process_2pass
  173498. JPP((j_decompress_ptr cinfo,
  173499. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173500. JDIMENSION in_row_groups_avail,
  173501. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173502. JDIMENSION out_rows_avail));
  173503. #endif
  173504. /*
  173505. * Initialize for a processing pass.
  173506. */
  173507. METHODDEF(void)
  173508. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173509. {
  173510. my_post_ptr post = (my_post_ptr) cinfo->post;
  173511. switch (pass_mode) {
  173512. case JBUF_PASS_THRU:
  173513. if (cinfo->quantize_colors) {
  173514. /* Single-pass processing with color quantization. */
  173515. post->pub.post_process_data = post_process_1pass;
  173516. /* We could be doing buffered-image output before starting a 2-pass
  173517. * color quantization; in that case, jinit_d_post_controller did not
  173518. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173519. */
  173520. if (post->buffer == NULL) {
  173521. post->buffer = (*cinfo->mem->access_virt_sarray)
  173522. ((j_common_ptr) cinfo, post->whole_image,
  173523. (JDIMENSION) 0, post->strip_height, TRUE);
  173524. }
  173525. } else {
  173526. /* For single-pass processing without color quantization,
  173527. * I have no work to do; just call the upsampler directly.
  173528. */
  173529. post->pub.post_process_data = cinfo->upsample->upsample;
  173530. }
  173531. break;
  173532. #ifdef QUANT_2PASS_SUPPORTED
  173533. case JBUF_SAVE_AND_PASS:
  173534. /* First pass of 2-pass quantization */
  173535. if (post->whole_image == NULL)
  173536. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173537. post->pub.post_process_data = post_process_prepass;
  173538. break;
  173539. case JBUF_CRANK_DEST:
  173540. /* Second pass of 2-pass quantization */
  173541. if (post->whole_image == NULL)
  173542. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173543. post->pub.post_process_data = post_process_2pass;
  173544. break;
  173545. #endif /* QUANT_2PASS_SUPPORTED */
  173546. default:
  173547. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173548. break;
  173549. }
  173550. post->starting_row = post->next_row = 0;
  173551. }
  173552. /*
  173553. * Process some data in the one-pass (strip buffer) case.
  173554. * This is used for color precision reduction as well as one-pass quantization.
  173555. */
  173556. METHODDEF(void)
  173557. post_process_1pass (j_decompress_ptr cinfo,
  173558. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173559. JDIMENSION in_row_groups_avail,
  173560. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173561. JDIMENSION out_rows_avail)
  173562. {
  173563. my_post_ptr post = (my_post_ptr) cinfo->post;
  173564. JDIMENSION num_rows, max_rows;
  173565. /* Fill the buffer, but not more than what we can dump out in one go. */
  173566. /* Note we rely on the upsampler to detect bottom of image. */
  173567. max_rows = out_rows_avail - *out_row_ctr;
  173568. if (max_rows > post->strip_height)
  173569. max_rows = post->strip_height;
  173570. num_rows = 0;
  173571. (*cinfo->upsample->upsample) (cinfo,
  173572. input_buf, in_row_group_ctr, in_row_groups_avail,
  173573. post->buffer, &num_rows, max_rows);
  173574. /* Quantize and emit data. */
  173575. (*cinfo->cquantize->color_quantize) (cinfo,
  173576. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173577. *out_row_ctr += num_rows;
  173578. }
  173579. #ifdef QUANT_2PASS_SUPPORTED
  173580. /*
  173581. * Process some data in the first pass of 2-pass quantization.
  173582. */
  173583. METHODDEF(void)
  173584. post_process_prepass (j_decompress_ptr cinfo,
  173585. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173586. JDIMENSION in_row_groups_avail,
  173587. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173588. JDIMENSION)
  173589. {
  173590. my_post_ptr post = (my_post_ptr) cinfo->post;
  173591. JDIMENSION old_next_row, num_rows;
  173592. /* Reposition virtual buffer if at start of strip. */
  173593. if (post->next_row == 0) {
  173594. post->buffer = (*cinfo->mem->access_virt_sarray)
  173595. ((j_common_ptr) cinfo, post->whole_image,
  173596. post->starting_row, post->strip_height, TRUE);
  173597. }
  173598. /* Upsample some data (up to a strip height's worth). */
  173599. old_next_row = post->next_row;
  173600. (*cinfo->upsample->upsample) (cinfo,
  173601. input_buf, in_row_group_ctr, in_row_groups_avail,
  173602. post->buffer, &post->next_row, post->strip_height);
  173603. /* Allow quantizer to scan new data. No data is emitted, */
  173604. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173605. if (post->next_row > old_next_row) {
  173606. num_rows = post->next_row - old_next_row;
  173607. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173608. (JSAMPARRAY) NULL, (int) num_rows);
  173609. *out_row_ctr += num_rows;
  173610. }
  173611. /* Advance if we filled the strip. */
  173612. if (post->next_row >= post->strip_height) {
  173613. post->starting_row += post->strip_height;
  173614. post->next_row = 0;
  173615. }
  173616. }
  173617. /*
  173618. * Process some data in the second pass of 2-pass quantization.
  173619. */
  173620. METHODDEF(void)
  173621. post_process_2pass (j_decompress_ptr cinfo,
  173622. JSAMPIMAGE, JDIMENSION *,
  173623. JDIMENSION,
  173624. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173625. JDIMENSION out_rows_avail)
  173626. {
  173627. my_post_ptr post = (my_post_ptr) cinfo->post;
  173628. JDIMENSION num_rows, max_rows;
  173629. /* Reposition virtual buffer if at start of strip. */
  173630. if (post->next_row == 0) {
  173631. post->buffer = (*cinfo->mem->access_virt_sarray)
  173632. ((j_common_ptr) cinfo, post->whole_image,
  173633. post->starting_row, post->strip_height, FALSE);
  173634. }
  173635. /* Determine number of rows to emit. */
  173636. num_rows = post->strip_height - post->next_row; /* available in strip */
  173637. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173638. if (num_rows > max_rows)
  173639. num_rows = max_rows;
  173640. /* We have to check bottom of image here, can't depend on upsampler. */
  173641. max_rows = cinfo->output_height - post->starting_row;
  173642. if (num_rows > max_rows)
  173643. num_rows = max_rows;
  173644. /* Quantize and emit data. */
  173645. (*cinfo->cquantize->color_quantize) (cinfo,
  173646. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173647. (int) num_rows);
  173648. *out_row_ctr += num_rows;
  173649. /* Advance if we filled the strip. */
  173650. post->next_row += num_rows;
  173651. if (post->next_row >= post->strip_height) {
  173652. post->starting_row += post->strip_height;
  173653. post->next_row = 0;
  173654. }
  173655. }
  173656. #endif /* QUANT_2PASS_SUPPORTED */
  173657. /*
  173658. * Initialize postprocessing controller.
  173659. */
  173660. GLOBAL(void)
  173661. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173662. {
  173663. my_post_ptr post;
  173664. post = (my_post_ptr)
  173665. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173666. SIZEOF(my_post_controller));
  173667. cinfo->post = (struct jpeg_d_post_controller *) post;
  173668. post->pub.start_pass = start_pass_dpost;
  173669. post->whole_image = NULL; /* flag for no virtual arrays */
  173670. post->buffer = NULL; /* flag for no strip buffer */
  173671. /* Create the quantization buffer, if needed */
  173672. if (cinfo->quantize_colors) {
  173673. /* The buffer strip height is max_v_samp_factor, which is typically
  173674. * an efficient number of rows for upsampling to return.
  173675. * (In the presence of output rescaling, we might want to be smarter?)
  173676. */
  173677. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173678. if (need_full_buffer) {
  173679. /* Two-pass color quantization: need full-image storage. */
  173680. /* We round up the number of rows to a multiple of the strip height. */
  173681. #ifdef QUANT_2PASS_SUPPORTED
  173682. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173683. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173684. cinfo->output_width * cinfo->out_color_components,
  173685. (JDIMENSION) jround_up((long) cinfo->output_height,
  173686. (long) post->strip_height),
  173687. post->strip_height);
  173688. #else
  173689. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173690. #endif /* QUANT_2PASS_SUPPORTED */
  173691. } else {
  173692. /* One-pass color quantization: just make a strip buffer. */
  173693. post->buffer = (*cinfo->mem->alloc_sarray)
  173694. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173695. cinfo->output_width * cinfo->out_color_components,
  173696. post->strip_height);
  173697. }
  173698. }
  173699. }
  173700. /*** End of inlined file: jdpostct.c ***/
  173701. #undef FIX
  173702. /*** Start of inlined file: jdsample.c ***/
  173703. #define JPEG_INTERNALS
  173704. /* Pointer to routine to upsample a single component */
  173705. typedef JMETHOD(void, upsample1_ptr,
  173706. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173707. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173708. /* Private subobject */
  173709. typedef struct {
  173710. struct jpeg_upsampler pub; /* public fields */
  173711. /* Color conversion buffer. When using separate upsampling and color
  173712. * conversion steps, this buffer holds one upsampled row group until it
  173713. * has been color converted and output.
  173714. * Note: we do not allocate any storage for component(s) which are full-size,
  173715. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173716. * simply set to point to the input data array, thereby avoiding copying.
  173717. */
  173718. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173719. /* Per-component upsampling method pointers */
  173720. upsample1_ptr methods[MAX_COMPONENTS];
  173721. int next_row_out; /* counts rows emitted from color_buf */
  173722. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173723. /* Height of an input row group for each component. */
  173724. int rowgroup_height[MAX_COMPONENTS];
  173725. /* These arrays save pixel expansion factors so that int_expand need not
  173726. * recompute them each time. They are unused for other upsampling methods.
  173727. */
  173728. UINT8 h_expand[MAX_COMPONENTS];
  173729. UINT8 v_expand[MAX_COMPONENTS];
  173730. } my_upsampler2;
  173731. typedef my_upsampler2 * my_upsample_ptr2;
  173732. /*
  173733. * Initialize for an upsampling pass.
  173734. */
  173735. METHODDEF(void)
  173736. start_pass_upsample (j_decompress_ptr cinfo)
  173737. {
  173738. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173739. /* Mark the conversion buffer empty */
  173740. upsample->next_row_out = cinfo->max_v_samp_factor;
  173741. /* Initialize total-height counter for detecting bottom of image */
  173742. upsample->rows_to_go = cinfo->output_height;
  173743. }
  173744. /*
  173745. * Control routine to do upsampling (and color conversion).
  173746. *
  173747. * In this version we upsample each component independently.
  173748. * We upsample one row group into the conversion buffer, then apply
  173749. * color conversion a row at a time.
  173750. */
  173751. METHODDEF(void)
  173752. sep_upsample (j_decompress_ptr cinfo,
  173753. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173754. JDIMENSION,
  173755. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173756. JDIMENSION out_rows_avail)
  173757. {
  173758. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173759. int ci;
  173760. jpeg_component_info * compptr;
  173761. JDIMENSION num_rows;
  173762. /* Fill the conversion buffer, if it's empty */
  173763. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173764. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173765. ci++, compptr++) {
  173766. /* Invoke per-component upsample method. Notice we pass a POINTER
  173767. * to color_buf[ci], so that fullsize_upsample can change it.
  173768. */
  173769. (*upsample->methods[ci]) (cinfo, compptr,
  173770. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173771. upsample->color_buf + ci);
  173772. }
  173773. upsample->next_row_out = 0;
  173774. }
  173775. /* Color-convert and emit rows */
  173776. /* How many we have in the buffer: */
  173777. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173778. /* Not more than the distance to the end of the image. Need this test
  173779. * in case the image height is not a multiple of max_v_samp_factor:
  173780. */
  173781. if (num_rows > upsample->rows_to_go)
  173782. num_rows = upsample->rows_to_go;
  173783. /* And not more than what the client can accept: */
  173784. out_rows_avail -= *out_row_ctr;
  173785. if (num_rows > out_rows_avail)
  173786. num_rows = out_rows_avail;
  173787. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173788. (JDIMENSION) upsample->next_row_out,
  173789. output_buf + *out_row_ctr,
  173790. (int) num_rows);
  173791. /* Adjust counts */
  173792. *out_row_ctr += num_rows;
  173793. upsample->rows_to_go -= num_rows;
  173794. upsample->next_row_out += num_rows;
  173795. /* When the buffer is emptied, declare this input row group consumed */
  173796. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173797. (*in_row_group_ctr)++;
  173798. }
  173799. /*
  173800. * These are the routines invoked by sep_upsample to upsample pixel values
  173801. * of a single component. One row group is processed per call.
  173802. */
  173803. /*
  173804. * For full-size components, we just make color_buf[ci] point at the
  173805. * input buffer, and thus avoid copying any data. Note that this is
  173806. * safe only because sep_upsample doesn't declare the input row group
  173807. * "consumed" until we are done color converting and emitting it.
  173808. */
  173809. METHODDEF(void)
  173810. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173811. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173812. {
  173813. *output_data_ptr = input_data;
  173814. }
  173815. /*
  173816. * This is a no-op version used for "uninteresting" components.
  173817. * These components will not be referenced by color conversion.
  173818. */
  173819. METHODDEF(void)
  173820. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173821. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173822. {
  173823. *output_data_ptr = NULL; /* safety check */
  173824. }
  173825. /*
  173826. * This version handles any integral sampling ratios.
  173827. * This is not used for typical JPEG files, so it need not be fast.
  173828. * Nor, for that matter, is it particularly accurate: the algorithm is
  173829. * simple replication of the input pixel onto the corresponding output
  173830. * pixels. The hi-falutin sampling literature refers to this as a
  173831. * "box filter". A box filter tends to introduce visible artifacts,
  173832. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173833. * you would be well advised to improve this code.
  173834. */
  173835. METHODDEF(void)
  173836. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173837. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173838. {
  173839. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173840. JSAMPARRAY output_data = *output_data_ptr;
  173841. register JSAMPROW inptr, outptr;
  173842. register JSAMPLE invalue;
  173843. register int h;
  173844. JSAMPROW outend;
  173845. int h_expand, v_expand;
  173846. int inrow, outrow;
  173847. h_expand = upsample->h_expand[compptr->component_index];
  173848. v_expand = upsample->v_expand[compptr->component_index];
  173849. inrow = outrow = 0;
  173850. while (outrow < cinfo->max_v_samp_factor) {
  173851. /* Generate one output row with proper horizontal expansion */
  173852. inptr = input_data[inrow];
  173853. outptr = output_data[outrow];
  173854. outend = outptr + cinfo->output_width;
  173855. while (outptr < outend) {
  173856. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173857. for (h = h_expand; h > 0; h--) {
  173858. *outptr++ = invalue;
  173859. }
  173860. }
  173861. /* Generate any additional output rows by duplicating the first one */
  173862. if (v_expand > 1) {
  173863. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173864. v_expand-1, cinfo->output_width);
  173865. }
  173866. inrow++;
  173867. outrow += v_expand;
  173868. }
  173869. }
  173870. /*
  173871. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173872. * It's still a box filter.
  173873. */
  173874. METHODDEF(void)
  173875. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173876. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173877. {
  173878. JSAMPARRAY output_data = *output_data_ptr;
  173879. register JSAMPROW inptr, outptr;
  173880. register JSAMPLE invalue;
  173881. JSAMPROW outend;
  173882. int inrow;
  173883. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173884. inptr = input_data[inrow];
  173885. outptr = output_data[inrow];
  173886. outend = outptr + cinfo->output_width;
  173887. while (outptr < outend) {
  173888. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173889. *outptr++ = invalue;
  173890. *outptr++ = invalue;
  173891. }
  173892. }
  173893. }
  173894. /*
  173895. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173896. * It's still a box filter.
  173897. */
  173898. METHODDEF(void)
  173899. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173900. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173901. {
  173902. JSAMPARRAY output_data = *output_data_ptr;
  173903. register JSAMPROW inptr, outptr;
  173904. register JSAMPLE invalue;
  173905. JSAMPROW outend;
  173906. int inrow, outrow;
  173907. inrow = outrow = 0;
  173908. while (outrow < cinfo->max_v_samp_factor) {
  173909. inptr = input_data[inrow];
  173910. outptr = output_data[outrow];
  173911. outend = outptr + cinfo->output_width;
  173912. while (outptr < outend) {
  173913. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173914. *outptr++ = invalue;
  173915. *outptr++ = invalue;
  173916. }
  173917. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173918. 1, cinfo->output_width);
  173919. inrow++;
  173920. outrow += 2;
  173921. }
  173922. }
  173923. /*
  173924. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173925. *
  173926. * The upsampling algorithm is linear interpolation between pixel centers,
  173927. * also known as a "triangle filter". This is a good compromise between
  173928. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173929. * of the way between input pixel centers.
  173930. *
  173931. * A note about the "bias" calculations: when rounding fractional values to
  173932. * integer, we do not want to always round 0.5 up to the next integer.
  173933. * If we did that, we'd introduce a noticeable bias towards larger values.
  173934. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173935. * alternate pixel locations (a simple ordered dither pattern).
  173936. */
  173937. METHODDEF(void)
  173938. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173939. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173940. {
  173941. JSAMPARRAY output_data = *output_data_ptr;
  173942. register JSAMPROW inptr, outptr;
  173943. register int invalue;
  173944. register JDIMENSION colctr;
  173945. int inrow;
  173946. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173947. inptr = input_data[inrow];
  173948. outptr = output_data[inrow];
  173949. /* Special case for first column */
  173950. invalue = GETJSAMPLE(*inptr++);
  173951. *outptr++ = (JSAMPLE) invalue;
  173952. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173953. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173954. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173955. invalue = GETJSAMPLE(*inptr++) * 3;
  173956. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173957. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173958. }
  173959. /* Special case for last column */
  173960. invalue = GETJSAMPLE(*inptr);
  173961. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173962. *outptr++ = (JSAMPLE) invalue;
  173963. }
  173964. }
  173965. /*
  173966. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173967. * Again a triangle filter; see comments for h2v1 case, above.
  173968. *
  173969. * It is OK for us to reference the adjacent input rows because we demanded
  173970. * context from the main buffer controller (see initialization code).
  173971. */
  173972. METHODDEF(void)
  173973. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173974. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173975. {
  173976. JSAMPARRAY output_data = *output_data_ptr;
  173977. register JSAMPROW inptr0, inptr1, outptr;
  173978. #if BITS_IN_JSAMPLE == 8
  173979. register int thiscolsum, lastcolsum, nextcolsum;
  173980. #else
  173981. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173982. #endif
  173983. register JDIMENSION colctr;
  173984. int inrow, outrow, v;
  173985. inrow = outrow = 0;
  173986. while (outrow < cinfo->max_v_samp_factor) {
  173987. for (v = 0; v < 2; v++) {
  173988. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173989. inptr0 = input_data[inrow];
  173990. if (v == 0) /* next nearest is row above */
  173991. inptr1 = input_data[inrow-1];
  173992. else /* next nearest is row below */
  173993. inptr1 = input_data[inrow+1];
  173994. outptr = output_data[outrow++];
  173995. /* Special case for first column */
  173996. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173997. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173998. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173999. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174000. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174001. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174002. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174003. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174004. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174005. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174006. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174007. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174008. }
  174009. /* Special case for last column */
  174010. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174011. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174012. }
  174013. inrow++;
  174014. }
  174015. }
  174016. /*
  174017. * Module initialization routine for upsampling.
  174018. */
  174019. GLOBAL(void)
  174020. jinit_upsampler (j_decompress_ptr cinfo)
  174021. {
  174022. my_upsample_ptr2 upsample;
  174023. int ci;
  174024. jpeg_component_info * compptr;
  174025. boolean need_buffer, do_fancy;
  174026. int h_in_group, v_in_group, h_out_group, v_out_group;
  174027. upsample = (my_upsample_ptr2)
  174028. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174029. SIZEOF(my_upsampler2));
  174030. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174031. upsample->pub.start_pass = start_pass_upsample;
  174032. upsample->pub.upsample = sep_upsample;
  174033. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174034. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174035. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174036. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174037. * so don't ask for it.
  174038. */
  174039. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174040. /* Verify we can handle the sampling factors, select per-component methods,
  174041. * and create storage as needed.
  174042. */
  174043. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174044. ci++, compptr++) {
  174045. /* Compute size of an "input group" after IDCT scaling. This many samples
  174046. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174047. */
  174048. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174049. cinfo->min_DCT_scaled_size;
  174050. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174051. cinfo->min_DCT_scaled_size;
  174052. h_out_group = cinfo->max_h_samp_factor;
  174053. v_out_group = cinfo->max_v_samp_factor;
  174054. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174055. need_buffer = TRUE;
  174056. if (! compptr->component_needed) {
  174057. /* Don't bother to upsample an uninteresting component. */
  174058. upsample->methods[ci] = noop_upsample;
  174059. need_buffer = FALSE;
  174060. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174061. /* Fullsize components can be processed without any work. */
  174062. upsample->methods[ci] = fullsize_upsample;
  174063. need_buffer = FALSE;
  174064. } else if (h_in_group * 2 == h_out_group &&
  174065. v_in_group == v_out_group) {
  174066. /* Special cases for 2h1v upsampling */
  174067. if (do_fancy && compptr->downsampled_width > 2)
  174068. upsample->methods[ci] = h2v1_fancy_upsample;
  174069. else
  174070. upsample->methods[ci] = h2v1_upsample;
  174071. } else if (h_in_group * 2 == h_out_group &&
  174072. v_in_group * 2 == v_out_group) {
  174073. /* Special cases for 2h2v upsampling */
  174074. if (do_fancy && compptr->downsampled_width > 2) {
  174075. upsample->methods[ci] = h2v2_fancy_upsample;
  174076. upsample->pub.need_context_rows = TRUE;
  174077. } else
  174078. upsample->methods[ci] = h2v2_upsample;
  174079. } else if ((h_out_group % h_in_group) == 0 &&
  174080. (v_out_group % v_in_group) == 0) {
  174081. /* Generic integral-factors upsampling method */
  174082. upsample->methods[ci] = int_upsample;
  174083. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174084. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174085. } else
  174086. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174087. if (need_buffer) {
  174088. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174089. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174090. (JDIMENSION) jround_up((long) cinfo->output_width,
  174091. (long) cinfo->max_h_samp_factor),
  174092. (JDIMENSION) cinfo->max_v_samp_factor);
  174093. }
  174094. }
  174095. }
  174096. /*** End of inlined file: jdsample.c ***/
  174097. /*** Start of inlined file: jdtrans.c ***/
  174098. #define JPEG_INTERNALS
  174099. /* Forward declarations */
  174100. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174101. /*
  174102. * Read the coefficient arrays from a JPEG file.
  174103. * jpeg_read_header must be completed before calling this.
  174104. *
  174105. * The entire image is read into a set of virtual coefficient-block arrays,
  174106. * one per component. The return value is a pointer to the array of
  174107. * virtual-array descriptors. These can be manipulated directly via the
  174108. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174109. * To release the memory occupied by the virtual arrays, call
  174110. * jpeg_finish_decompress() when done with the data.
  174111. *
  174112. * An alternative usage is to simply obtain access to the coefficient arrays
  174113. * during a buffered-image-mode decompression operation. This is allowed
  174114. * after any jpeg_finish_output() call. The arrays can be accessed until
  174115. * jpeg_finish_decompress() is called. (Note that any call to the library
  174116. * may reposition the arrays, so don't rely on access_virt_barray() results
  174117. * to stay valid across library calls.)
  174118. *
  174119. * Returns NULL if suspended. This case need be checked only if
  174120. * a suspending data source is used.
  174121. */
  174122. GLOBAL(jvirt_barray_ptr *)
  174123. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174124. {
  174125. if (cinfo->global_state == DSTATE_READY) {
  174126. /* First call: initialize active modules */
  174127. transdecode_master_selection(cinfo);
  174128. cinfo->global_state = DSTATE_RDCOEFS;
  174129. }
  174130. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174131. /* Absorb whole file into the coef buffer */
  174132. for (;;) {
  174133. int retcode;
  174134. /* Call progress monitor hook if present */
  174135. if (cinfo->progress != NULL)
  174136. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174137. /* Absorb some more input */
  174138. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174139. if (retcode == JPEG_SUSPENDED)
  174140. return NULL;
  174141. if (retcode == JPEG_REACHED_EOI)
  174142. break;
  174143. /* Advance progress counter if appropriate */
  174144. if (cinfo->progress != NULL &&
  174145. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174146. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174147. /* startup underestimated number of scans; ratchet up one scan */
  174148. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174149. }
  174150. }
  174151. }
  174152. /* Set state so that jpeg_finish_decompress does the right thing */
  174153. cinfo->global_state = DSTATE_STOPPING;
  174154. }
  174155. /* At this point we should be in state DSTATE_STOPPING if being used
  174156. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174157. * to the coefficients during a full buffered-image-mode decompression.
  174158. */
  174159. if ((cinfo->global_state == DSTATE_STOPPING ||
  174160. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174161. return cinfo->coef->coef_arrays;
  174162. }
  174163. /* Oops, improper usage */
  174164. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174165. return NULL; /* keep compiler happy */
  174166. }
  174167. /*
  174168. * Master selection of decompression modules for transcoding.
  174169. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174170. */
  174171. LOCAL(void)
  174172. transdecode_master_selection (j_decompress_ptr cinfo)
  174173. {
  174174. /* This is effectively a buffered-image operation. */
  174175. cinfo->buffered_image = TRUE;
  174176. /* Entropy decoding: either Huffman or arithmetic coding. */
  174177. if (cinfo->arith_code) {
  174178. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174179. } else {
  174180. if (cinfo->progressive_mode) {
  174181. #ifdef D_PROGRESSIVE_SUPPORTED
  174182. jinit_phuff_decoder(cinfo);
  174183. #else
  174184. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174185. #endif
  174186. } else
  174187. jinit_huff_decoder(cinfo);
  174188. }
  174189. /* Always get a full-image coefficient buffer. */
  174190. jinit_d_coef_controller(cinfo, TRUE);
  174191. /* We can now tell the memory manager to allocate virtual arrays. */
  174192. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174193. /* Initialize input side of decompressor to consume first scan. */
  174194. (*cinfo->inputctl->start_input_pass) (cinfo);
  174195. /* Initialize progress monitoring. */
  174196. if (cinfo->progress != NULL) {
  174197. int nscans;
  174198. /* Estimate number of scans to set pass_limit. */
  174199. if (cinfo->progressive_mode) {
  174200. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174201. nscans = 2 + 3 * cinfo->num_components;
  174202. } else if (cinfo->inputctl->has_multiple_scans) {
  174203. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174204. nscans = cinfo->num_components;
  174205. } else {
  174206. nscans = 1;
  174207. }
  174208. cinfo->progress->pass_counter = 0L;
  174209. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174210. cinfo->progress->completed_passes = 0;
  174211. cinfo->progress->total_passes = 1;
  174212. }
  174213. }
  174214. /*** End of inlined file: jdtrans.c ***/
  174215. /*** Start of inlined file: jfdctflt.c ***/
  174216. #define JPEG_INTERNALS
  174217. #ifdef DCT_FLOAT_SUPPORTED
  174218. /*
  174219. * This module is specialized to the case DCTSIZE = 8.
  174220. */
  174221. #if DCTSIZE != 8
  174222. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174223. #endif
  174224. /*
  174225. * Perform the forward DCT on one block of samples.
  174226. */
  174227. GLOBAL(void)
  174228. jpeg_fdct_float (FAST_FLOAT * data)
  174229. {
  174230. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174231. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174232. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174233. FAST_FLOAT *dataptr;
  174234. int ctr;
  174235. /* Pass 1: process rows. */
  174236. dataptr = data;
  174237. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174238. tmp0 = dataptr[0] + dataptr[7];
  174239. tmp7 = dataptr[0] - dataptr[7];
  174240. tmp1 = dataptr[1] + dataptr[6];
  174241. tmp6 = dataptr[1] - dataptr[6];
  174242. tmp2 = dataptr[2] + dataptr[5];
  174243. tmp5 = dataptr[2] - dataptr[5];
  174244. tmp3 = dataptr[3] + dataptr[4];
  174245. tmp4 = dataptr[3] - dataptr[4];
  174246. /* Even part */
  174247. tmp10 = tmp0 + tmp3; /* phase 2 */
  174248. tmp13 = tmp0 - tmp3;
  174249. tmp11 = tmp1 + tmp2;
  174250. tmp12 = tmp1 - tmp2;
  174251. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174252. dataptr[4] = tmp10 - tmp11;
  174253. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174254. dataptr[2] = tmp13 + z1; /* phase 5 */
  174255. dataptr[6] = tmp13 - z1;
  174256. /* Odd part */
  174257. tmp10 = tmp4 + tmp5; /* phase 2 */
  174258. tmp11 = tmp5 + tmp6;
  174259. tmp12 = tmp6 + tmp7;
  174260. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174261. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174262. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174263. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174264. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174265. z11 = tmp7 + z3; /* phase 5 */
  174266. z13 = tmp7 - z3;
  174267. dataptr[5] = z13 + z2; /* phase 6 */
  174268. dataptr[3] = z13 - z2;
  174269. dataptr[1] = z11 + z4;
  174270. dataptr[7] = z11 - z4;
  174271. dataptr += DCTSIZE; /* advance pointer to next row */
  174272. }
  174273. /* Pass 2: process columns. */
  174274. dataptr = data;
  174275. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174276. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174277. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174278. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174279. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174280. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174281. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174282. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174283. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174284. /* Even part */
  174285. tmp10 = tmp0 + tmp3; /* phase 2 */
  174286. tmp13 = tmp0 - tmp3;
  174287. tmp11 = tmp1 + tmp2;
  174288. tmp12 = tmp1 - tmp2;
  174289. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174290. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174291. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174292. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174293. dataptr[DCTSIZE*6] = tmp13 - z1;
  174294. /* Odd part */
  174295. tmp10 = tmp4 + tmp5; /* phase 2 */
  174296. tmp11 = tmp5 + tmp6;
  174297. tmp12 = tmp6 + tmp7;
  174298. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174299. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174300. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174301. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174302. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174303. z11 = tmp7 + z3; /* phase 5 */
  174304. z13 = tmp7 - z3;
  174305. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174306. dataptr[DCTSIZE*3] = z13 - z2;
  174307. dataptr[DCTSIZE*1] = z11 + z4;
  174308. dataptr[DCTSIZE*7] = z11 - z4;
  174309. dataptr++; /* advance pointer to next column */
  174310. }
  174311. }
  174312. #endif /* DCT_FLOAT_SUPPORTED */
  174313. /*** End of inlined file: jfdctflt.c ***/
  174314. /*** Start of inlined file: jfdctint.c ***/
  174315. #define JPEG_INTERNALS
  174316. #ifdef DCT_ISLOW_SUPPORTED
  174317. /*
  174318. * This module is specialized to the case DCTSIZE = 8.
  174319. */
  174320. #if DCTSIZE != 8
  174321. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174322. #endif
  174323. /*
  174324. * The poop on this scaling stuff is as follows:
  174325. *
  174326. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174327. * larger than the true DCT outputs. The final outputs are therefore
  174328. * a factor of N larger than desired; since N=8 this can be cured by
  174329. * a simple right shift at the end of the algorithm. The advantage of
  174330. * this arrangement is that we save two multiplications per 1-D DCT,
  174331. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174332. * In the IJG code, this factor of 8 is removed by the quantization step
  174333. * (in jcdctmgr.c), NOT in this module.
  174334. *
  174335. * We have to do addition and subtraction of the integer inputs, which
  174336. * is no problem, and multiplication by fractional constants, which is
  174337. * a problem to do in integer arithmetic. We multiply all the constants
  174338. * by CONST_SCALE and convert them to integer constants (thus retaining
  174339. * CONST_BITS bits of precision in the constants). After doing a
  174340. * multiplication we have to divide the product by CONST_SCALE, with proper
  174341. * rounding, to produce the correct output. This division can be done
  174342. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174343. * as long as possible so that partial sums can be added together with
  174344. * full fractional precision.
  174345. *
  174346. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174347. * they are represented to better-than-integral precision. These outputs
  174348. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174349. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174350. * array is INT32 anyway.)
  174351. *
  174352. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174353. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174354. * shows that the values given below are the most effective.
  174355. */
  174356. #if BITS_IN_JSAMPLE == 8
  174357. #define CONST_BITS 13
  174358. #define PASS1_BITS 2
  174359. #else
  174360. #define CONST_BITS 13
  174361. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174362. #endif
  174363. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174364. * causing a lot of useless floating-point operations at run time.
  174365. * To get around this we use the following pre-calculated constants.
  174366. * If you change CONST_BITS you may want to add appropriate values.
  174367. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174368. */
  174369. #if CONST_BITS == 13
  174370. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174371. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174372. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174373. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174374. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174375. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174376. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174377. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174378. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174379. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174380. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174381. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174382. #else
  174383. #define FIX_0_298631336 FIX(0.298631336)
  174384. #define FIX_0_390180644 FIX(0.390180644)
  174385. #define FIX_0_541196100 FIX(0.541196100)
  174386. #define FIX_0_765366865 FIX(0.765366865)
  174387. #define FIX_0_899976223 FIX(0.899976223)
  174388. #define FIX_1_175875602 FIX(1.175875602)
  174389. #define FIX_1_501321110 FIX(1.501321110)
  174390. #define FIX_1_847759065 FIX(1.847759065)
  174391. #define FIX_1_961570560 FIX(1.961570560)
  174392. #define FIX_2_053119869 FIX(2.053119869)
  174393. #define FIX_2_562915447 FIX(2.562915447)
  174394. #define FIX_3_072711026 FIX(3.072711026)
  174395. #endif
  174396. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174397. * For 8-bit samples with the recommended scaling, all the variable
  174398. * and constant values involved are no more than 16 bits wide, so a
  174399. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174400. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174401. */
  174402. #if BITS_IN_JSAMPLE == 8
  174403. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174404. #else
  174405. #define MULTIPLY(var,const) ((var) * (const))
  174406. #endif
  174407. /*
  174408. * Perform the forward DCT on one block of samples.
  174409. */
  174410. GLOBAL(void)
  174411. jpeg_fdct_islow (DCTELEM * data)
  174412. {
  174413. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174414. INT32 tmp10, tmp11, tmp12, tmp13;
  174415. INT32 z1, z2, z3, z4, z5;
  174416. DCTELEM *dataptr;
  174417. int ctr;
  174418. SHIFT_TEMPS
  174419. /* Pass 1: process rows. */
  174420. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174421. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174422. dataptr = data;
  174423. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174424. tmp0 = dataptr[0] + dataptr[7];
  174425. tmp7 = dataptr[0] - dataptr[7];
  174426. tmp1 = dataptr[1] + dataptr[6];
  174427. tmp6 = dataptr[1] - dataptr[6];
  174428. tmp2 = dataptr[2] + dataptr[5];
  174429. tmp5 = dataptr[2] - dataptr[5];
  174430. tmp3 = dataptr[3] + dataptr[4];
  174431. tmp4 = dataptr[3] - dataptr[4];
  174432. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174433. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174434. */
  174435. tmp10 = tmp0 + tmp3;
  174436. tmp13 = tmp0 - tmp3;
  174437. tmp11 = tmp1 + tmp2;
  174438. tmp12 = tmp1 - tmp2;
  174439. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174440. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174441. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174442. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174443. CONST_BITS-PASS1_BITS);
  174444. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174445. CONST_BITS-PASS1_BITS);
  174446. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174447. * cK represents cos(K*pi/16).
  174448. * i0..i3 in the paper are tmp4..tmp7 here.
  174449. */
  174450. z1 = tmp4 + tmp7;
  174451. z2 = tmp5 + tmp6;
  174452. z3 = tmp4 + tmp6;
  174453. z4 = tmp5 + tmp7;
  174454. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174455. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174456. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174457. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174458. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174459. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174460. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174461. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174462. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174463. z3 += z5;
  174464. z4 += z5;
  174465. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174466. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174467. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174468. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174469. dataptr += DCTSIZE; /* advance pointer to next row */
  174470. }
  174471. /* Pass 2: process columns.
  174472. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174473. * by an overall factor of 8.
  174474. */
  174475. dataptr = data;
  174476. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174477. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174478. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174479. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174480. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174481. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174482. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174483. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174484. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174485. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174486. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174487. */
  174488. tmp10 = tmp0 + tmp3;
  174489. tmp13 = tmp0 - tmp3;
  174490. tmp11 = tmp1 + tmp2;
  174491. tmp12 = tmp1 - tmp2;
  174492. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174493. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174494. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174495. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174496. CONST_BITS+PASS1_BITS);
  174497. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174498. CONST_BITS+PASS1_BITS);
  174499. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174500. * cK represents cos(K*pi/16).
  174501. * i0..i3 in the paper are tmp4..tmp7 here.
  174502. */
  174503. z1 = tmp4 + tmp7;
  174504. z2 = tmp5 + tmp6;
  174505. z3 = tmp4 + tmp6;
  174506. z4 = tmp5 + tmp7;
  174507. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174508. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174509. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174510. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174511. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174512. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174513. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174514. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174515. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174516. z3 += z5;
  174517. z4 += z5;
  174518. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174519. CONST_BITS+PASS1_BITS);
  174520. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174521. CONST_BITS+PASS1_BITS);
  174522. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174523. CONST_BITS+PASS1_BITS);
  174524. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174525. CONST_BITS+PASS1_BITS);
  174526. dataptr++; /* advance pointer to next column */
  174527. }
  174528. }
  174529. #endif /* DCT_ISLOW_SUPPORTED */
  174530. /*** End of inlined file: jfdctint.c ***/
  174531. #undef CONST_BITS
  174532. #undef MULTIPLY
  174533. #undef FIX_0_541196100
  174534. /*** Start of inlined file: jfdctfst.c ***/
  174535. #define JPEG_INTERNALS
  174536. #ifdef DCT_IFAST_SUPPORTED
  174537. /*
  174538. * This module is specialized to the case DCTSIZE = 8.
  174539. */
  174540. #if DCTSIZE != 8
  174541. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174542. #endif
  174543. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174544. * see jfdctint.c for more details. However, we choose to descale
  174545. * (right shift) multiplication products as soon as they are formed,
  174546. * rather than carrying additional fractional bits into subsequent additions.
  174547. * This compromises accuracy slightly, but it lets us save a few shifts.
  174548. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174549. * everywhere except in the multiplications proper; this saves a good deal
  174550. * of work on 16-bit-int machines.
  174551. *
  174552. * Again to save a few shifts, the intermediate results between pass 1 and
  174553. * pass 2 are not upscaled, but are represented only to integral precision.
  174554. *
  174555. * A final compromise is to represent the multiplicative constants to only
  174556. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174557. * machines, and may also reduce the cost of multiplication (since there
  174558. * are fewer one-bits in the constants).
  174559. */
  174560. #define CONST_BITS 8
  174561. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174562. * causing a lot of useless floating-point operations at run time.
  174563. * To get around this we use the following pre-calculated constants.
  174564. * If you change CONST_BITS you may want to add appropriate values.
  174565. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174566. */
  174567. #if CONST_BITS == 8
  174568. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174569. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174570. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174571. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174572. #else
  174573. #define FIX_0_382683433 FIX(0.382683433)
  174574. #define FIX_0_541196100 FIX(0.541196100)
  174575. #define FIX_0_707106781 FIX(0.707106781)
  174576. #define FIX_1_306562965 FIX(1.306562965)
  174577. #endif
  174578. /* We can gain a little more speed, with a further compromise in accuracy,
  174579. * by omitting the addition in a descaling shift. This yields an incorrectly
  174580. * rounded result half the time...
  174581. */
  174582. #ifndef USE_ACCURATE_ROUNDING
  174583. #undef DESCALE
  174584. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174585. #endif
  174586. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174587. * descale to yield a DCTELEM result.
  174588. */
  174589. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174590. /*
  174591. * Perform the forward DCT on one block of samples.
  174592. */
  174593. GLOBAL(void)
  174594. jpeg_fdct_ifast (DCTELEM * data)
  174595. {
  174596. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174597. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174598. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174599. DCTELEM *dataptr;
  174600. int ctr;
  174601. SHIFT_TEMPS
  174602. /* Pass 1: process rows. */
  174603. dataptr = data;
  174604. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174605. tmp0 = dataptr[0] + dataptr[7];
  174606. tmp7 = dataptr[0] - dataptr[7];
  174607. tmp1 = dataptr[1] + dataptr[6];
  174608. tmp6 = dataptr[1] - dataptr[6];
  174609. tmp2 = dataptr[2] + dataptr[5];
  174610. tmp5 = dataptr[2] - dataptr[5];
  174611. tmp3 = dataptr[3] + dataptr[4];
  174612. tmp4 = dataptr[3] - dataptr[4];
  174613. /* Even part */
  174614. tmp10 = tmp0 + tmp3; /* phase 2 */
  174615. tmp13 = tmp0 - tmp3;
  174616. tmp11 = tmp1 + tmp2;
  174617. tmp12 = tmp1 - tmp2;
  174618. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174619. dataptr[4] = tmp10 - tmp11;
  174620. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174621. dataptr[2] = tmp13 + z1; /* phase 5 */
  174622. dataptr[6] = tmp13 - z1;
  174623. /* Odd part */
  174624. tmp10 = tmp4 + tmp5; /* phase 2 */
  174625. tmp11 = tmp5 + tmp6;
  174626. tmp12 = tmp6 + tmp7;
  174627. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174628. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174629. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174630. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174631. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174632. z11 = tmp7 + z3; /* phase 5 */
  174633. z13 = tmp7 - z3;
  174634. dataptr[5] = z13 + z2; /* phase 6 */
  174635. dataptr[3] = z13 - z2;
  174636. dataptr[1] = z11 + z4;
  174637. dataptr[7] = z11 - z4;
  174638. dataptr += DCTSIZE; /* advance pointer to next row */
  174639. }
  174640. /* Pass 2: process columns. */
  174641. dataptr = data;
  174642. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174643. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174644. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174645. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174646. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174647. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174648. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174649. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174650. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174651. /* Even part */
  174652. tmp10 = tmp0 + tmp3; /* phase 2 */
  174653. tmp13 = tmp0 - tmp3;
  174654. tmp11 = tmp1 + tmp2;
  174655. tmp12 = tmp1 - tmp2;
  174656. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174657. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174658. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174659. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174660. dataptr[DCTSIZE*6] = tmp13 - z1;
  174661. /* Odd part */
  174662. tmp10 = tmp4 + tmp5; /* phase 2 */
  174663. tmp11 = tmp5 + tmp6;
  174664. tmp12 = tmp6 + tmp7;
  174665. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174666. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174667. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174668. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174669. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174670. z11 = tmp7 + z3; /* phase 5 */
  174671. z13 = tmp7 - z3;
  174672. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174673. dataptr[DCTSIZE*3] = z13 - z2;
  174674. dataptr[DCTSIZE*1] = z11 + z4;
  174675. dataptr[DCTSIZE*7] = z11 - z4;
  174676. dataptr++; /* advance pointer to next column */
  174677. }
  174678. }
  174679. #endif /* DCT_IFAST_SUPPORTED */
  174680. /*** End of inlined file: jfdctfst.c ***/
  174681. #undef FIX_0_541196100
  174682. /*** Start of inlined file: jidctflt.c ***/
  174683. #define JPEG_INTERNALS
  174684. #ifdef DCT_FLOAT_SUPPORTED
  174685. /*
  174686. * This module is specialized to the case DCTSIZE = 8.
  174687. */
  174688. #if DCTSIZE != 8
  174689. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174690. #endif
  174691. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174692. * entry; produce a float result.
  174693. */
  174694. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174695. /*
  174696. * Perform dequantization and inverse DCT on one block of coefficients.
  174697. */
  174698. GLOBAL(void)
  174699. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174700. JCOEFPTR coef_block,
  174701. JSAMPARRAY output_buf, JDIMENSION output_col)
  174702. {
  174703. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174704. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174705. FAST_FLOAT z5, z10, z11, z12, z13;
  174706. JCOEFPTR inptr;
  174707. FLOAT_MULT_TYPE * quantptr;
  174708. FAST_FLOAT * wsptr;
  174709. JSAMPROW outptr;
  174710. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174711. int ctr;
  174712. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174713. SHIFT_TEMPS
  174714. /* Pass 1: process columns from input, store into work array. */
  174715. inptr = coef_block;
  174716. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174717. wsptr = workspace;
  174718. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174719. /* Due to quantization, we will usually find that many of the input
  174720. * coefficients are zero, especially the AC terms. We can exploit this
  174721. * by short-circuiting the IDCT calculation for any column in which all
  174722. * the AC terms are zero. In that case each output is equal to the
  174723. * DC coefficient (with scale factor as needed).
  174724. * With typical images and quantization tables, half or more of the
  174725. * column DCT calculations can be simplified this way.
  174726. */
  174727. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174728. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174729. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174730. inptr[DCTSIZE*7] == 0) {
  174731. /* AC terms all zero */
  174732. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174733. wsptr[DCTSIZE*0] = dcval;
  174734. wsptr[DCTSIZE*1] = dcval;
  174735. wsptr[DCTSIZE*2] = dcval;
  174736. wsptr[DCTSIZE*3] = dcval;
  174737. wsptr[DCTSIZE*4] = dcval;
  174738. wsptr[DCTSIZE*5] = dcval;
  174739. wsptr[DCTSIZE*6] = dcval;
  174740. wsptr[DCTSIZE*7] = dcval;
  174741. inptr++; /* advance pointers to next column */
  174742. quantptr++;
  174743. wsptr++;
  174744. continue;
  174745. }
  174746. /* Even part */
  174747. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174748. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174749. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174750. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174751. tmp10 = tmp0 + tmp2; /* phase 3 */
  174752. tmp11 = tmp0 - tmp2;
  174753. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174754. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174755. tmp0 = tmp10 + tmp13; /* phase 2 */
  174756. tmp3 = tmp10 - tmp13;
  174757. tmp1 = tmp11 + tmp12;
  174758. tmp2 = tmp11 - tmp12;
  174759. /* Odd part */
  174760. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174761. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174762. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174763. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174764. z13 = tmp6 + tmp5; /* phase 6 */
  174765. z10 = tmp6 - tmp5;
  174766. z11 = tmp4 + tmp7;
  174767. z12 = tmp4 - tmp7;
  174768. tmp7 = z11 + z13; /* phase 5 */
  174769. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174770. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174771. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174772. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174773. tmp6 = tmp12 - tmp7; /* phase 2 */
  174774. tmp5 = tmp11 - tmp6;
  174775. tmp4 = tmp10 + tmp5;
  174776. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174777. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174778. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174779. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174780. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174781. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174782. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174783. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174784. inptr++; /* advance pointers to next column */
  174785. quantptr++;
  174786. wsptr++;
  174787. }
  174788. /* Pass 2: process rows from work array, store into output array. */
  174789. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174790. wsptr = workspace;
  174791. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174792. outptr = output_buf[ctr] + output_col;
  174793. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174794. * However, the column calculation has created many nonzero AC terms, so
  174795. * the simplification applies less often (typically 5% to 10% of the time).
  174796. * And testing floats for zero is relatively expensive, so we don't bother.
  174797. */
  174798. /* Even part */
  174799. tmp10 = wsptr[0] + wsptr[4];
  174800. tmp11 = wsptr[0] - wsptr[4];
  174801. tmp13 = wsptr[2] + wsptr[6];
  174802. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174803. tmp0 = tmp10 + tmp13;
  174804. tmp3 = tmp10 - tmp13;
  174805. tmp1 = tmp11 + tmp12;
  174806. tmp2 = tmp11 - tmp12;
  174807. /* Odd part */
  174808. z13 = wsptr[5] + wsptr[3];
  174809. z10 = wsptr[5] - wsptr[3];
  174810. z11 = wsptr[1] + wsptr[7];
  174811. z12 = wsptr[1] - wsptr[7];
  174812. tmp7 = z11 + z13;
  174813. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174814. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174815. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174816. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174817. tmp6 = tmp12 - tmp7;
  174818. tmp5 = tmp11 - tmp6;
  174819. tmp4 = tmp10 + tmp5;
  174820. /* Final output stage: scale down by a factor of 8 and range-limit */
  174821. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174822. & RANGE_MASK];
  174823. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174824. & RANGE_MASK];
  174825. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174826. & RANGE_MASK];
  174827. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174828. & RANGE_MASK];
  174829. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174830. & RANGE_MASK];
  174831. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174832. & RANGE_MASK];
  174833. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174834. & RANGE_MASK];
  174835. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174836. & RANGE_MASK];
  174837. wsptr += DCTSIZE; /* advance pointer to next row */
  174838. }
  174839. }
  174840. #endif /* DCT_FLOAT_SUPPORTED */
  174841. /*** End of inlined file: jidctflt.c ***/
  174842. #undef CONST_BITS
  174843. #undef FIX_1_847759065
  174844. #undef MULTIPLY
  174845. #undef DEQUANTIZE
  174846. #undef DESCALE
  174847. /*** Start of inlined file: jidctfst.c ***/
  174848. #define JPEG_INTERNALS
  174849. #ifdef DCT_IFAST_SUPPORTED
  174850. /*
  174851. * This module is specialized to the case DCTSIZE = 8.
  174852. */
  174853. #if DCTSIZE != 8
  174854. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174855. #endif
  174856. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174857. * see jidctint.c for more details. However, we choose to descale
  174858. * (right shift) multiplication products as soon as they are formed,
  174859. * rather than carrying additional fractional bits into subsequent additions.
  174860. * This compromises accuracy slightly, but it lets us save a few shifts.
  174861. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174862. * everywhere except in the multiplications proper; this saves a good deal
  174863. * of work on 16-bit-int machines.
  174864. *
  174865. * The dequantized coefficients are not integers because the AA&N scaling
  174866. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174867. * so that the first and second IDCT rounds have the same input scaling.
  174868. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174869. * avoid a descaling shift; this compromises accuracy rather drastically
  174870. * for small quantization table entries, but it saves a lot of shifts.
  174871. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174872. * so we use a much larger scaling factor to preserve accuracy.
  174873. *
  174874. * A final compromise is to represent the multiplicative constants to only
  174875. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174876. * machines, and may also reduce the cost of multiplication (since there
  174877. * are fewer one-bits in the constants).
  174878. */
  174879. #if BITS_IN_JSAMPLE == 8
  174880. #define CONST_BITS 8
  174881. #define PASS1_BITS 2
  174882. #else
  174883. #define CONST_BITS 8
  174884. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174885. #endif
  174886. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174887. * causing a lot of useless floating-point operations at run time.
  174888. * To get around this we use the following pre-calculated constants.
  174889. * If you change CONST_BITS you may want to add appropriate values.
  174890. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174891. */
  174892. #if CONST_BITS == 8
  174893. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174894. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174895. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174896. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174897. #else
  174898. #define FIX_1_082392200 FIX(1.082392200)
  174899. #define FIX_1_414213562 FIX(1.414213562)
  174900. #define FIX_1_847759065 FIX(1.847759065)
  174901. #define FIX_2_613125930 FIX(2.613125930)
  174902. #endif
  174903. /* We can gain a little more speed, with a further compromise in accuracy,
  174904. * by omitting the addition in a descaling shift. This yields an incorrectly
  174905. * rounded result half the time...
  174906. */
  174907. #ifndef USE_ACCURATE_ROUNDING
  174908. #undef DESCALE
  174909. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174910. #endif
  174911. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174912. * descale to yield a DCTELEM result.
  174913. */
  174914. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174915. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174916. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174917. * multiplication will do. For 12-bit data, the multiplier table is
  174918. * declared INT32, so a 32-bit multiply will be used.
  174919. */
  174920. #if BITS_IN_JSAMPLE == 8
  174921. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174922. #else
  174923. #define DEQUANTIZE(coef,quantval) \
  174924. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174925. #endif
  174926. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174927. * We assume that int right shift is unsigned if INT32 right shift is.
  174928. */
  174929. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174930. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174931. #if BITS_IN_JSAMPLE == 8
  174932. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174933. #else
  174934. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174935. #endif
  174936. #define IRIGHT_SHIFT(x,shft) \
  174937. ((ishift_temp = (x)) < 0 ? \
  174938. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174939. (ishift_temp >> (shft)))
  174940. #else
  174941. #define ISHIFT_TEMPS
  174942. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174943. #endif
  174944. #ifdef USE_ACCURATE_ROUNDING
  174945. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174946. #else
  174947. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174948. #endif
  174949. /*
  174950. * Perform dequantization and inverse DCT on one block of coefficients.
  174951. */
  174952. GLOBAL(void)
  174953. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174954. JCOEFPTR coef_block,
  174955. JSAMPARRAY output_buf, JDIMENSION output_col)
  174956. {
  174957. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174958. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174959. DCTELEM z5, z10, z11, z12, z13;
  174960. JCOEFPTR inptr;
  174961. IFAST_MULT_TYPE * quantptr;
  174962. int * wsptr;
  174963. JSAMPROW outptr;
  174964. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174965. int ctr;
  174966. int workspace[DCTSIZE2]; /* buffers data between passes */
  174967. SHIFT_TEMPS /* for DESCALE */
  174968. ISHIFT_TEMPS /* for IDESCALE */
  174969. /* Pass 1: process columns from input, store into work array. */
  174970. inptr = coef_block;
  174971. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174972. wsptr = workspace;
  174973. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174974. /* Due to quantization, we will usually find that many of the input
  174975. * coefficients are zero, especially the AC terms. We can exploit this
  174976. * by short-circuiting the IDCT calculation for any column in which all
  174977. * the AC terms are zero. In that case each output is equal to the
  174978. * DC coefficient (with scale factor as needed).
  174979. * With typical images and quantization tables, half or more of the
  174980. * column DCT calculations can be simplified this way.
  174981. */
  174982. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174983. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174984. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174985. inptr[DCTSIZE*7] == 0) {
  174986. /* AC terms all zero */
  174987. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174988. wsptr[DCTSIZE*0] = dcval;
  174989. wsptr[DCTSIZE*1] = dcval;
  174990. wsptr[DCTSIZE*2] = dcval;
  174991. wsptr[DCTSIZE*3] = dcval;
  174992. wsptr[DCTSIZE*4] = dcval;
  174993. wsptr[DCTSIZE*5] = dcval;
  174994. wsptr[DCTSIZE*6] = dcval;
  174995. wsptr[DCTSIZE*7] = dcval;
  174996. inptr++; /* advance pointers to next column */
  174997. quantptr++;
  174998. wsptr++;
  174999. continue;
  175000. }
  175001. /* Even part */
  175002. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175003. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175004. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175005. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175006. tmp10 = tmp0 + tmp2; /* phase 3 */
  175007. tmp11 = tmp0 - tmp2;
  175008. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175009. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175010. tmp0 = tmp10 + tmp13; /* phase 2 */
  175011. tmp3 = tmp10 - tmp13;
  175012. tmp1 = tmp11 + tmp12;
  175013. tmp2 = tmp11 - tmp12;
  175014. /* Odd part */
  175015. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175016. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175017. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175018. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175019. z13 = tmp6 + tmp5; /* phase 6 */
  175020. z10 = tmp6 - tmp5;
  175021. z11 = tmp4 + tmp7;
  175022. z12 = tmp4 - tmp7;
  175023. tmp7 = z11 + z13; /* phase 5 */
  175024. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175025. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175026. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175027. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175028. tmp6 = tmp12 - tmp7; /* phase 2 */
  175029. tmp5 = tmp11 - tmp6;
  175030. tmp4 = tmp10 + tmp5;
  175031. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175032. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175033. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175034. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175035. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175036. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175037. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175038. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175039. inptr++; /* advance pointers to next column */
  175040. quantptr++;
  175041. wsptr++;
  175042. }
  175043. /* Pass 2: process rows from work array, store into output array. */
  175044. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175045. /* and also undo the PASS1_BITS scaling. */
  175046. wsptr = workspace;
  175047. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175048. outptr = output_buf[ctr] + output_col;
  175049. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175050. * However, the column calculation has created many nonzero AC terms, so
  175051. * the simplification applies less often (typically 5% to 10% of the time).
  175052. * On machines with very fast multiplication, it's possible that the
  175053. * test takes more time than it's worth. In that case this section
  175054. * may be commented out.
  175055. */
  175056. #ifndef NO_ZERO_ROW_TEST
  175057. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175058. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175059. /* AC terms all zero */
  175060. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175061. & RANGE_MASK];
  175062. outptr[0] = dcval;
  175063. outptr[1] = dcval;
  175064. outptr[2] = dcval;
  175065. outptr[3] = dcval;
  175066. outptr[4] = dcval;
  175067. outptr[5] = dcval;
  175068. outptr[6] = dcval;
  175069. outptr[7] = dcval;
  175070. wsptr += DCTSIZE; /* advance pointer to next row */
  175071. continue;
  175072. }
  175073. #endif
  175074. /* Even part */
  175075. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175076. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175077. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175078. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175079. - tmp13;
  175080. tmp0 = tmp10 + tmp13;
  175081. tmp3 = tmp10 - tmp13;
  175082. tmp1 = tmp11 + tmp12;
  175083. tmp2 = tmp11 - tmp12;
  175084. /* Odd part */
  175085. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175086. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175087. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175088. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175089. tmp7 = z11 + z13; /* phase 5 */
  175090. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175091. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175092. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175093. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175094. tmp6 = tmp12 - tmp7; /* phase 2 */
  175095. tmp5 = tmp11 - tmp6;
  175096. tmp4 = tmp10 + tmp5;
  175097. /* Final output stage: scale down by a factor of 8 and range-limit */
  175098. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175099. & RANGE_MASK];
  175100. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175101. & RANGE_MASK];
  175102. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175103. & RANGE_MASK];
  175104. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175105. & RANGE_MASK];
  175106. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175107. & RANGE_MASK];
  175108. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175109. & RANGE_MASK];
  175110. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175111. & RANGE_MASK];
  175112. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175113. & RANGE_MASK];
  175114. wsptr += DCTSIZE; /* advance pointer to next row */
  175115. }
  175116. }
  175117. #endif /* DCT_IFAST_SUPPORTED */
  175118. /*** End of inlined file: jidctfst.c ***/
  175119. #undef CONST_BITS
  175120. #undef FIX_1_847759065
  175121. #undef MULTIPLY
  175122. #undef DEQUANTIZE
  175123. /*** Start of inlined file: jidctint.c ***/
  175124. #define JPEG_INTERNALS
  175125. #ifdef DCT_ISLOW_SUPPORTED
  175126. /*
  175127. * This module is specialized to the case DCTSIZE = 8.
  175128. */
  175129. #if DCTSIZE != 8
  175130. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175131. #endif
  175132. /*
  175133. * The poop on this scaling stuff is as follows:
  175134. *
  175135. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175136. * larger than the true IDCT outputs. The final outputs are therefore
  175137. * a factor of N larger than desired; since N=8 this can be cured by
  175138. * a simple right shift at the end of the algorithm. The advantage of
  175139. * this arrangement is that we save two multiplications per 1-D IDCT,
  175140. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175141. *
  175142. * We have to do addition and subtraction of the integer inputs, which
  175143. * is no problem, and multiplication by fractional constants, which is
  175144. * a problem to do in integer arithmetic. We multiply all the constants
  175145. * by CONST_SCALE and convert them to integer constants (thus retaining
  175146. * CONST_BITS bits of precision in the constants). After doing a
  175147. * multiplication we have to divide the product by CONST_SCALE, with proper
  175148. * rounding, to produce the correct output. This division can be done
  175149. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175150. * as long as possible so that partial sums can be added together with
  175151. * full fractional precision.
  175152. *
  175153. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175154. * they are represented to better-than-integral precision. These outputs
  175155. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175156. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175157. * intermediate INT32 array would be needed.)
  175158. *
  175159. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175160. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175161. * shows that the values given below are the most effective.
  175162. */
  175163. #if BITS_IN_JSAMPLE == 8
  175164. #define CONST_BITS 13
  175165. #define PASS1_BITS 2
  175166. #else
  175167. #define CONST_BITS 13
  175168. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175169. #endif
  175170. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175171. * causing a lot of useless floating-point operations at run time.
  175172. * To get around this we use the following pre-calculated constants.
  175173. * If you change CONST_BITS you may want to add appropriate values.
  175174. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175175. */
  175176. #if CONST_BITS == 13
  175177. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175178. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175179. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175180. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175181. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175182. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175183. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175184. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175185. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175186. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175187. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175188. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175189. #else
  175190. #define FIX_0_298631336 FIX(0.298631336)
  175191. #define FIX_0_390180644 FIX(0.390180644)
  175192. #define FIX_0_541196100 FIX(0.541196100)
  175193. #define FIX_0_765366865 FIX(0.765366865)
  175194. #define FIX_0_899976223 FIX(0.899976223)
  175195. #define FIX_1_175875602 FIX(1.175875602)
  175196. #define FIX_1_501321110 FIX(1.501321110)
  175197. #define FIX_1_847759065 FIX(1.847759065)
  175198. #define FIX_1_961570560 FIX(1.961570560)
  175199. #define FIX_2_053119869 FIX(2.053119869)
  175200. #define FIX_2_562915447 FIX(2.562915447)
  175201. #define FIX_3_072711026 FIX(3.072711026)
  175202. #endif
  175203. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175204. * For 8-bit samples with the recommended scaling, all the variable
  175205. * and constant values involved are no more than 16 bits wide, so a
  175206. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175207. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175208. */
  175209. #if BITS_IN_JSAMPLE == 8
  175210. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175211. #else
  175212. #define MULTIPLY(var,const) ((var) * (const))
  175213. #endif
  175214. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175215. * entry; produce an int result. In this module, both inputs and result
  175216. * are 16 bits or less, so either int or short multiply will work.
  175217. */
  175218. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175219. /*
  175220. * Perform dequantization and inverse DCT on one block of coefficients.
  175221. */
  175222. GLOBAL(void)
  175223. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175224. JCOEFPTR coef_block,
  175225. JSAMPARRAY output_buf, JDIMENSION output_col)
  175226. {
  175227. INT32 tmp0, tmp1, tmp2, tmp3;
  175228. INT32 tmp10, tmp11, tmp12, tmp13;
  175229. INT32 z1, z2, z3, z4, z5;
  175230. JCOEFPTR inptr;
  175231. ISLOW_MULT_TYPE * quantptr;
  175232. int * wsptr;
  175233. JSAMPROW outptr;
  175234. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175235. int ctr;
  175236. int workspace[DCTSIZE2]; /* buffers data between passes */
  175237. SHIFT_TEMPS
  175238. /* Pass 1: process columns from input, store into work array. */
  175239. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175240. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175241. inptr = coef_block;
  175242. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175243. wsptr = workspace;
  175244. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175245. /* Due to quantization, we will usually find that many of the input
  175246. * coefficients are zero, especially the AC terms. We can exploit this
  175247. * by short-circuiting the IDCT calculation for any column in which all
  175248. * the AC terms are zero. In that case each output is equal to the
  175249. * DC coefficient (with scale factor as needed).
  175250. * With typical images and quantization tables, half or more of the
  175251. * column DCT calculations can be simplified this way.
  175252. */
  175253. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175254. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175255. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175256. inptr[DCTSIZE*7] == 0) {
  175257. /* AC terms all zero */
  175258. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175259. wsptr[DCTSIZE*0] = dcval;
  175260. wsptr[DCTSIZE*1] = dcval;
  175261. wsptr[DCTSIZE*2] = dcval;
  175262. wsptr[DCTSIZE*3] = dcval;
  175263. wsptr[DCTSIZE*4] = dcval;
  175264. wsptr[DCTSIZE*5] = dcval;
  175265. wsptr[DCTSIZE*6] = dcval;
  175266. wsptr[DCTSIZE*7] = dcval;
  175267. inptr++; /* advance pointers to next column */
  175268. quantptr++;
  175269. wsptr++;
  175270. continue;
  175271. }
  175272. /* Even part: reverse the even part of the forward DCT. */
  175273. /* The rotator is sqrt(2)*c(-6). */
  175274. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175275. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175276. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175277. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175278. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175279. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175280. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175281. tmp0 = (z2 + z3) << CONST_BITS;
  175282. tmp1 = (z2 - z3) << CONST_BITS;
  175283. tmp10 = tmp0 + tmp3;
  175284. tmp13 = tmp0 - tmp3;
  175285. tmp11 = tmp1 + tmp2;
  175286. tmp12 = tmp1 - tmp2;
  175287. /* Odd part per figure 8; the matrix is unitary and hence its
  175288. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175289. */
  175290. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175291. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175292. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175293. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175294. z1 = tmp0 + tmp3;
  175295. z2 = tmp1 + tmp2;
  175296. z3 = tmp0 + tmp2;
  175297. z4 = tmp1 + tmp3;
  175298. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175299. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175300. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175301. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175302. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175303. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175304. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175305. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175306. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175307. z3 += z5;
  175308. z4 += z5;
  175309. tmp0 += z1 + z3;
  175310. tmp1 += z2 + z4;
  175311. tmp2 += z2 + z3;
  175312. tmp3 += z1 + z4;
  175313. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175314. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175315. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175316. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175317. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175318. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175319. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175320. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175321. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175322. inptr++; /* advance pointers to next column */
  175323. quantptr++;
  175324. wsptr++;
  175325. }
  175326. /* Pass 2: process rows from work array, store into output array. */
  175327. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175328. /* and also undo the PASS1_BITS scaling. */
  175329. wsptr = workspace;
  175330. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175331. outptr = output_buf[ctr] + output_col;
  175332. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175333. * However, the column calculation has created many nonzero AC terms, so
  175334. * the simplification applies less often (typically 5% to 10% of the time).
  175335. * On machines with very fast multiplication, it's possible that the
  175336. * test takes more time than it's worth. In that case this section
  175337. * may be commented out.
  175338. */
  175339. #ifndef NO_ZERO_ROW_TEST
  175340. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175341. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175342. /* AC terms all zero */
  175343. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175344. & RANGE_MASK];
  175345. outptr[0] = dcval;
  175346. outptr[1] = dcval;
  175347. outptr[2] = dcval;
  175348. outptr[3] = dcval;
  175349. outptr[4] = dcval;
  175350. outptr[5] = dcval;
  175351. outptr[6] = dcval;
  175352. outptr[7] = dcval;
  175353. wsptr += DCTSIZE; /* advance pointer to next row */
  175354. continue;
  175355. }
  175356. #endif
  175357. /* Even part: reverse the even part of the forward DCT. */
  175358. /* The rotator is sqrt(2)*c(-6). */
  175359. z2 = (INT32) wsptr[2];
  175360. z3 = (INT32) wsptr[6];
  175361. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175362. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175363. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175364. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175365. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175366. tmp10 = tmp0 + tmp3;
  175367. tmp13 = tmp0 - tmp3;
  175368. tmp11 = tmp1 + tmp2;
  175369. tmp12 = tmp1 - tmp2;
  175370. /* Odd part per figure 8; the matrix is unitary and hence its
  175371. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175372. */
  175373. tmp0 = (INT32) wsptr[7];
  175374. tmp1 = (INT32) wsptr[5];
  175375. tmp2 = (INT32) wsptr[3];
  175376. tmp3 = (INT32) wsptr[1];
  175377. z1 = tmp0 + tmp3;
  175378. z2 = tmp1 + tmp2;
  175379. z3 = tmp0 + tmp2;
  175380. z4 = tmp1 + tmp3;
  175381. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175382. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175383. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175384. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175385. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175386. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175387. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175388. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175389. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175390. z3 += z5;
  175391. z4 += z5;
  175392. tmp0 += z1 + z3;
  175393. tmp1 += z2 + z4;
  175394. tmp2 += z2 + z3;
  175395. tmp3 += z1 + z4;
  175396. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175397. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175398. CONST_BITS+PASS1_BITS+3)
  175399. & RANGE_MASK];
  175400. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175401. CONST_BITS+PASS1_BITS+3)
  175402. & RANGE_MASK];
  175403. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175404. CONST_BITS+PASS1_BITS+3)
  175405. & RANGE_MASK];
  175406. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175407. CONST_BITS+PASS1_BITS+3)
  175408. & RANGE_MASK];
  175409. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175410. CONST_BITS+PASS1_BITS+3)
  175411. & RANGE_MASK];
  175412. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175413. CONST_BITS+PASS1_BITS+3)
  175414. & RANGE_MASK];
  175415. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175416. CONST_BITS+PASS1_BITS+3)
  175417. & RANGE_MASK];
  175418. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175419. CONST_BITS+PASS1_BITS+3)
  175420. & RANGE_MASK];
  175421. wsptr += DCTSIZE; /* advance pointer to next row */
  175422. }
  175423. }
  175424. #endif /* DCT_ISLOW_SUPPORTED */
  175425. /*** End of inlined file: jidctint.c ***/
  175426. /*** Start of inlined file: jidctred.c ***/
  175427. #define JPEG_INTERNALS
  175428. #ifdef IDCT_SCALING_SUPPORTED
  175429. /*
  175430. * This module is specialized to the case DCTSIZE = 8.
  175431. */
  175432. #if DCTSIZE != 8
  175433. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175434. #endif
  175435. /* Scaling is the same as in jidctint.c. */
  175436. #if BITS_IN_JSAMPLE == 8
  175437. #define CONST_BITS 13
  175438. #define PASS1_BITS 2
  175439. #else
  175440. #define CONST_BITS 13
  175441. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175442. #endif
  175443. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175444. * causing a lot of useless floating-point operations at run time.
  175445. * To get around this we use the following pre-calculated constants.
  175446. * If you change CONST_BITS you may want to add appropriate values.
  175447. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175448. */
  175449. #if CONST_BITS == 13
  175450. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175451. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175452. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175453. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175454. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175455. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175456. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175457. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175458. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175459. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175460. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175461. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175462. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175463. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175464. #else
  175465. #define FIX_0_211164243 FIX(0.211164243)
  175466. #define FIX_0_509795579 FIX(0.509795579)
  175467. #define FIX_0_601344887 FIX(0.601344887)
  175468. #define FIX_0_720959822 FIX(0.720959822)
  175469. #define FIX_0_765366865 FIX(0.765366865)
  175470. #define FIX_0_850430095 FIX(0.850430095)
  175471. #define FIX_0_899976223 FIX(0.899976223)
  175472. #define FIX_1_061594337 FIX(1.061594337)
  175473. #define FIX_1_272758580 FIX(1.272758580)
  175474. #define FIX_1_451774981 FIX(1.451774981)
  175475. #define FIX_1_847759065 FIX(1.847759065)
  175476. #define FIX_2_172734803 FIX(2.172734803)
  175477. #define FIX_2_562915447 FIX(2.562915447)
  175478. #define FIX_3_624509785 FIX(3.624509785)
  175479. #endif
  175480. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175481. * For 8-bit samples with the recommended scaling, all the variable
  175482. * and constant values involved are no more than 16 bits wide, so a
  175483. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175484. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175485. */
  175486. #if BITS_IN_JSAMPLE == 8
  175487. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175488. #else
  175489. #define MULTIPLY(var,const) ((var) * (const))
  175490. #endif
  175491. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175492. * entry; produce an int result. In this module, both inputs and result
  175493. * are 16 bits or less, so either int or short multiply will work.
  175494. */
  175495. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175496. /*
  175497. * Perform dequantization and inverse DCT on one block of coefficients,
  175498. * producing a reduced-size 4x4 output block.
  175499. */
  175500. GLOBAL(void)
  175501. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175502. JCOEFPTR coef_block,
  175503. JSAMPARRAY output_buf, JDIMENSION output_col)
  175504. {
  175505. INT32 tmp0, tmp2, tmp10, tmp12;
  175506. INT32 z1, z2, z3, z4;
  175507. JCOEFPTR inptr;
  175508. ISLOW_MULT_TYPE * quantptr;
  175509. int * wsptr;
  175510. JSAMPROW outptr;
  175511. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175512. int ctr;
  175513. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175514. SHIFT_TEMPS
  175515. /* Pass 1: process columns from input, store into work array. */
  175516. inptr = coef_block;
  175517. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175518. wsptr = workspace;
  175519. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175520. /* Don't bother to process column 4, because second pass won't use it */
  175521. if (ctr == DCTSIZE-4)
  175522. continue;
  175523. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175524. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175525. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175526. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175527. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175528. wsptr[DCTSIZE*0] = dcval;
  175529. wsptr[DCTSIZE*1] = dcval;
  175530. wsptr[DCTSIZE*2] = dcval;
  175531. wsptr[DCTSIZE*3] = dcval;
  175532. continue;
  175533. }
  175534. /* Even part */
  175535. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175536. tmp0 <<= (CONST_BITS+1);
  175537. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175538. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175539. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175540. tmp10 = tmp0 + tmp2;
  175541. tmp12 = tmp0 - tmp2;
  175542. /* Odd part */
  175543. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175544. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175545. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175546. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175547. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175548. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175549. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175550. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175551. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175552. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175553. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175554. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175555. /* Final output stage */
  175556. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175557. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175558. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175559. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175560. }
  175561. /* Pass 2: process 4 rows from work array, store into output array. */
  175562. wsptr = workspace;
  175563. for (ctr = 0; ctr < 4; ctr++) {
  175564. outptr = output_buf[ctr] + output_col;
  175565. /* It's not clear whether a zero row test is worthwhile here ... */
  175566. #ifndef NO_ZERO_ROW_TEST
  175567. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175568. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175569. /* AC terms all zero */
  175570. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175571. & RANGE_MASK];
  175572. outptr[0] = dcval;
  175573. outptr[1] = dcval;
  175574. outptr[2] = dcval;
  175575. outptr[3] = dcval;
  175576. wsptr += DCTSIZE; /* advance pointer to next row */
  175577. continue;
  175578. }
  175579. #endif
  175580. /* Even part */
  175581. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175582. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175583. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175584. tmp10 = tmp0 + tmp2;
  175585. tmp12 = tmp0 - tmp2;
  175586. /* Odd part */
  175587. z1 = (INT32) wsptr[7];
  175588. z2 = (INT32) wsptr[5];
  175589. z3 = (INT32) wsptr[3];
  175590. z4 = (INT32) wsptr[1];
  175591. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175592. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175593. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175594. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175595. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175596. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175597. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175598. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175599. /* Final output stage */
  175600. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175601. CONST_BITS+PASS1_BITS+3+1)
  175602. & RANGE_MASK];
  175603. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175604. CONST_BITS+PASS1_BITS+3+1)
  175605. & RANGE_MASK];
  175606. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175607. CONST_BITS+PASS1_BITS+3+1)
  175608. & RANGE_MASK];
  175609. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175610. CONST_BITS+PASS1_BITS+3+1)
  175611. & RANGE_MASK];
  175612. wsptr += DCTSIZE; /* advance pointer to next row */
  175613. }
  175614. }
  175615. /*
  175616. * Perform dequantization and inverse DCT on one block of coefficients,
  175617. * producing a reduced-size 2x2 output block.
  175618. */
  175619. GLOBAL(void)
  175620. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175621. JCOEFPTR coef_block,
  175622. JSAMPARRAY output_buf, JDIMENSION output_col)
  175623. {
  175624. INT32 tmp0, tmp10, z1;
  175625. JCOEFPTR inptr;
  175626. ISLOW_MULT_TYPE * quantptr;
  175627. int * wsptr;
  175628. JSAMPROW outptr;
  175629. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175630. int ctr;
  175631. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175632. SHIFT_TEMPS
  175633. /* Pass 1: process columns from input, store into work array. */
  175634. inptr = coef_block;
  175635. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175636. wsptr = workspace;
  175637. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175638. /* Don't bother to process columns 2,4,6 */
  175639. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175640. continue;
  175641. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175642. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175643. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175644. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175645. wsptr[DCTSIZE*0] = dcval;
  175646. wsptr[DCTSIZE*1] = dcval;
  175647. continue;
  175648. }
  175649. /* Even part */
  175650. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175651. tmp10 = z1 << (CONST_BITS+2);
  175652. /* Odd part */
  175653. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175654. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175655. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175656. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175657. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175658. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175659. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175660. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175661. /* Final output stage */
  175662. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175663. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175664. }
  175665. /* Pass 2: process 2 rows from work array, store into output array. */
  175666. wsptr = workspace;
  175667. for (ctr = 0; ctr < 2; ctr++) {
  175668. outptr = output_buf[ctr] + output_col;
  175669. /* It's not clear whether a zero row test is worthwhile here ... */
  175670. #ifndef NO_ZERO_ROW_TEST
  175671. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175672. /* AC terms all zero */
  175673. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175674. & RANGE_MASK];
  175675. outptr[0] = dcval;
  175676. outptr[1] = dcval;
  175677. wsptr += DCTSIZE; /* advance pointer to next row */
  175678. continue;
  175679. }
  175680. #endif
  175681. /* Even part */
  175682. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175683. /* Odd part */
  175684. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175685. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175686. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175687. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175688. /* Final output stage */
  175689. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175690. CONST_BITS+PASS1_BITS+3+2)
  175691. & RANGE_MASK];
  175692. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175693. CONST_BITS+PASS1_BITS+3+2)
  175694. & RANGE_MASK];
  175695. wsptr += DCTSIZE; /* advance pointer to next row */
  175696. }
  175697. }
  175698. /*
  175699. * Perform dequantization and inverse DCT on one block of coefficients,
  175700. * producing a reduced-size 1x1 output block.
  175701. */
  175702. GLOBAL(void)
  175703. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175704. JCOEFPTR coef_block,
  175705. JSAMPARRAY output_buf, JDIMENSION output_col)
  175706. {
  175707. int dcval;
  175708. ISLOW_MULT_TYPE * quantptr;
  175709. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175710. SHIFT_TEMPS
  175711. /* We hardly need an inverse DCT routine for this: just take the
  175712. * average pixel value, which is one-eighth of the DC coefficient.
  175713. */
  175714. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175715. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175716. dcval = (int) DESCALE((INT32) dcval, 3);
  175717. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175718. }
  175719. #endif /* IDCT_SCALING_SUPPORTED */
  175720. /*** End of inlined file: jidctred.c ***/
  175721. /*** Start of inlined file: jmemmgr.c ***/
  175722. #define JPEG_INTERNALS
  175723. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175724. /*** Start of inlined file: jmemsys.h ***/
  175725. #ifndef __jmemsys_h__
  175726. #define __jmemsys_h__
  175727. /* Short forms of external names for systems with brain-damaged linkers. */
  175728. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175729. #define jpeg_get_small jGetSmall
  175730. #define jpeg_free_small jFreeSmall
  175731. #define jpeg_get_large jGetLarge
  175732. #define jpeg_free_large jFreeLarge
  175733. #define jpeg_mem_available jMemAvail
  175734. #define jpeg_open_backing_store jOpenBackStore
  175735. #define jpeg_mem_init jMemInit
  175736. #define jpeg_mem_term jMemTerm
  175737. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175738. /*
  175739. * These two functions are used to allocate and release small chunks of
  175740. * memory. (Typically the total amount requested through jpeg_get_small is
  175741. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175742. * Behavior should be the same as for the standard library functions malloc
  175743. * and free; in particular, jpeg_get_small must return NULL on failure.
  175744. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175745. * size of the object being freed, just in case it's needed.
  175746. * On an 80x86 machine using small-data memory model, these manage near heap.
  175747. */
  175748. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175749. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175750. size_t sizeofobject));
  175751. /*
  175752. * These two functions are used to allocate and release large chunks of
  175753. * memory (up to the total free space designated by jpeg_mem_available).
  175754. * The interface is the same as above, except that on an 80x86 machine,
  175755. * far pointers are used. On most other machines these are identical to
  175756. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175757. * in case a different allocation strategy is desirable for large chunks.
  175758. */
  175759. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175760. size_t sizeofobject));
  175761. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175762. size_t sizeofobject));
  175763. /*
  175764. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175765. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175766. * matter, but that case should never come into play). This macro is needed
  175767. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175768. * On those machines, we expect that jconfig.h will provide a proper value.
  175769. * On machines with 32-bit flat address spaces, any large constant may be used.
  175770. *
  175771. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175772. * size_t and will be a multiple of sizeof(align_type).
  175773. */
  175774. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175775. #define MAX_ALLOC_CHUNK 1000000000L
  175776. #endif
  175777. /*
  175778. * This routine computes the total space still available for allocation by
  175779. * jpeg_get_large. If more space than this is needed, backing store will be
  175780. * used. NOTE: any memory already allocated must not be counted.
  175781. *
  175782. * There is a minimum space requirement, corresponding to the minimum
  175783. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175784. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175785. * all working storage in memory, is also passed in case it is useful.
  175786. * Finally, the total space already allocated is passed. If no better
  175787. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175788. * is often a suitable calculation.
  175789. *
  175790. * It is OK for jpeg_mem_available to underestimate the space available
  175791. * (that'll just lead to more backing-store access than is really necessary).
  175792. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175793. * a slop factor from the true available space. 5% should be enough.
  175794. *
  175795. * On machines with lots of virtual memory, any large constant may be returned.
  175796. * Conversely, zero may be returned to always use the minimum amount of memory.
  175797. */
  175798. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175799. long min_bytes_needed,
  175800. long max_bytes_needed,
  175801. long already_allocated));
  175802. /*
  175803. * This structure holds whatever state is needed to access a single
  175804. * backing-store object. The read/write/close method pointers are called
  175805. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175806. * are private to the system-dependent backing store routines.
  175807. */
  175808. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175809. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175810. typedef unsigned short XMSH; /* type of extended-memory handles */
  175811. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175812. typedef union {
  175813. short file_handle; /* DOS file handle if it's a temp file */
  175814. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175815. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175816. } handle_union;
  175817. #endif /* USE_MSDOS_MEMMGR */
  175818. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175819. #include <Files.h>
  175820. #endif /* USE_MAC_MEMMGR */
  175821. //typedef struct backing_store_struct * backing_store_ptr;
  175822. typedef struct backing_store_struct {
  175823. /* Methods for reading/writing/closing this backing-store object */
  175824. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175825. struct backing_store_struct *info,
  175826. void FAR * buffer_address,
  175827. long file_offset, long byte_count));
  175828. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175829. struct backing_store_struct *info,
  175830. void FAR * buffer_address,
  175831. long file_offset, long byte_count));
  175832. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175833. struct backing_store_struct *info));
  175834. /* Private fields for system-dependent backing-store management */
  175835. #ifdef USE_MSDOS_MEMMGR
  175836. /* For the MS-DOS manager (jmemdos.c), we need: */
  175837. handle_union handle; /* reference to backing-store storage object */
  175838. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175839. #else
  175840. #ifdef USE_MAC_MEMMGR
  175841. /* For the Mac manager (jmemmac.c), we need: */
  175842. short temp_file; /* file reference number to temp file */
  175843. FSSpec tempSpec; /* the FSSpec for the temp file */
  175844. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175845. #else
  175846. /* For a typical implementation with temp files, we need: */
  175847. FILE * temp_file; /* stdio reference to temp file */
  175848. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175849. #endif
  175850. #endif
  175851. } backing_store_info;
  175852. /*
  175853. * Initial opening of a backing-store object. This must fill in the
  175854. * read/write/close pointers in the object. The read/write routines
  175855. * may take an error exit if the specified maximum file size is exceeded.
  175856. * (If jpeg_mem_available always returns a large value, this routine can
  175857. * just take an error exit.)
  175858. */
  175859. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175860. struct backing_store_struct *info,
  175861. long total_bytes_needed));
  175862. /*
  175863. * These routines take care of any system-dependent initialization and
  175864. * cleanup required. jpeg_mem_init will be called before anything is
  175865. * allocated (and, therefore, nothing in cinfo is of use except the error
  175866. * manager pointer). It should return a suitable default value for
  175867. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175868. * application. (Note that max_memory_to_use is only important if
  175869. * jpeg_mem_available chooses to consult it ... no one else will.)
  175870. * jpeg_mem_term may assume that all requested memory has been freed and that
  175871. * all opened backing-store objects have been closed.
  175872. */
  175873. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175874. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175875. #endif
  175876. /*** End of inlined file: jmemsys.h ***/
  175877. /* import the system-dependent declarations */
  175878. #ifndef NO_GETENV
  175879. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175880. extern char * getenv JPP((const char * name));
  175881. #endif
  175882. #endif
  175883. /*
  175884. * Some important notes:
  175885. * The allocation routines provided here must never return NULL.
  175886. * They should exit to error_exit if unsuccessful.
  175887. *
  175888. * It's not a good idea to try to merge the sarray and barray routines,
  175889. * even though they are textually almost the same, because samples are
  175890. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175891. * in machines where byte pointers have a different representation from
  175892. * word pointers, the resulting machine code could not be the same.
  175893. */
  175894. /*
  175895. * Many machines require storage alignment: longs must start on 4-byte
  175896. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175897. * always returns pointers that are multiples of the worst-case alignment
  175898. * requirement, and we had better do so too.
  175899. * There isn't any really portable way to determine the worst-case alignment
  175900. * requirement. This module assumes that the alignment requirement is
  175901. * multiples of sizeof(ALIGN_TYPE).
  175902. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175903. * workstations (where doubles really do need 8-byte alignment) and will work
  175904. * fine on nearly everything. If your machine has lesser alignment needs,
  175905. * you can save a few bytes by making ALIGN_TYPE smaller.
  175906. * The only place I know of where this will NOT work is certain Macintosh
  175907. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175908. * Doing 10-byte alignment is counterproductive because longwords won't be
  175909. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175910. * such a compiler.
  175911. */
  175912. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175913. #define ALIGN_TYPE double
  175914. #endif
  175915. /*
  175916. * We allocate objects from "pools", where each pool is gotten with a single
  175917. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175918. * overhead within a pool, except for alignment padding. Each pool has a
  175919. * header with a link to the next pool of the same class.
  175920. * Small and large pool headers are identical except that the latter's
  175921. * link pointer must be FAR on 80x86 machines.
  175922. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175923. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175924. * of the alignment requirement of ALIGN_TYPE.
  175925. */
  175926. typedef union small_pool_struct * small_pool_ptr;
  175927. typedef union small_pool_struct {
  175928. struct {
  175929. small_pool_ptr next; /* next in list of pools */
  175930. size_t bytes_used; /* how many bytes already used within pool */
  175931. size_t bytes_left; /* bytes still available in this pool */
  175932. } hdr;
  175933. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175934. } small_pool_hdr;
  175935. typedef union large_pool_struct FAR * large_pool_ptr;
  175936. typedef union large_pool_struct {
  175937. struct {
  175938. large_pool_ptr next; /* next in list of pools */
  175939. size_t bytes_used; /* how many bytes already used within pool */
  175940. size_t bytes_left; /* bytes still available in this pool */
  175941. } hdr;
  175942. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175943. } large_pool_hdr;
  175944. /*
  175945. * Here is the full definition of a memory manager object.
  175946. */
  175947. typedef struct {
  175948. struct jpeg_memory_mgr pub; /* public fields */
  175949. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175950. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175951. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175952. /* Since we only have one lifetime class of virtual arrays, only one
  175953. * linked list is necessary (for each datatype). Note that the virtual
  175954. * array control blocks being linked together are actually stored somewhere
  175955. * in the small-pool list.
  175956. */
  175957. jvirt_sarray_ptr virt_sarray_list;
  175958. jvirt_barray_ptr virt_barray_list;
  175959. /* This counts total space obtained from jpeg_get_small/large */
  175960. long total_space_allocated;
  175961. /* alloc_sarray and alloc_barray set this value for use by virtual
  175962. * array routines.
  175963. */
  175964. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175965. } my_memory_mgr;
  175966. typedef my_memory_mgr * my_mem_ptr;
  175967. /*
  175968. * The control blocks for virtual arrays.
  175969. * Note that these blocks are allocated in the "small" pool area.
  175970. * System-dependent info for the associated backing store (if any) is hidden
  175971. * inside the backing_store_info struct.
  175972. */
  175973. struct jvirt_sarray_control {
  175974. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175975. JDIMENSION rows_in_array; /* total virtual array height */
  175976. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175977. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175978. JDIMENSION rows_in_mem; /* height of memory buffer */
  175979. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175980. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175981. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175982. boolean pre_zero; /* pre-zero mode requested? */
  175983. boolean dirty; /* do current buffer contents need written? */
  175984. boolean b_s_open; /* is backing-store data valid? */
  175985. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175986. backing_store_info b_s_info; /* System-dependent control info */
  175987. };
  175988. struct jvirt_barray_control {
  175989. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175990. JDIMENSION rows_in_array; /* total virtual array height */
  175991. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175992. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175993. JDIMENSION rows_in_mem; /* height of memory buffer */
  175994. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175995. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175996. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175997. boolean pre_zero; /* pre-zero mode requested? */
  175998. boolean dirty; /* do current buffer contents need written? */
  175999. boolean b_s_open; /* is backing-store data valid? */
  176000. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176001. backing_store_info b_s_info; /* System-dependent control info */
  176002. };
  176003. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176004. LOCAL(void)
  176005. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176006. {
  176007. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176008. small_pool_ptr shdr_ptr;
  176009. large_pool_ptr lhdr_ptr;
  176010. /* Since this is only a debugging stub, we can cheat a little by using
  176011. * fprintf directly rather than going through the trace message code.
  176012. * This is helpful because message parm array can't handle longs.
  176013. */
  176014. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176015. pool_id, mem->total_space_allocated);
  176016. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176017. lhdr_ptr = lhdr_ptr->hdr.next) {
  176018. fprintf(stderr, " Large chunk used %ld\n",
  176019. (long) lhdr_ptr->hdr.bytes_used);
  176020. }
  176021. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176022. shdr_ptr = shdr_ptr->hdr.next) {
  176023. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176024. (long) shdr_ptr->hdr.bytes_used,
  176025. (long) shdr_ptr->hdr.bytes_left);
  176026. }
  176027. }
  176028. #endif /* MEM_STATS */
  176029. LOCAL(void)
  176030. out_of_memory (j_common_ptr cinfo, int which)
  176031. /* Report an out-of-memory error and stop execution */
  176032. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176033. {
  176034. #ifdef MEM_STATS
  176035. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176036. #endif
  176037. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176038. }
  176039. /*
  176040. * Allocation of "small" objects.
  176041. *
  176042. * For these, we use pooled storage. When a new pool must be created,
  176043. * we try to get enough space for the current request plus a "slop" factor,
  176044. * where the slop will be the amount of leftover space in the new pool.
  176045. * The speed vs. space tradeoff is largely determined by the slop values.
  176046. * A different slop value is provided for each pool class (lifetime),
  176047. * and we also distinguish the first pool of a class from later ones.
  176048. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176049. * machines, but may be too small if longs are 64 bits or more.
  176050. */
  176051. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176052. {
  176053. 1600, /* first PERMANENT pool */
  176054. 16000 /* first IMAGE pool */
  176055. };
  176056. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176057. {
  176058. 0, /* additional PERMANENT pools */
  176059. 5000 /* additional IMAGE pools */
  176060. };
  176061. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176062. METHODDEF(void *)
  176063. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176064. /* Allocate a "small" object */
  176065. {
  176066. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176067. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176068. char * data_ptr;
  176069. size_t odd_bytes, min_request, slop;
  176070. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176071. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176072. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176073. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176074. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176075. if (odd_bytes > 0)
  176076. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176077. /* See if space is available in any existing pool */
  176078. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176079. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176080. prev_hdr_ptr = NULL;
  176081. hdr_ptr = mem->small_list[pool_id];
  176082. while (hdr_ptr != NULL) {
  176083. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176084. break; /* found pool with enough space */
  176085. prev_hdr_ptr = hdr_ptr;
  176086. hdr_ptr = hdr_ptr->hdr.next;
  176087. }
  176088. /* Time to make a new pool? */
  176089. if (hdr_ptr == NULL) {
  176090. /* min_request is what we need now, slop is what will be leftover */
  176091. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176092. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176093. slop = first_pool_slop[pool_id];
  176094. else
  176095. slop = extra_pool_slop[pool_id];
  176096. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176097. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176098. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176099. /* Try to get space, if fail reduce slop and try again */
  176100. for (;;) {
  176101. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176102. if (hdr_ptr != NULL)
  176103. break;
  176104. slop /= 2;
  176105. if (slop < MIN_SLOP) /* give up when it gets real small */
  176106. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176107. }
  176108. mem->total_space_allocated += min_request + slop;
  176109. /* Success, initialize the new pool header and add to end of list */
  176110. hdr_ptr->hdr.next = NULL;
  176111. hdr_ptr->hdr.bytes_used = 0;
  176112. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176113. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176114. mem->small_list[pool_id] = hdr_ptr;
  176115. else
  176116. prev_hdr_ptr->hdr.next = hdr_ptr;
  176117. }
  176118. /* OK, allocate the object from the current pool */
  176119. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176120. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176121. hdr_ptr->hdr.bytes_used += sizeofobject;
  176122. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176123. return (void *) data_ptr;
  176124. }
  176125. /*
  176126. * Allocation of "large" objects.
  176127. *
  176128. * The external semantics of these are the same as "small" objects,
  176129. * except that FAR pointers are used on 80x86. However the pool
  176130. * management heuristics are quite different. We assume that each
  176131. * request is large enough that it may as well be passed directly to
  176132. * jpeg_get_large; the pool management just links everything together
  176133. * so that we can free it all on demand.
  176134. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176135. * structures. The routines that create these structures (see below)
  176136. * deliberately bunch rows together to ensure a large request size.
  176137. */
  176138. METHODDEF(void FAR *)
  176139. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176140. /* Allocate a "large" object */
  176141. {
  176142. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176143. large_pool_ptr hdr_ptr;
  176144. size_t odd_bytes;
  176145. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176146. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176147. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176148. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176149. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176150. if (odd_bytes > 0)
  176151. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176152. /* Always make a new pool */
  176153. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176154. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176155. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176156. SIZEOF(large_pool_hdr));
  176157. if (hdr_ptr == NULL)
  176158. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176159. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176160. /* Success, initialize the new pool header and add to list */
  176161. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176162. /* We maintain space counts in each pool header for statistical purposes,
  176163. * even though they are not needed for allocation.
  176164. */
  176165. hdr_ptr->hdr.bytes_used = sizeofobject;
  176166. hdr_ptr->hdr.bytes_left = 0;
  176167. mem->large_list[pool_id] = hdr_ptr;
  176168. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176169. }
  176170. /*
  176171. * Creation of 2-D sample arrays.
  176172. * The pointers are in near heap, the samples themselves in FAR heap.
  176173. *
  176174. * To minimize allocation overhead and to allow I/O of large contiguous
  176175. * blocks, we allocate the sample rows in groups of as many rows as possible
  176176. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176177. * NB: the virtual array control routines, later in this file, know about
  176178. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176179. * object so that it can be saved away if this sarray is the workspace for
  176180. * a virtual array.
  176181. */
  176182. METHODDEF(JSAMPARRAY)
  176183. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176184. JDIMENSION samplesperrow, JDIMENSION numrows)
  176185. /* Allocate a 2-D sample array */
  176186. {
  176187. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176188. JSAMPARRAY result;
  176189. JSAMPROW workspace;
  176190. JDIMENSION rowsperchunk, currow, i;
  176191. long ltemp;
  176192. /* Calculate max # of rows allowed in one allocation chunk */
  176193. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176194. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176195. if (ltemp <= 0)
  176196. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176197. if (ltemp < (long) numrows)
  176198. rowsperchunk = (JDIMENSION) ltemp;
  176199. else
  176200. rowsperchunk = numrows;
  176201. mem->last_rowsperchunk = rowsperchunk;
  176202. /* Get space for row pointers (small object) */
  176203. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176204. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176205. /* Get the rows themselves (large objects) */
  176206. currow = 0;
  176207. while (currow < numrows) {
  176208. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176209. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176210. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176211. * SIZEOF(JSAMPLE)));
  176212. for (i = rowsperchunk; i > 0; i--) {
  176213. result[currow++] = workspace;
  176214. workspace += samplesperrow;
  176215. }
  176216. }
  176217. return result;
  176218. }
  176219. /*
  176220. * Creation of 2-D coefficient-block arrays.
  176221. * This is essentially the same as the code for sample arrays, above.
  176222. */
  176223. METHODDEF(JBLOCKARRAY)
  176224. alloc_barray (j_common_ptr cinfo, int pool_id,
  176225. JDIMENSION blocksperrow, JDIMENSION numrows)
  176226. /* Allocate a 2-D coefficient-block array */
  176227. {
  176228. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176229. JBLOCKARRAY result;
  176230. JBLOCKROW workspace;
  176231. JDIMENSION rowsperchunk, currow, i;
  176232. long ltemp;
  176233. /* Calculate max # of rows allowed in one allocation chunk */
  176234. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176235. ((long) blocksperrow * SIZEOF(JBLOCK));
  176236. if (ltemp <= 0)
  176237. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176238. if (ltemp < (long) numrows)
  176239. rowsperchunk = (JDIMENSION) ltemp;
  176240. else
  176241. rowsperchunk = numrows;
  176242. mem->last_rowsperchunk = rowsperchunk;
  176243. /* Get space for row pointers (small object) */
  176244. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176245. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176246. /* Get the rows themselves (large objects) */
  176247. currow = 0;
  176248. while (currow < numrows) {
  176249. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176250. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176251. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176252. * SIZEOF(JBLOCK)));
  176253. for (i = rowsperchunk; i > 0; i--) {
  176254. result[currow++] = workspace;
  176255. workspace += blocksperrow;
  176256. }
  176257. }
  176258. return result;
  176259. }
  176260. /*
  176261. * About virtual array management:
  176262. *
  176263. * The above "normal" array routines are only used to allocate strip buffers
  176264. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176265. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176266. * time, but the memory manager must save the whole array for repeated
  176267. * accesses. The intended implementation is that there is a strip buffer in
  176268. * memory (as high as is possible given the desired memory limit), plus a
  176269. * backing file that holds the rest of the array.
  176270. *
  176271. * The request_virt_array routines are told the total size of the image and
  176272. * the maximum number of rows that will be accessed at once. The in-memory
  176273. * buffer must be at least as large as the maxaccess value.
  176274. *
  176275. * The request routines create control blocks but not the in-memory buffers.
  176276. * That is postponed until realize_virt_arrays is called. At that time the
  176277. * total amount of space needed is known (approximately, anyway), so free
  176278. * memory can be divided up fairly.
  176279. *
  176280. * The access_virt_array routines are responsible for making a specific strip
  176281. * area accessible (after reading or writing the backing file, if necessary).
  176282. * Note that the access routines are told whether the caller intends to modify
  176283. * the accessed strip; during a read-only pass this saves having to rewrite
  176284. * data to disk. The access routines are also responsible for pre-zeroing
  176285. * any newly accessed rows, if pre-zeroing was requested.
  176286. *
  176287. * In current usage, the access requests are usually for nonoverlapping
  176288. * strips; that is, successive access start_row numbers differ by exactly
  176289. * num_rows = maxaccess. This means we can get good performance with simple
  176290. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176291. * of the access height; then there will never be accesses across bufferload
  176292. * boundaries. The code will still work with overlapping access requests,
  176293. * but it doesn't handle bufferload overlaps very efficiently.
  176294. */
  176295. METHODDEF(jvirt_sarray_ptr)
  176296. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176297. JDIMENSION samplesperrow, JDIMENSION numrows,
  176298. JDIMENSION maxaccess)
  176299. /* Request a virtual 2-D sample array */
  176300. {
  176301. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176302. jvirt_sarray_ptr result;
  176303. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176304. if (pool_id != JPOOL_IMAGE)
  176305. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176306. /* get control block */
  176307. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176308. SIZEOF(struct jvirt_sarray_control));
  176309. result->mem_buffer = NULL; /* marks array not yet realized */
  176310. result->rows_in_array = numrows;
  176311. result->samplesperrow = samplesperrow;
  176312. result->maxaccess = maxaccess;
  176313. result->pre_zero = pre_zero;
  176314. result->b_s_open = FALSE; /* no associated backing-store object */
  176315. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176316. mem->virt_sarray_list = result;
  176317. return result;
  176318. }
  176319. METHODDEF(jvirt_barray_ptr)
  176320. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176321. JDIMENSION blocksperrow, JDIMENSION numrows,
  176322. JDIMENSION maxaccess)
  176323. /* Request a virtual 2-D coefficient-block array */
  176324. {
  176325. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176326. jvirt_barray_ptr result;
  176327. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176328. if (pool_id != JPOOL_IMAGE)
  176329. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176330. /* get control block */
  176331. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176332. SIZEOF(struct jvirt_barray_control));
  176333. result->mem_buffer = NULL; /* marks array not yet realized */
  176334. result->rows_in_array = numrows;
  176335. result->blocksperrow = blocksperrow;
  176336. result->maxaccess = maxaccess;
  176337. result->pre_zero = pre_zero;
  176338. result->b_s_open = FALSE; /* no associated backing-store object */
  176339. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176340. mem->virt_barray_list = result;
  176341. return result;
  176342. }
  176343. METHODDEF(void)
  176344. realize_virt_arrays (j_common_ptr cinfo)
  176345. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176346. {
  176347. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176348. long space_per_minheight, maximum_space, avail_mem;
  176349. long minheights, max_minheights;
  176350. jvirt_sarray_ptr sptr;
  176351. jvirt_barray_ptr bptr;
  176352. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176353. * and the maximum space needed (full image height in each buffer).
  176354. * These may be of use to the system-dependent jpeg_mem_available routine.
  176355. */
  176356. space_per_minheight = 0;
  176357. maximum_space = 0;
  176358. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176359. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176360. space_per_minheight += (long) sptr->maxaccess *
  176361. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176362. maximum_space += (long) sptr->rows_in_array *
  176363. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176364. }
  176365. }
  176366. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176367. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176368. space_per_minheight += (long) bptr->maxaccess *
  176369. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176370. maximum_space += (long) bptr->rows_in_array *
  176371. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176372. }
  176373. }
  176374. if (space_per_minheight <= 0)
  176375. return; /* no unrealized arrays, no work */
  176376. /* Determine amount of memory to actually use; this is system-dependent. */
  176377. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176378. mem->total_space_allocated);
  176379. /* If the maximum space needed is available, make all the buffers full
  176380. * height; otherwise parcel it out with the same number of minheights
  176381. * in each buffer.
  176382. */
  176383. if (avail_mem >= maximum_space)
  176384. max_minheights = 1000000000L;
  176385. else {
  176386. max_minheights = avail_mem / space_per_minheight;
  176387. /* If there doesn't seem to be enough space, try to get the minimum
  176388. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176389. */
  176390. if (max_minheights <= 0)
  176391. max_minheights = 1;
  176392. }
  176393. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176394. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176395. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176396. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176397. if (minheights <= max_minheights) {
  176398. /* This buffer fits in memory */
  176399. sptr->rows_in_mem = sptr->rows_in_array;
  176400. } else {
  176401. /* It doesn't fit in memory, create backing store. */
  176402. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176403. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176404. (long) sptr->rows_in_array *
  176405. (long) sptr->samplesperrow *
  176406. (long) SIZEOF(JSAMPLE));
  176407. sptr->b_s_open = TRUE;
  176408. }
  176409. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176410. sptr->samplesperrow, sptr->rows_in_mem);
  176411. sptr->rowsperchunk = mem->last_rowsperchunk;
  176412. sptr->cur_start_row = 0;
  176413. sptr->first_undef_row = 0;
  176414. sptr->dirty = FALSE;
  176415. }
  176416. }
  176417. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176418. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176419. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176420. if (minheights <= max_minheights) {
  176421. /* This buffer fits in memory */
  176422. bptr->rows_in_mem = bptr->rows_in_array;
  176423. } else {
  176424. /* It doesn't fit in memory, create backing store. */
  176425. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176426. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176427. (long) bptr->rows_in_array *
  176428. (long) bptr->blocksperrow *
  176429. (long) SIZEOF(JBLOCK));
  176430. bptr->b_s_open = TRUE;
  176431. }
  176432. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176433. bptr->blocksperrow, bptr->rows_in_mem);
  176434. bptr->rowsperchunk = mem->last_rowsperchunk;
  176435. bptr->cur_start_row = 0;
  176436. bptr->first_undef_row = 0;
  176437. bptr->dirty = FALSE;
  176438. }
  176439. }
  176440. }
  176441. LOCAL(void)
  176442. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176443. /* Do backing store read or write of a virtual sample array */
  176444. {
  176445. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176446. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176447. file_offset = ptr->cur_start_row * bytesperrow;
  176448. /* Loop to read or write each allocation chunk in mem_buffer */
  176449. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176450. /* One chunk, but check for short chunk at end of buffer */
  176451. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176452. /* Transfer no more than is currently defined */
  176453. thisrow = (long) ptr->cur_start_row + i;
  176454. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176455. /* Transfer no more than fits in file */
  176456. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176457. if (rows <= 0) /* this chunk might be past end of file! */
  176458. break;
  176459. byte_count = rows * bytesperrow;
  176460. if (writing)
  176461. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176462. (void FAR *) ptr->mem_buffer[i],
  176463. file_offset, byte_count);
  176464. else
  176465. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176466. (void FAR *) ptr->mem_buffer[i],
  176467. file_offset, byte_count);
  176468. file_offset += byte_count;
  176469. }
  176470. }
  176471. LOCAL(void)
  176472. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176473. /* Do backing store read or write of a virtual coefficient-block array */
  176474. {
  176475. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176476. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176477. file_offset = ptr->cur_start_row * bytesperrow;
  176478. /* Loop to read or write each allocation chunk in mem_buffer */
  176479. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176480. /* One chunk, but check for short chunk at end of buffer */
  176481. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176482. /* Transfer no more than is currently defined */
  176483. thisrow = (long) ptr->cur_start_row + i;
  176484. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176485. /* Transfer no more than fits in file */
  176486. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176487. if (rows <= 0) /* this chunk might be past end of file! */
  176488. break;
  176489. byte_count = rows * bytesperrow;
  176490. if (writing)
  176491. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176492. (void FAR *) ptr->mem_buffer[i],
  176493. file_offset, byte_count);
  176494. else
  176495. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176496. (void FAR *) ptr->mem_buffer[i],
  176497. file_offset, byte_count);
  176498. file_offset += byte_count;
  176499. }
  176500. }
  176501. METHODDEF(JSAMPARRAY)
  176502. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176503. JDIMENSION start_row, JDIMENSION num_rows,
  176504. boolean writable)
  176505. /* Access the part of a virtual sample array starting at start_row */
  176506. /* and extending for num_rows rows. writable is true if */
  176507. /* caller intends to modify the accessed area. */
  176508. {
  176509. JDIMENSION end_row = start_row + num_rows;
  176510. JDIMENSION undef_row;
  176511. /* debugging check */
  176512. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176513. ptr->mem_buffer == NULL)
  176514. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176515. /* Make the desired part of the virtual array accessible */
  176516. if (start_row < ptr->cur_start_row ||
  176517. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176518. if (! ptr->b_s_open)
  176519. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176520. /* Flush old buffer contents if necessary */
  176521. if (ptr->dirty) {
  176522. do_sarray_io(cinfo, ptr, TRUE);
  176523. ptr->dirty = FALSE;
  176524. }
  176525. /* Decide what part of virtual array to access.
  176526. * Algorithm: if target address > current window, assume forward scan,
  176527. * load starting at target address. If target address < current window,
  176528. * assume backward scan, load so that target area is top of window.
  176529. * Note that when switching from forward write to forward read, will have
  176530. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176531. */
  176532. if (start_row > ptr->cur_start_row) {
  176533. ptr->cur_start_row = start_row;
  176534. } else {
  176535. /* use long arithmetic here to avoid overflow & unsigned problems */
  176536. long ltemp;
  176537. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176538. if (ltemp < 0)
  176539. ltemp = 0; /* don't fall off front end of file */
  176540. ptr->cur_start_row = (JDIMENSION) ltemp;
  176541. }
  176542. /* Read in the selected part of the array.
  176543. * During the initial write pass, we will do no actual read
  176544. * because the selected part is all undefined.
  176545. */
  176546. do_sarray_io(cinfo, ptr, FALSE);
  176547. }
  176548. /* Ensure the accessed part of the array is defined; prezero if needed.
  176549. * To improve locality of access, we only prezero the part of the array
  176550. * that the caller is about to access, not the entire in-memory array.
  176551. */
  176552. if (ptr->first_undef_row < end_row) {
  176553. if (ptr->first_undef_row < start_row) {
  176554. if (writable) /* writer skipped over a section of array */
  176555. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176556. undef_row = start_row; /* but reader is allowed to read ahead */
  176557. } else {
  176558. undef_row = ptr->first_undef_row;
  176559. }
  176560. if (writable)
  176561. ptr->first_undef_row = end_row;
  176562. if (ptr->pre_zero) {
  176563. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176564. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176565. end_row -= ptr->cur_start_row;
  176566. while (undef_row < end_row) {
  176567. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176568. undef_row++;
  176569. }
  176570. } else {
  176571. if (! writable) /* reader looking at undefined data */
  176572. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176573. }
  176574. }
  176575. /* Flag the buffer dirty if caller will write in it */
  176576. if (writable)
  176577. ptr->dirty = TRUE;
  176578. /* Return address of proper part of the buffer */
  176579. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176580. }
  176581. METHODDEF(JBLOCKARRAY)
  176582. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176583. JDIMENSION start_row, JDIMENSION num_rows,
  176584. boolean writable)
  176585. /* Access the part of a virtual block array starting at start_row */
  176586. /* and extending for num_rows rows. writable is true if */
  176587. /* caller intends to modify the accessed area. */
  176588. {
  176589. JDIMENSION end_row = start_row + num_rows;
  176590. JDIMENSION undef_row;
  176591. /* debugging check */
  176592. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176593. ptr->mem_buffer == NULL)
  176594. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176595. /* Make the desired part of the virtual array accessible */
  176596. if (start_row < ptr->cur_start_row ||
  176597. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176598. if (! ptr->b_s_open)
  176599. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176600. /* Flush old buffer contents if necessary */
  176601. if (ptr->dirty) {
  176602. do_barray_io(cinfo, ptr, TRUE);
  176603. ptr->dirty = FALSE;
  176604. }
  176605. /* Decide what part of virtual array to access.
  176606. * Algorithm: if target address > current window, assume forward scan,
  176607. * load starting at target address. If target address < current window,
  176608. * assume backward scan, load so that target area is top of window.
  176609. * Note that when switching from forward write to forward read, will have
  176610. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176611. */
  176612. if (start_row > ptr->cur_start_row) {
  176613. ptr->cur_start_row = start_row;
  176614. } else {
  176615. /* use long arithmetic here to avoid overflow & unsigned problems */
  176616. long ltemp;
  176617. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176618. if (ltemp < 0)
  176619. ltemp = 0; /* don't fall off front end of file */
  176620. ptr->cur_start_row = (JDIMENSION) ltemp;
  176621. }
  176622. /* Read in the selected part of the array.
  176623. * During the initial write pass, we will do no actual read
  176624. * because the selected part is all undefined.
  176625. */
  176626. do_barray_io(cinfo, ptr, FALSE);
  176627. }
  176628. /* Ensure the accessed part of the array is defined; prezero if needed.
  176629. * To improve locality of access, we only prezero the part of the array
  176630. * that the caller is about to access, not the entire in-memory array.
  176631. */
  176632. if (ptr->first_undef_row < end_row) {
  176633. if (ptr->first_undef_row < start_row) {
  176634. if (writable) /* writer skipped over a section of array */
  176635. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176636. undef_row = start_row; /* but reader is allowed to read ahead */
  176637. } else {
  176638. undef_row = ptr->first_undef_row;
  176639. }
  176640. if (writable)
  176641. ptr->first_undef_row = end_row;
  176642. if (ptr->pre_zero) {
  176643. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176644. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176645. end_row -= ptr->cur_start_row;
  176646. while (undef_row < end_row) {
  176647. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176648. undef_row++;
  176649. }
  176650. } else {
  176651. if (! writable) /* reader looking at undefined data */
  176652. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176653. }
  176654. }
  176655. /* Flag the buffer dirty if caller will write in it */
  176656. if (writable)
  176657. ptr->dirty = TRUE;
  176658. /* Return address of proper part of the buffer */
  176659. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176660. }
  176661. /*
  176662. * Release all objects belonging to a specified pool.
  176663. */
  176664. METHODDEF(void)
  176665. free_pool (j_common_ptr cinfo, int pool_id)
  176666. {
  176667. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176668. small_pool_ptr shdr_ptr;
  176669. large_pool_ptr lhdr_ptr;
  176670. size_t space_freed;
  176671. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176672. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176673. #ifdef MEM_STATS
  176674. if (cinfo->err->trace_level > 1)
  176675. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176676. #endif
  176677. /* If freeing IMAGE pool, close any virtual arrays first */
  176678. if (pool_id == JPOOL_IMAGE) {
  176679. jvirt_sarray_ptr sptr;
  176680. jvirt_barray_ptr bptr;
  176681. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176682. if (sptr->b_s_open) { /* there may be no backing store */
  176683. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176684. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176685. }
  176686. }
  176687. mem->virt_sarray_list = NULL;
  176688. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176689. if (bptr->b_s_open) { /* there may be no backing store */
  176690. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176691. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176692. }
  176693. }
  176694. mem->virt_barray_list = NULL;
  176695. }
  176696. /* Release large objects */
  176697. lhdr_ptr = mem->large_list[pool_id];
  176698. mem->large_list[pool_id] = NULL;
  176699. while (lhdr_ptr != NULL) {
  176700. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176701. space_freed = lhdr_ptr->hdr.bytes_used +
  176702. lhdr_ptr->hdr.bytes_left +
  176703. SIZEOF(large_pool_hdr);
  176704. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176705. mem->total_space_allocated -= space_freed;
  176706. lhdr_ptr = next_lhdr_ptr;
  176707. }
  176708. /* Release small objects */
  176709. shdr_ptr = mem->small_list[pool_id];
  176710. mem->small_list[pool_id] = NULL;
  176711. while (shdr_ptr != NULL) {
  176712. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176713. space_freed = shdr_ptr->hdr.bytes_used +
  176714. shdr_ptr->hdr.bytes_left +
  176715. SIZEOF(small_pool_hdr);
  176716. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176717. mem->total_space_allocated -= space_freed;
  176718. shdr_ptr = next_shdr_ptr;
  176719. }
  176720. }
  176721. /*
  176722. * Close up shop entirely.
  176723. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176724. */
  176725. METHODDEF(void)
  176726. self_destruct (j_common_ptr cinfo)
  176727. {
  176728. int pool;
  176729. /* Close all backing store, release all memory.
  176730. * Releasing pools in reverse order might help avoid fragmentation
  176731. * with some (brain-damaged) malloc libraries.
  176732. */
  176733. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176734. free_pool(cinfo, pool);
  176735. }
  176736. /* Release the memory manager control block too. */
  176737. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176738. cinfo->mem = NULL; /* ensures I will be called only once */
  176739. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176740. }
  176741. /*
  176742. * Memory manager initialization.
  176743. * When this is called, only the error manager pointer is valid in cinfo!
  176744. */
  176745. GLOBAL(void)
  176746. jinit_memory_mgr (j_common_ptr cinfo)
  176747. {
  176748. my_mem_ptr mem;
  176749. long max_to_use;
  176750. int pool;
  176751. size_t test_mac;
  176752. cinfo->mem = NULL; /* for safety if init fails */
  176753. /* Check for configuration errors.
  176754. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176755. * doesn't reflect any real hardware alignment requirement.
  176756. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176757. * in common if and only if X is a power of 2, ie has only one one-bit.
  176758. * Some compilers may give an "unreachable code" warning here; ignore it.
  176759. */
  176760. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176761. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176762. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176763. * a multiple of SIZEOF(ALIGN_TYPE).
  176764. * Again, an "unreachable code" warning may be ignored here.
  176765. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176766. */
  176767. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176768. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176769. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176770. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176771. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176772. /* Attempt to allocate memory manager's control block */
  176773. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176774. if (mem == NULL) {
  176775. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176776. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176777. }
  176778. /* OK, fill in the method pointers */
  176779. mem->pub.alloc_small = alloc_small;
  176780. mem->pub.alloc_large = alloc_large;
  176781. mem->pub.alloc_sarray = alloc_sarray;
  176782. mem->pub.alloc_barray = alloc_barray;
  176783. mem->pub.request_virt_sarray = request_virt_sarray;
  176784. mem->pub.request_virt_barray = request_virt_barray;
  176785. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176786. mem->pub.access_virt_sarray = access_virt_sarray;
  176787. mem->pub.access_virt_barray = access_virt_barray;
  176788. mem->pub.free_pool = free_pool;
  176789. mem->pub.self_destruct = self_destruct;
  176790. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176791. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176792. /* Initialize working state */
  176793. mem->pub.max_memory_to_use = max_to_use;
  176794. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176795. mem->small_list[pool] = NULL;
  176796. mem->large_list[pool] = NULL;
  176797. }
  176798. mem->virt_sarray_list = NULL;
  176799. mem->virt_barray_list = NULL;
  176800. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176801. /* Declare ourselves open for business */
  176802. cinfo->mem = & mem->pub;
  176803. /* Check for an environment variable JPEGMEM; if found, override the
  176804. * default max_memory setting from jpeg_mem_init. Note that the
  176805. * surrounding application may again override this value.
  176806. * If your system doesn't support getenv(), define NO_GETENV to disable
  176807. * this feature.
  176808. */
  176809. #ifndef NO_GETENV
  176810. { char * memenv;
  176811. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176812. char ch = 'x';
  176813. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176814. if (ch == 'm' || ch == 'M')
  176815. max_to_use *= 1000L;
  176816. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176817. }
  176818. }
  176819. }
  176820. #endif
  176821. }
  176822. /*** End of inlined file: jmemmgr.c ***/
  176823. /*** Start of inlined file: jmemnobs.c ***/
  176824. #define JPEG_INTERNALS
  176825. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176826. extern void * malloc JPP((size_t size));
  176827. extern void free JPP((void *ptr));
  176828. #endif
  176829. /*
  176830. * Memory allocation and freeing are controlled by the regular library
  176831. * routines malloc() and free().
  176832. */
  176833. GLOBAL(void *)
  176834. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176835. {
  176836. return (void *) malloc(sizeofobject);
  176837. }
  176838. GLOBAL(void)
  176839. jpeg_free_small (j_common_ptr , void * object, size_t)
  176840. {
  176841. free(object);
  176842. }
  176843. /*
  176844. * "Large" objects are treated the same as "small" ones.
  176845. * NB: although we include FAR keywords in the routine declarations,
  176846. * this file won't actually work in 80x86 small/medium model; at least,
  176847. * you probably won't be able to process useful-size images in only 64KB.
  176848. */
  176849. GLOBAL(void FAR *)
  176850. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176851. {
  176852. return (void FAR *) malloc(sizeofobject);
  176853. }
  176854. GLOBAL(void)
  176855. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176856. {
  176857. free(object);
  176858. }
  176859. /*
  176860. * This routine computes the total memory space available for allocation.
  176861. * Here we always say, "we got all you want bud!"
  176862. */
  176863. GLOBAL(long)
  176864. jpeg_mem_available (j_common_ptr, long,
  176865. long max_bytes_needed, long)
  176866. {
  176867. return max_bytes_needed;
  176868. }
  176869. /*
  176870. * Backing store (temporary file) management.
  176871. * Since jpeg_mem_available always promised the moon,
  176872. * this should never be called and we can just error out.
  176873. */
  176874. GLOBAL(void)
  176875. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176876. long )
  176877. {
  176878. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176879. }
  176880. /*
  176881. * These routines take care of any system-dependent initialization and
  176882. * cleanup required. Here, there isn't any.
  176883. */
  176884. GLOBAL(long)
  176885. jpeg_mem_init (j_common_ptr)
  176886. {
  176887. return 0; /* just set max_memory_to_use to 0 */
  176888. }
  176889. GLOBAL(void)
  176890. jpeg_mem_term (j_common_ptr)
  176891. {
  176892. /* no work */
  176893. }
  176894. /*** End of inlined file: jmemnobs.c ***/
  176895. /*** Start of inlined file: jquant1.c ***/
  176896. #define JPEG_INTERNALS
  176897. #ifdef QUANT_1PASS_SUPPORTED
  176898. /*
  176899. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176900. * high quality, colormapped output capability. A 2-pass quantizer usually
  176901. * gives better visual quality; however, for quantized grayscale output this
  176902. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176903. * quantizer, though you can turn it off if you really want to.
  176904. *
  176905. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176906. * image. We use a map consisting of all combinations of Ncolors[i] color
  176907. * values for the i'th component. The Ncolors[] values are chosen so that
  176908. * their product, the total number of colors, is no more than that requested.
  176909. * (In most cases, the product will be somewhat less.)
  176910. *
  176911. * Since the colormap is orthogonal, the representative value for each color
  176912. * component can be determined without considering the other components;
  176913. * then these indexes can be combined into a colormap index by a standard
  176914. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176915. * can be precalculated and stored in the lookup table colorindex[].
  176916. * colorindex[i][j] maps pixel value j in component i to the nearest
  176917. * representative value (grid plane) for that component; this index is
  176918. * multiplied by the array stride for component i, so that the
  176919. * index of the colormap entry closest to a given pixel value is just
  176920. * sum( colorindex[component-number][pixel-component-value] )
  176921. * Aside from being fast, this scheme allows for variable spacing between
  176922. * representative values with no additional lookup cost.
  176923. *
  176924. * If gamma correction has been applied in color conversion, it might be wise
  176925. * to adjust the color grid spacing so that the representative colors are
  176926. * equidistant in linear space. At this writing, gamma correction is not
  176927. * implemented by jdcolor, so nothing is done here.
  176928. */
  176929. /* Declarations for ordered dithering.
  176930. *
  176931. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176932. * dithering is described in many references, for instance Dale Schumacher's
  176933. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176934. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176935. * "dither" value to the input pixel and then round the result to the nearest
  176936. * output value. The dither value is equivalent to (0.5 - threshold) times
  176937. * the distance between output values. For ordered dithering, we assume that
  176938. * the output colors are equally spaced; if not, results will probably be
  176939. * worse, since the dither may be too much or too little at a given point.
  176940. *
  176941. * The normal calculation would be to form pixel value + dither, range-limit
  176942. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176943. * We can skip the separate range-limiting step by extending the colorindex
  176944. * table in both directions.
  176945. */
  176946. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176947. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176948. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176949. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176950. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176951. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176952. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176953. /* Bayer's order-4 dither array. Generated by the code given in
  176954. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176955. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176956. */
  176957. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176958. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176959. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176960. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176961. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176962. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176963. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176964. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176965. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176966. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176967. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176968. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176969. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176970. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176971. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176972. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176973. };
  176974. /* Declarations for Floyd-Steinberg dithering.
  176975. *
  176976. * Errors are accumulated into the array fserrors[], at a resolution of
  176977. * 1/16th of a pixel count. The error at a given pixel is propagated
  176978. * to its not-yet-processed neighbors using the standard F-S fractions,
  176979. * ... (here) 7/16
  176980. * 3/16 5/16 1/16
  176981. * We work left-to-right on even rows, right-to-left on odd rows.
  176982. *
  176983. * We can get away with a single array (holding one row's worth of errors)
  176984. * by using it to store the current row's errors at pixel columns not yet
  176985. * processed, but the next row's errors at columns already processed. We
  176986. * need only a few extra variables to hold the errors immediately around the
  176987. * current column. (If we are lucky, those variables are in registers, but
  176988. * even if not, they're probably cheaper to access than array elements are.)
  176989. *
  176990. * The fserrors[] array is indexed [component#][position].
  176991. * We provide (#columns + 2) entries per component; the extra entry at each
  176992. * end saves us from special-casing the first and last pixels.
  176993. *
  176994. * Note: on a wide image, we might not have enough room in a PC's near data
  176995. * segment to hold the error array; so it is allocated with alloc_large.
  176996. */
  176997. #if BITS_IN_JSAMPLE == 8
  176998. typedef INT16 FSERROR; /* 16 bits should be enough */
  176999. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177000. #else
  177001. typedef INT32 FSERROR; /* may need more than 16 bits */
  177002. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177003. #endif
  177004. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177005. /* Private subobject */
  177006. #define MAX_Q_COMPS 4 /* max components I can handle */
  177007. typedef struct {
  177008. struct jpeg_color_quantizer pub; /* public fields */
  177009. /* Initially allocated colormap is saved here */
  177010. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177011. int sv_actual; /* number of entries in use */
  177012. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177013. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177014. * premultiplied as described above. Since colormap indexes must fit into
  177015. * JSAMPLEs, the entries of this array will too.
  177016. */
  177017. boolean is_padded; /* is the colorindex padded for odither? */
  177018. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177019. /* Variables for ordered dithering */
  177020. int row_index; /* cur row's vertical index in dither matrix */
  177021. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177022. /* Variables for Floyd-Steinberg dithering */
  177023. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177024. boolean on_odd_row; /* flag to remember which row we are on */
  177025. } my_cquantizer;
  177026. typedef my_cquantizer * my_cquantize_ptr;
  177027. /*
  177028. * Policy-making subroutines for create_colormap and create_colorindex.
  177029. * These routines determine the colormap to be used. The rest of the module
  177030. * only assumes that the colormap is orthogonal.
  177031. *
  177032. * * select_ncolors decides how to divvy up the available colors
  177033. * among the components.
  177034. * * output_value defines the set of representative values for a component.
  177035. * * largest_input_value defines the mapping from input values to
  177036. * representative values for a component.
  177037. * Note that the latter two routines may impose different policies for
  177038. * different components, though this is not currently done.
  177039. */
  177040. LOCAL(int)
  177041. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177042. /* Determine allocation of desired colors to components, */
  177043. /* and fill in Ncolors[] array to indicate choice. */
  177044. /* Return value is total number of colors (product of Ncolors[] values). */
  177045. {
  177046. int nc = cinfo->out_color_components; /* number of color components */
  177047. int max_colors = cinfo->desired_number_of_colors;
  177048. int total_colors, iroot, i, j;
  177049. boolean changed;
  177050. long temp;
  177051. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177052. /* We can allocate at least the nc'th root of max_colors per component. */
  177053. /* Compute floor(nc'th root of max_colors). */
  177054. iroot = 1;
  177055. do {
  177056. iroot++;
  177057. temp = iroot; /* set temp = iroot ** nc */
  177058. for (i = 1; i < nc; i++)
  177059. temp *= iroot;
  177060. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177061. iroot--; /* now iroot = floor(root) */
  177062. /* Must have at least 2 color values per component */
  177063. if (iroot < 2)
  177064. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177065. /* Initialize to iroot color values for each component */
  177066. total_colors = 1;
  177067. for (i = 0; i < nc; i++) {
  177068. Ncolors[i] = iroot;
  177069. total_colors *= iroot;
  177070. }
  177071. /* We may be able to increment the count for one or more components without
  177072. * exceeding max_colors, though we know not all can be incremented.
  177073. * Sometimes, the first component can be incremented more than once!
  177074. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177075. * In RGB colorspace, try to increment G first, then R, then B.
  177076. */
  177077. do {
  177078. changed = FALSE;
  177079. for (i = 0; i < nc; i++) {
  177080. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177081. /* calculate new total_colors if Ncolors[j] is incremented */
  177082. temp = total_colors / Ncolors[j];
  177083. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177084. if (temp > (long) max_colors)
  177085. break; /* won't fit, done with this pass */
  177086. Ncolors[j]++; /* OK, apply the increment */
  177087. total_colors = (int) temp;
  177088. changed = TRUE;
  177089. }
  177090. } while (changed);
  177091. return total_colors;
  177092. }
  177093. LOCAL(int)
  177094. output_value (j_decompress_ptr, int, int j, int maxj)
  177095. /* Return j'th output value, where j will range from 0 to maxj */
  177096. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177097. {
  177098. /* We always provide values 0 and MAXJSAMPLE for each component;
  177099. * any additional values are equally spaced between these limits.
  177100. * (Forcing the upper and lower values to the limits ensures that
  177101. * dithering can't produce a color outside the selected gamut.)
  177102. */
  177103. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177104. }
  177105. LOCAL(int)
  177106. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177107. /* Return largest input value that should map to j'th output value */
  177108. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177109. {
  177110. /* Breakpoints are halfway between values returned by output_value */
  177111. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177112. }
  177113. /*
  177114. * Create the colormap.
  177115. */
  177116. LOCAL(void)
  177117. create_colormap (j_decompress_ptr cinfo)
  177118. {
  177119. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177120. JSAMPARRAY colormap; /* Created colormap */
  177121. int total_colors; /* Number of distinct output colors */
  177122. int i,j,k, nci, blksize, blkdist, ptr, val;
  177123. /* Select number of colors for each component */
  177124. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177125. /* Report selected color counts */
  177126. if (cinfo->out_color_components == 3)
  177127. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177128. total_colors, cquantize->Ncolors[0],
  177129. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177130. else
  177131. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177132. /* Allocate and fill in the colormap. */
  177133. /* The colors are ordered in the map in standard row-major order, */
  177134. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177135. colormap = (*cinfo->mem->alloc_sarray)
  177136. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177137. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177138. /* blksize is number of adjacent repeated entries for a component */
  177139. /* blkdist is distance between groups of identical entries for a component */
  177140. blkdist = total_colors;
  177141. for (i = 0; i < cinfo->out_color_components; i++) {
  177142. /* fill in colormap entries for i'th color component */
  177143. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177144. blksize = blkdist / nci;
  177145. for (j = 0; j < nci; j++) {
  177146. /* Compute j'th output value (out of nci) for component */
  177147. val = output_value(cinfo, i, j, nci-1);
  177148. /* Fill in all colormap entries that have this value of this component */
  177149. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177150. /* fill in blksize entries beginning at ptr */
  177151. for (k = 0; k < blksize; k++)
  177152. colormap[i][ptr+k] = (JSAMPLE) val;
  177153. }
  177154. }
  177155. blkdist = blksize; /* blksize of this color is blkdist of next */
  177156. }
  177157. /* Save the colormap in private storage,
  177158. * where it will survive color quantization mode changes.
  177159. */
  177160. cquantize->sv_colormap = colormap;
  177161. cquantize->sv_actual = total_colors;
  177162. }
  177163. /*
  177164. * Create the color index table.
  177165. */
  177166. LOCAL(void)
  177167. create_colorindex (j_decompress_ptr cinfo)
  177168. {
  177169. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177170. JSAMPROW indexptr;
  177171. int i,j,k, nci, blksize, val, pad;
  177172. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177173. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177174. * This is not necessary in the other dithering modes. However, we
  177175. * flag whether it was done in case user changes dithering mode.
  177176. */
  177177. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177178. pad = MAXJSAMPLE*2;
  177179. cquantize->is_padded = TRUE;
  177180. } else {
  177181. pad = 0;
  177182. cquantize->is_padded = FALSE;
  177183. }
  177184. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177185. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177186. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177187. (JDIMENSION) cinfo->out_color_components);
  177188. /* blksize is number of adjacent repeated entries for a component */
  177189. blksize = cquantize->sv_actual;
  177190. for (i = 0; i < cinfo->out_color_components; i++) {
  177191. /* fill in colorindex entries for i'th color component */
  177192. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177193. blksize = blksize / nci;
  177194. /* adjust colorindex pointers to provide padding at negative indexes. */
  177195. if (pad)
  177196. cquantize->colorindex[i] += MAXJSAMPLE;
  177197. /* in loop, val = index of current output value, */
  177198. /* and k = largest j that maps to current val */
  177199. indexptr = cquantize->colorindex[i];
  177200. val = 0;
  177201. k = largest_input_value(cinfo, i, 0, nci-1);
  177202. for (j = 0; j <= MAXJSAMPLE; j++) {
  177203. while (j > k) /* advance val if past boundary */
  177204. k = largest_input_value(cinfo, i, ++val, nci-1);
  177205. /* premultiply so that no multiplication needed in main processing */
  177206. indexptr[j] = (JSAMPLE) (val * blksize);
  177207. }
  177208. /* Pad at both ends if necessary */
  177209. if (pad)
  177210. for (j = 1; j <= MAXJSAMPLE; j++) {
  177211. indexptr[-j] = indexptr[0];
  177212. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177213. }
  177214. }
  177215. }
  177216. /*
  177217. * Create an ordered-dither array for a component having ncolors
  177218. * distinct output values.
  177219. */
  177220. LOCAL(ODITHER_MATRIX_PTR)
  177221. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177222. {
  177223. ODITHER_MATRIX_PTR odither;
  177224. int j,k;
  177225. INT32 num,den;
  177226. odither = (ODITHER_MATRIX_PTR)
  177227. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177228. SIZEOF(ODITHER_MATRIX));
  177229. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177230. * Hence the dither value for the matrix cell with fill order f
  177231. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177232. * On 16-bit-int machine, be careful to avoid overflow.
  177233. */
  177234. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177235. for (j = 0; j < ODITHER_SIZE; j++) {
  177236. for (k = 0; k < ODITHER_SIZE; k++) {
  177237. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177238. * MAXJSAMPLE;
  177239. /* Ensure round towards zero despite C's lack of consistency
  177240. * about rounding negative values in integer division...
  177241. */
  177242. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177243. }
  177244. }
  177245. return odither;
  177246. }
  177247. /*
  177248. * Create the ordered-dither tables.
  177249. * Components having the same number of representative colors may
  177250. * share a dither table.
  177251. */
  177252. LOCAL(void)
  177253. create_odither_tables (j_decompress_ptr cinfo)
  177254. {
  177255. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177256. ODITHER_MATRIX_PTR odither;
  177257. int i, j, nci;
  177258. for (i = 0; i < cinfo->out_color_components; i++) {
  177259. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177260. odither = NULL; /* search for matching prior component */
  177261. for (j = 0; j < i; j++) {
  177262. if (nci == cquantize->Ncolors[j]) {
  177263. odither = cquantize->odither[j];
  177264. break;
  177265. }
  177266. }
  177267. if (odither == NULL) /* need a new table? */
  177268. odither = make_odither_array(cinfo, nci);
  177269. cquantize->odither[i] = odither;
  177270. }
  177271. }
  177272. /*
  177273. * Map some rows of pixels to the output colormapped representation.
  177274. */
  177275. METHODDEF(void)
  177276. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177277. JSAMPARRAY output_buf, int num_rows)
  177278. /* General case, no dithering */
  177279. {
  177280. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177281. JSAMPARRAY colorindex = cquantize->colorindex;
  177282. register int pixcode, ci;
  177283. register JSAMPROW ptrin, ptrout;
  177284. int row;
  177285. JDIMENSION col;
  177286. JDIMENSION width = cinfo->output_width;
  177287. register int nc = cinfo->out_color_components;
  177288. for (row = 0; row < num_rows; row++) {
  177289. ptrin = input_buf[row];
  177290. ptrout = output_buf[row];
  177291. for (col = width; col > 0; col--) {
  177292. pixcode = 0;
  177293. for (ci = 0; ci < nc; ci++) {
  177294. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177295. }
  177296. *ptrout++ = (JSAMPLE) pixcode;
  177297. }
  177298. }
  177299. }
  177300. METHODDEF(void)
  177301. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177302. JSAMPARRAY output_buf, int num_rows)
  177303. /* Fast path for out_color_components==3, no dithering */
  177304. {
  177305. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177306. register int pixcode;
  177307. register JSAMPROW ptrin, ptrout;
  177308. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177309. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177310. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177311. int row;
  177312. JDIMENSION col;
  177313. JDIMENSION width = cinfo->output_width;
  177314. for (row = 0; row < num_rows; row++) {
  177315. ptrin = input_buf[row];
  177316. ptrout = output_buf[row];
  177317. for (col = width; col > 0; col--) {
  177318. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177319. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177320. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177321. *ptrout++ = (JSAMPLE) pixcode;
  177322. }
  177323. }
  177324. }
  177325. METHODDEF(void)
  177326. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177327. JSAMPARRAY output_buf, int num_rows)
  177328. /* General case, with ordered dithering */
  177329. {
  177330. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177331. register JSAMPROW input_ptr;
  177332. register JSAMPROW output_ptr;
  177333. JSAMPROW colorindex_ci;
  177334. int * dither; /* points to active row of dither matrix */
  177335. int row_index, col_index; /* current indexes into dither matrix */
  177336. int nc = cinfo->out_color_components;
  177337. int ci;
  177338. int row;
  177339. JDIMENSION col;
  177340. JDIMENSION width = cinfo->output_width;
  177341. for (row = 0; row < num_rows; row++) {
  177342. /* Initialize output values to 0 so can process components separately */
  177343. jzero_far((void FAR *) output_buf[row],
  177344. (size_t) (width * SIZEOF(JSAMPLE)));
  177345. row_index = cquantize->row_index;
  177346. for (ci = 0; ci < nc; ci++) {
  177347. input_ptr = input_buf[row] + ci;
  177348. output_ptr = output_buf[row];
  177349. colorindex_ci = cquantize->colorindex[ci];
  177350. dither = cquantize->odither[ci][row_index];
  177351. col_index = 0;
  177352. for (col = width; col > 0; col--) {
  177353. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177354. * select output value, accumulate into output code for this pixel.
  177355. * Range-limiting need not be done explicitly, as we have extended
  177356. * the colorindex table to produce the right answers for out-of-range
  177357. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177358. * required amount of padding.
  177359. */
  177360. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177361. input_ptr += nc;
  177362. output_ptr++;
  177363. col_index = (col_index + 1) & ODITHER_MASK;
  177364. }
  177365. }
  177366. /* Advance row index for next row */
  177367. row_index = (row_index + 1) & ODITHER_MASK;
  177368. cquantize->row_index = row_index;
  177369. }
  177370. }
  177371. METHODDEF(void)
  177372. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177373. JSAMPARRAY output_buf, int num_rows)
  177374. /* Fast path for out_color_components==3, with ordered dithering */
  177375. {
  177376. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177377. register int pixcode;
  177378. register JSAMPROW input_ptr;
  177379. register JSAMPROW output_ptr;
  177380. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177381. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177382. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177383. int * dither0; /* points to active row of dither matrix */
  177384. int * dither1;
  177385. int * dither2;
  177386. int row_index, col_index; /* current indexes into dither matrix */
  177387. int row;
  177388. JDIMENSION col;
  177389. JDIMENSION width = cinfo->output_width;
  177390. for (row = 0; row < num_rows; row++) {
  177391. row_index = cquantize->row_index;
  177392. input_ptr = input_buf[row];
  177393. output_ptr = output_buf[row];
  177394. dither0 = cquantize->odither[0][row_index];
  177395. dither1 = cquantize->odither[1][row_index];
  177396. dither2 = cquantize->odither[2][row_index];
  177397. col_index = 0;
  177398. for (col = width; col > 0; col--) {
  177399. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177400. dither0[col_index]]);
  177401. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177402. dither1[col_index]]);
  177403. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177404. dither2[col_index]]);
  177405. *output_ptr++ = (JSAMPLE) pixcode;
  177406. col_index = (col_index + 1) & ODITHER_MASK;
  177407. }
  177408. row_index = (row_index + 1) & ODITHER_MASK;
  177409. cquantize->row_index = row_index;
  177410. }
  177411. }
  177412. METHODDEF(void)
  177413. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177414. JSAMPARRAY output_buf, int num_rows)
  177415. /* General case, with Floyd-Steinberg dithering */
  177416. {
  177417. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177418. register LOCFSERROR cur; /* current error or pixel value */
  177419. LOCFSERROR belowerr; /* error for pixel below cur */
  177420. LOCFSERROR bpreverr; /* error for below/prev col */
  177421. LOCFSERROR bnexterr; /* error for below/next col */
  177422. LOCFSERROR delta;
  177423. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177424. register JSAMPROW input_ptr;
  177425. register JSAMPROW output_ptr;
  177426. JSAMPROW colorindex_ci;
  177427. JSAMPROW colormap_ci;
  177428. int pixcode;
  177429. int nc = cinfo->out_color_components;
  177430. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177431. int dirnc; /* dir * nc */
  177432. int ci;
  177433. int row;
  177434. JDIMENSION col;
  177435. JDIMENSION width = cinfo->output_width;
  177436. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177437. SHIFT_TEMPS
  177438. for (row = 0; row < num_rows; row++) {
  177439. /* Initialize output values to 0 so can process components separately */
  177440. jzero_far((void FAR *) output_buf[row],
  177441. (size_t) (width * SIZEOF(JSAMPLE)));
  177442. for (ci = 0; ci < nc; ci++) {
  177443. input_ptr = input_buf[row] + ci;
  177444. output_ptr = output_buf[row];
  177445. if (cquantize->on_odd_row) {
  177446. /* work right to left in this row */
  177447. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177448. output_ptr += width-1;
  177449. dir = -1;
  177450. dirnc = -nc;
  177451. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177452. } else {
  177453. /* work left to right in this row */
  177454. dir = 1;
  177455. dirnc = nc;
  177456. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177457. }
  177458. colorindex_ci = cquantize->colorindex[ci];
  177459. colormap_ci = cquantize->sv_colormap[ci];
  177460. /* Preset error values: no error propagated to first pixel from left */
  177461. cur = 0;
  177462. /* and no error propagated to row below yet */
  177463. belowerr = bpreverr = 0;
  177464. for (col = width; col > 0; col--) {
  177465. /* cur holds the error propagated from the previous pixel on the
  177466. * current line. Add the error propagated from the previous line
  177467. * to form the complete error correction term for this pixel, and
  177468. * round the error term (which is expressed * 16) to an integer.
  177469. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177470. * for either sign of the error value.
  177471. * Note: errorptr points to *previous* column's array entry.
  177472. */
  177473. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177474. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177475. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177476. * of the range_limit array.
  177477. */
  177478. cur += GETJSAMPLE(*input_ptr);
  177479. cur = GETJSAMPLE(range_limit[cur]);
  177480. /* Select output value, accumulate into output code for this pixel */
  177481. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177482. *output_ptr += (JSAMPLE) pixcode;
  177483. /* Compute actual representation error at this pixel */
  177484. /* Note: we can do this even though we don't have the final */
  177485. /* pixel code, because the colormap is orthogonal. */
  177486. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177487. /* Compute error fractions to be propagated to adjacent pixels.
  177488. * Add these into the running sums, and simultaneously shift the
  177489. * next-line error sums left by 1 column.
  177490. */
  177491. bnexterr = cur;
  177492. delta = cur * 2;
  177493. cur += delta; /* form error * 3 */
  177494. errorptr[0] = (FSERROR) (bpreverr + cur);
  177495. cur += delta; /* form error * 5 */
  177496. bpreverr = belowerr + cur;
  177497. belowerr = bnexterr;
  177498. cur += delta; /* form error * 7 */
  177499. /* At this point cur contains the 7/16 error value to be propagated
  177500. * to the next pixel on the current line, and all the errors for the
  177501. * next line have been shifted over. We are therefore ready to move on.
  177502. */
  177503. input_ptr += dirnc; /* advance input ptr to next column */
  177504. output_ptr += dir; /* advance output ptr to next column */
  177505. errorptr += dir; /* advance errorptr to current column */
  177506. }
  177507. /* Post-loop cleanup: we must unload the final error value into the
  177508. * final fserrors[] entry. Note we need not unload belowerr because
  177509. * it is for the dummy column before or after the actual array.
  177510. */
  177511. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177512. }
  177513. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177514. }
  177515. }
  177516. /*
  177517. * Allocate workspace for Floyd-Steinberg errors.
  177518. */
  177519. LOCAL(void)
  177520. alloc_fs_workspace (j_decompress_ptr cinfo)
  177521. {
  177522. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177523. size_t arraysize;
  177524. int i;
  177525. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177526. for (i = 0; i < cinfo->out_color_components; i++) {
  177527. cquantize->fserrors[i] = (FSERRPTR)
  177528. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177529. }
  177530. }
  177531. /*
  177532. * Initialize for one-pass color quantization.
  177533. */
  177534. METHODDEF(void)
  177535. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177536. {
  177537. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177538. size_t arraysize;
  177539. int i;
  177540. /* Install my colormap. */
  177541. cinfo->colormap = cquantize->sv_colormap;
  177542. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177543. /* Initialize for desired dithering mode. */
  177544. switch (cinfo->dither_mode) {
  177545. case JDITHER_NONE:
  177546. if (cinfo->out_color_components == 3)
  177547. cquantize->pub.color_quantize = color_quantize3;
  177548. else
  177549. cquantize->pub.color_quantize = color_quantize;
  177550. break;
  177551. case JDITHER_ORDERED:
  177552. if (cinfo->out_color_components == 3)
  177553. cquantize->pub.color_quantize = quantize3_ord_dither;
  177554. else
  177555. cquantize->pub.color_quantize = quantize_ord_dither;
  177556. cquantize->row_index = 0; /* initialize state for ordered dither */
  177557. /* If user changed to ordered dither from another mode,
  177558. * we must recreate the color index table with padding.
  177559. * This will cost extra space, but probably isn't very likely.
  177560. */
  177561. if (! cquantize->is_padded)
  177562. create_colorindex(cinfo);
  177563. /* Create ordered-dither tables if we didn't already. */
  177564. if (cquantize->odither[0] == NULL)
  177565. create_odither_tables(cinfo);
  177566. break;
  177567. case JDITHER_FS:
  177568. cquantize->pub.color_quantize = quantize_fs_dither;
  177569. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177570. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177571. if (cquantize->fserrors[0] == NULL)
  177572. alloc_fs_workspace(cinfo);
  177573. /* Initialize the propagated errors to zero. */
  177574. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177575. for (i = 0; i < cinfo->out_color_components; i++)
  177576. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177577. break;
  177578. default:
  177579. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177580. break;
  177581. }
  177582. }
  177583. /*
  177584. * Finish up at the end of the pass.
  177585. */
  177586. METHODDEF(void)
  177587. finish_pass_1_quant (j_decompress_ptr)
  177588. {
  177589. /* no work in 1-pass case */
  177590. }
  177591. /*
  177592. * Switch to a new external colormap between output passes.
  177593. * Shouldn't get to this module!
  177594. */
  177595. METHODDEF(void)
  177596. new_color_map_1_quant (j_decompress_ptr cinfo)
  177597. {
  177598. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177599. }
  177600. /*
  177601. * Module initialization routine for 1-pass color quantization.
  177602. */
  177603. GLOBAL(void)
  177604. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177605. {
  177606. my_cquantize_ptr cquantize;
  177607. cquantize = (my_cquantize_ptr)
  177608. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177609. SIZEOF(my_cquantizer));
  177610. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177611. cquantize->pub.start_pass = start_pass_1_quant;
  177612. cquantize->pub.finish_pass = finish_pass_1_quant;
  177613. cquantize->pub.new_color_map = new_color_map_1_quant;
  177614. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177615. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177616. /* Make sure my internal arrays won't overflow */
  177617. if (cinfo->out_color_components > MAX_Q_COMPS)
  177618. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177619. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177620. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177621. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177622. /* Create the colormap and color index table. */
  177623. create_colormap(cinfo);
  177624. create_colorindex(cinfo);
  177625. /* Allocate Floyd-Steinberg workspace now if requested.
  177626. * We do this now since it is FAR storage and may affect the memory
  177627. * manager's space calculations. If the user changes to FS dither
  177628. * mode in a later pass, we will allocate the space then, and will
  177629. * possibly overrun the max_memory_to_use setting.
  177630. */
  177631. if (cinfo->dither_mode == JDITHER_FS)
  177632. alloc_fs_workspace(cinfo);
  177633. }
  177634. #endif /* QUANT_1PASS_SUPPORTED */
  177635. /*** End of inlined file: jquant1.c ***/
  177636. /*** Start of inlined file: jquant2.c ***/
  177637. #define JPEG_INTERNALS
  177638. #ifdef QUANT_2PASS_SUPPORTED
  177639. /*
  177640. * This module implements the well-known Heckbert paradigm for color
  177641. * quantization. Most of the ideas used here can be traced back to
  177642. * Heckbert's seminal paper
  177643. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177644. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177645. *
  177646. * In the first pass over the image, we accumulate a histogram showing the
  177647. * usage count of each possible color. To keep the histogram to a reasonable
  177648. * size, we reduce the precision of the input; typical practice is to retain
  177649. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177650. * in the same histogram cell.
  177651. *
  177652. * Next, the color-selection step begins with a box representing the whole
  177653. * color space, and repeatedly splits the "largest" remaining box until we
  177654. * have as many boxes as desired colors. Then the mean color in each
  177655. * remaining box becomes one of the possible output colors.
  177656. *
  177657. * The second pass over the image maps each input pixel to the closest output
  177658. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177659. * This mapping is logically trivial, but making it go fast enough requires
  177660. * considerable care.
  177661. *
  177662. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177663. * the "largest" box and deciding where to cut it. The particular policies
  177664. * used here have proved out well in experimental comparisons, but better ones
  177665. * may yet be found.
  177666. *
  177667. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177668. * space, processing the raw upsampled data without a color conversion step.
  177669. * This allowed the color conversion math to be done only once per colormap
  177670. * entry, not once per pixel. However, that optimization precluded other
  177671. * useful optimizations (such as merging color conversion with upsampling)
  177672. * and it also interfered with desired capabilities such as quantizing to an
  177673. * externally-supplied colormap. We have therefore abandoned that approach.
  177674. * The present code works in the post-conversion color space, typically RGB.
  177675. *
  177676. * To improve the visual quality of the results, we actually work in scaled
  177677. * RGB space, giving G distances more weight than R, and R in turn more than
  177678. * B. To do everything in integer math, we must use integer scale factors.
  177679. * The 2/3/1 scale factors used here correspond loosely to the relative
  177680. * weights of the colors in the NTSC grayscale equation.
  177681. * If you want to use this code to quantize a non-RGB color space, you'll
  177682. * probably need to change these scale factors.
  177683. */
  177684. #define R_SCALE 2 /* scale R distances by this much */
  177685. #define G_SCALE 3 /* scale G distances by this much */
  177686. #define B_SCALE 1 /* and B by this much */
  177687. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177688. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177689. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177690. * you'll get compile errors until you extend this logic. In that case
  177691. * you'll probably want to tweak the histogram sizes too.
  177692. */
  177693. #if RGB_RED == 0
  177694. #define C0_SCALE R_SCALE
  177695. #endif
  177696. #if RGB_BLUE == 0
  177697. #define C0_SCALE B_SCALE
  177698. #endif
  177699. #if RGB_GREEN == 1
  177700. #define C1_SCALE G_SCALE
  177701. #endif
  177702. #if RGB_RED == 2
  177703. #define C2_SCALE R_SCALE
  177704. #endif
  177705. #if RGB_BLUE == 2
  177706. #define C2_SCALE B_SCALE
  177707. #endif
  177708. /*
  177709. * First we have the histogram data structure and routines for creating it.
  177710. *
  177711. * The number of bits of precision can be adjusted by changing these symbols.
  177712. * We recommend keeping 6 bits for G and 5 each for R and B.
  177713. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177714. * better results; if you are short of memory, 5 bits all around will save
  177715. * some space but degrade the results.
  177716. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177717. * (preferably unsigned long) for each cell. In practice this is overkill;
  177718. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177719. * and clamping those that do overflow to the maximum value will give close-
  177720. * enough results. This reduces the recommended histogram size from 256Kb
  177721. * to 128Kb, which is a useful savings on PC-class machines.
  177722. * (In the second pass the histogram space is re-used for pixel mapping data;
  177723. * in that capacity, each cell must be able to store zero to the number of
  177724. * desired colors. 16 bits/cell is plenty for that too.)
  177725. * Since the JPEG code is intended to run in small memory model on 80x86
  177726. * machines, we can't just allocate the histogram in one chunk. Instead
  177727. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177728. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177729. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177730. * on 80x86 machines, the pointer row is in near memory but the actual
  177731. * arrays are in far memory (same arrangement as we use for image arrays).
  177732. */
  177733. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177734. /* These will do the right thing for either R,G,B or B,G,R color order,
  177735. * but you may not like the results for other color orders.
  177736. */
  177737. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177738. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177739. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177740. /* Number of elements along histogram axes. */
  177741. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177742. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177743. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177744. /* These are the amounts to shift an input value to get a histogram index. */
  177745. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177746. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177747. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177748. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177749. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177750. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177751. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177752. typedef hist2d * hist3d; /* type for top-level pointer */
  177753. /* Declarations for Floyd-Steinberg dithering.
  177754. *
  177755. * Errors are accumulated into the array fserrors[], at a resolution of
  177756. * 1/16th of a pixel count. The error at a given pixel is propagated
  177757. * to its not-yet-processed neighbors using the standard F-S fractions,
  177758. * ... (here) 7/16
  177759. * 3/16 5/16 1/16
  177760. * We work left-to-right on even rows, right-to-left on odd rows.
  177761. *
  177762. * We can get away with a single array (holding one row's worth of errors)
  177763. * by using it to store the current row's errors at pixel columns not yet
  177764. * processed, but the next row's errors at columns already processed. We
  177765. * need only a few extra variables to hold the errors immediately around the
  177766. * current column. (If we are lucky, those variables are in registers, but
  177767. * even if not, they're probably cheaper to access than array elements are.)
  177768. *
  177769. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177770. * each end saves us from special-casing the first and last pixels.
  177771. * Each entry is three values long, one value for each color component.
  177772. *
  177773. * Note: on a wide image, we might not have enough room in a PC's near data
  177774. * segment to hold the error array; so it is allocated with alloc_large.
  177775. */
  177776. #if BITS_IN_JSAMPLE == 8
  177777. typedef INT16 FSERROR; /* 16 bits should be enough */
  177778. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177779. #else
  177780. typedef INT32 FSERROR; /* may need more than 16 bits */
  177781. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177782. #endif
  177783. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177784. /* Private subobject */
  177785. typedef struct {
  177786. struct jpeg_color_quantizer pub; /* public fields */
  177787. /* Space for the eventually created colormap is stashed here */
  177788. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177789. int desired; /* desired # of colors = size of colormap */
  177790. /* Variables for accumulating image statistics */
  177791. hist3d histogram; /* pointer to the histogram */
  177792. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177793. /* Variables for Floyd-Steinberg dithering */
  177794. FSERRPTR fserrors; /* accumulated errors */
  177795. boolean on_odd_row; /* flag to remember which row we are on */
  177796. int * error_limiter; /* table for clamping the applied error */
  177797. } my_cquantizer2;
  177798. typedef my_cquantizer2 * my_cquantize_ptr2;
  177799. /*
  177800. * Prescan some rows of pixels.
  177801. * In this module the prescan simply updates the histogram, which has been
  177802. * initialized to zeroes by start_pass.
  177803. * An output_buf parameter is required by the method signature, but no data
  177804. * is actually output (in fact the buffer controller is probably passing a
  177805. * NULL pointer).
  177806. */
  177807. METHODDEF(void)
  177808. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177809. JSAMPARRAY, int num_rows)
  177810. {
  177811. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177812. register JSAMPROW ptr;
  177813. register histptr histp;
  177814. register hist3d histogram = cquantize->histogram;
  177815. int row;
  177816. JDIMENSION col;
  177817. JDIMENSION width = cinfo->output_width;
  177818. for (row = 0; row < num_rows; row++) {
  177819. ptr = input_buf[row];
  177820. for (col = width; col > 0; col--) {
  177821. /* get pixel value and index into the histogram */
  177822. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177823. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177824. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177825. /* increment, check for overflow and undo increment if so. */
  177826. if (++(*histp) <= 0)
  177827. (*histp)--;
  177828. ptr += 3;
  177829. }
  177830. }
  177831. }
  177832. /*
  177833. * Next we have the really interesting routines: selection of a colormap
  177834. * given the completed histogram.
  177835. * These routines work with a list of "boxes", each representing a rectangular
  177836. * subset of the input color space (to histogram precision).
  177837. */
  177838. typedef struct {
  177839. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177840. int c0min, c0max;
  177841. int c1min, c1max;
  177842. int c2min, c2max;
  177843. /* The volume (actually 2-norm) of the box */
  177844. INT32 volume;
  177845. /* The number of nonzero histogram cells within this box */
  177846. long colorcount;
  177847. } box;
  177848. typedef box * boxptr;
  177849. LOCAL(boxptr)
  177850. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177851. /* Find the splittable box with the largest color population */
  177852. /* Returns NULL if no splittable boxes remain */
  177853. {
  177854. register boxptr boxp;
  177855. register int i;
  177856. register long maxc = 0;
  177857. boxptr which = NULL;
  177858. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177859. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177860. which = boxp;
  177861. maxc = boxp->colorcount;
  177862. }
  177863. }
  177864. return which;
  177865. }
  177866. LOCAL(boxptr)
  177867. find_biggest_volume (boxptr boxlist, int numboxes)
  177868. /* Find the splittable box with the largest (scaled) volume */
  177869. /* Returns NULL if no splittable boxes remain */
  177870. {
  177871. register boxptr boxp;
  177872. register int i;
  177873. register INT32 maxv = 0;
  177874. boxptr which = NULL;
  177875. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177876. if (boxp->volume > maxv) {
  177877. which = boxp;
  177878. maxv = boxp->volume;
  177879. }
  177880. }
  177881. return which;
  177882. }
  177883. LOCAL(void)
  177884. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177885. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177886. /* and recompute its volume and population */
  177887. {
  177888. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177889. hist3d histogram = cquantize->histogram;
  177890. histptr histp;
  177891. int c0,c1,c2;
  177892. int c0min,c0max,c1min,c1max,c2min,c2max;
  177893. INT32 dist0,dist1,dist2;
  177894. long ccount;
  177895. c0min = boxp->c0min; c0max = boxp->c0max;
  177896. c1min = boxp->c1min; c1max = boxp->c1max;
  177897. c2min = boxp->c2min; c2max = boxp->c2max;
  177898. if (c0max > c0min)
  177899. for (c0 = c0min; c0 <= c0max; c0++)
  177900. for (c1 = c1min; c1 <= c1max; c1++) {
  177901. histp = & histogram[c0][c1][c2min];
  177902. for (c2 = c2min; c2 <= c2max; c2++)
  177903. if (*histp++ != 0) {
  177904. boxp->c0min = c0min = c0;
  177905. goto have_c0min;
  177906. }
  177907. }
  177908. have_c0min:
  177909. if (c0max > c0min)
  177910. for (c0 = c0max; c0 >= c0min; c0--)
  177911. for (c1 = c1min; c1 <= c1max; c1++) {
  177912. histp = & histogram[c0][c1][c2min];
  177913. for (c2 = c2min; c2 <= c2max; c2++)
  177914. if (*histp++ != 0) {
  177915. boxp->c0max = c0max = c0;
  177916. goto have_c0max;
  177917. }
  177918. }
  177919. have_c0max:
  177920. if (c1max > c1min)
  177921. for (c1 = c1min; c1 <= c1max; c1++)
  177922. for (c0 = c0min; c0 <= c0max; c0++) {
  177923. histp = & histogram[c0][c1][c2min];
  177924. for (c2 = c2min; c2 <= c2max; c2++)
  177925. if (*histp++ != 0) {
  177926. boxp->c1min = c1min = c1;
  177927. goto have_c1min;
  177928. }
  177929. }
  177930. have_c1min:
  177931. if (c1max > c1min)
  177932. for (c1 = c1max; c1 >= c1min; c1--)
  177933. for (c0 = c0min; c0 <= c0max; c0++) {
  177934. histp = & histogram[c0][c1][c2min];
  177935. for (c2 = c2min; c2 <= c2max; c2++)
  177936. if (*histp++ != 0) {
  177937. boxp->c1max = c1max = c1;
  177938. goto have_c1max;
  177939. }
  177940. }
  177941. have_c1max:
  177942. if (c2max > c2min)
  177943. for (c2 = c2min; c2 <= c2max; c2++)
  177944. for (c0 = c0min; c0 <= c0max; c0++) {
  177945. histp = & histogram[c0][c1min][c2];
  177946. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177947. if (*histp != 0) {
  177948. boxp->c2min = c2min = c2;
  177949. goto have_c2min;
  177950. }
  177951. }
  177952. have_c2min:
  177953. if (c2max > c2min)
  177954. for (c2 = c2max; c2 >= c2min; c2--)
  177955. for (c0 = c0min; c0 <= c0max; c0++) {
  177956. histp = & histogram[c0][c1min][c2];
  177957. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177958. if (*histp != 0) {
  177959. boxp->c2max = c2max = c2;
  177960. goto have_c2max;
  177961. }
  177962. }
  177963. have_c2max:
  177964. /* Update box volume.
  177965. * We use 2-norm rather than real volume here; this biases the method
  177966. * against making long narrow boxes, and it has the side benefit that
  177967. * a box is splittable iff norm > 0.
  177968. * Since the differences are expressed in histogram-cell units,
  177969. * we have to shift back to JSAMPLE units to get consistent distances;
  177970. * after which, we scale according to the selected distance scale factors.
  177971. */
  177972. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177973. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177974. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177975. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177976. /* Now scan remaining volume of box and compute population */
  177977. ccount = 0;
  177978. for (c0 = c0min; c0 <= c0max; c0++)
  177979. for (c1 = c1min; c1 <= c1max; c1++) {
  177980. histp = & histogram[c0][c1][c2min];
  177981. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177982. if (*histp != 0) {
  177983. ccount++;
  177984. }
  177985. }
  177986. boxp->colorcount = ccount;
  177987. }
  177988. LOCAL(int)
  177989. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177990. int desired_colors)
  177991. /* Repeatedly select and split the largest box until we have enough boxes */
  177992. {
  177993. int n,lb;
  177994. int c0,c1,c2,cmax;
  177995. register boxptr b1,b2;
  177996. while (numboxes < desired_colors) {
  177997. /* Select box to split.
  177998. * Current algorithm: by population for first half, then by volume.
  177999. */
  178000. if (numboxes*2 <= desired_colors) {
  178001. b1 = find_biggest_color_pop(boxlist, numboxes);
  178002. } else {
  178003. b1 = find_biggest_volume(boxlist, numboxes);
  178004. }
  178005. if (b1 == NULL) /* no splittable boxes left! */
  178006. break;
  178007. b2 = &boxlist[numboxes]; /* where new box will go */
  178008. /* Copy the color bounds to the new box. */
  178009. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178010. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178011. /* Choose which axis to split the box on.
  178012. * Current algorithm: longest scaled axis.
  178013. * See notes in update_box about scaling distances.
  178014. */
  178015. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178016. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178017. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178018. /* We want to break any ties in favor of green, then red, blue last.
  178019. * This code does the right thing for R,G,B or B,G,R color orders only.
  178020. */
  178021. #if RGB_RED == 0
  178022. cmax = c1; n = 1;
  178023. if (c0 > cmax) { cmax = c0; n = 0; }
  178024. if (c2 > cmax) { n = 2; }
  178025. #else
  178026. cmax = c1; n = 1;
  178027. if (c2 > cmax) { cmax = c2; n = 2; }
  178028. if (c0 > cmax) { n = 0; }
  178029. #endif
  178030. /* Choose split point along selected axis, and update box bounds.
  178031. * Current algorithm: split at halfway point.
  178032. * (Since the box has been shrunk to minimum volume,
  178033. * any split will produce two nonempty subboxes.)
  178034. * Note that lb value is max for lower box, so must be < old max.
  178035. */
  178036. switch (n) {
  178037. case 0:
  178038. lb = (b1->c0max + b1->c0min) / 2;
  178039. b1->c0max = lb;
  178040. b2->c0min = lb+1;
  178041. break;
  178042. case 1:
  178043. lb = (b1->c1max + b1->c1min) / 2;
  178044. b1->c1max = lb;
  178045. b2->c1min = lb+1;
  178046. break;
  178047. case 2:
  178048. lb = (b1->c2max + b1->c2min) / 2;
  178049. b1->c2max = lb;
  178050. b2->c2min = lb+1;
  178051. break;
  178052. }
  178053. /* Update stats for boxes */
  178054. update_box(cinfo, b1);
  178055. update_box(cinfo, b2);
  178056. numboxes++;
  178057. }
  178058. return numboxes;
  178059. }
  178060. LOCAL(void)
  178061. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178062. /* Compute representative color for a box, put it in colormap[icolor] */
  178063. {
  178064. /* Current algorithm: mean weighted by pixels (not colors) */
  178065. /* Note it is important to get the rounding correct! */
  178066. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178067. hist3d histogram = cquantize->histogram;
  178068. histptr histp;
  178069. int c0,c1,c2;
  178070. int c0min,c0max,c1min,c1max,c2min,c2max;
  178071. long count;
  178072. long total = 0;
  178073. long c0total = 0;
  178074. long c1total = 0;
  178075. long c2total = 0;
  178076. c0min = boxp->c0min; c0max = boxp->c0max;
  178077. c1min = boxp->c1min; c1max = boxp->c1max;
  178078. c2min = boxp->c2min; c2max = boxp->c2max;
  178079. for (c0 = c0min; c0 <= c0max; c0++)
  178080. for (c1 = c1min; c1 <= c1max; c1++) {
  178081. histp = & histogram[c0][c1][c2min];
  178082. for (c2 = c2min; c2 <= c2max; c2++) {
  178083. if ((count = *histp++) != 0) {
  178084. total += count;
  178085. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178086. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178087. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178088. }
  178089. }
  178090. }
  178091. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178092. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178093. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178094. }
  178095. LOCAL(void)
  178096. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178097. /* Master routine for color selection */
  178098. {
  178099. boxptr boxlist;
  178100. int numboxes;
  178101. int i;
  178102. /* Allocate workspace for box list */
  178103. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178104. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178105. /* Initialize one box containing whole space */
  178106. numboxes = 1;
  178107. boxlist[0].c0min = 0;
  178108. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178109. boxlist[0].c1min = 0;
  178110. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178111. boxlist[0].c2min = 0;
  178112. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178113. /* Shrink it to actually-used volume and set its statistics */
  178114. update_box(cinfo, & boxlist[0]);
  178115. /* Perform median-cut to produce final box list */
  178116. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178117. /* Compute the representative color for each box, fill colormap */
  178118. for (i = 0; i < numboxes; i++)
  178119. compute_color(cinfo, & boxlist[i], i);
  178120. cinfo->actual_number_of_colors = numboxes;
  178121. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178122. }
  178123. /*
  178124. * These routines are concerned with the time-critical task of mapping input
  178125. * colors to the nearest color in the selected colormap.
  178126. *
  178127. * We re-use the histogram space as an "inverse color map", essentially a
  178128. * cache for the results of nearest-color searches. All colors within a
  178129. * histogram cell will be mapped to the same colormap entry, namely the one
  178130. * closest to the cell's center. This may not be quite the closest entry to
  178131. * the actual input color, but it's almost as good. A zero in the cache
  178132. * indicates we haven't found the nearest color for that cell yet; the array
  178133. * is cleared to zeroes before starting the mapping pass. When we find the
  178134. * nearest color for a cell, its colormap index plus one is recorded in the
  178135. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178136. * when they need to use an unfilled entry in the cache.
  178137. *
  178138. * Our method of efficiently finding nearest colors is based on the "locally
  178139. * sorted search" idea described by Heckbert and on the incremental distance
  178140. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178141. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178142. * the distances from a given colormap entry to each cell of the histogram can
  178143. * be computed quickly using an incremental method: the differences between
  178144. * distances to adjacent cells themselves differ by a constant. This allows a
  178145. * fairly fast implementation of the "brute force" approach of computing the
  178146. * distance from every colormap entry to every histogram cell. Unfortunately,
  178147. * it needs a work array to hold the best-distance-so-far for each histogram
  178148. * cell (because the inner loop has to be over cells, not colormap entries).
  178149. * The work array elements have to be INT32s, so the work array would need
  178150. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178151. *
  178152. * To get around these problems, we apply Thomas' method to compute the
  178153. * nearest colors for only the cells within a small subbox of the histogram.
  178154. * The work array need be only as big as the subbox, so the memory usage
  178155. * problem is solved. Furthermore, we need not fill subboxes that are never
  178156. * referenced in pass2; many images use only part of the color gamut, so a
  178157. * fair amount of work is saved. An additional advantage of this
  178158. * approach is that we can apply Heckbert's locality criterion to quickly
  178159. * eliminate colormap entries that are far away from the subbox; typically
  178160. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178161. * and we need not compute their distances to individual cells in the subbox.
  178162. * The speed of this approach is heavily influenced by the subbox size: too
  178163. * small means too much overhead, too big loses because Heckbert's criterion
  178164. * can't eliminate as many colormap entries. Empirically the best subbox
  178165. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178166. *
  178167. * Thomas' article also describes a refined method which is asymptotically
  178168. * faster than the brute-force method, but it is also far more complex and
  178169. * cannot efficiently be applied to small subboxes. It is therefore not
  178170. * useful for programs intended to be portable to DOS machines. On machines
  178171. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178172. * refined method might be faster than the present code --- but then again,
  178173. * it might not be any faster, and it's certainly more complicated.
  178174. */
  178175. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178176. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178177. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178178. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178179. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178180. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178181. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178182. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178183. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178184. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178185. /*
  178186. * The next three routines implement inverse colormap filling. They could
  178187. * all be folded into one big routine, but splitting them up this way saves
  178188. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178189. * and may allow some compilers to produce better code by registerizing more
  178190. * inner-loop variables.
  178191. */
  178192. LOCAL(int)
  178193. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178194. JSAMPLE colorlist[])
  178195. /* Locate the colormap entries close enough to an update box to be candidates
  178196. * for the nearest entry to some cell(s) in the update box. The update box
  178197. * is specified by the center coordinates of its first cell. The number of
  178198. * candidate colormap entries is returned, and their colormap indexes are
  178199. * placed in colorlist[].
  178200. * This routine uses Heckbert's "locally sorted search" criterion to select
  178201. * the colors that need further consideration.
  178202. */
  178203. {
  178204. int numcolors = cinfo->actual_number_of_colors;
  178205. int maxc0, maxc1, maxc2;
  178206. int centerc0, centerc1, centerc2;
  178207. int i, x, ncolors;
  178208. INT32 minmaxdist, min_dist, max_dist, tdist;
  178209. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178210. /* Compute true coordinates of update box's upper corner and center.
  178211. * Actually we compute the coordinates of the center of the upper-corner
  178212. * histogram cell, which are the upper bounds of the volume we care about.
  178213. * Note that since ">>" rounds down, the "center" values may be closer to
  178214. * min than to max; hence comparisons to them must be "<=", not "<".
  178215. */
  178216. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178217. centerc0 = (minc0 + maxc0) >> 1;
  178218. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178219. centerc1 = (minc1 + maxc1) >> 1;
  178220. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178221. centerc2 = (minc2 + maxc2) >> 1;
  178222. /* For each color in colormap, find:
  178223. * 1. its minimum squared-distance to any point in the update box
  178224. * (zero if color is within update box);
  178225. * 2. its maximum squared-distance to any point in the update box.
  178226. * Both of these can be found by considering only the corners of the box.
  178227. * We save the minimum distance for each color in mindist[];
  178228. * only the smallest maximum distance is of interest.
  178229. */
  178230. minmaxdist = 0x7FFFFFFFL;
  178231. for (i = 0; i < numcolors; i++) {
  178232. /* We compute the squared-c0-distance term, then add in the other two. */
  178233. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178234. if (x < minc0) {
  178235. tdist = (x - minc0) * C0_SCALE;
  178236. min_dist = tdist*tdist;
  178237. tdist = (x - maxc0) * C0_SCALE;
  178238. max_dist = tdist*tdist;
  178239. } else if (x > maxc0) {
  178240. tdist = (x - maxc0) * C0_SCALE;
  178241. min_dist = tdist*tdist;
  178242. tdist = (x - minc0) * C0_SCALE;
  178243. max_dist = tdist*tdist;
  178244. } else {
  178245. /* within cell range so no contribution to min_dist */
  178246. min_dist = 0;
  178247. if (x <= centerc0) {
  178248. tdist = (x - maxc0) * C0_SCALE;
  178249. max_dist = tdist*tdist;
  178250. } else {
  178251. tdist = (x - minc0) * C0_SCALE;
  178252. max_dist = tdist*tdist;
  178253. }
  178254. }
  178255. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178256. if (x < minc1) {
  178257. tdist = (x - minc1) * C1_SCALE;
  178258. min_dist += tdist*tdist;
  178259. tdist = (x - maxc1) * C1_SCALE;
  178260. max_dist += tdist*tdist;
  178261. } else if (x > maxc1) {
  178262. tdist = (x - maxc1) * C1_SCALE;
  178263. min_dist += tdist*tdist;
  178264. tdist = (x - minc1) * C1_SCALE;
  178265. max_dist += tdist*tdist;
  178266. } else {
  178267. /* within cell range so no contribution to min_dist */
  178268. if (x <= centerc1) {
  178269. tdist = (x - maxc1) * C1_SCALE;
  178270. max_dist += tdist*tdist;
  178271. } else {
  178272. tdist = (x - minc1) * C1_SCALE;
  178273. max_dist += tdist*tdist;
  178274. }
  178275. }
  178276. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178277. if (x < minc2) {
  178278. tdist = (x - minc2) * C2_SCALE;
  178279. min_dist += tdist*tdist;
  178280. tdist = (x - maxc2) * C2_SCALE;
  178281. max_dist += tdist*tdist;
  178282. } else if (x > maxc2) {
  178283. tdist = (x - maxc2) * C2_SCALE;
  178284. min_dist += tdist*tdist;
  178285. tdist = (x - minc2) * C2_SCALE;
  178286. max_dist += tdist*tdist;
  178287. } else {
  178288. /* within cell range so no contribution to min_dist */
  178289. if (x <= centerc2) {
  178290. tdist = (x - maxc2) * C2_SCALE;
  178291. max_dist += tdist*tdist;
  178292. } else {
  178293. tdist = (x - minc2) * C2_SCALE;
  178294. max_dist += tdist*tdist;
  178295. }
  178296. }
  178297. mindist[i] = min_dist; /* save away the results */
  178298. if (max_dist < minmaxdist)
  178299. minmaxdist = max_dist;
  178300. }
  178301. /* Now we know that no cell in the update box is more than minmaxdist
  178302. * away from some colormap entry. Therefore, only colors that are
  178303. * within minmaxdist of some part of the box need be considered.
  178304. */
  178305. ncolors = 0;
  178306. for (i = 0; i < numcolors; i++) {
  178307. if (mindist[i] <= minmaxdist)
  178308. colorlist[ncolors++] = (JSAMPLE) i;
  178309. }
  178310. return ncolors;
  178311. }
  178312. LOCAL(void)
  178313. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178314. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178315. /* Find the closest colormap entry for each cell in the update box,
  178316. * given the list of candidate colors prepared by find_nearby_colors.
  178317. * Return the indexes of the closest entries in the bestcolor[] array.
  178318. * This routine uses Thomas' incremental distance calculation method to
  178319. * find the distance from a colormap entry to successive cells in the box.
  178320. */
  178321. {
  178322. int ic0, ic1, ic2;
  178323. int i, icolor;
  178324. register INT32 * bptr; /* pointer into bestdist[] array */
  178325. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178326. INT32 dist0, dist1; /* initial distance values */
  178327. register INT32 dist2; /* current distance in inner loop */
  178328. INT32 xx0, xx1; /* distance increments */
  178329. register INT32 xx2;
  178330. INT32 inc0, inc1, inc2; /* initial values for increments */
  178331. /* This array holds the distance to the nearest-so-far color for each cell */
  178332. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178333. /* Initialize best-distance for each cell of the update box */
  178334. bptr = bestdist;
  178335. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178336. *bptr++ = 0x7FFFFFFFL;
  178337. /* For each color selected by find_nearby_colors,
  178338. * compute its distance to the center of each cell in the box.
  178339. * If that's less than best-so-far, update best distance and color number.
  178340. */
  178341. /* Nominal steps between cell centers ("x" in Thomas article) */
  178342. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178343. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178344. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178345. for (i = 0; i < numcolors; i++) {
  178346. icolor = GETJSAMPLE(colorlist[i]);
  178347. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178348. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178349. dist0 = inc0*inc0;
  178350. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178351. dist0 += inc1*inc1;
  178352. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178353. dist0 += inc2*inc2;
  178354. /* Form the initial difference increments */
  178355. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178356. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178357. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178358. /* Now loop over all cells in box, updating distance per Thomas method */
  178359. bptr = bestdist;
  178360. cptr = bestcolor;
  178361. xx0 = inc0;
  178362. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178363. dist1 = dist0;
  178364. xx1 = inc1;
  178365. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178366. dist2 = dist1;
  178367. xx2 = inc2;
  178368. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178369. if (dist2 < *bptr) {
  178370. *bptr = dist2;
  178371. *cptr = (JSAMPLE) icolor;
  178372. }
  178373. dist2 += xx2;
  178374. xx2 += 2 * STEP_C2 * STEP_C2;
  178375. bptr++;
  178376. cptr++;
  178377. }
  178378. dist1 += xx1;
  178379. xx1 += 2 * STEP_C1 * STEP_C1;
  178380. }
  178381. dist0 += xx0;
  178382. xx0 += 2 * STEP_C0 * STEP_C0;
  178383. }
  178384. }
  178385. }
  178386. LOCAL(void)
  178387. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178388. /* Fill the inverse-colormap entries in the update box that contains */
  178389. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178390. /* we can fill as many others as we wish.) */
  178391. {
  178392. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178393. hist3d histogram = cquantize->histogram;
  178394. int minc0, minc1, minc2; /* lower left corner of update box */
  178395. int ic0, ic1, ic2;
  178396. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178397. register histptr cachep; /* pointer into main cache array */
  178398. /* This array lists the candidate colormap indexes. */
  178399. JSAMPLE colorlist[MAXNUMCOLORS];
  178400. int numcolors; /* number of candidate colors */
  178401. /* This array holds the actually closest colormap index for each cell. */
  178402. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178403. /* Convert cell coordinates to update box ID */
  178404. c0 >>= BOX_C0_LOG;
  178405. c1 >>= BOX_C1_LOG;
  178406. c2 >>= BOX_C2_LOG;
  178407. /* Compute true coordinates of update box's origin corner.
  178408. * Actually we compute the coordinates of the center of the corner
  178409. * histogram cell, which are the lower bounds of the volume we care about.
  178410. */
  178411. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178412. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178413. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178414. /* Determine which colormap entries are close enough to be candidates
  178415. * for the nearest entry to some cell in the update box.
  178416. */
  178417. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178418. /* Determine the actually nearest colors. */
  178419. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178420. bestcolor);
  178421. /* Save the best color numbers (plus 1) in the main cache array */
  178422. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178423. c1 <<= BOX_C1_LOG;
  178424. c2 <<= BOX_C2_LOG;
  178425. cptr = bestcolor;
  178426. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178427. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178428. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178429. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178430. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178431. }
  178432. }
  178433. }
  178434. }
  178435. /*
  178436. * Map some rows of pixels to the output colormapped representation.
  178437. */
  178438. METHODDEF(void)
  178439. pass2_no_dither (j_decompress_ptr cinfo,
  178440. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178441. /* This version performs no dithering */
  178442. {
  178443. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178444. hist3d histogram = cquantize->histogram;
  178445. register JSAMPROW inptr, outptr;
  178446. register histptr cachep;
  178447. register int c0, c1, c2;
  178448. int row;
  178449. JDIMENSION col;
  178450. JDIMENSION width = cinfo->output_width;
  178451. for (row = 0; row < num_rows; row++) {
  178452. inptr = input_buf[row];
  178453. outptr = output_buf[row];
  178454. for (col = width; col > 0; col--) {
  178455. /* get pixel value and index into the cache */
  178456. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178457. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178458. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178459. cachep = & histogram[c0][c1][c2];
  178460. /* If we have not seen this color before, find nearest colormap entry */
  178461. /* and update the cache */
  178462. if (*cachep == 0)
  178463. fill_inverse_cmap(cinfo, c0,c1,c2);
  178464. /* Now emit the colormap index for this cell */
  178465. *outptr++ = (JSAMPLE) (*cachep - 1);
  178466. }
  178467. }
  178468. }
  178469. METHODDEF(void)
  178470. pass2_fs_dither (j_decompress_ptr cinfo,
  178471. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178472. /* This version performs Floyd-Steinberg dithering */
  178473. {
  178474. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178475. hist3d histogram = cquantize->histogram;
  178476. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178477. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178478. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178479. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178480. JSAMPROW inptr; /* => current input pixel */
  178481. JSAMPROW outptr; /* => current output pixel */
  178482. histptr cachep;
  178483. int dir; /* +1 or -1 depending on direction */
  178484. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178485. int row;
  178486. JDIMENSION col;
  178487. JDIMENSION width = cinfo->output_width;
  178488. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178489. int *error_limit = cquantize->error_limiter;
  178490. JSAMPROW colormap0 = cinfo->colormap[0];
  178491. JSAMPROW colormap1 = cinfo->colormap[1];
  178492. JSAMPROW colormap2 = cinfo->colormap[2];
  178493. SHIFT_TEMPS
  178494. for (row = 0; row < num_rows; row++) {
  178495. inptr = input_buf[row];
  178496. outptr = output_buf[row];
  178497. if (cquantize->on_odd_row) {
  178498. /* work right to left in this row */
  178499. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178500. outptr += width-1;
  178501. dir = -1;
  178502. dir3 = -3;
  178503. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178504. cquantize->on_odd_row = FALSE; /* flip for next time */
  178505. } else {
  178506. /* work left to right in this row */
  178507. dir = 1;
  178508. dir3 = 3;
  178509. errorptr = cquantize->fserrors; /* => entry before first real column */
  178510. cquantize->on_odd_row = TRUE; /* flip for next time */
  178511. }
  178512. /* Preset error values: no error propagated to first pixel from left */
  178513. cur0 = cur1 = cur2 = 0;
  178514. /* and no error propagated to row below yet */
  178515. belowerr0 = belowerr1 = belowerr2 = 0;
  178516. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178517. for (col = width; col > 0; col--) {
  178518. /* curN holds the error propagated from the previous pixel on the
  178519. * current line. Add the error propagated from the previous line
  178520. * to form the complete error correction term for this pixel, and
  178521. * round the error term (which is expressed * 16) to an integer.
  178522. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178523. * for either sign of the error value.
  178524. * Note: errorptr points to *previous* column's array entry.
  178525. */
  178526. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178527. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178528. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178529. /* Limit the error using transfer function set by init_error_limit.
  178530. * See comments with init_error_limit for rationale.
  178531. */
  178532. cur0 = error_limit[cur0];
  178533. cur1 = error_limit[cur1];
  178534. cur2 = error_limit[cur2];
  178535. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178536. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178537. * this sets the required size of the range_limit array.
  178538. */
  178539. cur0 += GETJSAMPLE(inptr[0]);
  178540. cur1 += GETJSAMPLE(inptr[1]);
  178541. cur2 += GETJSAMPLE(inptr[2]);
  178542. cur0 = GETJSAMPLE(range_limit[cur0]);
  178543. cur1 = GETJSAMPLE(range_limit[cur1]);
  178544. cur2 = GETJSAMPLE(range_limit[cur2]);
  178545. /* Index into the cache with adjusted pixel value */
  178546. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178547. /* If we have not seen this color before, find nearest colormap */
  178548. /* entry and update the cache */
  178549. if (*cachep == 0)
  178550. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178551. /* Now emit the colormap index for this cell */
  178552. { register int pixcode = *cachep - 1;
  178553. *outptr = (JSAMPLE) pixcode;
  178554. /* Compute representation error for this pixel */
  178555. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178556. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178557. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178558. }
  178559. /* Compute error fractions to be propagated to adjacent pixels.
  178560. * Add these into the running sums, and simultaneously shift the
  178561. * next-line error sums left by 1 column.
  178562. */
  178563. { register LOCFSERROR bnexterr, delta;
  178564. bnexterr = cur0; /* Process component 0 */
  178565. delta = cur0 * 2;
  178566. cur0 += delta; /* form error * 3 */
  178567. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178568. cur0 += delta; /* form error * 5 */
  178569. bpreverr0 = belowerr0 + cur0;
  178570. belowerr0 = bnexterr;
  178571. cur0 += delta; /* form error * 7 */
  178572. bnexterr = cur1; /* Process component 1 */
  178573. delta = cur1 * 2;
  178574. cur1 += delta; /* form error * 3 */
  178575. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178576. cur1 += delta; /* form error * 5 */
  178577. bpreverr1 = belowerr1 + cur1;
  178578. belowerr1 = bnexterr;
  178579. cur1 += delta; /* form error * 7 */
  178580. bnexterr = cur2; /* Process component 2 */
  178581. delta = cur2 * 2;
  178582. cur2 += delta; /* form error * 3 */
  178583. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178584. cur2 += delta; /* form error * 5 */
  178585. bpreverr2 = belowerr2 + cur2;
  178586. belowerr2 = bnexterr;
  178587. cur2 += delta; /* form error * 7 */
  178588. }
  178589. /* At this point curN contains the 7/16 error value to be propagated
  178590. * to the next pixel on the current line, and all the errors for the
  178591. * next line have been shifted over. We are therefore ready to move on.
  178592. */
  178593. inptr += dir3; /* Advance pixel pointers to next column */
  178594. outptr += dir;
  178595. errorptr += dir3; /* advance errorptr to current column */
  178596. }
  178597. /* Post-loop cleanup: we must unload the final error values into the
  178598. * final fserrors[] entry. Note we need not unload belowerrN because
  178599. * it is for the dummy column before or after the actual array.
  178600. */
  178601. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178602. errorptr[1] = (FSERROR) bpreverr1;
  178603. errorptr[2] = (FSERROR) bpreverr2;
  178604. }
  178605. }
  178606. /*
  178607. * Initialize the error-limiting transfer function (lookup table).
  178608. * The raw F-S error computation can potentially compute error values of up to
  178609. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178610. * much less, otherwise obviously wrong pixels will be created. (Typical
  178611. * effects include weird fringes at color-area boundaries, isolated bright
  178612. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178613. * is to ensure that the "corners" of the color cube are allocated as output
  178614. * colors; then repeated errors in the same direction cannot cause cascading
  178615. * error buildup. However, that only prevents the error from getting
  178616. * completely out of hand; Aaron Giles reports that error limiting improves
  178617. * the results even with corner colors allocated.
  178618. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178619. * well, but the smoother transfer function used below is even better. Thanks
  178620. * to Aaron Giles for this idea.
  178621. */
  178622. LOCAL(void)
  178623. init_error_limit (j_decompress_ptr cinfo)
  178624. /* Allocate and fill in the error_limiter table */
  178625. {
  178626. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178627. int * table;
  178628. int in, out;
  178629. table = (int *) (*cinfo->mem->alloc_small)
  178630. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178631. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178632. cquantize->error_limiter = table;
  178633. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178634. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178635. out = 0;
  178636. for (in = 0; in < STEPSIZE; in++, out++) {
  178637. table[in] = out; table[-in] = -out;
  178638. }
  178639. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178640. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178641. table[in] = out; table[-in] = -out;
  178642. }
  178643. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178644. for (; in <= MAXJSAMPLE; in++) {
  178645. table[in] = out; table[-in] = -out;
  178646. }
  178647. #undef STEPSIZE
  178648. }
  178649. /*
  178650. * Finish up at the end of each pass.
  178651. */
  178652. METHODDEF(void)
  178653. finish_pass1 (j_decompress_ptr cinfo)
  178654. {
  178655. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178656. /* Select the representative colors and fill in cinfo->colormap */
  178657. cinfo->colormap = cquantize->sv_colormap;
  178658. select_colors(cinfo, cquantize->desired);
  178659. /* Force next pass to zero the color index table */
  178660. cquantize->needs_zeroed = TRUE;
  178661. }
  178662. METHODDEF(void)
  178663. finish_pass2 (j_decompress_ptr)
  178664. {
  178665. /* no work */
  178666. }
  178667. /*
  178668. * Initialize for each processing pass.
  178669. */
  178670. METHODDEF(void)
  178671. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178672. {
  178673. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178674. hist3d histogram = cquantize->histogram;
  178675. int i;
  178676. /* Only F-S dithering or no dithering is supported. */
  178677. /* If user asks for ordered dither, give him F-S. */
  178678. if (cinfo->dither_mode != JDITHER_NONE)
  178679. cinfo->dither_mode = JDITHER_FS;
  178680. if (is_pre_scan) {
  178681. /* Set up method pointers */
  178682. cquantize->pub.color_quantize = prescan_quantize;
  178683. cquantize->pub.finish_pass = finish_pass1;
  178684. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178685. } else {
  178686. /* Set up method pointers */
  178687. if (cinfo->dither_mode == JDITHER_FS)
  178688. cquantize->pub.color_quantize = pass2_fs_dither;
  178689. else
  178690. cquantize->pub.color_quantize = pass2_no_dither;
  178691. cquantize->pub.finish_pass = finish_pass2;
  178692. /* Make sure color count is acceptable */
  178693. i = cinfo->actual_number_of_colors;
  178694. if (i < 1)
  178695. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178696. if (i > MAXNUMCOLORS)
  178697. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178698. if (cinfo->dither_mode == JDITHER_FS) {
  178699. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178700. (3 * SIZEOF(FSERROR)));
  178701. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178702. if (cquantize->fserrors == NULL)
  178703. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178704. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178705. /* Initialize the propagated errors to zero. */
  178706. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178707. /* Make the error-limit table if we didn't already. */
  178708. if (cquantize->error_limiter == NULL)
  178709. init_error_limit(cinfo);
  178710. cquantize->on_odd_row = FALSE;
  178711. }
  178712. }
  178713. /* Zero the histogram or inverse color map, if necessary */
  178714. if (cquantize->needs_zeroed) {
  178715. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178716. jzero_far((void FAR *) histogram[i],
  178717. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178718. }
  178719. cquantize->needs_zeroed = FALSE;
  178720. }
  178721. }
  178722. /*
  178723. * Switch to a new external colormap between output passes.
  178724. */
  178725. METHODDEF(void)
  178726. new_color_map_2_quant (j_decompress_ptr cinfo)
  178727. {
  178728. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178729. /* Reset the inverse color map */
  178730. cquantize->needs_zeroed = TRUE;
  178731. }
  178732. /*
  178733. * Module initialization routine for 2-pass color quantization.
  178734. */
  178735. GLOBAL(void)
  178736. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178737. {
  178738. my_cquantize_ptr2 cquantize;
  178739. int i;
  178740. cquantize = (my_cquantize_ptr2)
  178741. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178742. SIZEOF(my_cquantizer2));
  178743. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178744. cquantize->pub.start_pass = start_pass_2_quant;
  178745. cquantize->pub.new_color_map = new_color_map_2_quant;
  178746. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178747. cquantize->error_limiter = NULL;
  178748. /* Make sure jdmaster didn't give me a case I can't handle */
  178749. if (cinfo->out_color_components != 3)
  178750. ERREXIT(cinfo, JERR_NOTIMPL);
  178751. /* Allocate the histogram/inverse colormap storage */
  178752. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178753. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178754. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178755. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178756. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178757. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178758. }
  178759. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178760. /* Allocate storage for the completed colormap, if required.
  178761. * We do this now since it is FAR storage and may affect
  178762. * the memory manager's space calculations.
  178763. */
  178764. if (cinfo->enable_2pass_quant) {
  178765. /* Make sure color count is acceptable */
  178766. int desired = cinfo->desired_number_of_colors;
  178767. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178768. if (desired < 8)
  178769. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178770. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178771. if (desired > MAXNUMCOLORS)
  178772. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178773. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178774. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178775. cquantize->desired = desired;
  178776. } else
  178777. cquantize->sv_colormap = NULL;
  178778. /* Only F-S dithering or no dithering is supported. */
  178779. /* If user asks for ordered dither, give him F-S. */
  178780. if (cinfo->dither_mode != JDITHER_NONE)
  178781. cinfo->dither_mode = JDITHER_FS;
  178782. /* Allocate Floyd-Steinberg workspace if necessary.
  178783. * This isn't really needed until pass 2, but again it is FAR storage.
  178784. * Although we will cope with a later change in dither_mode,
  178785. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178786. */
  178787. if (cinfo->dither_mode == JDITHER_FS) {
  178788. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178789. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178790. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178791. /* Might as well create the error-limiting table too. */
  178792. init_error_limit(cinfo);
  178793. }
  178794. }
  178795. #endif /* QUANT_2PASS_SUPPORTED */
  178796. /*** End of inlined file: jquant2.c ***/
  178797. /*** Start of inlined file: jutils.c ***/
  178798. #define JPEG_INTERNALS
  178799. /*
  178800. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178801. * of a DCT block read in natural order (left to right, top to bottom).
  178802. */
  178803. #if 0 /* This table is not actually needed in v6a */
  178804. const int jpeg_zigzag_order[DCTSIZE2] = {
  178805. 0, 1, 5, 6, 14, 15, 27, 28,
  178806. 2, 4, 7, 13, 16, 26, 29, 42,
  178807. 3, 8, 12, 17, 25, 30, 41, 43,
  178808. 9, 11, 18, 24, 31, 40, 44, 53,
  178809. 10, 19, 23, 32, 39, 45, 52, 54,
  178810. 20, 22, 33, 38, 46, 51, 55, 60,
  178811. 21, 34, 37, 47, 50, 56, 59, 61,
  178812. 35, 36, 48, 49, 57, 58, 62, 63
  178813. };
  178814. #endif
  178815. /*
  178816. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178817. * of zigzag order.
  178818. *
  178819. * When reading corrupted data, the Huffman decoders could attempt
  178820. * to reference an entry beyond the end of this array (if the decoded
  178821. * zero run length reaches past the end of the block). To prevent
  178822. * wild stores without adding an inner-loop test, we put some extra
  178823. * "63"s after the real entries. This will cause the extra coefficient
  178824. * to be stored in location 63 of the block, not somewhere random.
  178825. * The worst case would be a run-length of 15, which means we need 16
  178826. * fake entries.
  178827. */
  178828. const int jpeg_natural_order[DCTSIZE2+16] = {
  178829. 0, 1, 8, 16, 9, 2, 3, 10,
  178830. 17, 24, 32, 25, 18, 11, 4, 5,
  178831. 12, 19, 26, 33, 40, 48, 41, 34,
  178832. 27, 20, 13, 6, 7, 14, 21, 28,
  178833. 35, 42, 49, 56, 57, 50, 43, 36,
  178834. 29, 22, 15, 23, 30, 37, 44, 51,
  178835. 58, 59, 52, 45, 38, 31, 39, 46,
  178836. 53, 60, 61, 54, 47, 55, 62, 63,
  178837. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178838. 63, 63, 63, 63, 63, 63, 63, 63
  178839. };
  178840. /*
  178841. * Arithmetic utilities
  178842. */
  178843. GLOBAL(long)
  178844. jdiv_round_up (long a, long b)
  178845. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178846. /* Assumes a >= 0, b > 0 */
  178847. {
  178848. return (a + b - 1L) / b;
  178849. }
  178850. GLOBAL(long)
  178851. jround_up (long a, long b)
  178852. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178853. /* Assumes a >= 0, b > 0 */
  178854. {
  178855. a += b - 1L;
  178856. return a - (a % b);
  178857. }
  178858. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178859. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178860. * are FAR and we're assuming a small-pointer memory model. However, some
  178861. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178862. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178863. * Otherwise, the routines below do it the hard way. (The performance cost
  178864. * is not all that great, because these routines aren't very heavily used.)
  178865. */
  178866. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178867. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178868. #define FMEMZERO(target,size) MEMZERO(target,size)
  178869. #else /* 80x86 case, define if we can */
  178870. #ifdef USE_FMEM
  178871. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178872. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178873. #endif
  178874. #endif
  178875. GLOBAL(void)
  178876. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178877. JSAMPARRAY output_array, int dest_row,
  178878. int num_rows, JDIMENSION num_cols)
  178879. /* Copy some rows of samples from one place to another.
  178880. * num_rows rows are copied from input_array[source_row++]
  178881. * to output_array[dest_row++]; these areas may overlap for duplication.
  178882. * The source and destination arrays must be at least as wide as num_cols.
  178883. */
  178884. {
  178885. register JSAMPROW inptr, outptr;
  178886. #ifdef FMEMCOPY
  178887. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178888. #else
  178889. register JDIMENSION count;
  178890. #endif
  178891. register int row;
  178892. input_array += source_row;
  178893. output_array += dest_row;
  178894. for (row = num_rows; row > 0; row--) {
  178895. inptr = *input_array++;
  178896. outptr = *output_array++;
  178897. #ifdef FMEMCOPY
  178898. FMEMCOPY(outptr, inptr, count);
  178899. #else
  178900. for (count = num_cols; count > 0; count--)
  178901. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178902. #endif
  178903. }
  178904. }
  178905. GLOBAL(void)
  178906. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178907. JDIMENSION num_blocks)
  178908. /* Copy a row of coefficient blocks from one place to another. */
  178909. {
  178910. #ifdef FMEMCOPY
  178911. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178912. #else
  178913. register JCOEFPTR inptr, outptr;
  178914. register long count;
  178915. inptr = (JCOEFPTR) input_row;
  178916. outptr = (JCOEFPTR) output_row;
  178917. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178918. *outptr++ = *inptr++;
  178919. }
  178920. #endif
  178921. }
  178922. GLOBAL(void)
  178923. jzero_far (void FAR * target, size_t bytestozero)
  178924. /* Zero out a chunk of FAR memory. */
  178925. /* This might be sample-array data, block-array data, or alloc_large data. */
  178926. {
  178927. #ifdef FMEMZERO
  178928. FMEMZERO(target, bytestozero);
  178929. #else
  178930. register char FAR * ptr = (char FAR *) target;
  178931. register size_t count;
  178932. for (count = bytestozero; count > 0; count--) {
  178933. *ptr++ = 0;
  178934. }
  178935. #endif
  178936. }
  178937. /*** End of inlined file: jutils.c ***/
  178938. /*** Start of inlined file: transupp.c ***/
  178939. /* Although this file really shouldn't have access to the library internals,
  178940. * it's helpful to let it call jround_up() and jcopy_block_row().
  178941. */
  178942. #define JPEG_INTERNALS
  178943. /*** Start of inlined file: transupp.h ***/
  178944. /* If you happen not to want the image transform support, disable it here */
  178945. #ifndef TRANSFORMS_SUPPORTED
  178946. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178947. #endif
  178948. /* Short forms of external names for systems with brain-damaged linkers. */
  178949. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178950. #define jtransform_request_workspace jTrRequest
  178951. #define jtransform_adjust_parameters jTrAdjust
  178952. #define jtransform_execute_transformation jTrExec
  178953. #define jcopy_markers_setup jCMrkSetup
  178954. #define jcopy_markers_execute jCMrkExec
  178955. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178956. /*
  178957. * Codes for supported types of image transformations.
  178958. */
  178959. typedef enum {
  178960. JXFORM_NONE, /* no transformation */
  178961. JXFORM_FLIP_H, /* horizontal flip */
  178962. JXFORM_FLIP_V, /* vertical flip */
  178963. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178964. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178965. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178966. JXFORM_ROT_180, /* 180-degree rotation */
  178967. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178968. } JXFORM_CODE;
  178969. /*
  178970. * Although rotating and flipping data expressed as DCT coefficients is not
  178971. * hard, there is an asymmetry in the JPEG format specification for images
  178972. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178973. * image edges are padded out to the next iMCU boundary with junk data; but
  178974. * no padding is possible at the top and left edges. If we were to flip
  178975. * the whole image including the pad data, then pad garbage would become
  178976. * visible at the top and/or left, and real pixels would disappear into the
  178977. * pad margins --- perhaps permanently, since encoders & decoders may not
  178978. * bother to preserve DCT blocks that appear to be completely outside the
  178979. * nominal image area. So, we have to exclude any partial iMCUs from the
  178980. * basic transformation.
  178981. *
  178982. * Transpose is the only transformation that can handle partial iMCUs at the
  178983. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178984. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178985. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178986. * The other transforms are defined as combinations of these basic transforms
  178987. * and process edge blocks in a way that preserves the equivalence.
  178988. *
  178989. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178990. * this is not strictly lossless, but it usually gives the best-looking
  178991. * result for odd-size images. Note that when this option is active,
  178992. * the expected mathematical equivalences between the transforms may not hold.
  178993. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178994. * followed by -rot 180 -trim trims both edges.)
  178995. *
  178996. * We also offer a "force to grayscale" option, which simply discards the
  178997. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178998. * the luminance channel is preserved exactly. It's not the same kind of
  178999. * thing as the rotate/flip transformations, but it's convenient to handle it
  179000. * as part of this package, mainly because the transformation routines have to
  179001. * be aware of the option to know how many components to work on.
  179002. */
  179003. typedef struct {
  179004. /* Options: set by caller */
  179005. JXFORM_CODE transform; /* image transform operator */
  179006. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179007. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179008. /* Internal workspace: caller should not touch these */
  179009. int num_components; /* # of components in workspace */
  179010. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179011. } jpeg_transform_info;
  179012. #if TRANSFORMS_SUPPORTED
  179013. /* Request any required workspace */
  179014. EXTERN(void) jtransform_request_workspace
  179015. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179016. /* Adjust output image parameters */
  179017. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179018. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179019. jvirt_barray_ptr *src_coef_arrays,
  179020. jpeg_transform_info *info));
  179021. /* Execute the actual transformation, if any */
  179022. EXTERN(void) jtransform_execute_transformation
  179023. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179024. jvirt_barray_ptr *src_coef_arrays,
  179025. jpeg_transform_info *info));
  179026. #endif /* TRANSFORMS_SUPPORTED */
  179027. /*
  179028. * Support for copying optional markers from source to destination file.
  179029. */
  179030. typedef enum {
  179031. JCOPYOPT_NONE, /* copy no optional markers */
  179032. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179033. JCOPYOPT_ALL /* copy all optional markers */
  179034. } JCOPY_OPTION;
  179035. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179036. /* Setup decompression object to save desired markers in memory */
  179037. EXTERN(void) jcopy_markers_setup
  179038. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179039. /* Copy markers saved in the given source object to the destination object */
  179040. EXTERN(void) jcopy_markers_execute
  179041. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179042. JCOPY_OPTION option));
  179043. /*** End of inlined file: transupp.h ***/
  179044. /* My own external interface */
  179045. #if TRANSFORMS_SUPPORTED
  179046. /*
  179047. * Lossless image transformation routines. These routines work on DCT
  179048. * coefficient arrays and thus do not require any lossy decompression
  179049. * or recompression of the image.
  179050. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179051. *
  179052. * Horizontal flipping is done in-place, using a single top-to-bottom
  179053. * pass through the virtual source array. It will thus be much the
  179054. * fastest option for images larger than main memory.
  179055. *
  179056. * The other routines require a set of destination virtual arrays, so they
  179057. * need twice as much memory as jpegtran normally does. The destination
  179058. * arrays are always written in normal scan order (top to bottom) because
  179059. * the virtual array manager expects this. The source arrays will be scanned
  179060. * in the corresponding order, which means multiple passes through the source
  179061. * arrays for most of the transforms. That could result in much thrashing
  179062. * if the image is larger than main memory.
  179063. *
  179064. * Some notes about the operating environment of the individual transform
  179065. * routines:
  179066. * 1. Both the source and destination virtual arrays are allocated from the
  179067. * source JPEG object, and therefore should be manipulated by calling the
  179068. * source's memory manager.
  179069. * 2. The destination's component count should be used. It may be smaller
  179070. * than the source's when forcing to grayscale.
  179071. * 3. Likewise the destination's sampling factors should be used. When
  179072. * forcing to grayscale the destination's sampling factors will be all 1,
  179073. * and we may as well take that as the effective iMCU size.
  179074. * 4. When "trim" is in effect, the destination's dimensions will be the
  179075. * trimmed values but the source's will be untrimmed.
  179076. * 5. All the routines assume that the source and destination buffers are
  179077. * padded out to a full iMCU boundary. This is true, although for the
  179078. * source buffer it is an undocumented property of jdcoefct.c.
  179079. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179080. * dimensions and ignore the source's.
  179081. */
  179082. LOCAL(void)
  179083. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179084. jvirt_barray_ptr *src_coef_arrays)
  179085. /* Horizontal flip; done in-place, so no separate dest array is required */
  179086. {
  179087. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179088. int ci, k, offset_y;
  179089. JBLOCKARRAY buffer;
  179090. JCOEFPTR ptr1, ptr2;
  179091. JCOEF temp1, temp2;
  179092. jpeg_component_info *compptr;
  179093. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179094. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179095. * mirroring by changing the signs of odd-numbered columns.
  179096. * Partial iMCUs at the right edge are left untouched.
  179097. */
  179098. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179099. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179100. compptr = dstinfo->comp_info + ci;
  179101. comp_width = MCU_cols * compptr->h_samp_factor;
  179102. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179103. blk_y += compptr->v_samp_factor) {
  179104. buffer = (*srcinfo->mem->access_virt_barray)
  179105. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179106. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179107. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179108. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179109. ptr1 = buffer[offset_y][blk_x];
  179110. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179111. /* this unrolled loop doesn't need to know which row it's on... */
  179112. for (k = 0; k < DCTSIZE2; k += 2) {
  179113. temp1 = *ptr1; /* swap even column */
  179114. temp2 = *ptr2;
  179115. *ptr1++ = temp2;
  179116. *ptr2++ = temp1;
  179117. temp1 = *ptr1; /* swap odd column with sign change */
  179118. temp2 = *ptr2;
  179119. *ptr1++ = -temp2;
  179120. *ptr2++ = -temp1;
  179121. }
  179122. }
  179123. }
  179124. }
  179125. }
  179126. }
  179127. LOCAL(void)
  179128. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179129. jvirt_barray_ptr *src_coef_arrays,
  179130. jvirt_barray_ptr *dst_coef_arrays)
  179131. /* Vertical flip */
  179132. {
  179133. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179134. int ci, i, j, offset_y;
  179135. JBLOCKARRAY src_buffer, dst_buffer;
  179136. JBLOCKROW src_row_ptr, dst_row_ptr;
  179137. JCOEFPTR src_ptr, dst_ptr;
  179138. jpeg_component_info *compptr;
  179139. /* We output into a separate array because we can't touch different
  179140. * rows of the source virtual array simultaneously. Otherwise, this
  179141. * is a pretty straightforward analog of horizontal flip.
  179142. * Within a DCT block, vertical mirroring is done by changing the signs
  179143. * of odd-numbered rows.
  179144. * Partial iMCUs at the bottom edge are copied verbatim.
  179145. */
  179146. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179147. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179148. compptr = dstinfo->comp_info + ci;
  179149. comp_height = MCU_rows * compptr->v_samp_factor;
  179150. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179151. dst_blk_y += compptr->v_samp_factor) {
  179152. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179153. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179154. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179155. if (dst_blk_y < comp_height) {
  179156. /* Row is within the mirrorable area. */
  179157. src_buffer = (*srcinfo->mem->access_virt_barray)
  179158. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179159. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179160. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179161. } else {
  179162. /* Bottom-edge blocks will be copied verbatim. */
  179163. src_buffer = (*srcinfo->mem->access_virt_barray)
  179164. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179165. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179166. }
  179167. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179168. if (dst_blk_y < comp_height) {
  179169. /* Row is within the mirrorable area. */
  179170. dst_row_ptr = dst_buffer[offset_y];
  179171. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179172. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179173. dst_blk_x++) {
  179174. dst_ptr = dst_row_ptr[dst_blk_x];
  179175. src_ptr = src_row_ptr[dst_blk_x];
  179176. for (i = 0; i < DCTSIZE; i += 2) {
  179177. /* copy even row */
  179178. for (j = 0; j < DCTSIZE; j++)
  179179. *dst_ptr++ = *src_ptr++;
  179180. /* copy odd row with sign change */
  179181. for (j = 0; j < DCTSIZE; j++)
  179182. *dst_ptr++ = - *src_ptr++;
  179183. }
  179184. }
  179185. } else {
  179186. /* Just copy row verbatim. */
  179187. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179188. compptr->width_in_blocks);
  179189. }
  179190. }
  179191. }
  179192. }
  179193. }
  179194. LOCAL(void)
  179195. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179196. jvirt_barray_ptr *src_coef_arrays,
  179197. jvirt_barray_ptr *dst_coef_arrays)
  179198. /* Transpose source into destination */
  179199. {
  179200. JDIMENSION dst_blk_x, dst_blk_y;
  179201. int ci, i, j, offset_x, offset_y;
  179202. JBLOCKARRAY src_buffer, dst_buffer;
  179203. JCOEFPTR src_ptr, dst_ptr;
  179204. jpeg_component_info *compptr;
  179205. /* Transposing pixels within a block just requires transposing the
  179206. * DCT coefficients.
  179207. * Partial iMCUs at the edges require no special treatment; we simply
  179208. * process all the available DCT blocks for every component.
  179209. */
  179210. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179211. compptr = dstinfo->comp_info + ci;
  179212. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179213. dst_blk_y += compptr->v_samp_factor) {
  179214. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179215. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179216. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179217. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179218. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179219. dst_blk_x += compptr->h_samp_factor) {
  179220. src_buffer = (*srcinfo->mem->access_virt_barray)
  179221. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179222. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179223. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179224. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179225. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179226. for (i = 0; i < DCTSIZE; i++)
  179227. for (j = 0; j < DCTSIZE; j++)
  179228. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179229. }
  179230. }
  179231. }
  179232. }
  179233. }
  179234. }
  179235. LOCAL(void)
  179236. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179237. jvirt_barray_ptr *src_coef_arrays,
  179238. jvirt_barray_ptr *dst_coef_arrays)
  179239. /* 90 degree rotation is equivalent to
  179240. * 1. Transposing the image;
  179241. * 2. Horizontal mirroring.
  179242. * These two steps are merged into a single processing routine.
  179243. */
  179244. {
  179245. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179246. int ci, i, j, offset_x, offset_y;
  179247. JBLOCKARRAY src_buffer, dst_buffer;
  179248. JCOEFPTR src_ptr, dst_ptr;
  179249. jpeg_component_info *compptr;
  179250. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179251. * at the (output) right edge properly. They just get transposed and
  179252. * not mirrored.
  179253. */
  179254. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179255. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179256. compptr = dstinfo->comp_info + ci;
  179257. comp_width = MCU_cols * compptr->h_samp_factor;
  179258. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179259. dst_blk_y += compptr->v_samp_factor) {
  179260. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179261. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179262. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179263. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179264. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179265. dst_blk_x += compptr->h_samp_factor) {
  179266. src_buffer = (*srcinfo->mem->access_virt_barray)
  179267. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179268. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179269. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179270. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179271. if (dst_blk_x < comp_width) {
  179272. /* Block is within the mirrorable area. */
  179273. dst_ptr = dst_buffer[offset_y]
  179274. [comp_width - dst_blk_x - offset_x - 1];
  179275. for (i = 0; i < DCTSIZE; i++) {
  179276. for (j = 0; j < DCTSIZE; j++)
  179277. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179278. i++;
  179279. for (j = 0; j < DCTSIZE; j++)
  179280. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179281. }
  179282. } else {
  179283. /* Edge blocks are transposed but not mirrored. */
  179284. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179285. for (i = 0; i < DCTSIZE; i++)
  179286. for (j = 0; j < DCTSIZE; j++)
  179287. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179288. }
  179289. }
  179290. }
  179291. }
  179292. }
  179293. }
  179294. }
  179295. LOCAL(void)
  179296. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179297. jvirt_barray_ptr *src_coef_arrays,
  179298. jvirt_barray_ptr *dst_coef_arrays)
  179299. /* 270 degree rotation is equivalent to
  179300. * 1. Horizontal mirroring;
  179301. * 2. Transposing the image.
  179302. * These two steps are merged into a single processing routine.
  179303. */
  179304. {
  179305. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179306. int ci, i, j, offset_x, offset_y;
  179307. JBLOCKARRAY src_buffer, dst_buffer;
  179308. JCOEFPTR src_ptr, dst_ptr;
  179309. jpeg_component_info *compptr;
  179310. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179311. * at the (output) bottom edge properly. They just get transposed and
  179312. * not mirrored.
  179313. */
  179314. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179315. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179316. compptr = dstinfo->comp_info + ci;
  179317. comp_height = MCU_rows * compptr->v_samp_factor;
  179318. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179319. dst_blk_y += compptr->v_samp_factor) {
  179320. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179321. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179322. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179323. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179324. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179325. dst_blk_x += compptr->h_samp_factor) {
  179326. src_buffer = (*srcinfo->mem->access_virt_barray)
  179327. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179328. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179329. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179330. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179331. if (dst_blk_y < comp_height) {
  179332. /* Block is within the mirrorable area. */
  179333. src_ptr = src_buffer[offset_x]
  179334. [comp_height - dst_blk_y - offset_y - 1];
  179335. for (i = 0; i < DCTSIZE; i++) {
  179336. for (j = 0; j < DCTSIZE; j++) {
  179337. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179338. j++;
  179339. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179340. }
  179341. }
  179342. } else {
  179343. /* Edge blocks are transposed but not mirrored. */
  179344. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179345. for (i = 0; i < DCTSIZE; i++)
  179346. for (j = 0; j < DCTSIZE; j++)
  179347. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179348. }
  179349. }
  179350. }
  179351. }
  179352. }
  179353. }
  179354. }
  179355. LOCAL(void)
  179356. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179357. jvirt_barray_ptr *src_coef_arrays,
  179358. jvirt_barray_ptr *dst_coef_arrays)
  179359. /* 180 degree rotation is equivalent to
  179360. * 1. Vertical mirroring;
  179361. * 2. Horizontal mirroring.
  179362. * These two steps are merged into a single processing routine.
  179363. */
  179364. {
  179365. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179366. int ci, i, j, offset_y;
  179367. JBLOCKARRAY src_buffer, dst_buffer;
  179368. JBLOCKROW src_row_ptr, dst_row_ptr;
  179369. JCOEFPTR src_ptr, dst_ptr;
  179370. jpeg_component_info *compptr;
  179371. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179372. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179373. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179374. compptr = dstinfo->comp_info + ci;
  179375. comp_width = MCU_cols * compptr->h_samp_factor;
  179376. comp_height = MCU_rows * compptr->v_samp_factor;
  179377. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179378. dst_blk_y += compptr->v_samp_factor) {
  179379. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179380. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179381. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179382. if (dst_blk_y < comp_height) {
  179383. /* Row is within the vertically mirrorable area. */
  179384. src_buffer = (*srcinfo->mem->access_virt_barray)
  179385. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179386. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179387. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179388. } else {
  179389. /* Bottom-edge rows are only mirrored horizontally. */
  179390. src_buffer = (*srcinfo->mem->access_virt_barray)
  179391. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179392. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179393. }
  179394. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179395. if (dst_blk_y < comp_height) {
  179396. /* Row is within the mirrorable area. */
  179397. dst_row_ptr = dst_buffer[offset_y];
  179398. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179399. /* Process the blocks that can be mirrored both ways. */
  179400. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179401. dst_ptr = dst_row_ptr[dst_blk_x];
  179402. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179403. for (i = 0; i < DCTSIZE; i += 2) {
  179404. /* For even row, negate every odd column. */
  179405. for (j = 0; j < DCTSIZE; j += 2) {
  179406. *dst_ptr++ = *src_ptr++;
  179407. *dst_ptr++ = - *src_ptr++;
  179408. }
  179409. /* For odd row, negate every even column. */
  179410. for (j = 0; j < DCTSIZE; j += 2) {
  179411. *dst_ptr++ = - *src_ptr++;
  179412. *dst_ptr++ = *src_ptr++;
  179413. }
  179414. }
  179415. }
  179416. /* Any remaining right-edge blocks are only mirrored vertically. */
  179417. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179418. dst_ptr = dst_row_ptr[dst_blk_x];
  179419. src_ptr = src_row_ptr[dst_blk_x];
  179420. for (i = 0; i < DCTSIZE; i += 2) {
  179421. for (j = 0; j < DCTSIZE; j++)
  179422. *dst_ptr++ = *src_ptr++;
  179423. for (j = 0; j < DCTSIZE; j++)
  179424. *dst_ptr++ = - *src_ptr++;
  179425. }
  179426. }
  179427. } else {
  179428. /* Remaining rows are just mirrored horizontally. */
  179429. dst_row_ptr = dst_buffer[offset_y];
  179430. src_row_ptr = src_buffer[offset_y];
  179431. /* Process the blocks that can be mirrored. */
  179432. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179433. dst_ptr = dst_row_ptr[dst_blk_x];
  179434. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179435. for (i = 0; i < DCTSIZE2; i += 2) {
  179436. *dst_ptr++ = *src_ptr++;
  179437. *dst_ptr++ = - *src_ptr++;
  179438. }
  179439. }
  179440. /* Any remaining right-edge blocks are only copied. */
  179441. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179442. dst_ptr = dst_row_ptr[dst_blk_x];
  179443. src_ptr = src_row_ptr[dst_blk_x];
  179444. for (i = 0; i < DCTSIZE2; i++)
  179445. *dst_ptr++ = *src_ptr++;
  179446. }
  179447. }
  179448. }
  179449. }
  179450. }
  179451. }
  179452. LOCAL(void)
  179453. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179454. jvirt_barray_ptr *src_coef_arrays,
  179455. jvirt_barray_ptr *dst_coef_arrays)
  179456. /* Transverse transpose is equivalent to
  179457. * 1. 180 degree rotation;
  179458. * 2. Transposition;
  179459. * or
  179460. * 1. Horizontal mirroring;
  179461. * 2. Transposition;
  179462. * 3. Horizontal mirroring.
  179463. * These steps are merged into a single processing routine.
  179464. */
  179465. {
  179466. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179467. int ci, i, j, offset_x, offset_y;
  179468. JBLOCKARRAY src_buffer, dst_buffer;
  179469. JCOEFPTR src_ptr, dst_ptr;
  179470. jpeg_component_info *compptr;
  179471. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179472. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179473. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179474. compptr = dstinfo->comp_info + ci;
  179475. comp_width = MCU_cols * compptr->h_samp_factor;
  179476. comp_height = MCU_rows * compptr->v_samp_factor;
  179477. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179478. dst_blk_y += compptr->v_samp_factor) {
  179479. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179480. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179481. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179482. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179483. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179484. dst_blk_x += compptr->h_samp_factor) {
  179485. src_buffer = (*srcinfo->mem->access_virt_barray)
  179486. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179487. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179488. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179489. if (dst_blk_y < comp_height) {
  179490. src_ptr = src_buffer[offset_x]
  179491. [comp_height - dst_blk_y - offset_y - 1];
  179492. if (dst_blk_x < comp_width) {
  179493. /* Block is within the mirrorable area. */
  179494. dst_ptr = dst_buffer[offset_y]
  179495. [comp_width - dst_blk_x - offset_x - 1];
  179496. for (i = 0; i < DCTSIZE; i++) {
  179497. for (j = 0; j < DCTSIZE; j++) {
  179498. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179499. j++;
  179500. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179501. }
  179502. i++;
  179503. for (j = 0; j < DCTSIZE; j++) {
  179504. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179505. j++;
  179506. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179507. }
  179508. }
  179509. } else {
  179510. /* Right-edge blocks are mirrored in y only */
  179511. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179512. for (i = 0; i < DCTSIZE; i++) {
  179513. for (j = 0; j < DCTSIZE; j++) {
  179514. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179515. j++;
  179516. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179517. }
  179518. }
  179519. }
  179520. } else {
  179521. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179522. if (dst_blk_x < comp_width) {
  179523. /* Bottom-edge blocks are mirrored in x only */
  179524. dst_ptr = dst_buffer[offset_y]
  179525. [comp_width - dst_blk_x - offset_x - 1];
  179526. for (i = 0; i < DCTSIZE; i++) {
  179527. for (j = 0; j < DCTSIZE; j++)
  179528. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179529. i++;
  179530. for (j = 0; j < DCTSIZE; j++)
  179531. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179532. }
  179533. } else {
  179534. /* At lower right corner, just transpose, no mirroring */
  179535. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179536. for (i = 0; i < DCTSIZE; i++)
  179537. for (j = 0; j < DCTSIZE; j++)
  179538. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179539. }
  179540. }
  179541. }
  179542. }
  179543. }
  179544. }
  179545. }
  179546. }
  179547. /* Request any required workspace.
  179548. *
  179549. * We allocate the workspace virtual arrays from the source decompression
  179550. * object, so that all the arrays (both the original data and the workspace)
  179551. * will be taken into account while making memory management decisions.
  179552. * Hence, this routine must be called after jpeg_read_header (which reads
  179553. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179554. * the source's virtual arrays).
  179555. */
  179556. GLOBAL(void)
  179557. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179558. jpeg_transform_info *info)
  179559. {
  179560. jvirt_barray_ptr *coef_arrays = NULL;
  179561. jpeg_component_info *compptr;
  179562. int ci;
  179563. if (info->force_grayscale &&
  179564. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179565. srcinfo->num_components == 3) {
  179566. /* We'll only process the first component */
  179567. info->num_components = 1;
  179568. } else {
  179569. /* Process all the components */
  179570. info->num_components = srcinfo->num_components;
  179571. }
  179572. switch (info->transform) {
  179573. case JXFORM_NONE:
  179574. case JXFORM_FLIP_H:
  179575. /* Don't need a workspace array */
  179576. break;
  179577. case JXFORM_FLIP_V:
  179578. case JXFORM_ROT_180:
  179579. /* Need workspace arrays having same dimensions as source image.
  179580. * Note that we allocate arrays padded out to the next iMCU boundary,
  179581. * so that transform routines need not worry about missing edge blocks.
  179582. */
  179583. coef_arrays = (jvirt_barray_ptr *)
  179584. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179585. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179586. for (ci = 0; ci < info->num_components; ci++) {
  179587. compptr = srcinfo->comp_info + ci;
  179588. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179589. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179590. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179591. (long) compptr->h_samp_factor),
  179592. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179593. (long) compptr->v_samp_factor),
  179594. (JDIMENSION) compptr->v_samp_factor);
  179595. }
  179596. break;
  179597. case JXFORM_TRANSPOSE:
  179598. case JXFORM_TRANSVERSE:
  179599. case JXFORM_ROT_90:
  179600. case JXFORM_ROT_270:
  179601. /* Need workspace arrays having transposed dimensions.
  179602. * Note that we allocate arrays padded out to the next iMCU boundary,
  179603. * so that transform routines need not worry about missing edge blocks.
  179604. */
  179605. coef_arrays = (jvirt_barray_ptr *)
  179606. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179607. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179608. for (ci = 0; ci < info->num_components; ci++) {
  179609. compptr = srcinfo->comp_info + ci;
  179610. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179611. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179612. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179613. (long) compptr->v_samp_factor),
  179614. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179615. (long) compptr->h_samp_factor),
  179616. (JDIMENSION) compptr->h_samp_factor);
  179617. }
  179618. break;
  179619. }
  179620. info->workspace_coef_arrays = coef_arrays;
  179621. }
  179622. /* Transpose destination image parameters */
  179623. LOCAL(void)
  179624. transpose_critical_parameters (j_compress_ptr dstinfo)
  179625. {
  179626. int tblno, i, j, ci, itemp;
  179627. jpeg_component_info *compptr;
  179628. JQUANT_TBL *qtblptr;
  179629. JDIMENSION dtemp;
  179630. UINT16 qtemp;
  179631. /* Transpose basic image dimensions */
  179632. dtemp = dstinfo->image_width;
  179633. dstinfo->image_width = dstinfo->image_height;
  179634. dstinfo->image_height = dtemp;
  179635. /* Transpose sampling factors */
  179636. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179637. compptr = dstinfo->comp_info + ci;
  179638. itemp = compptr->h_samp_factor;
  179639. compptr->h_samp_factor = compptr->v_samp_factor;
  179640. compptr->v_samp_factor = itemp;
  179641. }
  179642. /* Transpose quantization tables */
  179643. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179644. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179645. if (qtblptr != NULL) {
  179646. for (i = 0; i < DCTSIZE; i++) {
  179647. for (j = 0; j < i; j++) {
  179648. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179649. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179650. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179651. }
  179652. }
  179653. }
  179654. }
  179655. }
  179656. /* Trim off any partial iMCUs on the indicated destination edge */
  179657. LOCAL(void)
  179658. trim_right_edge (j_compress_ptr dstinfo)
  179659. {
  179660. int ci, max_h_samp_factor;
  179661. JDIMENSION MCU_cols;
  179662. /* We have to compute max_h_samp_factor ourselves,
  179663. * because it hasn't been set yet in the destination
  179664. * (and we don't want to use the source's value).
  179665. */
  179666. max_h_samp_factor = 1;
  179667. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179668. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179669. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179670. }
  179671. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179672. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179673. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179674. }
  179675. LOCAL(void)
  179676. trim_bottom_edge (j_compress_ptr dstinfo)
  179677. {
  179678. int ci, max_v_samp_factor;
  179679. JDIMENSION MCU_rows;
  179680. /* We have to compute max_v_samp_factor ourselves,
  179681. * because it hasn't been set yet in the destination
  179682. * (and we don't want to use the source's value).
  179683. */
  179684. max_v_samp_factor = 1;
  179685. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179686. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179687. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179688. }
  179689. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179690. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179691. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179692. }
  179693. /* Adjust output image parameters as needed.
  179694. *
  179695. * This must be called after jpeg_copy_critical_parameters()
  179696. * and before jpeg_write_coefficients().
  179697. *
  179698. * The return value is the set of virtual coefficient arrays to be written
  179699. * (either the ones allocated by jtransform_request_workspace, or the
  179700. * original source data arrays). The caller will need to pass this value
  179701. * to jpeg_write_coefficients().
  179702. */
  179703. GLOBAL(jvirt_barray_ptr *)
  179704. jtransform_adjust_parameters (j_decompress_ptr,
  179705. j_compress_ptr dstinfo,
  179706. jvirt_barray_ptr *src_coef_arrays,
  179707. jpeg_transform_info *info)
  179708. {
  179709. /* If force-to-grayscale is requested, adjust destination parameters */
  179710. if (info->force_grayscale) {
  179711. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179712. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179713. * will get set to 1, which typically won't match the source.
  179714. * In fact we do this even if the source is already grayscale; that
  179715. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179716. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179717. */
  179718. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179719. dstinfo->num_components == 3) ||
  179720. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179721. dstinfo->num_components == 1)) {
  179722. /* We have to preserve the source's quantization table number. */
  179723. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179724. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179725. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179726. } else {
  179727. /* Sorry, can't do it */
  179728. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179729. }
  179730. }
  179731. /* Correct the destination's image dimensions etc if necessary */
  179732. switch (info->transform) {
  179733. case JXFORM_NONE:
  179734. /* Nothing to do */
  179735. break;
  179736. case JXFORM_FLIP_H:
  179737. if (info->trim)
  179738. trim_right_edge(dstinfo);
  179739. break;
  179740. case JXFORM_FLIP_V:
  179741. if (info->trim)
  179742. trim_bottom_edge(dstinfo);
  179743. break;
  179744. case JXFORM_TRANSPOSE:
  179745. transpose_critical_parameters(dstinfo);
  179746. /* transpose does NOT have to trim anything */
  179747. break;
  179748. case JXFORM_TRANSVERSE:
  179749. transpose_critical_parameters(dstinfo);
  179750. if (info->trim) {
  179751. trim_right_edge(dstinfo);
  179752. trim_bottom_edge(dstinfo);
  179753. }
  179754. break;
  179755. case JXFORM_ROT_90:
  179756. transpose_critical_parameters(dstinfo);
  179757. if (info->trim)
  179758. trim_right_edge(dstinfo);
  179759. break;
  179760. case JXFORM_ROT_180:
  179761. if (info->trim) {
  179762. trim_right_edge(dstinfo);
  179763. trim_bottom_edge(dstinfo);
  179764. }
  179765. break;
  179766. case JXFORM_ROT_270:
  179767. transpose_critical_parameters(dstinfo);
  179768. if (info->trim)
  179769. trim_bottom_edge(dstinfo);
  179770. break;
  179771. }
  179772. /* Return the appropriate output data set */
  179773. if (info->workspace_coef_arrays != NULL)
  179774. return info->workspace_coef_arrays;
  179775. return src_coef_arrays;
  179776. }
  179777. /* Execute the actual transformation, if any.
  179778. *
  179779. * This must be called *after* jpeg_write_coefficients, because it depends
  179780. * on jpeg_write_coefficients to have computed subsidiary values such as
  179781. * the per-component width and height fields in the destination object.
  179782. *
  179783. * Note that some transformations will modify the source data arrays!
  179784. */
  179785. GLOBAL(void)
  179786. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179787. j_compress_ptr dstinfo,
  179788. jvirt_barray_ptr *src_coef_arrays,
  179789. jpeg_transform_info *info)
  179790. {
  179791. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179792. switch (info->transform) {
  179793. case JXFORM_NONE:
  179794. break;
  179795. case JXFORM_FLIP_H:
  179796. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179797. break;
  179798. case JXFORM_FLIP_V:
  179799. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179800. break;
  179801. case JXFORM_TRANSPOSE:
  179802. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179803. break;
  179804. case JXFORM_TRANSVERSE:
  179805. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179806. break;
  179807. case JXFORM_ROT_90:
  179808. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179809. break;
  179810. case JXFORM_ROT_180:
  179811. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179812. break;
  179813. case JXFORM_ROT_270:
  179814. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179815. break;
  179816. }
  179817. }
  179818. #endif /* TRANSFORMS_SUPPORTED */
  179819. /* Setup decompression object to save desired markers in memory.
  179820. * This must be called before jpeg_read_header() to have the desired effect.
  179821. */
  179822. GLOBAL(void)
  179823. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179824. {
  179825. #ifdef SAVE_MARKERS_SUPPORTED
  179826. int m;
  179827. /* Save comments except under NONE option */
  179828. if (option != JCOPYOPT_NONE) {
  179829. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179830. }
  179831. /* Save all types of APPn markers iff ALL option */
  179832. if (option == JCOPYOPT_ALL) {
  179833. for (m = 0; m < 16; m++)
  179834. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179835. }
  179836. #endif /* SAVE_MARKERS_SUPPORTED */
  179837. }
  179838. /* Copy markers saved in the given source object to the destination object.
  179839. * This should be called just after jpeg_start_compress() or
  179840. * jpeg_write_coefficients().
  179841. * Note that those routines will have written the SOI, and also the
  179842. * JFIF APP0 or Adobe APP14 markers if selected.
  179843. */
  179844. GLOBAL(void)
  179845. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179846. JCOPY_OPTION)
  179847. {
  179848. jpeg_saved_marker_ptr marker;
  179849. /* In the current implementation, we don't actually need to examine the
  179850. * option flag here; we just copy everything that got saved.
  179851. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179852. * if the encoder library already wrote one.
  179853. */
  179854. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179855. if (dstinfo->write_JFIF_header &&
  179856. marker->marker == JPEG_APP0 &&
  179857. marker->data_length >= 5 &&
  179858. GETJOCTET(marker->data[0]) == 0x4A &&
  179859. GETJOCTET(marker->data[1]) == 0x46 &&
  179860. GETJOCTET(marker->data[2]) == 0x49 &&
  179861. GETJOCTET(marker->data[3]) == 0x46 &&
  179862. GETJOCTET(marker->data[4]) == 0)
  179863. continue; /* reject duplicate JFIF */
  179864. if (dstinfo->write_Adobe_marker &&
  179865. marker->marker == JPEG_APP0+14 &&
  179866. marker->data_length >= 5 &&
  179867. GETJOCTET(marker->data[0]) == 0x41 &&
  179868. GETJOCTET(marker->data[1]) == 0x64 &&
  179869. GETJOCTET(marker->data[2]) == 0x6F &&
  179870. GETJOCTET(marker->data[3]) == 0x62 &&
  179871. GETJOCTET(marker->data[4]) == 0x65)
  179872. continue; /* reject duplicate Adobe */
  179873. #ifdef NEED_FAR_POINTERS
  179874. /* We could use jpeg_write_marker if the data weren't FAR... */
  179875. {
  179876. unsigned int i;
  179877. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179878. for (i = 0; i < marker->data_length; i++)
  179879. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179880. }
  179881. #else
  179882. jpeg_write_marker(dstinfo, marker->marker,
  179883. marker->data, marker->data_length);
  179884. #endif
  179885. }
  179886. }
  179887. /*** End of inlined file: transupp.c ***/
  179888. }
  179889. #else
  179890. #define JPEG_INTERNALS
  179891. #undef FAR
  179892. #include <jpeglib.h>
  179893. #endif
  179894. }
  179895. #undef max
  179896. #undef min
  179897. #if JUCE_MSVC
  179898. #pragma warning (pop)
  179899. #endif
  179900. BEGIN_JUCE_NAMESPACE
  179901. namespace JPEGHelpers
  179902. {
  179903. using namespace jpeglibNamespace;
  179904. #if ! JUCE_MSVC
  179905. using jpeglibNamespace::boolean;
  179906. #endif
  179907. struct JPEGDecodingFailure {};
  179908. static void fatalErrorHandler (j_common_ptr)
  179909. {
  179910. throw JPEGDecodingFailure();
  179911. }
  179912. static void silentErrorCallback1 (j_common_ptr) {}
  179913. static void silentErrorCallback2 (j_common_ptr, int) {}
  179914. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179915. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179916. {
  179917. zerostruct (err);
  179918. err.error_exit = fatalErrorHandler;
  179919. err.emit_message = silentErrorCallback2;
  179920. err.output_message = silentErrorCallback1;
  179921. err.format_message = silentErrorCallback3;
  179922. err.reset_error_mgr = silentErrorCallback1;
  179923. }
  179924. static void dummyCallback1 (j_decompress_ptr)
  179925. {
  179926. }
  179927. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179928. {
  179929. decompStruct->src->next_input_byte += num;
  179930. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179931. decompStruct->src->bytes_in_buffer -= num;
  179932. }
  179933. static boolean jpegFill (j_decompress_ptr)
  179934. {
  179935. return 0;
  179936. }
  179937. static const int jpegBufferSize = 512;
  179938. struct JuceJpegDest : public jpeg_destination_mgr
  179939. {
  179940. OutputStream* output;
  179941. char* buffer;
  179942. };
  179943. static void jpegWriteInit (j_compress_ptr)
  179944. {
  179945. }
  179946. static void jpegWriteTerminate (j_compress_ptr cinfo)
  179947. {
  179948. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179949. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179950. dest->output->write (dest->buffer, (int) numToWrite);
  179951. }
  179952. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  179953. {
  179954. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179955. const int numToWrite = jpegBufferSize;
  179956. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179957. dest->free_in_buffer = jpegBufferSize;
  179958. return dest->output->write (dest->buffer, numToWrite);
  179959. }
  179960. }
  179961. JPEGImageFormat::JPEGImageFormat()
  179962. : quality (-1.0f)
  179963. {
  179964. }
  179965. JPEGImageFormat::~JPEGImageFormat() {}
  179966. void JPEGImageFormat::setQuality (const float newQuality)
  179967. {
  179968. quality = newQuality;
  179969. }
  179970. const String JPEGImageFormat::getFormatName()
  179971. {
  179972. return "JPEG";
  179973. }
  179974. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179975. {
  179976. const int bytesNeeded = 10;
  179977. uint8 header [bytesNeeded];
  179978. if (in.read (header, bytesNeeded) == bytesNeeded)
  179979. {
  179980. return header[0] == 0xff
  179981. && header[1] == 0xd8
  179982. && header[2] == 0xff
  179983. && (header[3] == 0xe0 || header[3] == 0xe1);
  179984. }
  179985. return false;
  179986. }
  179987. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179988. {
  179989. using namespace jpeglibNamespace;
  179990. using namespace JPEGHelpers;
  179991. MemoryOutputStream mb;
  179992. mb.writeFromInputStream (in, -1);
  179993. Image image;
  179994. if (mb.getDataSize() > 16)
  179995. {
  179996. struct jpeg_decompress_struct jpegDecompStruct;
  179997. struct jpeg_error_mgr jerr;
  179998. setupSilentErrorHandler (jerr);
  179999. jpegDecompStruct.err = &jerr;
  180000. jpeg_create_decompress (&jpegDecompStruct);
  180001. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180002. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180003. jpegDecompStruct.src->init_source = dummyCallback1;
  180004. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180005. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180006. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180007. jpegDecompStruct.src->term_source = dummyCallback1;
  180008. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180009. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180010. try
  180011. {
  180012. jpeg_read_header (&jpegDecompStruct, TRUE);
  180013. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180014. const int width = jpegDecompStruct.output_width;
  180015. const int height = jpegDecompStruct.output_height;
  180016. jpegDecompStruct.out_color_space = JCS_RGB;
  180017. JSAMPARRAY buffer
  180018. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180019. JPOOL_IMAGE,
  180020. width * 3, 1);
  180021. if (jpeg_start_decompress (&jpegDecompStruct))
  180022. {
  180023. image = Image (Image::RGB, width, height, false);
  180024. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180025. const Image::BitmapData destData (image, true);
  180026. for (int y = 0; y < height; ++y)
  180027. {
  180028. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180029. const uint8* src = *buffer;
  180030. uint8* dest = destData.getLinePointer (y);
  180031. if (hasAlphaChan)
  180032. {
  180033. for (int i = width; --i >= 0;)
  180034. {
  180035. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180036. ((PixelARGB*) dest)->premultiply();
  180037. dest += destData.pixelStride;
  180038. src += 3;
  180039. }
  180040. }
  180041. else
  180042. {
  180043. for (int i = width; --i >= 0;)
  180044. {
  180045. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180046. dest += destData.pixelStride;
  180047. src += 3;
  180048. }
  180049. }
  180050. }
  180051. jpeg_finish_decompress (&jpegDecompStruct);
  180052. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180053. }
  180054. jpeg_destroy_decompress (&jpegDecompStruct);
  180055. }
  180056. catch (...)
  180057. {}
  180058. }
  180059. return image;
  180060. }
  180061. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180062. {
  180063. using namespace jpeglibNamespace;
  180064. using namespace JPEGHelpers;
  180065. if (image.hasAlphaChannel())
  180066. {
  180067. // this method could fill the background in white and still save the image..
  180068. jassertfalse;
  180069. return true;
  180070. }
  180071. struct jpeg_compress_struct jpegCompStruct;
  180072. struct jpeg_error_mgr jerr;
  180073. setupSilentErrorHandler (jerr);
  180074. jpegCompStruct.err = &jerr;
  180075. jpeg_create_compress (&jpegCompStruct);
  180076. JuceJpegDest dest;
  180077. jpegCompStruct.dest = &dest;
  180078. dest.output = &out;
  180079. HeapBlock <char> tempBuffer (jpegBufferSize);
  180080. dest.buffer = tempBuffer;
  180081. dest.next_output_byte = (JOCTET*) dest.buffer;
  180082. dest.free_in_buffer = jpegBufferSize;
  180083. dest.init_destination = jpegWriteInit;
  180084. dest.empty_output_buffer = jpegWriteFlush;
  180085. dest.term_destination = jpegWriteTerminate;
  180086. jpegCompStruct.image_width = image.getWidth();
  180087. jpegCompStruct.image_height = image.getHeight();
  180088. jpegCompStruct.input_components = 3;
  180089. jpegCompStruct.in_color_space = JCS_RGB;
  180090. jpegCompStruct.write_JFIF_header = 1;
  180091. jpegCompStruct.X_density = 72;
  180092. jpegCompStruct.Y_density = 72;
  180093. jpeg_set_defaults (&jpegCompStruct);
  180094. jpegCompStruct.dct_method = JDCT_FLOAT;
  180095. jpegCompStruct.optimize_coding = 1;
  180096. //jpegCompStruct.smoothing_factor = 10;
  180097. if (quality < 0.0f)
  180098. quality = 0.85f;
  180099. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180100. jpeg_start_compress (&jpegCompStruct, TRUE);
  180101. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180102. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180103. JPOOL_IMAGE, strideBytes, 1);
  180104. const Image::BitmapData srcData (image, false);
  180105. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180106. {
  180107. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180108. uint8* dst = *buffer;
  180109. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180110. {
  180111. *dst++ = ((const PixelRGB*) src)->getRed();
  180112. *dst++ = ((const PixelRGB*) src)->getGreen();
  180113. *dst++ = ((const PixelRGB*) src)->getBlue();
  180114. src += srcData.pixelStride;
  180115. }
  180116. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180117. }
  180118. jpeg_finish_compress (&jpegCompStruct);
  180119. jpeg_destroy_compress (&jpegCompStruct);
  180120. out.flush();
  180121. return true;
  180122. }
  180123. END_JUCE_NAMESPACE
  180124. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180125. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180126. #if JUCE_MSVC
  180127. #pragma warning (push)
  180128. #pragma warning (disable: 4390 4611)
  180129. #endif
  180130. namespace zlibNamespace
  180131. {
  180132. #if JUCE_INCLUDE_ZLIB_CODE
  180133. #undef OS_CODE
  180134. #undef fdopen
  180135. #undef OS_CODE
  180136. #else
  180137. #include <zlib.h>
  180138. #endif
  180139. }
  180140. namespace pnglibNamespace
  180141. {
  180142. using namespace zlibNamespace;
  180143. #if JUCE_INCLUDE_PNGLIB_CODE
  180144. #if _MSC_VER != 1310
  180145. using ::calloc; // (causes conflict in VS.NET 2003)
  180146. using ::malloc;
  180147. using ::free;
  180148. #endif
  180149. using ::abs;
  180150. #define PNG_INTERNAL
  180151. #define NO_DUMMY_DECL
  180152. #define PNG_SETJMP_NOT_SUPPORTED
  180153. /*** Start of inlined file: png.h ***/
  180154. /* png.h - header file for PNG reference library
  180155. *
  180156. * libpng version 1.2.21 - October 4, 2007
  180157. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180158. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180159. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180160. *
  180161. * Authors and maintainers:
  180162. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180163. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180164. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180165. * See also "Contributing Authors", below.
  180166. *
  180167. * Note about libpng version numbers:
  180168. *
  180169. * Due to various miscommunications, unforeseen code incompatibilities
  180170. * and occasional factors outside the authors' control, version numbering
  180171. * on the library has not always been consistent and straightforward.
  180172. * The following table summarizes matters since version 0.89c, which was
  180173. * the first widely used release:
  180174. *
  180175. * source png.h png.h shared-lib
  180176. * version string int version
  180177. * ------- ------ ----- ----------
  180178. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180179. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180180. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180181. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180182. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180183. * 0.97c 0.97 97 2.0.97
  180184. * 0.98 0.98 98 2.0.98
  180185. * 0.99 0.99 98 2.0.99
  180186. * 0.99a-m 0.99 99 2.0.99
  180187. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180188. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180189. * 1.0.1 png.h string is 10001 2.1.0
  180190. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180191. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180192. * 1.0.2a-b 10003 version, except as noted.
  180193. * 1.0.3 10003
  180194. * 1.0.3a-d 10004
  180195. * 1.0.4 10004
  180196. * 1.0.4a-f 10005
  180197. * 1.0.5 (+ 2 patches) 10005
  180198. * 1.0.5a-d 10006
  180199. * 1.0.5e-r 10100 (not source compatible)
  180200. * 1.0.5s-v 10006 (not binary compatible)
  180201. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180202. * 1.0.6d-f 10007 (still binary incompatible)
  180203. * 1.0.6g 10007
  180204. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180205. * 1.0.6i 10007 10.6i
  180206. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180207. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180208. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180209. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180210. * 1.0.7 1 10007 (still compatible)
  180211. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180212. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180213. * 1.0.8 1 10008 2.1.0.8
  180214. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180215. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180216. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180217. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180218. * 1.0.9 1 10009 2.1.0.9
  180219. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180220. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180221. * 1.0.10 1 10010 2.1.0.10
  180222. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180223. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180224. * 1.0.11 1 10011 2.1.0.11
  180225. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180226. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180227. * 1.0.12 2 10012 2.1.0.12
  180228. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180229. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180230. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180231. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180232. * 1.2.0 3 10200 3.1.2.0
  180233. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180234. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180235. * 1.2.1 3 10201 3.1.2.1
  180236. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180237. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180238. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180239. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180240. * 1.0.13 10 10013 10.so.0.1.0.13
  180241. * 1.2.2 12 10202 12.so.0.1.2.2
  180242. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180243. * 1.2.3 12 10203 12.so.0.1.2.3
  180244. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180245. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180246. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180247. * 1.0.14 10 10014 10.so.0.1.0.14
  180248. * 1.2.4 13 10204 12.so.0.1.2.4
  180249. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180250. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180251. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180252. * 1.0.15 10 10015 10.so.0.1.0.15
  180253. * 1.2.5 13 10205 12.so.0.1.2.5
  180254. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180255. * 1.0.16 10 10016 10.so.0.1.0.16
  180256. * 1.2.6 13 10206 12.so.0.1.2.6
  180257. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180258. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180259. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180260. * 1.0.17 10 10017 10.so.0.1.0.17
  180261. * 1.2.7 13 10207 12.so.0.1.2.7
  180262. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180263. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180264. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180265. * 1.0.18 10 10018 10.so.0.1.0.18
  180266. * 1.2.8 13 10208 12.so.0.1.2.8
  180267. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180268. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180269. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180270. * 1.2.9 13 10209 12.so.0.9[.0]
  180271. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180272. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180273. * 1.2.10 13 10210 12.so.0.10[.0]
  180274. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180275. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180276. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180277. * 1.0.19 10 10019 10.so.0.19[.0]
  180278. * 1.2.11 13 10211 12.so.0.11[.0]
  180279. * 1.0.20 10 10020 10.so.0.20[.0]
  180280. * 1.2.12 13 10212 12.so.0.12[.0]
  180281. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180282. * 1.0.21 10 10021 10.so.0.21[.0]
  180283. * 1.2.13 13 10213 12.so.0.13[.0]
  180284. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180285. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180286. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180287. * 1.0.22 10 10022 10.so.0.22[.0]
  180288. * 1.2.14 13 10214 12.so.0.14[.0]
  180289. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180290. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180291. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180292. * 1.0.23 10 10023 10.so.0.23[.0]
  180293. * 1.2.15 13 10215 12.so.0.15[.0]
  180294. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180295. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180296. * 1.0.24 10 10024 10.so.0.24[.0]
  180297. * 1.2.16 13 10216 12.so.0.16[.0]
  180298. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180299. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180300. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180301. * 1.0.25 10 10025 10.so.0.25[.0]
  180302. * 1.2.17 13 10217 12.so.0.17[.0]
  180303. * 1.0.26 10 10026 10.so.0.26[.0]
  180304. * 1.2.18 13 10218 12.so.0.18[.0]
  180305. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180306. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180307. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180308. * 1.0.27 10 10027 10.so.0.27[.0]
  180309. * 1.2.19 13 10219 12.so.0.19[.0]
  180310. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180311. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180312. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180313. * 1.0.28 10 10028 10.so.0.28[.0]
  180314. * 1.2.20 13 10220 12.so.0.20[.0]
  180315. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180316. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180317. * 1.0.29 10 10029 10.so.0.29[.0]
  180318. * 1.2.21 13 10221 12.so.0.21[.0]
  180319. *
  180320. * Henceforth the source version will match the shared-library major
  180321. * and minor numbers; the shared-library major version number will be
  180322. * used for changes in backward compatibility, as it is intended. The
  180323. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180324. * for applications, is an unsigned integer of the form xyyzz corresponding
  180325. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180326. * were given the previous public release number plus a letter, until
  180327. * version 1.0.6j; from then on they were given the upcoming public
  180328. * release number plus "betaNN" or "rcN".
  180329. *
  180330. * Binary incompatibility exists only when applications make direct access
  180331. * to the info_ptr or png_ptr members through png.h, and the compiled
  180332. * application is loaded with a different version of the library.
  180333. *
  180334. * DLLNUM will change each time there are forward or backward changes
  180335. * in binary compatibility (e.g., when a new feature is added).
  180336. *
  180337. * See libpng.txt or libpng.3 for more information. The PNG specification
  180338. * is available as a W3C Recommendation and as an ISO Specification,
  180339. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180340. */
  180341. /*
  180342. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180343. *
  180344. * If you modify libpng you may insert additional notices immediately following
  180345. * this sentence.
  180346. *
  180347. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180348. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180349. * distributed according to the same disclaimer and license as libpng-1.2.5
  180350. * with the following individual added to the list of Contributing Authors:
  180351. *
  180352. * Cosmin Truta
  180353. *
  180354. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180355. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180356. * distributed according to the same disclaimer and license as libpng-1.0.6
  180357. * with the following individuals added to the list of Contributing Authors:
  180358. *
  180359. * Simon-Pierre Cadieux
  180360. * Eric S. Raymond
  180361. * Gilles Vollant
  180362. *
  180363. * and with the following additions to the disclaimer:
  180364. *
  180365. * There is no warranty against interference with your enjoyment of the
  180366. * library or against infringement. There is no warranty that our
  180367. * efforts or the library will fulfill any of your particular purposes
  180368. * or needs. This library is provided with all faults, and the entire
  180369. * risk of satisfactory quality, performance, accuracy, and effort is with
  180370. * the user.
  180371. *
  180372. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180373. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180374. * distributed according to the same disclaimer and license as libpng-0.96,
  180375. * with the following individuals added to the list of Contributing Authors:
  180376. *
  180377. * Tom Lane
  180378. * Glenn Randers-Pehrson
  180379. * Willem van Schaik
  180380. *
  180381. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180382. * Copyright (c) 1996, 1997 Andreas Dilger
  180383. * Distributed according to the same disclaimer and license as libpng-0.88,
  180384. * with the following individuals added to the list of Contributing Authors:
  180385. *
  180386. * John Bowler
  180387. * Kevin Bracey
  180388. * Sam Bushell
  180389. * Magnus Holmgren
  180390. * Greg Roelofs
  180391. * Tom Tanner
  180392. *
  180393. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180394. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180395. *
  180396. * For the purposes of this copyright and license, "Contributing Authors"
  180397. * is defined as the following set of individuals:
  180398. *
  180399. * Andreas Dilger
  180400. * Dave Martindale
  180401. * Guy Eric Schalnat
  180402. * Paul Schmidt
  180403. * Tim Wegner
  180404. *
  180405. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180406. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180407. * including, without limitation, the warranties of merchantability and of
  180408. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180409. * assume no liability for direct, indirect, incidental, special, exemplary,
  180410. * or consequential damages, which may result from the use of the PNG
  180411. * Reference Library, even if advised of the possibility of such damage.
  180412. *
  180413. * Permission is hereby granted to use, copy, modify, and distribute this
  180414. * source code, or portions hereof, for any purpose, without fee, subject
  180415. * to the following restrictions:
  180416. *
  180417. * 1. The origin of this source code must not be misrepresented.
  180418. *
  180419. * 2. Altered versions must be plainly marked as such and
  180420. * must not be misrepresented as being the original source.
  180421. *
  180422. * 3. This Copyright notice may not be removed or altered from
  180423. * any source or altered source distribution.
  180424. *
  180425. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180426. * fee, and encourage the use of this source code as a component to
  180427. * supporting the PNG file format in commercial products. If you use this
  180428. * source code in a product, acknowledgment is not required but would be
  180429. * appreciated.
  180430. */
  180431. /*
  180432. * A "png_get_copyright" function is available, for convenient use in "about"
  180433. * boxes and the like:
  180434. *
  180435. * printf("%s",png_get_copyright(NULL));
  180436. *
  180437. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180438. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180439. */
  180440. /*
  180441. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180442. * certification mark of the Open Source Initiative.
  180443. */
  180444. /*
  180445. * The contributing authors would like to thank all those who helped
  180446. * with testing, bug fixes, and patience. This wouldn't have been
  180447. * possible without all of you.
  180448. *
  180449. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180450. */
  180451. /*
  180452. * Y2K compliance in libpng:
  180453. * =========================
  180454. *
  180455. * October 4, 2007
  180456. *
  180457. * Since the PNG Development group is an ad-hoc body, we can't make
  180458. * an official declaration.
  180459. *
  180460. * This is your unofficial assurance that libpng from version 0.71 and
  180461. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180462. * versions were also Y2K compliant.
  180463. *
  180464. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180465. * that will hold years up to 65535. The other two hold the date in text
  180466. * format, and will hold years up to 9999.
  180467. *
  180468. * The integer is
  180469. * "png_uint_16 year" in png_time_struct.
  180470. *
  180471. * The strings are
  180472. * "png_charp time_buffer" in png_struct and
  180473. * "near_time_buffer", which is a local character string in png.c.
  180474. *
  180475. * There are seven time-related functions:
  180476. * png.c: png_convert_to_rfc_1123() in png.c
  180477. * (formerly png_convert_to_rfc_1152() in error)
  180478. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180479. * png_convert_from_time_t() in pngwrite.c
  180480. * png_get_tIME() in pngget.c
  180481. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180482. * png_set_tIME() in pngset.c
  180483. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180484. *
  180485. * All handle dates properly in a Y2K environment. The
  180486. * png_convert_from_time_t() function calls gmtime() to convert from system
  180487. * clock time, which returns (year - 1900), which we properly convert to
  180488. * the full 4-digit year. There is a possibility that applications using
  180489. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180490. * function, or that they are incorrectly passing only a 2-digit year
  180491. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180492. * but this is not under our control. The libpng documentation has always
  180493. * stated that it works with 4-digit years, and the APIs have been
  180494. * documented as such.
  180495. *
  180496. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180497. * integer to hold the year, and can hold years as large as 65535.
  180498. *
  180499. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180500. * no date-related code.
  180501. *
  180502. * Glenn Randers-Pehrson
  180503. * libpng maintainer
  180504. * PNG Development Group
  180505. */
  180506. #ifndef PNG_H
  180507. #define PNG_H
  180508. /* This is not the place to learn how to use libpng. The file libpng.txt
  180509. * describes how to use libpng, and the file example.c summarizes it
  180510. * with some code on which to build. This file is useful for looking
  180511. * at the actual function definitions and structure components.
  180512. */
  180513. /* Version information for png.h - this should match the version in png.c */
  180514. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180515. #define PNG_HEADER_VERSION_STRING \
  180516. " libpng version 1.2.21 - October 4, 2007\n"
  180517. #define PNG_LIBPNG_VER_SONUM 0
  180518. #define PNG_LIBPNG_VER_DLLNUM 13
  180519. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180520. #define PNG_LIBPNG_VER_MAJOR 1
  180521. #define PNG_LIBPNG_VER_MINOR 2
  180522. #define PNG_LIBPNG_VER_RELEASE 21
  180523. /* This should match the numeric part of the final component of
  180524. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180525. #define PNG_LIBPNG_VER_BUILD 0
  180526. /* Release Status */
  180527. #define PNG_LIBPNG_BUILD_ALPHA 1
  180528. #define PNG_LIBPNG_BUILD_BETA 2
  180529. #define PNG_LIBPNG_BUILD_RC 3
  180530. #define PNG_LIBPNG_BUILD_STABLE 4
  180531. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180532. /* Release-Specific Flags */
  180533. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180534. PNG_LIBPNG_BUILD_STABLE only */
  180535. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180536. PNG_LIBPNG_BUILD_SPECIAL */
  180537. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180538. PNG_LIBPNG_BUILD_PRIVATE */
  180539. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180540. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180541. * We must not include leading zeros.
  180542. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180543. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180544. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180545. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180546. #ifndef PNG_VERSION_INFO_ONLY
  180547. /* include the compression library's header */
  180548. #endif
  180549. /* include all user configurable info, including optional assembler routines */
  180550. /*** Start of inlined file: pngconf.h ***/
  180551. /* pngconf.h - machine configurable file for libpng
  180552. *
  180553. * libpng version 1.2.21 - October 4, 2007
  180554. * For conditions of distribution and use, see copyright notice in png.h
  180555. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180556. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180557. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180558. */
  180559. /* Any machine specific code is near the front of this file, so if you
  180560. * are configuring libpng for a machine, you may want to read the section
  180561. * starting here down to where it starts to typedef png_color, png_text,
  180562. * and png_info.
  180563. */
  180564. #ifndef PNGCONF_H
  180565. #define PNGCONF_H
  180566. #define PNG_1_2_X
  180567. // These are some Juce config settings that should remove any unnecessary code bloat..
  180568. #define PNG_NO_STDIO 1
  180569. #define PNG_DEBUG 0
  180570. #define PNG_NO_WARNINGS 1
  180571. #define PNG_NO_ERROR_TEXT 1
  180572. #define PNG_NO_ERROR_NUMBERS 1
  180573. #define PNG_NO_USER_MEM 1
  180574. #define PNG_NO_READ_iCCP 1
  180575. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180576. #define PNG_NO_READ_USER_CHUNKS 1
  180577. #define PNG_NO_READ_iTXt 1
  180578. #define PNG_NO_READ_sCAL 1
  180579. #define PNG_NO_READ_sPLT 1
  180580. #define png_error(a, b) png_err(a)
  180581. #define png_warning(a, b)
  180582. #define png_chunk_error(a, b) png_err(a)
  180583. #define png_chunk_warning(a, b)
  180584. /*
  180585. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180586. * includes the resource compiler for Windows DLL configurations.
  180587. */
  180588. #ifdef PNG_USER_CONFIG
  180589. # ifndef PNG_USER_PRIVATEBUILD
  180590. # define PNG_USER_PRIVATEBUILD
  180591. # endif
  180592. #include "pngusr.h"
  180593. #endif
  180594. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180595. #ifdef PNG_CONFIGURE_LIBPNG
  180596. #ifdef HAVE_CONFIG_H
  180597. #include "config.h"
  180598. #endif
  180599. #endif
  180600. /*
  180601. * Added at libpng-1.2.8
  180602. *
  180603. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180604. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180605. * the DLL was built>
  180606. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180607. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180608. * distinguish your DLL from those of the official release. These
  180609. * correspond to the trailing letters that come after the version
  180610. * number and must match your private DLL name>
  180611. * e.g. // private DLL "libpng13gx.dll"
  180612. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180613. *
  180614. * The following macros are also at your disposal if you want to complete the
  180615. * DLL VERSIONINFO structure.
  180616. * - PNG_USER_VERSIONINFO_COMMENTS
  180617. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180618. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180619. */
  180620. #ifdef __STDC__
  180621. #ifdef SPECIALBUILD
  180622. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180623. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180624. #endif
  180625. #ifdef PRIVATEBUILD
  180626. # pragma message("PRIVATEBUILD is deprecated.\
  180627. Use PNG_USER_PRIVATEBUILD instead.")
  180628. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180629. #endif
  180630. #endif /* __STDC__ */
  180631. #ifndef PNG_VERSION_INFO_ONLY
  180632. /* End of material added to libpng-1.2.8 */
  180633. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180634. Restored at libpng-1.2.21 */
  180635. # define PNG_WARN_UNINITIALIZED_ROW 1
  180636. /* End of material added at libpng-1.2.19/1.2.21 */
  180637. /* This is the size of the compression buffer, and thus the size of
  180638. * an IDAT chunk. Make this whatever size you feel is best for your
  180639. * machine. One of these will be allocated per png_struct. When this
  180640. * is full, it writes the data to the disk, and does some other
  180641. * calculations. Making this an extremely small size will slow
  180642. * the library down, but you may want to experiment to determine
  180643. * where it becomes significant, if you are concerned with memory
  180644. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180645. * this describes the size of the buffer available to read the data in.
  180646. * Unless this gets smaller than the size of a row (compressed),
  180647. * it should not make much difference how big this is.
  180648. */
  180649. #ifndef PNG_ZBUF_SIZE
  180650. # define PNG_ZBUF_SIZE 8192
  180651. #endif
  180652. /* Enable if you want a write-only libpng */
  180653. #ifndef PNG_NO_READ_SUPPORTED
  180654. # define PNG_READ_SUPPORTED
  180655. #endif
  180656. /* Enable if you want a read-only libpng */
  180657. #ifndef PNG_NO_WRITE_SUPPORTED
  180658. # define PNG_WRITE_SUPPORTED
  180659. #endif
  180660. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180661. support PNGs that are embedded in MNG datastreams */
  180662. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180663. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180664. # define PNG_MNG_FEATURES_SUPPORTED
  180665. # endif
  180666. #endif
  180667. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180668. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180669. # define PNG_FLOATING_POINT_SUPPORTED
  180670. # endif
  180671. #endif
  180672. /* If you are running on a machine where you cannot allocate more
  180673. * than 64K of memory at once, uncomment this. While libpng will not
  180674. * normally need that much memory in a chunk (unless you load up a very
  180675. * large file), zlib needs to know how big of a chunk it can use, and
  180676. * libpng thus makes sure to check any memory allocation to verify it
  180677. * will fit into memory.
  180678. #define PNG_MAX_MALLOC_64K
  180679. */
  180680. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180681. # define PNG_MAX_MALLOC_64K
  180682. #endif
  180683. /* Special munging to support doing things the 'cygwin' way:
  180684. * 'Normal' png-on-win32 defines/defaults:
  180685. * PNG_BUILD_DLL -- building dll
  180686. * PNG_USE_DLL -- building an application, linking to dll
  180687. * (no define) -- building static library, or building an
  180688. * application and linking to the static lib
  180689. * 'Cygwin' defines/defaults:
  180690. * PNG_BUILD_DLL -- (ignored) building the dll
  180691. * (no define) -- (ignored) building an application, linking to the dll
  180692. * PNG_STATIC -- (ignored) building the static lib, or building an
  180693. * application that links to the static lib.
  180694. * ALL_STATIC -- (ignored) building various static libs, or building an
  180695. * application that links to the static libs.
  180696. * Thus,
  180697. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180698. * this bit of #ifdefs will define the 'correct' config variables based on
  180699. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180700. * unnecessary.
  180701. *
  180702. * Also, the precedence order is:
  180703. * ALL_STATIC (since we can't #undef something outside our namespace)
  180704. * PNG_BUILD_DLL
  180705. * PNG_STATIC
  180706. * (nothing) == PNG_USE_DLL
  180707. *
  180708. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180709. * of auto-import in binutils, we no longer need to worry about
  180710. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180711. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180712. * to __declspec() stuff. However, we DO need to worry about
  180713. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180714. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180715. */
  180716. #if defined(__CYGWIN__)
  180717. # if defined(ALL_STATIC)
  180718. # if defined(PNG_BUILD_DLL)
  180719. # undef PNG_BUILD_DLL
  180720. # endif
  180721. # if defined(PNG_USE_DLL)
  180722. # undef PNG_USE_DLL
  180723. # endif
  180724. # if defined(PNG_DLL)
  180725. # undef PNG_DLL
  180726. # endif
  180727. # if !defined(PNG_STATIC)
  180728. # define PNG_STATIC
  180729. # endif
  180730. # else
  180731. # if defined (PNG_BUILD_DLL)
  180732. # if defined(PNG_STATIC)
  180733. # undef PNG_STATIC
  180734. # endif
  180735. # if defined(PNG_USE_DLL)
  180736. # undef PNG_USE_DLL
  180737. # endif
  180738. # if !defined(PNG_DLL)
  180739. # define PNG_DLL
  180740. # endif
  180741. # else
  180742. # if defined(PNG_STATIC)
  180743. # if defined(PNG_USE_DLL)
  180744. # undef PNG_USE_DLL
  180745. # endif
  180746. # if defined(PNG_DLL)
  180747. # undef PNG_DLL
  180748. # endif
  180749. # else
  180750. # if !defined(PNG_USE_DLL)
  180751. # define PNG_USE_DLL
  180752. # endif
  180753. # if !defined(PNG_DLL)
  180754. # define PNG_DLL
  180755. # endif
  180756. # endif
  180757. # endif
  180758. # endif
  180759. #endif
  180760. /* This protects us against compilers that run on a windowing system
  180761. * and thus don't have or would rather us not use the stdio types:
  180762. * stdin, stdout, and stderr. The only one currently used is stderr
  180763. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180764. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180765. * will also prevent these, plus will prevent the entire set of stdio
  180766. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180767. * unless (PNG_DEBUG > 0) has been #defined.
  180768. *
  180769. * #define PNG_NO_CONSOLE_IO
  180770. * #define PNG_NO_STDIO
  180771. */
  180772. #if defined(_WIN32_WCE)
  180773. # include <windows.h>
  180774. /* Console I/O functions are not supported on WindowsCE */
  180775. # define PNG_NO_CONSOLE_IO
  180776. # ifdef PNG_DEBUG
  180777. # undef PNG_DEBUG
  180778. # endif
  180779. #endif
  180780. #ifdef PNG_BUILD_DLL
  180781. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180782. # ifndef PNG_NO_CONSOLE_IO
  180783. # define PNG_NO_CONSOLE_IO
  180784. # endif
  180785. # endif
  180786. #endif
  180787. # ifdef PNG_NO_STDIO
  180788. # ifndef PNG_NO_CONSOLE_IO
  180789. # define PNG_NO_CONSOLE_IO
  180790. # endif
  180791. # ifdef PNG_DEBUG
  180792. # if (PNG_DEBUG > 0)
  180793. # include <stdio.h>
  180794. # endif
  180795. # endif
  180796. # else
  180797. # if !defined(_WIN32_WCE)
  180798. /* "stdio.h" functions are not supported on WindowsCE */
  180799. # include <stdio.h>
  180800. # endif
  180801. # endif
  180802. /* This macro protects us against machines that don't have function
  180803. * prototypes (ie K&R style headers). If your compiler does not handle
  180804. * function prototypes, define this macro and use the included ansi2knr.
  180805. * I've always been able to use _NO_PROTO as the indicator, but you may
  180806. * need to drag the empty declaration out in front of here, or change the
  180807. * ifdef to suit your own needs.
  180808. */
  180809. #ifndef PNGARG
  180810. #ifdef OF /* zlib prototype munger */
  180811. # define PNGARG(arglist) OF(arglist)
  180812. #else
  180813. #ifdef _NO_PROTO
  180814. # define PNGARG(arglist) ()
  180815. # ifndef PNG_TYPECAST_NULL
  180816. # define PNG_TYPECAST_NULL
  180817. # endif
  180818. #else
  180819. # define PNGARG(arglist) arglist
  180820. #endif /* _NO_PROTO */
  180821. #endif /* OF */
  180822. #endif /* PNGARG */
  180823. /* Try to determine if we are compiling on a Mac. Note that testing for
  180824. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180825. * on non-Mac platforms.
  180826. */
  180827. #ifndef MACOS
  180828. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180829. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180830. # define MACOS
  180831. # endif
  180832. #endif
  180833. /* enough people need this for various reasons to include it here */
  180834. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180835. # include <sys/types.h>
  180836. #endif
  180837. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180838. # define PNG_SETJMP_SUPPORTED
  180839. #endif
  180840. #ifdef PNG_SETJMP_SUPPORTED
  180841. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180842. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180843. */
  180844. # ifdef __linux__
  180845. # ifdef _BSD_SOURCE
  180846. # define PNG_SAVE_BSD_SOURCE
  180847. # undef _BSD_SOURCE
  180848. # endif
  180849. # ifdef _SETJMP_H
  180850. /* If you encounter a compiler error here, see the explanation
  180851. * near the end of INSTALL.
  180852. */
  180853. __png.h__ already includes setjmp.h;
  180854. __dont__ include it again.;
  180855. # endif
  180856. # endif /* __linux__ */
  180857. /* include setjmp.h for error handling */
  180858. # include <setjmp.h>
  180859. # ifdef __linux__
  180860. # ifdef PNG_SAVE_BSD_SOURCE
  180861. # define _BSD_SOURCE
  180862. # undef PNG_SAVE_BSD_SOURCE
  180863. # endif
  180864. # endif /* __linux__ */
  180865. #endif /* PNG_SETJMP_SUPPORTED */
  180866. #ifdef BSD
  180867. #if ! JUCE_MAC
  180868. # include <strings.h>
  180869. #endif
  180870. #else
  180871. # include <string.h>
  180872. #endif
  180873. /* Other defines for things like memory and the like can go here. */
  180874. #ifdef PNG_INTERNAL
  180875. #include <stdlib.h>
  180876. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180877. * aren't usually used outside the library (as far as I know), so it is
  180878. * debatable if they should be exported at all. In the future, when it is
  180879. * possible to have run-time registry of chunk-handling functions, some of
  180880. * these will be made available again.
  180881. #define PNG_EXTERN extern
  180882. */
  180883. #define PNG_EXTERN
  180884. /* Other defines specific to compilers can go here. Try to keep
  180885. * them inside an appropriate ifdef/endif pair for portability.
  180886. */
  180887. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180888. # if defined(MACOS)
  180889. /* We need to check that <math.h> hasn't already been included earlier
  180890. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180891. * <fp.h> if possible.
  180892. */
  180893. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180894. # include <fp.h>
  180895. # endif
  180896. # else
  180897. # include <math.h>
  180898. # endif
  180899. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180900. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180901. * MATH=68881
  180902. */
  180903. # include <m68881.h>
  180904. # endif
  180905. #endif
  180906. /* Codewarrior on NT has linking problems without this. */
  180907. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180908. # define PNG_ALWAYS_EXTERN
  180909. #endif
  180910. /* This provides the non-ANSI (far) memory allocation routines. */
  180911. #if defined(__TURBOC__) && defined(__MSDOS__)
  180912. # include <mem.h>
  180913. # include <alloc.h>
  180914. #endif
  180915. /* I have no idea why is this necessary... */
  180916. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180917. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180918. # include <malloc.h>
  180919. #endif
  180920. /* This controls how fine the dithering gets. As this allocates
  180921. * a largish chunk of memory (32K), those who are not as concerned
  180922. * with dithering quality can decrease some or all of these.
  180923. */
  180924. #ifndef PNG_DITHER_RED_BITS
  180925. # define PNG_DITHER_RED_BITS 5
  180926. #endif
  180927. #ifndef PNG_DITHER_GREEN_BITS
  180928. # define PNG_DITHER_GREEN_BITS 5
  180929. #endif
  180930. #ifndef PNG_DITHER_BLUE_BITS
  180931. # define PNG_DITHER_BLUE_BITS 5
  180932. #endif
  180933. /* This controls how fine the gamma correction becomes when you
  180934. * are only interested in 8 bits anyway. Increasing this value
  180935. * results in more memory being used, and more pow() functions
  180936. * being called to fill in the gamma tables. Don't set this value
  180937. * less then 8, and even that may not work (I haven't tested it).
  180938. */
  180939. #ifndef PNG_MAX_GAMMA_8
  180940. # define PNG_MAX_GAMMA_8 11
  180941. #endif
  180942. /* This controls how much a difference in gamma we can tolerate before
  180943. * we actually start doing gamma conversion.
  180944. */
  180945. #ifndef PNG_GAMMA_THRESHOLD
  180946. # define PNG_GAMMA_THRESHOLD 0.05
  180947. #endif
  180948. #endif /* PNG_INTERNAL */
  180949. /* The following uses const char * instead of char * for error
  180950. * and warning message functions, so some compilers won't complain.
  180951. * If you do not want to use const, define PNG_NO_CONST here.
  180952. */
  180953. #ifndef PNG_NO_CONST
  180954. # define PNG_CONST const
  180955. #else
  180956. # define PNG_CONST
  180957. #endif
  180958. /* The following defines give you the ability to remove code from the
  180959. * library that you will not be using. I wish I could figure out how to
  180960. * automate this, but I can't do that without making it seriously hard
  180961. * on the users. So if you are not using an ability, change the #define
  180962. * to and #undef, and that part of the library will not be compiled. If
  180963. * your linker can't find a function, you may want to make sure the
  180964. * ability is defined here. Some of these depend upon some others being
  180965. * defined. I haven't figured out all the interactions here, so you may
  180966. * have to experiment awhile to get everything to compile. If you are
  180967. * creating or using a shared library, you probably shouldn't touch this,
  180968. * as it will affect the size of the structures, and this will cause bad
  180969. * things to happen if the library and/or application ever change.
  180970. */
  180971. /* Any features you will not be using can be undef'ed here */
  180972. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180973. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180974. * on the compile line, then pick and choose which ones to define without
  180975. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180976. * if you only want to have a png-compliant reader/writer but don't need
  180977. * any of the extra transformations. This saves about 80 kbytes in a
  180978. * typical installation of the library. (PNG_NO_* form added in version
  180979. * 1.0.1c, for consistency)
  180980. */
  180981. /* The size of the png_text structure changed in libpng-1.0.6 when
  180982. * iTXt support was added. iTXt support was turned off by default through
  180983. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180984. * instead of calling png_set_text() and letting libpng malloc it. It
  180985. * was turned on by default in libpng-1.3.0.
  180986. */
  180987. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180988. # ifndef PNG_NO_iTXt_SUPPORTED
  180989. # define PNG_NO_iTXt_SUPPORTED
  180990. # endif
  180991. # ifndef PNG_NO_READ_iTXt
  180992. # define PNG_NO_READ_iTXt
  180993. # endif
  180994. # ifndef PNG_NO_WRITE_iTXt
  180995. # define PNG_NO_WRITE_iTXt
  180996. # endif
  180997. #endif
  180998. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180999. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181000. # define PNG_READ_iTXt
  181001. # endif
  181002. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181003. # define PNG_WRITE_iTXt
  181004. # endif
  181005. #endif
  181006. /* The following support, added after version 1.0.0, can be turned off here en
  181007. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181008. * with old applications that require the length of png_struct and png_info
  181009. * to remain unchanged.
  181010. */
  181011. #ifdef PNG_LEGACY_SUPPORTED
  181012. # define PNG_NO_FREE_ME
  181013. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181014. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181015. # define PNG_NO_READ_USER_CHUNKS
  181016. # define PNG_NO_READ_iCCP
  181017. # define PNG_NO_WRITE_iCCP
  181018. # define PNG_NO_READ_iTXt
  181019. # define PNG_NO_WRITE_iTXt
  181020. # define PNG_NO_READ_sCAL
  181021. # define PNG_NO_WRITE_sCAL
  181022. # define PNG_NO_READ_sPLT
  181023. # define PNG_NO_WRITE_sPLT
  181024. # define PNG_NO_INFO_IMAGE
  181025. # define PNG_NO_READ_RGB_TO_GRAY
  181026. # define PNG_NO_READ_USER_TRANSFORM
  181027. # define PNG_NO_WRITE_USER_TRANSFORM
  181028. # define PNG_NO_USER_MEM
  181029. # define PNG_NO_READ_EMPTY_PLTE
  181030. # define PNG_NO_MNG_FEATURES
  181031. # define PNG_NO_FIXED_POINT_SUPPORTED
  181032. #endif
  181033. /* Ignore attempt to turn off both floating and fixed point support */
  181034. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181035. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181036. # define PNG_FIXED_POINT_SUPPORTED
  181037. #endif
  181038. #ifndef PNG_NO_FREE_ME
  181039. # define PNG_FREE_ME_SUPPORTED
  181040. #endif
  181041. #if defined(PNG_READ_SUPPORTED)
  181042. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181043. !defined(PNG_NO_READ_TRANSFORMS)
  181044. # define PNG_READ_TRANSFORMS_SUPPORTED
  181045. #endif
  181046. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181047. # ifndef PNG_NO_READ_EXPAND
  181048. # define PNG_READ_EXPAND_SUPPORTED
  181049. # endif
  181050. # ifndef PNG_NO_READ_SHIFT
  181051. # define PNG_READ_SHIFT_SUPPORTED
  181052. # endif
  181053. # ifndef PNG_NO_READ_PACK
  181054. # define PNG_READ_PACK_SUPPORTED
  181055. # endif
  181056. # ifndef PNG_NO_READ_BGR
  181057. # define PNG_READ_BGR_SUPPORTED
  181058. # endif
  181059. # ifndef PNG_NO_READ_SWAP
  181060. # define PNG_READ_SWAP_SUPPORTED
  181061. # endif
  181062. # ifndef PNG_NO_READ_PACKSWAP
  181063. # define PNG_READ_PACKSWAP_SUPPORTED
  181064. # endif
  181065. # ifndef PNG_NO_READ_INVERT
  181066. # define PNG_READ_INVERT_SUPPORTED
  181067. # endif
  181068. # ifndef PNG_NO_READ_DITHER
  181069. # define PNG_READ_DITHER_SUPPORTED
  181070. # endif
  181071. # ifndef PNG_NO_READ_BACKGROUND
  181072. # define PNG_READ_BACKGROUND_SUPPORTED
  181073. # endif
  181074. # ifndef PNG_NO_READ_16_TO_8
  181075. # define PNG_READ_16_TO_8_SUPPORTED
  181076. # endif
  181077. # ifndef PNG_NO_READ_FILLER
  181078. # define PNG_READ_FILLER_SUPPORTED
  181079. # endif
  181080. # ifndef PNG_NO_READ_GAMMA
  181081. # define PNG_READ_GAMMA_SUPPORTED
  181082. # endif
  181083. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181084. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181085. # endif
  181086. # ifndef PNG_NO_READ_SWAP_ALPHA
  181087. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181088. # endif
  181089. # ifndef PNG_NO_READ_INVERT_ALPHA
  181090. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181091. # endif
  181092. # ifndef PNG_NO_READ_STRIP_ALPHA
  181093. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181094. # endif
  181095. # ifndef PNG_NO_READ_USER_TRANSFORM
  181096. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181097. # endif
  181098. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181099. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181100. # endif
  181101. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181102. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181103. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181104. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181105. #endif /* about interlacing capability! You'll */
  181106. /* still have interlacing unless you change the following line: */
  181107. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181108. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181109. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181110. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181111. # endif
  181112. #endif
  181113. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181114. /* Deprecated, will be removed from version 2.0.0.
  181115. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181116. #ifndef PNG_NO_READ_EMPTY_PLTE
  181117. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181118. #endif
  181119. #endif
  181120. #endif /* PNG_READ_SUPPORTED */
  181121. #if defined(PNG_WRITE_SUPPORTED)
  181122. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181123. !defined(PNG_NO_WRITE_TRANSFORMS)
  181124. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181125. #endif
  181126. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181127. # ifndef PNG_NO_WRITE_SHIFT
  181128. # define PNG_WRITE_SHIFT_SUPPORTED
  181129. # endif
  181130. # ifndef PNG_NO_WRITE_PACK
  181131. # define PNG_WRITE_PACK_SUPPORTED
  181132. # endif
  181133. # ifndef PNG_NO_WRITE_BGR
  181134. # define PNG_WRITE_BGR_SUPPORTED
  181135. # endif
  181136. # ifndef PNG_NO_WRITE_SWAP
  181137. # define PNG_WRITE_SWAP_SUPPORTED
  181138. # endif
  181139. # ifndef PNG_NO_WRITE_PACKSWAP
  181140. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181141. # endif
  181142. # ifndef PNG_NO_WRITE_INVERT
  181143. # define PNG_WRITE_INVERT_SUPPORTED
  181144. # endif
  181145. # ifndef PNG_NO_WRITE_FILLER
  181146. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181147. # endif
  181148. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181149. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181150. # endif
  181151. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181152. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181153. # endif
  181154. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181155. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181156. # endif
  181157. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181158. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181159. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181160. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181161. encoders, but can cause trouble
  181162. if left undefined */
  181163. #endif
  181164. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181165. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181166. defined(PNG_FLOATING_POINT_SUPPORTED)
  181167. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181168. #endif
  181169. #ifndef PNG_NO_WRITE_FLUSH
  181170. # define PNG_WRITE_FLUSH_SUPPORTED
  181171. #endif
  181172. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181173. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181174. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181175. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181176. #endif
  181177. #endif
  181178. #endif /* PNG_WRITE_SUPPORTED */
  181179. #ifndef PNG_1_0_X
  181180. # ifndef PNG_NO_ERROR_NUMBERS
  181181. # define PNG_ERROR_NUMBERS_SUPPORTED
  181182. # endif
  181183. #endif /* PNG_1_0_X */
  181184. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181185. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181186. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181187. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181188. # endif
  181189. #endif
  181190. #ifndef PNG_NO_STDIO
  181191. # define PNG_TIME_RFC1123_SUPPORTED
  181192. #endif
  181193. /* This adds extra functions in pngget.c for accessing data from the
  181194. * info pointer (added in version 0.99)
  181195. * png_get_image_width()
  181196. * png_get_image_height()
  181197. * png_get_bit_depth()
  181198. * png_get_color_type()
  181199. * png_get_compression_type()
  181200. * png_get_filter_type()
  181201. * png_get_interlace_type()
  181202. * png_get_pixel_aspect_ratio()
  181203. * png_get_pixels_per_meter()
  181204. * png_get_x_offset_pixels()
  181205. * png_get_y_offset_pixels()
  181206. * png_get_x_offset_microns()
  181207. * png_get_y_offset_microns()
  181208. */
  181209. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181210. # define PNG_EASY_ACCESS_SUPPORTED
  181211. #endif
  181212. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181213. * and removed from version 1.2.20. The following will be removed
  181214. * from libpng-1.4.0
  181215. */
  181216. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181217. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181218. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181219. # endif
  181220. #endif
  181221. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181222. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181223. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181224. # endif
  181225. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181226. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181227. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181228. # define PNG_NO_MMX_CODE
  181229. # endif
  181230. # endif
  181231. # if defined(__APPLE__)
  181232. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181233. # define PNG_NO_MMX_CODE
  181234. # endif
  181235. # endif
  181236. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181237. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181238. # define PNG_NO_MMX_CODE
  181239. # endif
  181240. # endif
  181241. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181242. # define PNG_MMX_CODE_SUPPORTED
  181243. # endif
  181244. #endif
  181245. /* end of obsolete code to be removed from libpng-1.4.0 */
  181246. #if !defined(PNG_1_0_X)
  181247. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181248. # define PNG_USER_MEM_SUPPORTED
  181249. #endif
  181250. #endif /* PNG_1_0_X */
  181251. /* Added at libpng-1.2.6 */
  181252. #if !defined(PNG_1_0_X)
  181253. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181254. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181255. # define PNG_SET_USER_LIMITS_SUPPORTED
  181256. #endif
  181257. #endif
  181258. #endif /* PNG_1_0_X */
  181259. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181260. * how large, set these limits to 0x7fffffffL
  181261. */
  181262. #ifndef PNG_USER_WIDTH_MAX
  181263. # define PNG_USER_WIDTH_MAX 1000000L
  181264. #endif
  181265. #ifndef PNG_USER_HEIGHT_MAX
  181266. # define PNG_USER_HEIGHT_MAX 1000000L
  181267. #endif
  181268. /* These are currently experimental features, define them if you want */
  181269. /* very little testing */
  181270. /*
  181271. #ifdef PNG_READ_SUPPORTED
  181272. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181273. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181274. # endif
  181275. #endif
  181276. */
  181277. /* This is only for PowerPC big-endian and 680x0 systems */
  181278. /* some testing */
  181279. /*
  181280. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181281. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181282. #endif
  181283. */
  181284. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181285. /*
  181286. #define PNG_NO_POINTER_INDEXING
  181287. */
  181288. /* These functions are turned off by default, as they will be phased out. */
  181289. /*
  181290. #define PNG_USELESS_TESTS_SUPPORTED
  181291. #define PNG_CORRECT_PALETTE_SUPPORTED
  181292. */
  181293. /* Any chunks you are not interested in, you can undef here. The
  181294. * ones that allocate memory may be expecially important (hIST,
  181295. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181296. * a bit smaller.
  181297. */
  181298. #if defined(PNG_READ_SUPPORTED) && \
  181299. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181300. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181301. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181302. #endif
  181303. #if defined(PNG_WRITE_SUPPORTED) && \
  181304. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181305. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181306. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181307. #endif
  181308. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181309. #ifdef PNG_NO_READ_TEXT
  181310. # define PNG_NO_READ_iTXt
  181311. # define PNG_NO_READ_tEXt
  181312. # define PNG_NO_READ_zTXt
  181313. #endif
  181314. #ifndef PNG_NO_READ_bKGD
  181315. # define PNG_READ_bKGD_SUPPORTED
  181316. # define PNG_bKGD_SUPPORTED
  181317. #endif
  181318. #ifndef PNG_NO_READ_cHRM
  181319. # define PNG_READ_cHRM_SUPPORTED
  181320. # define PNG_cHRM_SUPPORTED
  181321. #endif
  181322. #ifndef PNG_NO_READ_gAMA
  181323. # define PNG_READ_gAMA_SUPPORTED
  181324. # define PNG_gAMA_SUPPORTED
  181325. #endif
  181326. #ifndef PNG_NO_READ_hIST
  181327. # define PNG_READ_hIST_SUPPORTED
  181328. # define PNG_hIST_SUPPORTED
  181329. #endif
  181330. #ifndef PNG_NO_READ_iCCP
  181331. # define PNG_READ_iCCP_SUPPORTED
  181332. # define PNG_iCCP_SUPPORTED
  181333. #endif
  181334. #ifndef PNG_NO_READ_iTXt
  181335. # ifndef PNG_READ_iTXt_SUPPORTED
  181336. # define PNG_READ_iTXt_SUPPORTED
  181337. # endif
  181338. # ifndef PNG_iTXt_SUPPORTED
  181339. # define PNG_iTXt_SUPPORTED
  181340. # endif
  181341. #endif
  181342. #ifndef PNG_NO_READ_oFFs
  181343. # define PNG_READ_oFFs_SUPPORTED
  181344. # define PNG_oFFs_SUPPORTED
  181345. #endif
  181346. #ifndef PNG_NO_READ_pCAL
  181347. # define PNG_READ_pCAL_SUPPORTED
  181348. # define PNG_pCAL_SUPPORTED
  181349. #endif
  181350. #ifndef PNG_NO_READ_sCAL
  181351. # define PNG_READ_sCAL_SUPPORTED
  181352. # define PNG_sCAL_SUPPORTED
  181353. #endif
  181354. #ifndef PNG_NO_READ_pHYs
  181355. # define PNG_READ_pHYs_SUPPORTED
  181356. # define PNG_pHYs_SUPPORTED
  181357. #endif
  181358. #ifndef PNG_NO_READ_sBIT
  181359. # define PNG_READ_sBIT_SUPPORTED
  181360. # define PNG_sBIT_SUPPORTED
  181361. #endif
  181362. #ifndef PNG_NO_READ_sPLT
  181363. # define PNG_READ_sPLT_SUPPORTED
  181364. # define PNG_sPLT_SUPPORTED
  181365. #endif
  181366. #ifndef PNG_NO_READ_sRGB
  181367. # define PNG_READ_sRGB_SUPPORTED
  181368. # define PNG_sRGB_SUPPORTED
  181369. #endif
  181370. #ifndef PNG_NO_READ_tEXt
  181371. # define PNG_READ_tEXt_SUPPORTED
  181372. # define PNG_tEXt_SUPPORTED
  181373. #endif
  181374. #ifndef PNG_NO_READ_tIME
  181375. # define PNG_READ_tIME_SUPPORTED
  181376. # define PNG_tIME_SUPPORTED
  181377. #endif
  181378. #ifndef PNG_NO_READ_tRNS
  181379. # define PNG_READ_tRNS_SUPPORTED
  181380. # define PNG_tRNS_SUPPORTED
  181381. #endif
  181382. #ifndef PNG_NO_READ_zTXt
  181383. # define PNG_READ_zTXt_SUPPORTED
  181384. # define PNG_zTXt_SUPPORTED
  181385. #endif
  181386. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181387. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181388. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181389. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181390. # endif
  181391. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181392. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181393. # endif
  181394. #endif
  181395. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181396. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181397. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181398. # define PNG_USER_CHUNKS_SUPPORTED
  181399. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181400. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181401. # endif
  181402. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181403. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181404. # endif
  181405. #endif
  181406. #ifndef PNG_NO_READ_OPT_PLTE
  181407. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181408. #endif /* optional PLTE chunk in RGB and RGBA images */
  181409. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181410. defined(PNG_READ_zTXt_SUPPORTED)
  181411. # define PNG_READ_TEXT_SUPPORTED
  181412. # define PNG_TEXT_SUPPORTED
  181413. #endif
  181414. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181415. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181416. #ifdef PNG_NO_WRITE_TEXT
  181417. # define PNG_NO_WRITE_iTXt
  181418. # define PNG_NO_WRITE_tEXt
  181419. # define PNG_NO_WRITE_zTXt
  181420. #endif
  181421. #ifndef PNG_NO_WRITE_bKGD
  181422. # define PNG_WRITE_bKGD_SUPPORTED
  181423. # ifndef PNG_bKGD_SUPPORTED
  181424. # define PNG_bKGD_SUPPORTED
  181425. # endif
  181426. #endif
  181427. #ifndef PNG_NO_WRITE_cHRM
  181428. # define PNG_WRITE_cHRM_SUPPORTED
  181429. # ifndef PNG_cHRM_SUPPORTED
  181430. # define PNG_cHRM_SUPPORTED
  181431. # endif
  181432. #endif
  181433. #ifndef PNG_NO_WRITE_gAMA
  181434. # define PNG_WRITE_gAMA_SUPPORTED
  181435. # ifndef PNG_gAMA_SUPPORTED
  181436. # define PNG_gAMA_SUPPORTED
  181437. # endif
  181438. #endif
  181439. #ifndef PNG_NO_WRITE_hIST
  181440. # define PNG_WRITE_hIST_SUPPORTED
  181441. # ifndef PNG_hIST_SUPPORTED
  181442. # define PNG_hIST_SUPPORTED
  181443. # endif
  181444. #endif
  181445. #ifndef PNG_NO_WRITE_iCCP
  181446. # define PNG_WRITE_iCCP_SUPPORTED
  181447. # ifndef PNG_iCCP_SUPPORTED
  181448. # define PNG_iCCP_SUPPORTED
  181449. # endif
  181450. #endif
  181451. #ifndef PNG_NO_WRITE_iTXt
  181452. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181453. # define PNG_WRITE_iTXt_SUPPORTED
  181454. # endif
  181455. # ifndef PNG_iTXt_SUPPORTED
  181456. # define PNG_iTXt_SUPPORTED
  181457. # endif
  181458. #endif
  181459. #ifndef PNG_NO_WRITE_oFFs
  181460. # define PNG_WRITE_oFFs_SUPPORTED
  181461. # ifndef PNG_oFFs_SUPPORTED
  181462. # define PNG_oFFs_SUPPORTED
  181463. # endif
  181464. #endif
  181465. #ifndef PNG_NO_WRITE_pCAL
  181466. # define PNG_WRITE_pCAL_SUPPORTED
  181467. # ifndef PNG_pCAL_SUPPORTED
  181468. # define PNG_pCAL_SUPPORTED
  181469. # endif
  181470. #endif
  181471. #ifndef PNG_NO_WRITE_sCAL
  181472. # define PNG_WRITE_sCAL_SUPPORTED
  181473. # ifndef PNG_sCAL_SUPPORTED
  181474. # define PNG_sCAL_SUPPORTED
  181475. # endif
  181476. #endif
  181477. #ifndef PNG_NO_WRITE_pHYs
  181478. # define PNG_WRITE_pHYs_SUPPORTED
  181479. # ifndef PNG_pHYs_SUPPORTED
  181480. # define PNG_pHYs_SUPPORTED
  181481. # endif
  181482. #endif
  181483. #ifndef PNG_NO_WRITE_sBIT
  181484. # define PNG_WRITE_sBIT_SUPPORTED
  181485. # ifndef PNG_sBIT_SUPPORTED
  181486. # define PNG_sBIT_SUPPORTED
  181487. # endif
  181488. #endif
  181489. #ifndef PNG_NO_WRITE_sPLT
  181490. # define PNG_WRITE_sPLT_SUPPORTED
  181491. # ifndef PNG_sPLT_SUPPORTED
  181492. # define PNG_sPLT_SUPPORTED
  181493. # endif
  181494. #endif
  181495. #ifndef PNG_NO_WRITE_sRGB
  181496. # define PNG_WRITE_sRGB_SUPPORTED
  181497. # ifndef PNG_sRGB_SUPPORTED
  181498. # define PNG_sRGB_SUPPORTED
  181499. # endif
  181500. #endif
  181501. #ifndef PNG_NO_WRITE_tEXt
  181502. # define PNG_WRITE_tEXt_SUPPORTED
  181503. # ifndef PNG_tEXt_SUPPORTED
  181504. # define PNG_tEXt_SUPPORTED
  181505. # endif
  181506. #endif
  181507. #ifndef PNG_NO_WRITE_tIME
  181508. # define PNG_WRITE_tIME_SUPPORTED
  181509. # ifndef PNG_tIME_SUPPORTED
  181510. # define PNG_tIME_SUPPORTED
  181511. # endif
  181512. #endif
  181513. #ifndef PNG_NO_WRITE_tRNS
  181514. # define PNG_WRITE_tRNS_SUPPORTED
  181515. # ifndef PNG_tRNS_SUPPORTED
  181516. # define PNG_tRNS_SUPPORTED
  181517. # endif
  181518. #endif
  181519. #ifndef PNG_NO_WRITE_zTXt
  181520. # define PNG_WRITE_zTXt_SUPPORTED
  181521. # ifndef PNG_zTXt_SUPPORTED
  181522. # define PNG_zTXt_SUPPORTED
  181523. # endif
  181524. #endif
  181525. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181526. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181527. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181528. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181529. # endif
  181530. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181531. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181532. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181533. # endif
  181534. # endif
  181535. #endif
  181536. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181537. defined(PNG_WRITE_zTXt_SUPPORTED)
  181538. # define PNG_WRITE_TEXT_SUPPORTED
  181539. # ifndef PNG_TEXT_SUPPORTED
  181540. # define PNG_TEXT_SUPPORTED
  181541. # endif
  181542. #endif
  181543. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181544. /* Turn this off to disable png_read_png() and
  181545. * png_write_png() and leave the row_pointers member
  181546. * out of the info structure.
  181547. */
  181548. #ifndef PNG_NO_INFO_IMAGE
  181549. # define PNG_INFO_IMAGE_SUPPORTED
  181550. #endif
  181551. /* need the time information for reading tIME chunks */
  181552. #if defined(PNG_tIME_SUPPORTED)
  181553. # if !defined(_WIN32_WCE)
  181554. /* "time.h" functions are not supported on WindowsCE */
  181555. # include <time.h>
  181556. # endif
  181557. #endif
  181558. /* Some typedefs to get us started. These should be safe on most of the
  181559. * common platforms. The typedefs should be at least as large as the
  181560. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181561. * don't have to be exactly that size. Some compilers dislike passing
  181562. * unsigned shorts as function parameters, so you may be better off using
  181563. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181564. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181565. */
  181566. typedef unsigned long png_uint_32;
  181567. typedef long png_int_32;
  181568. typedef unsigned short png_uint_16;
  181569. typedef short png_int_16;
  181570. typedef unsigned char png_byte;
  181571. /* This is usually size_t. It is typedef'ed just in case you need it to
  181572. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181573. #ifdef PNG_SIZE_T
  181574. typedef PNG_SIZE_T png_size_t;
  181575. # define png_sizeof(x) png_convert_size(sizeof (x))
  181576. #else
  181577. typedef size_t png_size_t;
  181578. # define png_sizeof(x) sizeof (x)
  181579. #endif
  181580. /* The following is needed for medium model support. It cannot be in the
  181581. * PNG_INTERNAL section. Needs modification for other compilers besides
  181582. * MSC. Model independent support declares all arrays and pointers to be
  181583. * large using the far keyword. The zlib version used must also support
  181584. * model independent data. As of version zlib 1.0.4, the necessary changes
  181585. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181586. * changes that are needed. (Tim Wegner)
  181587. */
  181588. /* Separate compiler dependencies (problem here is that zlib.h always
  181589. defines FAR. (SJT) */
  181590. #ifdef __BORLANDC__
  181591. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181592. # define LDATA 1
  181593. # else
  181594. # define LDATA 0
  181595. # endif
  181596. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181597. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181598. # define PNG_MAX_MALLOC_64K
  181599. # if (LDATA != 1)
  181600. # ifndef FAR
  181601. # define FAR __far
  181602. # endif
  181603. # define USE_FAR_KEYWORD
  181604. # endif /* LDATA != 1 */
  181605. /* Possibly useful for moving data out of default segment.
  181606. * Uncomment it if you want. Could also define FARDATA as
  181607. * const if your compiler supports it. (SJT)
  181608. # define FARDATA FAR
  181609. */
  181610. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181611. #endif /* __BORLANDC__ */
  181612. /* Suggest testing for specific compiler first before testing for
  181613. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181614. * making reliance oncertain keywords suspect. (SJT)
  181615. */
  181616. /* MSC Medium model */
  181617. #if defined(FAR)
  181618. # if defined(M_I86MM)
  181619. # define USE_FAR_KEYWORD
  181620. # define FARDATA FAR
  181621. # include <dos.h>
  181622. # endif
  181623. #endif
  181624. /* SJT: default case */
  181625. #ifndef FAR
  181626. # define FAR
  181627. #endif
  181628. /* At this point FAR is always defined */
  181629. #ifndef FARDATA
  181630. # define FARDATA
  181631. #endif
  181632. /* Typedef for floating-point numbers that are converted
  181633. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181634. typedef png_int_32 png_fixed_point;
  181635. /* Add typedefs for pointers */
  181636. typedef void FAR * png_voidp;
  181637. typedef png_byte FAR * png_bytep;
  181638. typedef png_uint_32 FAR * png_uint_32p;
  181639. typedef png_int_32 FAR * png_int_32p;
  181640. typedef png_uint_16 FAR * png_uint_16p;
  181641. typedef png_int_16 FAR * png_int_16p;
  181642. typedef PNG_CONST char FAR * png_const_charp;
  181643. typedef char FAR * png_charp;
  181644. typedef png_fixed_point FAR * png_fixed_point_p;
  181645. #ifndef PNG_NO_STDIO
  181646. #if defined(_WIN32_WCE)
  181647. typedef HANDLE png_FILE_p;
  181648. #else
  181649. typedef FILE * png_FILE_p;
  181650. #endif
  181651. #endif
  181652. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181653. typedef double FAR * png_doublep;
  181654. #endif
  181655. /* Pointers to pointers; i.e. arrays */
  181656. typedef png_byte FAR * FAR * png_bytepp;
  181657. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181658. typedef png_int_32 FAR * FAR * png_int_32pp;
  181659. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181660. typedef png_int_16 FAR * FAR * png_int_16pp;
  181661. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181662. typedef char FAR * FAR * png_charpp;
  181663. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181664. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181665. typedef double FAR * FAR * png_doublepp;
  181666. #endif
  181667. /* Pointers to pointers to pointers; i.e., pointer to array */
  181668. typedef char FAR * FAR * FAR * png_charppp;
  181669. #if 0
  181670. /* SPC - Is this stuff deprecated? */
  181671. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181672. /* libpng typedefs for types in zlib. If zlib changes
  181673. * or another compression library is used, then change these.
  181674. * Eliminates need to change all the source files.
  181675. */
  181676. typedef charf * png_zcharp;
  181677. typedef charf * FAR * png_zcharpp;
  181678. typedef z_stream FAR * png_zstreamp;
  181679. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181680. /*
  181681. * Define PNG_BUILD_DLL if the module being built is a Windows
  181682. * LIBPNG DLL.
  181683. *
  181684. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181685. * It is equivalent to Microsoft predefined macro _DLL that is
  181686. * automatically defined when you compile using the share
  181687. * version of the CRT (C Run-Time library)
  181688. *
  181689. * The cygwin mods make this behavior a little different:
  181690. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181691. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181692. * -or- if you are building an application that you want to link to the
  181693. * static library.
  181694. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181695. * the other flags is defined.
  181696. */
  181697. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181698. # define PNG_DLL
  181699. #endif
  181700. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181701. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181702. * command-line override
  181703. */
  181704. #if defined(__CYGWIN__)
  181705. # if !defined(PNG_STATIC)
  181706. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181707. # undef PNG_USE_GLOBAL_ARRAYS
  181708. # endif
  181709. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181710. # define PNG_USE_LOCAL_ARRAYS
  181711. # endif
  181712. # else
  181713. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181714. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181715. # undef PNG_USE_GLOBAL_ARRAYS
  181716. # endif
  181717. # endif
  181718. # endif
  181719. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181720. # define PNG_USE_LOCAL_ARRAYS
  181721. # endif
  181722. #endif
  181723. /* Do not use global arrays (helps with building DLL's)
  181724. * They are no longer used in libpng itself, since version 1.0.5c,
  181725. * but might be required for some pre-1.0.5c applications.
  181726. */
  181727. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181728. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181729. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181730. # define PNG_USE_LOCAL_ARRAYS
  181731. # else
  181732. # define PNG_USE_GLOBAL_ARRAYS
  181733. # endif
  181734. #endif
  181735. #if defined(__CYGWIN__)
  181736. # undef PNGAPI
  181737. # define PNGAPI __cdecl
  181738. # undef PNG_IMPEXP
  181739. # define PNG_IMPEXP
  181740. #endif
  181741. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181742. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181743. * Don't ignore those warnings; you must also reset the default calling
  181744. * convention in your compiler to match your PNGAPI, and you must build
  181745. * zlib and your applications the same way you build libpng.
  181746. */
  181747. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181748. # ifndef PNG_NO_MODULEDEF
  181749. # define PNG_NO_MODULEDEF
  181750. # endif
  181751. #endif
  181752. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181753. # define PNG_IMPEXP
  181754. #endif
  181755. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181756. (( defined(_Windows) || defined(_WINDOWS) || \
  181757. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181758. # ifndef PNGAPI
  181759. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181760. # define PNGAPI __cdecl
  181761. # else
  181762. # define PNGAPI _cdecl
  181763. # endif
  181764. # endif
  181765. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181766. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181767. # define PNG_IMPEXP
  181768. # endif
  181769. # if !defined(PNG_IMPEXP)
  181770. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181771. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181772. /* Borland/Microsoft */
  181773. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181774. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181775. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181776. # else
  181777. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181778. # if defined(PNG_BUILD_DLL)
  181779. # define PNG_IMPEXP __export
  181780. # else
  181781. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181782. VC++ */
  181783. # endif /* Exists in Borland C++ for
  181784. C++ classes (== huge) */
  181785. # endif
  181786. # endif
  181787. # if !defined(PNG_IMPEXP)
  181788. # if defined(PNG_BUILD_DLL)
  181789. # define PNG_IMPEXP __declspec(dllexport)
  181790. # else
  181791. # define PNG_IMPEXP __declspec(dllimport)
  181792. # endif
  181793. # endif
  181794. # endif /* PNG_IMPEXP */
  181795. #else /* !(DLL || non-cygwin WINDOWS) */
  181796. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181797. # ifndef PNGAPI
  181798. # define PNGAPI _System
  181799. # endif
  181800. # else
  181801. # if 0 /* ... other platforms, with other meanings */
  181802. # endif
  181803. # endif
  181804. #endif
  181805. #ifndef PNGAPI
  181806. # define PNGAPI
  181807. #endif
  181808. #ifndef PNG_IMPEXP
  181809. # define PNG_IMPEXP
  181810. #endif
  181811. #ifdef PNG_BUILDSYMS
  181812. # ifndef PNG_EXPORT
  181813. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181814. # endif
  181815. # ifdef PNG_USE_GLOBAL_ARRAYS
  181816. # ifndef PNG_EXPORT_VAR
  181817. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181818. # endif
  181819. # endif
  181820. #endif
  181821. #ifndef PNG_EXPORT
  181822. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181823. #endif
  181824. #ifdef PNG_USE_GLOBAL_ARRAYS
  181825. # ifndef PNG_EXPORT_VAR
  181826. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181827. # endif
  181828. #endif
  181829. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181830. * functions that are passed far data must be model independent.
  181831. */
  181832. #ifndef PNG_ABORT
  181833. # define PNG_ABORT() abort()
  181834. #endif
  181835. #ifdef PNG_SETJMP_SUPPORTED
  181836. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181837. #else
  181838. # define png_jmpbuf(png_ptr) \
  181839. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181840. #endif
  181841. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181842. /* use this to make far-to-near assignments */
  181843. # define CHECK 1
  181844. # define NOCHECK 0
  181845. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181846. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181847. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181848. # define png_strcpy _fstrcpy
  181849. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181850. # define png_strlen _fstrlen
  181851. # define png_memcmp _fmemcmp /* SJT: added */
  181852. # define png_memcpy _fmemcpy
  181853. # define png_memset _fmemset
  181854. #else /* use the usual functions */
  181855. # define CVT_PTR(ptr) (ptr)
  181856. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181857. # ifndef PNG_NO_SNPRINTF
  181858. # ifdef _MSC_VER
  181859. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181860. # define png_snprintf2 _snprintf
  181861. # define png_snprintf6 _snprintf
  181862. # else
  181863. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181864. # define png_snprintf2 snprintf
  181865. # define png_snprintf6 snprintf
  181866. # endif
  181867. # else
  181868. /* You don't have or don't want to use snprintf(). Caution: Using
  181869. * sprintf instead of snprintf exposes your application to accidental
  181870. * or malevolent buffer overflows. If you don't have snprintf()
  181871. * as a general rule you should provide one (you can get one from
  181872. * Portable OpenSSH). */
  181873. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181874. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181875. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181876. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181877. # endif
  181878. # define png_strcpy strcpy
  181879. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181880. # define png_strlen strlen
  181881. # define png_memcmp memcmp /* SJT: added */
  181882. # define png_memcpy memcpy
  181883. # define png_memset memset
  181884. #endif
  181885. /* End of memory model independent support */
  181886. /* Just a little check that someone hasn't tried to define something
  181887. * contradictory.
  181888. */
  181889. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181890. # undef PNG_ZBUF_SIZE
  181891. # define PNG_ZBUF_SIZE 65536L
  181892. #endif
  181893. /* Added at libpng-1.2.8 */
  181894. #endif /* PNG_VERSION_INFO_ONLY */
  181895. #endif /* PNGCONF_H */
  181896. /*** End of inlined file: pngconf.h ***/
  181897. #ifdef _MSC_VER
  181898. #pragma warning (disable: 4996 4100)
  181899. #endif
  181900. /*
  181901. * Added at libpng-1.2.8 */
  181902. /* Ref MSDN: Private as priority over Special
  181903. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181904. * procedures. If this value is given, the StringFileInfo block must
  181905. * contain a PrivateBuild string.
  181906. *
  181907. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181908. * standard release procedures but is a variation of the standard
  181909. * file of the same version number. If this value is given, the
  181910. * StringFileInfo block must contain a SpecialBuild string.
  181911. */
  181912. #if defined(PNG_USER_PRIVATEBUILD)
  181913. # define PNG_LIBPNG_BUILD_TYPE \
  181914. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181915. #else
  181916. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181917. # define PNG_LIBPNG_BUILD_TYPE \
  181918. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181919. # else
  181920. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181921. # endif
  181922. #endif
  181923. #ifndef PNG_VERSION_INFO_ONLY
  181924. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181925. #ifdef __cplusplus
  181926. //extern "C" {
  181927. #endif /* __cplusplus */
  181928. /* This file is arranged in several sections. The first section contains
  181929. * structure and type definitions. The second section contains the external
  181930. * library functions, while the third has the internal library functions,
  181931. * which applications aren't expected to use directly.
  181932. */
  181933. #ifndef PNG_NO_TYPECAST_NULL
  181934. #define int_p_NULL (int *)NULL
  181935. #define png_bytep_NULL (png_bytep)NULL
  181936. #define png_bytepp_NULL (png_bytepp)NULL
  181937. #define png_doublep_NULL (png_doublep)NULL
  181938. #define png_error_ptr_NULL (png_error_ptr)NULL
  181939. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181940. #define png_free_ptr_NULL (png_free_ptr)NULL
  181941. #define png_infopp_NULL (png_infopp)NULL
  181942. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181943. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181944. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181945. #define png_structp_NULL (png_structp)NULL
  181946. #define png_uint_16p_NULL (png_uint_16p)NULL
  181947. #define png_voidp_NULL (png_voidp)NULL
  181948. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181949. #else
  181950. #define int_p_NULL NULL
  181951. #define png_bytep_NULL NULL
  181952. #define png_bytepp_NULL NULL
  181953. #define png_doublep_NULL NULL
  181954. #define png_error_ptr_NULL NULL
  181955. #define png_flush_ptr_NULL NULL
  181956. #define png_free_ptr_NULL NULL
  181957. #define png_infopp_NULL NULL
  181958. #define png_malloc_ptr_NULL NULL
  181959. #define png_read_status_ptr_NULL NULL
  181960. #define png_rw_ptr_NULL NULL
  181961. #define png_structp_NULL NULL
  181962. #define png_uint_16p_NULL NULL
  181963. #define png_voidp_NULL NULL
  181964. #define png_write_status_ptr_NULL NULL
  181965. #endif
  181966. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181967. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181968. /* Version information for C files, stored in png.c. This had better match
  181969. * the version above.
  181970. */
  181971. #ifdef PNG_USE_GLOBAL_ARRAYS
  181972. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181973. /* need room for 99.99.99beta99z */
  181974. #else
  181975. #define png_libpng_ver png_get_header_ver(NULL)
  181976. #endif
  181977. #ifdef PNG_USE_GLOBAL_ARRAYS
  181978. /* This was removed in version 1.0.5c */
  181979. /* Structures to facilitate easy interlacing. See png.c for more details */
  181980. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181981. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181982. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181983. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181984. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181985. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181986. /* This isn't currently used. If you need it, see png.c for more details.
  181987. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181988. */
  181989. #endif
  181990. #endif /* PNG_NO_EXTERN */
  181991. /* Three color definitions. The order of the red, green, and blue, (and the
  181992. * exact size) is not important, although the size of the fields need to
  181993. * be png_byte or png_uint_16 (as defined below).
  181994. */
  181995. typedef struct png_color_struct
  181996. {
  181997. png_byte red;
  181998. png_byte green;
  181999. png_byte blue;
  182000. } png_color;
  182001. typedef png_color FAR * png_colorp;
  182002. typedef png_color FAR * FAR * png_colorpp;
  182003. typedef struct png_color_16_struct
  182004. {
  182005. png_byte index; /* used for palette files */
  182006. png_uint_16 red; /* for use in red green blue files */
  182007. png_uint_16 green;
  182008. png_uint_16 blue;
  182009. png_uint_16 gray; /* for use in grayscale files */
  182010. } png_color_16;
  182011. typedef png_color_16 FAR * png_color_16p;
  182012. typedef png_color_16 FAR * FAR * png_color_16pp;
  182013. typedef struct png_color_8_struct
  182014. {
  182015. png_byte red; /* for use in red green blue files */
  182016. png_byte green;
  182017. png_byte blue;
  182018. png_byte gray; /* for use in grayscale files */
  182019. png_byte alpha; /* for alpha channel files */
  182020. } png_color_8;
  182021. typedef png_color_8 FAR * png_color_8p;
  182022. typedef png_color_8 FAR * FAR * png_color_8pp;
  182023. /*
  182024. * The following two structures are used for the in-core representation
  182025. * of sPLT chunks.
  182026. */
  182027. typedef struct png_sPLT_entry_struct
  182028. {
  182029. png_uint_16 red;
  182030. png_uint_16 green;
  182031. png_uint_16 blue;
  182032. png_uint_16 alpha;
  182033. png_uint_16 frequency;
  182034. } png_sPLT_entry;
  182035. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182036. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182037. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182038. * occupy the LSB of their respective members, and the MSB of each member
  182039. * is zero-filled. The frequency member always occupies the full 16 bits.
  182040. */
  182041. typedef struct png_sPLT_struct
  182042. {
  182043. png_charp name; /* palette name */
  182044. png_byte depth; /* depth of palette samples */
  182045. png_sPLT_entryp entries; /* palette entries */
  182046. png_int_32 nentries; /* number of palette entries */
  182047. } png_sPLT_t;
  182048. typedef png_sPLT_t FAR * png_sPLT_tp;
  182049. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182050. #ifdef PNG_TEXT_SUPPORTED
  182051. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182052. * and whether that contents is compressed or not. The "key" field
  182053. * points to a regular zero-terminated C string. The "text", "lang", and
  182054. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182055. * However, the * structure returned by png_get_text() will always contain
  182056. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182057. * so they can be safely used in printf() and other string-handling functions.
  182058. */
  182059. typedef struct png_text_struct
  182060. {
  182061. int compression; /* compression value:
  182062. -1: tEXt, none
  182063. 0: zTXt, deflate
  182064. 1: iTXt, none
  182065. 2: iTXt, deflate */
  182066. png_charp key; /* keyword, 1-79 character description of "text" */
  182067. png_charp text; /* comment, may be an empty string (ie "")
  182068. or a NULL pointer */
  182069. png_size_t text_length; /* length of the text string */
  182070. #ifdef PNG_iTXt_SUPPORTED
  182071. png_size_t itxt_length; /* length of the itxt string */
  182072. png_charp lang; /* language code, 0-79 characters
  182073. or a NULL pointer */
  182074. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182075. chars or a NULL pointer */
  182076. #endif
  182077. } png_text;
  182078. typedef png_text FAR * png_textp;
  182079. typedef png_text FAR * FAR * png_textpp;
  182080. #endif
  182081. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182082. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182083. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182084. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182085. #define PNG_TEXT_COMPRESSION_NONE -1
  182086. #define PNG_TEXT_COMPRESSION_zTXt 0
  182087. #define PNG_ITXT_COMPRESSION_NONE 1
  182088. #define PNG_ITXT_COMPRESSION_zTXt 2
  182089. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182090. /* png_time is a way to hold the time in an machine independent way.
  182091. * Two conversions are provided, both from time_t and struct tm. There
  182092. * is no portable way to convert to either of these structures, as far
  182093. * as I know. If you know of a portable way, send it to me. As a side
  182094. * note - PNG has always been Year 2000 compliant!
  182095. */
  182096. typedef struct png_time_struct
  182097. {
  182098. png_uint_16 year; /* full year, as in, 1995 */
  182099. png_byte month; /* month of year, 1 - 12 */
  182100. png_byte day; /* day of month, 1 - 31 */
  182101. png_byte hour; /* hour of day, 0 - 23 */
  182102. png_byte minute; /* minute of hour, 0 - 59 */
  182103. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182104. } png_time;
  182105. typedef png_time FAR * png_timep;
  182106. typedef png_time FAR * FAR * png_timepp;
  182107. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182108. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182109. * no specific support. The idea is that we can use this to queue
  182110. * up private chunks for output even though the library doesn't actually
  182111. * know about their semantics.
  182112. */
  182113. typedef struct png_unknown_chunk_t
  182114. {
  182115. png_byte name[5];
  182116. png_byte *data;
  182117. png_size_t size;
  182118. /* libpng-using applications should NOT directly modify this byte. */
  182119. png_byte location; /* mode of operation at read time */
  182120. }
  182121. png_unknown_chunk;
  182122. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182123. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182124. #endif
  182125. /* png_info is a structure that holds the information in a PNG file so
  182126. * that the application can find out the characteristics of the image.
  182127. * If you are reading the file, this structure will tell you what is
  182128. * in the PNG file. If you are writing the file, fill in the information
  182129. * you want to put into the PNG file, then call png_write_info().
  182130. * The names chosen should be very close to the PNG specification, so
  182131. * consult that document for information about the meaning of each field.
  182132. *
  182133. * With libpng < 0.95, it was only possible to directly set and read the
  182134. * the values in the png_info_struct, which meant that the contents and
  182135. * order of the values had to remain fixed. With libpng 0.95 and later,
  182136. * however, there are now functions that abstract the contents of
  182137. * png_info_struct from the application, so this makes it easier to use
  182138. * libpng with dynamic libraries, and even makes it possible to use
  182139. * libraries that don't have all of the libpng ancillary chunk-handing
  182140. * functionality.
  182141. *
  182142. * In any case, the order of the parameters in png_info_struct should NOT
  182143. * be changed for as long as possible to keep compatibility with applications
  182144. * that use the old direct-access method with png_info_struct.
  182145. *
  182146. * The following members may have allocated storage attached that should be
  182147. * cleaned up before the structure is discarded: palette, trans, text,
  182148. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182149. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182150. * are automatically freed when the info structure is deallocated, if they were
  182151. * allocated internally by libpng. This behavior can be changed by means
  182152. * of the png_data_freer() function.
  182153. *
  182154. * More allocation details: all the chunk-reading functions that
  182155. * change these members go through the corresponding png_set_*
  182156. * functions. A function to clear these members is available: see
  182157. * png_free_data(). The png_set_* functions do not depend on being
  182158. * able to point info structure members to any of the storage they are
  182159. * passed (they make their own copies), EXCEPT that the png_set_text
  182160. * functions use the same storage passed to them in the text_ptr or
  182161. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182162. * functions do not make their own copies.
  182163. */
  182164. typedef struct png_info_struct
  182165. {
  182166. /* the following are necessary for every PNG file */
  182167. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182168. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182169. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182170. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182171. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182172. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182173. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182174. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182175. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182176. /* The following three should have been named *_method not *_type */
  182177. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182178. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182179. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182180. /* The following is informational only on read, and not used on writes. */
  182181. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182182. png_byte pixel_depth; /* number of bits per pixel */
  182183. png_byte spare_byte; /* to align the data, and for future use */
  182184. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182185. /* The rest of the data is optional. If you are reading, check the
  182186. * valid field to see if the information in these are valid. If you
  182187. * are writing, set the valid field to those chunks you want written,
  182188. * and initialize the appropriate fields below.
  182189. */
  182190. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182191. /* The gAMA chunk describes the gamma characteristics of the system
  182192. * on which the image was created, normally in the range [1.0, 2.5].
  182193. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182194. */
  182195. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182196. #endif
  182197. #if defined(PNG_sRGB_SUPPORTED)
  182198. /* GR-P, 0.96a */
  182199. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182200. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182201. #endif
  182202. #if defined(PNG_TEXT_SUPPORTED)
  182203. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182204. * uncompressed, compressed, and optionally compressed forms, respectively.
  182205. * The data in "text" is an array of pointers to uncompressed,
  182206. * null-terminated C strings. Each chunk has a keyword that describes the
  182207. * textual data contained in that chunk. Keywords are not required to be
  182208. * unique, and the text string may be empty. Any number of text chunks may
  182209. * be in an image.
  182210. */
  182211. int num_text; /* number of comments read/to write */
  182212. int max_text; /* current size of text array */
  182213. png_textp text; /* array of comments read/to write */
  182214. #endif /* PNG_TEXT_SUPPORTED */
  182215. #if defined(PNG_tIME_SUPPORTED)
  182216. /* The tIME chunk holds the last time the displayed image data was
  182217. * modified. See the png_time struct for the contents of this struct.
  182218. */
  182219. png_time mod_time;
  182220. #endif
  182221. #if defined(PNG_sBIT_SUPPORTED)
  182222. /* The sBIT chunk specifies the number of significant high-order bits
  182223. * in the pixel data. Values are in the range [1, bit_depth], and are
  182224. * only specified for the channels in the pixel data. The contents of
  182225. * the low-order bits is not specified. Data is valid if
  182226. * (valid & PNG_INFO_sBIT) is non-zero.
  182227. */
  182228. png_color_8 sig_bit; /* significant bits in color channels */
  182229. #endif
  182230. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182231. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182232. /* The tRNS chunk supplies transparency data for paletted images and
  182233. * other image types that don't need a full alpha channel. There are
  182234. * "num_trans" transparency values for a paletted image, stored in the
  182235. * same order as the palette colors, starting from index 0. Values
  182236. * for the data are in the range [0, 255], ranging from fully transparent
  182237. * to fully opaque, respectively. For non-paletted images, there is a
  182238. * single color specified that should be treated as fully transparent.
  182239. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182240. */
  182241. png_bytep trans; /* transparent values for paletted image */
  182242. png_color_16 trans_values; /* transparent color for non-palette image */
  182243. #endif
  182244. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182245. /* The bKGD chunk gives the suggested image background color if the
  182246. * display program does not have its own background color and the image
  182247. * is needs to composited onto a background before display. The colors
  182248. * in "background" are normally in the same color space/depth as the
  182249. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182250. */
  182251. png_color_16 background;
  182252. #endif
  182253. #if defined(PNG_oFFs_SUPPORTED)
  182254. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182255. * and downwards from the top-left corner of the display, page, or other
  182256. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182257. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182258. */
  182259. png_int_32 x_offset; /* x offset on page */
  182260. png_int_32 y_offset; /* y offset on page */
  182261. png_byte offset_unit_type; /* offset units type */
  182262. #endif
  182263. #if defined(PNG_pHYs_SUPPORTED)
  182264. /* The pHYs chunk gives the physical pixel density of the image for
  182265. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182266. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182267. */
  182268. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182269. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182270. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182271. #endif
  182272. #if defined(PNG_hIST_SUPPORTED)
  182273. /* The hIST chunk contains the relative frequency or importance of the
  182274. * various palette entries, so that a viewer can intelligently select a
  182275. * reduced-color palette, if required. Data is an array of "num_palette"
  182276. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182277. * is non-zero.
  182278. */
  182279. png_uint_16p hist;
  182280. #endif
  182281. #ifdef PNG_cHRM_SUPPORTED
  182282. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182283. * on which the PNG was created. This data allows the viewer to do gamut
  182284. * mapping of the input image to ensure that the viewer sees the same
  182285. * colors in the image as the creator. Values are in the range
  182286. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182287. */
  182288. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182289. float x_white;
  182290. float y_white;
  182291. float x_red;
  182292. float y_red;
  182293. float x_green;
  182294. float y_green;
  182295. float x_blue;
  182296. float y_blue;
  182297. #endif
  182298. #endif
  182299. #if defined(PNG_pCAL_SUPPORTED)
  182300. /* The pCAL chunk describes a transformation between the stored pixel
  182301. * values and original physical data values used to create the image.
  182302. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182303. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182304. * (possibly non-linear) transformation function given by "pcal_type"
  182305. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182306. * defines below, and the PNG-Group's PNG extensions document for a
  182307. * complete description of the transformations and how they should be
  182308. * implemented, and for a description of the ASCII parameter strings.
  182309. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182310. */
  182311. png_charp pcal_purpose; /* pCAL chunk description string */
  182312. png_int_32 pcal_X0; /* minimum value */
  182313. png_int_32 pcal_X1; /* maximum value */
  182314. png_charp pcal_units; /* Latin-1 string giving physical units */
  182315. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182316. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182317. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182318. #endif
  182319. /* New members added in libpng-1.0.6 */
  182320. #ifdef PNG_FREE_ME_SUPPORTED
  182321. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182322. #endif
  182323. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182324. /* storage for unknown chunks that the library doesn't recognize. */
  182325. png_unknown_chunkp unknown_chunks;
  182326. png_size_t unknown_chunks_num;
  182327. #endif
  182328. #if defined(PNG_iCCP_SUPPORTED)
  182329. /* iCCP chunk data. */
  182330. png_charp iccp_name; /* profile name */
  182331. png_charp iccp_profile; /* International Color Consortium profile data */
  182332. /* Note to maintainer: should be png_bytep */
  182333. png_uint_32 iccp_proflen; /* ICC profile data length */
  182334. png_byte iccp_compression; /* Always zero */
  182335. #endif
  182336. #if defined(PNG_sPLT_SUPPORTED)
  182337. /* data on sPLT chunks (there may be more than one). */
  182338. png_sPLT_tp splt_palettes;
  182339. png_uint_32 splt_palettes_num;
  182340. #endif
  182341. #if defined(PNG_sCAL_SUPPORTED)
  182342. /* The sCAL chunk describes the actual physical dimensions of the
  182343. * subject matter of the graphic. The chunk contains a unit specification
  182344. * a byte value, and two ASCII strings representing floating-point
  182345. * values. The values are width and height corresponsing to one pixel
  182346. * in the image. This external representation is converted to double
  182347. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182348. */
  182349. png_byte scal_unit; /* unit of physical scale */
  182350. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182351. double scal_pixel_width; /* width of one pixel */
  182352. double scal_pixel_height; /* height of one pixel */
  182353. #endif
  182354. #ifdef PNG_FIXED_POINT_SUPPORTED
  182355. png_charp scal_s_width; /* string containing height */
  182356. png_charp scal_s_height; /* string containing width */
  182357. #endif
  182358. #endif
  182359. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182360. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182361. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182362. png_bytepp row_pointers; /* the image bits */
  182363. #endif
  182364. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182365. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182366. #endif
  182367. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182368. png_fixed_point int_x_white;
  182369. png_fixed_point int_y_white;
  182370. png_fixed_point int_x_red;
  182371. png_fixed_point int_y_red;
  182372. png_fixed_point int_x_green;
  182373. png_fixed_point int_y_green;
  182374. png_fixed_point int_x_blue;
  182375. png_fixed_point int_y_blue;
  182376. #endif
  182377. } png_info;
  182378. typedef png_info FAR * png_infop;
  182379. typedef png_info FAR * FAR * png_infopp;
  182380. /* Maximum positive integer used in PNG is (2^31)-1 */
  182381. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182382. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182383. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182384. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182385. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182386. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182387. #endif
  182388. /* These describe the color_type field in png_info. */
  182389. /* color type masks */
  182390. #define PNG_COLOR_MASK_PALETTE 1
  182391. #define PNG_COLOR_MASK_COLOR 2
  182392. #define PNG_COLOR_MASK_ALPHA 4
  182393. /* color types. Note that not all combinations are legal */
  182394. #define PNG_COLOR_TYPE_GRAY 0
  182395. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182396. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182397. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182398. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182399. /* aliases */
  182400. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182401. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182402. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182403. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182404. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182405. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182406. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182407. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182408. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182409. /* These are for the interlacing type. These values should NOT be changed. */
  182410. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182411. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182412. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182413. /* These are for the oFFs chunk. These values should NOT be changed. */
  182414. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182415. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182416. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182417. /* These are for the pCAL chunk. These values should NOT be changed. */
  182418. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182419. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182420. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182421. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182422. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182423. /* These are for the sCAL chunk. These values should NOT be changed. */
  182424. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182425. #define PNG_SCALE_METER 1 /* meters per pixel */
  182426. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182427. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182428. /* These are for the pHYs chunk. These values should NOT be changed. */
  182429. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182430. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182431. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182432. /* These are for the sRGB chunk. These values should NOT be changed. */
  182433. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182434. #define PNG_sRGB_INTENT_RELATIVE 1
  182435. #define PNG_sRGB_INTENT_SATURATION 2
  182436. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182437. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182438. /* This is for text chunks */
  182439. #define PNG_KEYWORD_MAX_LENGTH 79
  182440. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182441. #define PNG_MAX_PALETTE_LENGTH 256
  182442. /* These determine if an ancillary chunk's data has been successfully read
  182443. * from the PNG header, or if the application has filled in the corresponding
  182444. * data in the info_struct to be written into the output file. The values
  182445. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182446. */
  182447. #define PNG_INFO_gAMA 0x0001
  182448. #define PNG_INFO_sBIT 0x0002
  182449. #define PNG_INFO_cHRM 0x0004
  182450. #define PNG_INFO_PLTE 0x0008
  182451. #define PNG_INFO_tRNS 0x0010
  182452. #define PNG_INFO_bKGD 0x0020
  182453. #define PNG_INFO_hIST 0x0040
  182454. #define PNG_INFO_pHYs 0x0080
  182455. #define PNG_INFO_oFFs 0x0100
  182456. #define PNG_INFO_tIME 0x0200
  182457. #define PNG_INFO_pCAL 0x0400
  182458. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182459. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182460. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182461. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182462. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182463. /* This is used for the transformation routines, as some of them
  182464. * change these values for the row. It also should enable using
  182465. * the routines for other purposes.
  182466. */
  182467. typedef struct png_row_info_struct
  182468. {
  182469. png_uint_32 width; /* width of row */
  182470. png_uint_32 rowbytes; /* number of bytes in row */
  182471. png_byte color_type; /* color type of row */
  182472. png_byte bit_depth; /* bit depth of row */
  182473. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182474. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182475. } png_row_info;
  182476. typedef png_row_info FAR * png_row_infop;
  182477. typedef png_row_info FAR * FAR * png_row_infopp;
  182478. /* These are the function types for the I/O functions and for the functions
  182479. * that allow the user to override the default I/O functions with his or her
  182480. * own. The png_error_ptr type should match that of user-supplied warning
  182481. * and error functions, while the png_rw_ptr type should match that of the
  182482. * user read/write data functions.
  182483. */
  182484. typedef struct png_struct_def png_struct;
  182485. typedef png_struct FAR * png_structp;
  182486. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182487. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182488. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182489. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182490. int));
  182491. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182492. int));
  182493. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182494. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182495. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182496. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182497. png_uint_32, int));
  182498. #endif
  182499. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182500. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182501. defined(PNG_LEGACY_SUPPORTED)
  182502. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182503. png_row_infop, png_bytep));
  182504. #endif
  182505. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182506. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182507. #endif
  182508. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182509. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182510. #endif
  182511. /* Transform masks for the high-level interface */
  182512. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182513. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182514. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182515. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182516. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182517. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182518. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182519. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182520. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182521. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182522. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182523. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182524. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182525. /* Flags for MNG supported features */
  182526. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182527. #define PNG_FLAG_MNG_FILTER_64 0x04
  182528. #define PNG_ALL_MNG_FEATURES 0x05
  182529. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182530. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182531. /* The structure that holds the information to read and write PNG files.
  182532. * The only people who need to care about what is inside of this are the
  182533. * people who will be modifying the library for their own special needs.
  182534. * It should NOT be accessed directly by an application, except to store
  182535. * the jmp_buf.
  182536. */
  182537. struct png_struct_def
  182538. {
  182539. #ifdef PNG_SETJMP_SUPPORTED
  182540. jmp_buf jmpbuf; /* used in png_error */
  182541. #endif
  182542. png_error_ptr error_fn; /* function for printing errors and aborting */
  182543. png_error_ptr warning_fn; /* function for printing warnings */
  182544. png_voidp error_ptr; /* user supplied struct for error functions */
  182545. png_rw_ptr write_data_fn; /* function for writing output data */
  182546. png_rw_ptr read_data_fn; /* function for reading input data */
  182547. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182548. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182549. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182550. #endif
  182551. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182552. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182553. #endif
  182554. /* These were added in libpng-1.0.2 */
  182555. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182556. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182557. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182558. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182559. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182560. png_byte user_transform_channels; /* channels in user transformed pixels */
  182561. #endif
  182562. #endif
  182563. png_uint_32 mode; /* tells us where we are in the PNG file */
  182564. png_uint_32 flags; /* flags indicating various things to libpng */
  182565. png_uint_32 transformations; /* which transformations to perform */
  182566. z_stream zstream; /* pointer to decompression structure (below) */
  182567. png_bytep zbuf; /* buffer for zlib */
  182568. png_size_t zbuf_size; /* size of zbuf */
  182569. int zlib_level; /* holds zlib compression level */
  182570. int zlib_method; /* holds zlib compression method */
  182571. int zlib_window_bits; /* holds zlib compression window bits */
  182572. int zlib_mem_level; /* holds zlib compression memory level */
  182573. int zlib_strategy; /* holds zlib compression strategy */
  182574. png_uint_32 width; /* width of image in pixels */
  182575. png_uint_32 height; /* height of image in pixels */
  182576. png_uint_32 num_rows; /* number of rows in current pass */
  182577. png_uint_32 usr_width; /* width of row at start of write */
  182578. png_uint_32 rowbytes; /* size of row in bytes */
  182579. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182580. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182581. png_uint_32 row_number; /* current row in interlace pass */
  182582. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182583. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182584. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182585. png_bytep up_row; /* buffer to save "up" row when filtering */
  182586. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182587. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182588. png_row_info row_info; /* used for transformation routines */
  182589. png_uint_32 idat_size; /* current IDAT size for read */
  182590. png_uint_32 crc; /* current chunk CRC value */
  182591. png_colorp palette; /* palette from the input file */
  182592. png_uint_16 num_palette; /* number of color entries in palette */
  182593. png_uint_16 num_trans; /* number of transparency values */
  182594. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182595. png_byte compression; /* file compression type (always 0) */
  182596. png_byte filter; /* file filter type (always 0) */
  182597. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182598. png_byte pass; /* current interlace pass (0 - 6) */
  182599. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182600. png_byte color_type; /* color type of file */
  182601. png_byte bit_depth; /* bit depth of file */
  182602. png_byte usr_bit_depth; /* bit depth of users row */
  182603. png_byte pixel_depth; /* number of bits per pixel */
  182604. png_byte channels; /* number of channels in file */
  182605. png_byte usr_channels; /* channels at start of write */
  182606. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182607. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182608. #ifdef PNG_LEGACY_SUPPORTED
  182609. png_byte filler; /* filler byte for pixel expansion */
  182610. #else
  182611. png_uint_16 filler; /* filler bytes for pixel expansion */
  182612. #endif
  182613. #endif
  182614. #if defined(PNG_bKGD_SUPPORTED)
  182615. png_byte background_gamma_type;
  182616. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182617. float background_gamma;
  182618. # endif
  182619. png_color_16 background; /* background color in screen gamma space */
  182620. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182621. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182622. #endif
  182623. #endif /* PNG_bKGD_SUPPORTED */
  182624. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182625. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182626. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182627. png_uint_32 flush_rows; /* number of rows written since last flush */
  182628. #endif
  182629. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182630. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182631. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182632. float gamma; /* file gamma value */
  182633. float screen_gamma; /* screen gamma value (display_exponent) */
  182634. #endif
  182635. #endif
  182636. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182637. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182638. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182639. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182640. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182641. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182642. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182643. #endif
  182644. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182645. png_color_8 sig_bit; /* significant bits in each available channel */
  182646. #endif
  182647. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182648. png_color_8 shift; /* shift for significant bit tranformation */
  182649. #endif
  182650. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182651. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182652. png_bytep trans; /* transparency values for paletted files */
  182653. png_color_16 trans_values; /* transparency values for non-paletted files */
  182654. #endif
  182655. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182656. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182657. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182658. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182659. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182660. png_progressive_end_ptr end_fn; /* called after image is complete */
  182661. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182662. png_bytep save_buffer; /* buffer for previously read data */
  182663. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182664. png_bytep current_buffer; /* buffer for recently used data */
  182665. png_uint_32 push_length; /* size of current input chunk */
  182666. png_uint_32 skip_length; /* bytes to skip in input data */
  182667. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182668. png_size_t save_buffer_max; /* total size of save_buffer */
  182669. png_size_t buffer_size; /* total amount of available input data */
  182670. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182671. int process_mode; /* what push library is currently doing */
  182672. int cur_palette; /* current push library palette index */
  182673. # if defined(PNG_TEXT_SUPPORTED)
  182674. png_size_t current_text_size; /* current size of text input data */
  182675. png_size_t current_text_left; /* how much text left to read in input */
  182676. png_charp current_text; /* current text chunk buffer */
  182677. png_charp current_text_ptr; /* current location in current_text */
  182678. # endif /* PNG_TEXT_SUPPORTED */
  182679. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182680. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182681. /* for the Borland special 64K segment handler */
  182682. png_bytepp offset_table_ptr;
  182683. png_bytep offset_table;
  182684. png_uint_16 offset_table_number;
  182685. png_uint_16 offset_table_count;
  182686. png_uint_16 offset_table_count_free;
  182687. #endif
  182688. #if defined(PNG_READ_DITHER_SUPPORTED)
  182689. png_bytep palette_lookup; /* lookup table for dithering */
  182690. png_bytep dither_index; /* index translation for palette files */
  182691. #endif
  182692. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182693. png_uint_16p hist; /* histogram */
  182694. #endif
  182695. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182696. png_byte heuristic_method; /* heuristic for row filter selection */
  182697. png_byte num_prev_filters; /* number of weights for previous rows */
  182698. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182699. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182700. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182701. png_uint_16p filter_costs; /* relative filter calculation cost */
  182702. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182703. #endif
  182704. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182705. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182706. #endif
  182707. /* New members added in libpng-1.0.6 */
  182708. #ifdef PNG_FREE_ME_SUPPORTED
  182709. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182710. #endif
  182711. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182712. png_voidp user_chunk_ptr;
  182713. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182714. #endif
  182715. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182716. int num_chunk_list;
  182717. png_bytep chunk_list;
  182718. #endif
  182719. /* New members added in libpng-1.0.3 */
  182720. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182721. png_byte rgb_to_gray_status;
  182722. /* These were changed from png_byte in libpng-1.0.6 */
  182723. png_uint_16 rgb_to_gray_red_coeff;
  182724. png_uint_16 rgb_to_gray_green_coeff;
  182725. png_uint_16 rgb_to_gray_blue_coeff;
  182726. #endif
  182727. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182728. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182729. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182730. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182731. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182732. #ifdef PNG_1_0_X
  182733. png_byte mng_features_permitted;
  182734. #else
  182735. png_uint_32 mng_features_permitted;
  182736. #endif /* PNG_1_0_X */
  182737. #endif
  182738. /* New member added in libpng-1.0.7 */
  182739. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182740. png_fixed_point int_gamma;
  182741. #endif
  182742. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182743. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182744. png_byte filter_type;
  182745. #endif
  182746. #if defined(PNG_1_0_X)
  182747. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182748. png_uint_32 row_buf_size;
  182749. #endif
  182750. /* New members added in libpng-1.2.0 */
  182751. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182752. # if !defined(PNG_1_0_X)
  182753. # if defined(PNG_MMX_CODE_SUPPORTED)
  182754. png_byte mmx_bitdepth_threshold;
  182755. png_uint_32 mmx_rowbytes_threshold;
  182756. # endif
  182757. png_uint_32 asm_flags;
  182758. # endif
  182759. #endif
  182760. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182761. #ifdef PNG_USER_MEM_SUPPORTED
  182762. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182763. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182764. png_free_ptr free_fn; /* function for freeing memory */
  182765. #endif
  182766. /* New member added in libpng-1.0.13 and 1.2.0 */
  182767. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182768. #if defined(PNG_READ_DITHER_SUPPORTED)
  182769. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182770. png_bytep dither_sort; /* working sort array */
  182771. png_bytep index_to_palette; /* where the original index currently is */
  182772. /* in the palette */
  182773. png_bytep palette_to_index; /* which original index points to this */
  182774. /* palette color */
  182775. #endif
  182776. /* New members added in libpng-1.0.16 and 1.2.6 */
  182777. png_byte compression_type;
  182778. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182779. png_uint_32 user_width_max;
  182780. png_uint_32 user_height_max;
  182781. #endif
  182782. /* New member added in libpng-1.0.25 and 1.2.17 */
  182783. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182784. /* storage for unknown chunk that the library doesn't recognize. */
  182785. png_unknown_chunk unknown_chunk;
  182786. #endif
  182787. };
  182788. /* This triggers a compiler error in png.c, if png.c and png.h
  182789. * do not agree upon the version number.
  182790. */
  182791. typedef png_structp version_1_2_21;
  182792. typedef png_struct FAR * FAR * png_structpp;
  182793. /* Here are the function definitions most commonly used. This is not
  182794. * the place to find out how to use libpng. See libpng.txt for the
  182795. * full explanation, see example.c for the summary. This just provides
  182796. * a simple one line description of the use of each function.
  182797. */
  182798. /* Returns the version number of the library */
  182799. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182800. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182801. * Handling more than 8 bytes from the beginning of the file is an error.
  182802. */
  182803. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182804. int num_bytes));
  182805. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182806. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182807. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182808. * start > 7 will always fail (ie return non-zero).
  182809. */
  182810. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182811. png_size_t num_to_check));
  182812. /* Simple signature checking function. This is the same as calling
  182813. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182814. */
  182815. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182816. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182817. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182818. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182819. png_error_ptr error_fn, png_error_ptr warn_fn));
  182820. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182821. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182822. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182823. png_error_ptr error_fn, png_error_ptr warn_fn));
  182824. #ifdef PNG_WRITE_SUPPORTED
  182825. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182826. PNGARG((png_structp png_ptr));
  182827. #endif
  182828. #ifdef PNG_WRITE_SUPPORTED
  182829. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182830. PNGARG((png_structp png_ptr, png_uint_32 size));
  182831. #endif
  182832. /* Reset the compression stream */
  182833. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182834. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182835. #ifdef PNG_USER_MEM_SUPPORTED
  182836. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182837. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182838. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182839. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182840. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182841. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182842. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182843. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182844. #endif
  182845. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182846. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182847. png_bytep chunk_name, png_bytep data, png_size_t length));
  182848. /* Write the start of a PNG chunk - length and chunk name. */
  182849. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182850. png_bytep chunk_name, png_uint_32 length));
  182851. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182852. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182853. png_bytep data, png_size_t length));
  182854. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182855. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182856. /* Allocate and initialize the info structure */
  182857. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182858. PNGARG((png_structp png_ptr));
  182859. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182860. /* Initialize the info structure (old interface - DEPRECATED) */
  182861. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182862. #undef png_info_init
  182863. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182864. png_sizeof(png_info));
  182865. #endif
  182866. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182867. png_size_t png_info_struct_size));
  182868. /* Writes all the PNG information before the image. */
  182869. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182870. png_infop info_ptr));
  182871. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182872. png_infop info_ptr));
  182873. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182874. /* read the information before the actual image data. */
  182875. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182876. png_infop info_ptr));
  182877. #endif
  182878. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182879. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182880. PNGARG((png_structp png_ptr, png_timep ptime));
  182881. #endif
  182882. #if !defined(_WIN32_WCE)
  182883. /* "time.h" functions are not supported on WindowsCE */
  182884. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182885. /* convert from a struct tm to png_time */
  182886. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182887. struct tm FAR * ttime));
  182888. /* convert from time_t to png_time. Uses gmtime() */
  182889. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182890. time_t ttime));
  182891. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182892. #endif /* _WIN32_WCE */
  182893. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182894. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182895. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182896. #if !defined(PNG_1_0_X)
  182897. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182898. png_ptr));
  182899. #endif
  182900. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182901. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182902. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182903. /* Deprecated */
  182904. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182905. #endif
  182906. #endif
  182907. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182908. /* Use blue, green, red order for pixels. */
  182909. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182910. #endif
  182911. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182912. /* Expand the grayscale to 24-bit RGB if necessary. */
  182913. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182914. #endif
  182915. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182916. /* Reduce RGB to grayscale. */
  182917. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182918. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182919. int error_action, double red, double green ));
  182920. #endif
  182921. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182922. int error_action, png_fixed_point red, png_fixed_point green ));
  182923. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182924. png_ptr));
  182925. #endif
  182926. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182927. png_colorp palette));
  182928. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182929. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182930. #endif
  182931. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182932. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182933. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182934. #endif
  182935. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182936. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182937. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182938. #endif
  182939. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182940. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182941. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182942. png_uint_32 filler, int flags));
  182943. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182944. #define PNG_FILLER_BEFORE 0
  182945. #define PNG_FILLER_AFTER 1
  182946. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182947. #if !defined(PNG_1_0_X)
  182948. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182949. png_uint_32 filler, int flags));
  182950. #endif
  182951. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182952. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182953. /* Swap bytes in 16-bit depth files. */
  182954. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182955. #endif
  182956. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182957. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182958. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182959. #endif
  182960. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182961. /* Swap packing order of pixels in bytes. */
  182962. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182963. #endif
  182964. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182965. /* Converts files to legal bit depths. */
  182966. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182967. png_color_8p true_bits));
  182968. #endif
  182969. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182970. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182971. /* Have the code handle the interlacing. Returns the number of passes. */
  182972. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182973. #endif
  182974. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182975. /* Invert monochrome files */
  182976. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182977. #endif
  182978. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182979. /* Handle alpha and tRNS by replacing with a background color. */
  182980. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182981. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182982. png_color_16p background_color, int background_gamma_code,
  182983. int need_expand, double background_gamma));
  182984. #endif
  182985. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182986. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182987. #define PNG_BACKGROUND_GAMMA_FILE 2
  182988. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182989. #endif
  182990. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182991. /* strip the second byte of information from a 16-bit depth file. */
  182992. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182993. #endif
  182994. #if defined(PNG_READ_DITHER_SUPPORTED)
  182995. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182996. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182997. png_colorp palette, int num_palette, int maximum_colors,
  182998. png_uint_16p histogram, int full_dither));
  182999. #endif
  183000. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183001. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183002. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183003. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183004. double screen_gamma, double default_file_gamma));
  183005. #endif
  183006. #endif
  183007. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183008. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183009. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183010. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183011. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183012. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183013. int empty_plte_permitted));
  183014. #endif
  183015. #endif
  183016. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183017. /* Set how many lines between output flushes - 0 for no flushing */
  183018. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183019. /* Flush the current PNG output buffer */
  183020. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183021. #endif
  183022. /* optional update palette with requested transformations */
  183023. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183024. /* optional call to update the users info structure */
  183025. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183026. png_infop info_ptr));
  183027. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183028. /* read one or more rows of image data. */
  183029. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183030. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183031. #endif
  183032. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183033. /* read a row of data. */
  183034. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183035. png_bytep row,
  183036. png_bytep display_row));
  183037. #endif
  183038. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183039. /* read the whole image into memory at once. */
  183040. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183041. png_bytepp image));
  183042. #endif
  183043. /* write a row of image data */
  183044. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183045. png_bytep row));
  183046. /* write a few rows of image data */
  183047. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183048. png_bytepp row, png_uint_32 num_rows));
  183049. /* write the image data */
  183050. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183051. png_bytepp image));
  183052. /* writes the end of the PNG file. */
  183053. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183054. png_infop info_ptr));
  183055. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183056. /* read the end of the PNG file. */
  183057. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183058. png_infop info_ptr));
  183059. #endif
  183060. /* free any memory associated with the png_info_struct */
  183061. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183062. png_infopp info_ptr_ptr));
  183063. /* free any memory associated with the png_struct and the png_info_structs */
  183064. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183065. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183066. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183067. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183068. png_infop end_info_ptr));
  183069. /* free any memory associated with the png_struct and the png_info_structs */
  183070. extern PNG_EXPORT(void,png_destroy_write_struct)
  183071. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183072. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183073. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183074. /* set the libpng method of handling chunk CRC errors */
  183075. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183076. int crit_action, int ancil_action));
  183077. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183078. * ancillary and critical chunks, and whether to use the data contained
  183079. * therein. Note that it is impossible to "discard" data in a critical
  183080. * chunk. For versions prior to 0.90, the action was always error/quit,
  183081. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183082. * chunks is warn/discard. These values should NOT be changed.
  183083. *
  183084. * value action:critical action:ancillary
  183085. */
  183086. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183087. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183088. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183089. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183090. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183091. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183092. /* These functions give the user control over the scan-line filtering in
  183093. * libpng and the compression methods used by zlib. These functions are
  183094. * mainly useful for testing, as the defaults should work with most users.
  183095. * Those users who are tight on memory or want faster performance at the
  183096. * expense of compression can modify them. See the compression library
  183097. * header file (zlib.h) for an explination of the compression functions.
  183098. */
  183099. /* set the filtering method(s) used by libpng. Currently, the only valid
  183100. * value for "method" is 0.
  183101. */
  183102. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183103. int filters));
  183104. /* Flags for png_set_filter() to say which filters to use. The flags
  183105. * are chosen so that they don't conflict with real filter types
  183106. * below, in case they are supplied instead of the #defined constants.
  183107. * These values should NOT be changed.
  183108. */
  183109. #define PNG_NO_FILTERS 0x00
  183110. #define PNG_FILTER_NONE 0x08
  183111. #define PNG_FILTER_SUB 0x10
  183112. #define PNG_FILTER_UP 0x20
  183113. #define PNG_FILTER_AVG 0x40
  183114. #define PNG_FILTER_PAETH 0x80
  183115. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183116. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183117. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183118. * These defines should NOT be changed.
  183119. */
  183120. #define PNG_FILTER_VALUE_NONE 0
  183121. #define PNG_FILTER_VALUE_SUB 1
  183122. #define PNG_FILTER_VALUE_UP 2
  183123. #define PNG_FILTER_VALUE_AVG 3
  183124. #define PNG_FILTER_VALUE_PAETH 4
  183125. #define PNG_FILTER_VALUE_LAST 5
  183126. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183127. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183128. * defines, either the default (minimum-sum-of-absolute-differences), or
  183129. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183130. *
  183131. * Weights are factors >= 1.0, indicating how important it is to keep the
  183132. * filter type consistent between rows. Larger numbers mean the current
  183133. * filter is that many times as likely to be the same as the "num_weights"
  183134. * previous filters. This is cumulative for each previous row with a weight.
  183135. * There needs to be "num_weights" values in "filter_weights", or it can be
  183136. * NULL if the weights aren't being specified. Weights have no influence on
  183137. * the selection of the first row filter. Well chosen weights can (in theory)
  183138. * improve the compression for a given image.
  183139. *
  183140. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183141. * filter type. Higher costs indicate more decoding expense, and are
  183142. * therefore less likely to be selected over a filter with lower computational
  183143. * costs. There needs to be a value in "filter_costs" for each valid filter
  183144. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183145. * setting the costs. Costs try to improve the speed of decompression without
  183146. * unduly increasing the compressed image size.
  183147. *
  183148. * A negative weight or cost indicates the default value is to be used, and
  183149. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183150. * The default values for both weights and costs are currently 1.0, but may
  183151. * change if good general weighting/cost heuristics can be found. If both
  183152. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183153. * to the UNWEIGHTED method, but with added encoding time/computation.
  183154. */
  183155. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183156. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183157. int heuristic_method, int num_weights, png_doublep filter_weights,
  183158. png_doublep filter_costs));
  183159. #endif
  183160. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183161. /* Heuristic used for row filter selection. These defines should NOT be
  183162. * changed.
  183163. */
  183164. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183165. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183166. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183167. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183168. /* Set the library compression level. Currently, valid values range from
  183169. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183170. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183171. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183172. * for PNG images, and do considerably fewer caclulations. In the future,
  183173. * these values may not correspond directly to the zlib compression levels.
  183174. */
  183175. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183176. int level));
  183177. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183178. PNGARG((png_structp png_ptr, int mem_level));
  183179. extern PNG_EXPORT(void,png_set_compression_strategy)
  183180. PNGARG((png_structp png_ptr, int strategy));
  183181. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183182. PNGARG((png_structp png_ptr, int window_bits));
  183183. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183184. int method));
  183185. /* These next functions are called for input/output, memory, and error
  183186. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183187. * and call standard C I/O routines such as fread(), fwrite(), and
  183188. * fprintf(). These functions can be made to use other I/O routines
  183189. * at run time for those applications that need to handle I/O in a
  183190. * different manner by calling png_set_???_fn(). See libpng.txt for
  183191. * more information.
  183192. */
  183193. #if !defined(PNG_NO_STDIO)
  183194. /* Initialize the input/output for the PNG file to the default functions. */
  183195. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183196. #endif
  183197. /* Replace the (error and abort), and warning functions with user
  183198. * supplied functions. If no messages are to be printed you must still
  183199. * write and use replacement functions. The replacement error_fn should
  183200. * still do a longjmp to the last setjmp location if you are using this
  183201. * method of error handling. If error_fn or warning_fn is NULL, the
  183202. * default function will be used.
  183203. */
  183204. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183205. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183206. /* Return the user pointer associated with the error functions */
  183207. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183208. /* Replace the default data output functions with a user supplied one(s).
  183209. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183210. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183211. * output_flush_fn will be ignored (and thus can be NULL).
  183212. */
  183213. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183214. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183215. /* Replace the default data input function with a user supplied one. */
  183216. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183217. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183218. /* Return the user pointer associated with the I/O functions */
  183219. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183220. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183221. png_read_status_ptr read_row_fn));
  183222. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183223. png_write_status_ptr write_row_fn));
  183224. #ifdef PNG_USER_MEM_SUPPORTED
  183225. /* Replace the default memory allocation functions with user supplied one(s). */
  183226. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183227. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183228. /* Return the user pointer associated with the memory functions */
  183229. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183230. #endif
  183231. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183232. defined(PNG_LEGACY_SUPPORTED)
  183233. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183234. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183235. #endif
  183236. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183237. defined(PNG_LEGACY_SUPPORTED)
  183238. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183239. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183240. #endif
  183241. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183242. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183243. defined(PNG_LEGACY_SUPPORTED)
  183244. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183245. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183246. int user_transform_channels));
  183247. /* Return the user pointer associated with the user transform functions */
  183248. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183249. PNGARG((png_structp png_ptr));
  183250. #endif
  183251. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183252. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183253. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183254. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183255. png_ptr));
  183256. #endif
  183257. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183258. /* Sets the function callbacks for the push reader, and a pointer to a
  183259. * user-defined structure available to the callback functions.
  183260. */
  183261. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183262. png_voidp progressive_ptr,
  183263. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183264. png_progressive_end_ptr end_fn));
  183265. /* returns the user pointer associated with the push read functions */
  183266. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183267. PNGARG((png_structp png_ptr));
  183268. /* function to be called when data becomes available */
  183269. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183270. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183271. /* function that combines rows. Not very much different than the
  183272. * png_combine_row() call. Is this even used?????
  183273. */
  183274. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183275. png_bytep old_row, png_bytep new_row));
  183276. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183277. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183278. png_uint_32 size));
  183279. #if defined(PNG_1_0_X)
  183280. # define png_malloc_warn png_malloc
  183281. #else
  183282. /* Added at libpng version 1.2.4 */
  183283. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183284. png_uint_32 size));
  183285. #endif
  183286. /* frees a pointer allocated by png_malloc() */
  183287. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183288. #if defined(PNG_1_0_X)
  183289. /* Function to allocate memory for zlib. */
  183290. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183291. uInt size));
  183292. /* Function to free memory for zlib */
  183293. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183294. #endif
  183295. /* Free data that was allocated internally */
  183296. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183297. png_infop info_ptr, png_uint_32 free_me, int num));
  183298. #ifdef PNG_FREE_ME_SUPPORTED
  183299. /* Reassign responsibility for freeing existing data, whether allocated
  183300. * by libpng or by the application */
  183301. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183302. png_infop info_ptr, int freer, png_uint_32 mask));
  183303. #endif
  183304. /* assignments for png_data_freer */
  183305. #define PNG_DESTROY_WILL_FREE_DATA 1
  183306. #define PNG_SET_WILL_FREE_DATA 1
  183307. #define PNG_USER_WILL_FREE_DATA 2
  183308. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183309. #define PNG_FREE_HIST 0x0008
  183310. #define PNG_FREE_ICCP 0x0010
  183311. #define PNG_FREE_SPLT 0x0020
  183312. #define PNG_FREE_ROWS 0x0040
  183313. #define PNG_FREE_PCAL 0x0080
  183314. #define PNG_FREE_SCAL 0x0100
  183315. #define PNG_FREE_UNKN 0x0200
  183316. #define PNG_FREE_LIST 0x0400
  183317. #define PNG_FREE_PLTE 0x1000
  183318. #define PNG_FREE_TRNS 0x2000
  183319. #define PNG_FREE_TEXT 0x4000
  183320. #define PNG_FREE_ALL 0x7fff
  183321. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183322. #ifdef PNG_USER_MEM_SUPPORTED
  183323. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183324. png_uint_32 size));
  183325. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183326. png_voidp ptr));
  183327. #endif
  183328. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183329. png_voidp s1, png_voidp s2, png_uint_32 size));
  183330. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183331. png_voidp s1, int value, png_uint_32 size));
  183332. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183333. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183334. int check));
  183335. #endif /* USE_FAR_KEYWORD */
  183336. #ifndef PNG_NO_ERROR_TEXT
  183337. /* Fatal error in PNG image of libpng - can't continue */
  183338. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183339. png_const_charp error_message));
  183340. /* The same, but the chunk name is prepended to the error string. */
  183341. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183342. png_const_charp error_message));
  183343. #else
  183344. /* Fatal error in PNG image of libpng - can't continue */
  183345. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183346. #endif
  183347. #ifndef PNG_NO_WARNINGS
  183348. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183349. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183350. png_const_charp warning_message));
  183351. #ifdef PNG_READ_SUPPORTED
  183352. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183353. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183354. png_const_charp warning_message));
  183355. #endif /* PNG_READ_SUPPORTED */
  183356. #endif /* PNG_NO_WARNINGS */
  183357. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183358. * Similarly, the png_get_<chunk> calls are used to read values from the
  183359. * png_info_struct, either storing the parameters in the passed variables, or
  183360. * setting pointers into the png_info_struct where the data is stored. The
  183361. * png_get_<chunk> functions return a non-zero value if the data was available
  183362. * in info_ptr, or return zero and do not change any of the parameters if the
  183363. * data was not available.
  183364. *
  183365. * These functions should be used instead of directly accessing png_info
  183366. * to avoid problems with future changes in the size and internal layout of
  183367. * png_info_struct.
  183368. */
  183369. /* Returns "flag" if chunk data is valid in info_ptr. */
  183370. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183371. png_infop info_ptr, png_uint_32 flag));
  183372. /* Returns number of bytes needed to hold a transformed row. */
  183373. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183374. png_infop info_ptr));
  183375. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183376. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183377. returned from png_read_png(). */
  183378. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183379. png_infop info_ptr));
  183380. /* Set row_pointers, which is an array of pointers to scanlines for use
  183381. by png_write_png(). */
  183382. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183383. png_infop info_ptr, png_bytepp row_pointers));
  183384. #endif
  183385. /* Returns number of color channels in image. */
  183386. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183387. png_infop info_ptr));
  183388. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183389. /* Returns image width in pixels. */
  183390. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183391. png_ptr, png_infop info_ptr));
  183392. /* Returns image height in pixels. */
  183393. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183394. png_ptr, png_infop info_ptr));
  183395. /* Returns image bit_depth. */
  183396. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183397. png_ptr, png_infop info_ptr));
  183398. /* Returns image color_type. */
  183399. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183400. png_ptr, png_infop info_ptr));
  183401. /* Returns image filter_type. */
  183402. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183403. png_ptr, png_infop info_ptr));
  183404. /* Returns image interlace_type. */
  183405. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183406. png_ptr, png_infop info_ptr));
  183407. /* Returns image compression_type. */
  183408. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183409. png_ptr, png_infop info_ptr));
  183410. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183411. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183412. png_ptr, png_infop info_ptr));
  183413. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183414. png_ptr, png_infop info_ptr));
  183415. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183416. png_ptr, png_infop info_ptr));
  183417. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183418. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183419. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183420. png_ptr, png_infop info_ptr));
  183421. #endif
  183422. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183423. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183424. png_ptr, png_infop info_ptr));
  183425. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183426. png_ptr, png_infop info_ptr));
  183427. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183428. png_ptr, png_infop info_ptr));
  183429. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183430. png_ptr, png_infop info_ptr));
  183431. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183432. /* Returns pointer to signature string read from PNG header */
  183433. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183434. png_infop info_ptr));
  183435. #if defined(PNG_bKGD_SUPPORTED)
  183436. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183437. png_infop info_ptr, png_color_16p *background));
  183438. #endif
  183439. #if defined(PNG_bKGD_SUPPORTED)
  183440. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183441. png_infop info_ptr, png_color_16p background));
  183442. #endif
  183443. #if defined(PNG_cHRM_SUPPORTED)
  183444. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183445. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183446. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183447. double *red_y, double *green_x, double *green_y, double *blue_x,
  183448. double *blue_y));
  183449. #endif
  183450. #ifdef PNG_FIXED_POINT_SUPPORTED
  183451. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183452. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183453. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183454. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183455. *int_blue_x, png_fixed_point *int_blue_y));
  183456. #endif
  183457. #endif
  183458. #if defined(PNG_cHRM_SUPPORTED)
  183459. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183460. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183461. png_infop info_ptr, double white_x, double white_y, double red_x,
  183462. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183463. #endif
  183464. #ifdef PNG_FIXED_POINT_SUPPORTED
  183465. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183466. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183467. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183468. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183469. png_fixed_point int_blue_y));
  183470. #endif
  183471. #endif
  183472. #if defined(PNG_gAMA_SUPPORTED)
  183473. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183474. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183475. png_infop info_ptr, double *file_gamma));
  183476. #endif
  183477. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183478. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183479. #endif
  183480. #if defined(PNG_gAMA_SUPPORTED)
  183481. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183482. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183483. png_infop info_ptr, double file_gamma));
  183484. #endif
  183485. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183486. png_infop info_ptr, png_fixed_point int_file_gamma));
  183487. #endif
  183488. #if defined(PNG_hIST_SUPPORTED)
  183489. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183490. png_infop info_ptr, png_uint_16p *hist));
  183491. #endif
  183492. #if defined(PNG_hIST_SUPPORTED)
  183493. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183494. png_infop info_ptr, png_uint_16p hist));
  183495. #endif
  183496. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183497. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183498. int *bit_depth, int *color_type, int *interlace_method,
  183499. int *compression_method, int *filter_method));
  183500. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183501. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183502. int color_type, int interlace_method, int compression_method,
  183503. int filter_method));
  183504. #if defined(PNG_oFFs_SUPPORTED)
  183505. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183506. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183507. int *unit_type));
  183508. #endif
  183509. #if defined(PNG_oFFs_SUPPORTED)
  183510. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183511. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183512. int unit_type));
  183513. #endif
  183514. #if defined(PNG_pCAL_SUPPORTED)
  183515. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183516. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183517. int *type, int *nparams, png_charp *units, png_charpp *params));
  183518. #endif
  183519. #if defined(PNG_pCAL_SUPPORTED)
  183520. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183521. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183522. int type, int nparams, png_charp units, png_charpp params));
  183523. #endif
  183524. #if defined(PNG_pHYs_SUPPORTED)
  183525. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183526. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183527. #endif
  183528. #if defined(PNG_pHYs_SUPPORTED)
  183529. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183530. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183531. #endif
  183532. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183533. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183534. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183535. png_infop info_ptr, png_colorp palette, int num_palette));
  183536. #if defined(PNG_sBIT_SUPPORTED)
  183537. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183538. png_infop info_ptr, png_color_8p *sig_bit));
  183539. #endif
  183540. #if defined(PNG_sBIT_SUPPORTED)
  183541. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183542. png_infop info_ptr, png_color_8p sig_bit));
  183543. #endif
  183544. #if defined(PNG_sRGB_SUPPORTED)
  183545. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183546. png_infop info_ptr, int *intent));
  183547. #endif
  183548. #if defined(PNG_sRGB_SUPPORTED)
  183549. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183550. png_infop info_ptr, int intent));
  183551. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183552. png_infop info_ptr, int intent));
  183553. #endif
  183554. #if defined(PNG_iCCP_SUPPORTED)
  183555. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183556. png_infop info_ptr, png_charpp name, int *compression_type,
  183557. png_charpp profile, png_uint_32 *proflen));
  183558. /* Note to maintainer: profile should be png_bytepp */
  183559. #endif
  183560. #if defined(PNG_iCCP_SUPPORTED)
  183561. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183562. png_infop info_ptr, png_charp name, int compression_type,
  183563. png_charp profile, png_uint_32 proflen));
  183564. /* Note to maintainer: profile should be png_bytep */
  183565. #endif
  183566. #if defined(PNG_sPLT_SUPPORTED)
  183567. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183568. png_infop info_ptr, png_sPLT_tpp entries));
  183569. #endif
  183570. #if defined(PNG_sPLT_SUPPORTED)
  183571. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183572. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183573. #endif
  183574. #if defined(PNG_TEXT_SUPPORTED)
  183575. /* png_get_text also returns the number of text chunks in *num_text */
  183576. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183577. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183578. #endif
  183579. /*
  183580. * Note while png_set_text() will accept a structure whose text,
  183581. * language, and translated keywords are NULL pointers, the structure
  183582. * returned by png_get_text will always contain regular
  183583. * zero-terminated C strings. They might be empty strings but
  183584. * they will never be NULL pointers.
  183585. */
  183586. #if defined(PNG_TEXT_SUPPORTED)
  183587. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183588. png_infop info_ptr, png_textp text_ptr, int num_text));
  183589. #endif
  183590. #if defined(PNG_tIME_SUPPORTED)
  183591. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183592. png_infop info_ptr, png_timep *mod_time));
  183593. #endif
  183594. #if defined(PNG_tIME_SUPPORTED)
  183595. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183596. png_infop info_ptr, png_timep mod_time));
  183597. #endif
  183598. #if defined(PNG_tRNS_SUPPORTED)
  183599. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183600. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183601. png_color_16p *trans_values));
  183602. #endif
  183603. #if defined(PNG_tRNS_SUPPORTED)
  183604. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183605. png_infop info_ptr, png_bytep trans, int num_trans,
  183606. png_color_16p trans_values));
  183607. #endif
  183608. #if defined(PNG_tRNS_SUPPORTED)
  183609. #endif
  183610. #if defined(PNG_sCAL_SUPPORTED)
  183611. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183612. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183613. png_infop info_ptr, int *unit, double *width, double *height));
  183614. #else
  183615. #ifdef PNG_FIXED_POINT_SUPPORTED
  183616. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183617. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183618. #endif
  183619. #endif
  183620. #endif /* PNG_sCAL_SUPPORTED */
  183621. #if defined(PNG_sCAL_SUPPORTED)
  183622. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183623. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183624. png_infop info_ptr, int unit, double width, double height));
  183625. #else
  183626. #ifdef PNG_FIXED_POINT_SUPPORTED
  183627. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183628. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183629. #endif
  183630. #endif
  183631. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183632. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183633. /* provide a list of chunks and how they are to be handled, if the built-in
  183634. handling or default unknown chunk handling is not desired. Any chunks not
  183635. listed will be handled in the default manner. The IHDR and IEND chunks
  183636. must not be listed.
  183637. keep = 0: follow default behaviour
  183638. = 1: do not keep
  183639. = 2: keep only if safe-to-copy
  183640. = 3: keep even if unsafe-to-copy
  183641. */
  183642. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183643. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183644. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183645. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183646. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183647. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183648. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183649. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183650. #endif
  183651. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183652. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183653. chunk_name));
  183654. #endif
  183655. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183656. If you need to turn it off for a chunk that your application has freed,
  183657. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183658. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183659. png_infop info_ptr, int mask));
  183660. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183661. /* The "params" pointer is currently not used and is for future expansion. */
  183662. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183663. png_infop info_ptr,
  183664. int transforms,
  183665. png_voidp params));
  183666. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183667. png_infop info_ptr,
  183668. int transforms,
  183669. png_voidp params));
  183670. #endif
  183671. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183672. * numbers for PNG_DEBUG mean more debugging information. This has
  183673. * only been added since version 0.95 so it is not implemented throughout
  183674. * libpng yet, but more support will be added as needed.
  183675. */
  183676. #ifdef PNG_DEBUG
  183677. #if (PNG_DEBUG > 0)
  183678. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183679. #include <crtdbg.h>
  183680. #if (PNG_DEBUG > 1)
  183681. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183682. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183683. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183684. #endif
  183685. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183686. #ifndef PNG_DEBUG_FILE
  183687. #define PNG_DEBUG_FILE stderr
  183688. #endif /* PNG_DEBUG_FILE */
  183689. #if (PNG_DEBUG > 1)
  183690. #define png_debug(l,m) \
  183691. { \
  183692. int num_tabs=l; \
  183693. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183694. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183695. }
  183696. #define png_debug1(l,m,p1) \
  183697. { \
  183698. int num_tabs=l; \
  183699. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183700. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183701. }
  183702. #define png_debug2(l,m,p1,p2) \
  183703. { \
  183704. int num_tabs=l; \
  183705. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183706. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183707. }
  183708. #endif /* (PNG_DEBUG > 1) */
  183709. #endif /* _MSC_VER */
  183710. #endif /* (PNG_DEBUG > 0) */
  183711. #endif /* PNG_DEBUG */
  183712. #ifndef png_debug
  183713. #define png_debug(l, m)
  183714. #endif
  183715. #ifndef png_debug1
  183716. #define png_debug1(l, m, p1)
  183717. #endif
  183718. #ifndef png_debug2
  183719. #define png_debug2(l, m, p1, p2)
  183720. #endif
  183721. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183722. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183723. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183724. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183725. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183726. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183727. png_ptr, png_uint_32 mng_features_permitted));
  183728. #endif
  183729. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183730. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183731. #define PNG_HANDLE_CHUNK_NEVER 1
  183732. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183733. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183734. /* Added to version 1.2.0 */
  183735. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183736. #if defined(PNG_MMX_CODE_SUPPORTED)
  183737. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183738. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183739. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183740. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183741. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183742. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183743. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183744. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183745. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183746. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183747. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183748. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183749. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183750. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183751. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183752. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183753. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183754. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183755. | PNG_MMX_READ_FLAGS \
  183756. | PNG_MMX_WRITE_FLAGS )
  183757. #define PNG_SELECT_READ 1
  183758. #define PNG_SELECT_WRITE 2
  183759. #endif /* PNG_MMX_CODE_SUPPORTED */
  183760. #if !defined(PNG_1_0_X)
  183761. /* pngget.c */
  183762. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183763. PNGARG((int flag_select, int *compilerID));
  183764. /* pngget.c */
  183765. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183766. PNGARG((int flag_select));
  183767. /* pngget.c */
  183768. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183769. PNGARG((png_structp png_ptr));
  183770. /* pngget.c */
  183771. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183772. PNGARG((png_structp png_ptr));
  183773. /* pngget.c */
  183774. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183775. PNGARG((png_structp png_ptr));
  183776. /* pngset.c */
  183777. extern PNG_EXPORT(void,png_set_asm_flags)
  183778. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183779. /* pngset.c */
  183780. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183781. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183782. png_uint_32 mmx_rowbytes_threshold));
  183783. #endif /* PNG_1_0_X */
  183784. #if !defined(PNG_1_0_X)
  183785. /* png.c, pnggccrd.c, or pngvcrd.c */
  183786. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183787. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183788. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183789. * messages before passing them to the error or warning handler. */
  183790. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183791. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183792. png_ptr, png_uint_32 strip_mode));
  183793. #endif
  183794. #endif /* PNG_1_0_X */
  183795. /* Added at libpng-1.2.6 */
  183796. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183797. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183798. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183799. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183800. png_ptr));
  183801. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183802. png_ptr));
  183803. #endif
  183804. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183805. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183806. /* With these routines we avoid an integer divide, which will be slower on
  183807. * most machines. However, it does take more operations than the corresponding
  183808. * divide method, so it may be slower on a few RISC systems. There are two
  183809. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183810. *
  183811. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183812. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183813. * standard method.
  183814. *
  183815. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183816. */
  183817. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183818. # define png_composite(composite, fg, alpha, bg) \
  183819. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183820. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183821. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183822. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183823. # define png_composite_16(composite, fg, alpha, bg) \
  183824. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183825. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183826. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183827. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183828. #else /* standard method using integer division */
  183829. # define png_composite(composite, fg, alpha, bg) \
  183830. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183831. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183832. (png_uint_16)127) / 255)
  183833. # define png_composite_16(composite, fg, alpha, bg) \
  183834. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183835. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183836. (png_uint_32)32767) / (png_uint_32)65535L)
  183837. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183838. /* Inline macros to do direct reads of bytes from the input buffer. These
  183839. * require that you are using an architecture that uses PNG byte ordering
  183840. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183841. * in big-endian mode and 680x0 are the only ones that will support this.
  183842. * The x86 line of processors definitely do not. The png_get_int_32()
  183843. * routine also assumes we are using two's complement format for negative
  183844. * values, which is almost certainly true.
  183845. */
  183846. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183847. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183848. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183849. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183850. #else
  183851. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183852. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183853. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183854. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183855. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183856. PNGARG((png_structp png_ptr, png_bytep buf));
  183857. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183858. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183859. */
  183860. extern PNG_EXPORT(void,png_save_uint_32)
  183861. PNGARG((png_bytep buf, png_uint_32 i));
  183862. extern PNG_EXPORT(void,png_save_int_32)
  183863. PNGARG((png_bytep buf, png_int_32 i));
  183864. /* Place a 16-bit number into a buffer in PNG byte order.
  183865. * The parameter is declared unsigned int, not png_uint_16,
  183866. * just to avoid potential problems on pre-ANSI C compilers.
  183867. */
  183868. extern PNG_EXPORT(void,png_save_uint_16)
  183869. PNGARG((png_bytep buf, unsigned int i));
  183870. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183871. /* ************************************************************************* */
  183872. /* These next functions are used internally in the code. They generally
  183873. * shouldn't be used unless you are writing code to add or replace some
  183874. * functionality in libpng. More information about most functions can
  183875. * be found in the files where the functions are located.
  183876. */
  183877. /* Various modes of operation, that are visible to applications because
  183878. * they are used for unknown chunk location.
  183879. */
  183880. #define PNG_HAVE_IHDR 0x01
  183881. #define PNG_HAVE_PLTE 0x02
  183882. #define PNG_HAVE_IDAT 0x04
  183883. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183884. #define PNG_HAVE_IEND 0x10
  183885. #if defined(PNG_INTERNAL)
  183886. /* More modes of operation. Note that after an init, mode is set to
  183887. * zero automatically when the structure is created.
  183888. */
  183889. #define PNG_HAVE_gAMA 0x20
  183890. #define PNG_HAVE_cHRM 0x40
  183891. #define PNG_HAVE_sRGB 0x80
  183892. #define PNG_HAVE_CHUNK_HEADER 0x100
  183893. #define PNG_WROTE_tIME 0x200
  183894. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183895. #define PNG_BACKGROUND_IS_GRAY 0x800
  183896. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183897. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183898. /* flags for the transformations the PNG library does on the image data */
  183899. #define PNG_BGR 0x0001
  183900. #define PNG_INTERLACE 0x0002
  183901. #define PNG_PACK 0x0004
  183902. #define PNG_SHIFT 0x0008
  183903. #define PNG_SWAP_BYTES 0x0010
  183904. #define PNG_INVERT_MONO 0x0020
  183905. #define PNG_DITHER 0x0040
  183906. #define PNG_BACKGROUND 0x0080
  183907. #define PNG_BACKGROUND_EXPAND 0x0100
  183908. /* 0x0200 unused */
  183909. #define PNG_16_TO_8 0x0400
  183910. #define PNG_RGBA 0x0800
  183911. #define PNG_EXPAND 0x1000
  183912. #define PNG_GAMMA 0x2000
  183913. #define PNG_GRAY_TO_RGB 0x4000
  183914. #define PNG_FILLER 0x8000L
  183915. #define PNG_PACKSWAP 0x10000L
  183916. #define PNG_SWAP_ALPHA 0x20000L
  183917. #define PNG_STRIP_ALPHA 0x40000L
  183918. #define PNG_INVERT_ALPHA 0x80000L
  183919. #define PNG_USER_TRANSFORM 0x100000L
  183920. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183921. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183922. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183923. /* 0x800000L Unused */
  183924. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183925. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183926. /* 0x4000000L unused */
  183927. /* 0x8000000L unused */
  183928. /* 0x10000000L unused */
  183929. /* 0x20000000L unused */
  183930. /* 0x40000000L unused */
  183931. /* flags for png_create_struct */
  183932. #define PNG_STRUCT_PNG 0x0001
  183933. #define PNG_STRUCT_INFO 0x0002
  183934. /* Scaling factor for filter heuristic weighting calculations */
  183935. #define PNG_WEIGHT_SHIFT 8
  183936. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183937. #define PNG_COST_SHIFT 3
  183938. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183939. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183940. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183941. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183942. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183943. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183944. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183945. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183946. #define PNG_FLAG_ROW_INIT 0x0040
  183947. #define PNG_FLAG_FILLER_AFTER 0x0080
  183948. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183949. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183950. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183951. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183952. #define PNG_FLAG_FREE_PLTE 0x1000
  183953. #define PNG_FLAG_FREE_TRNS 0x2000
  183954. #define PNG_FLAG_FREE_HIST 0x4000
  183955. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183956. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183957. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183958. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183959. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183960. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183961. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183962. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183963. /* 0x800000L unused */
  183964. /* 0x1000000L unused */
  183965. /* 0x2000000L unused */
  183966. /* 0x4000000L unused */
  183967. /* 0x8000000L unused */
  183968. /* 0x10000000L unused */
  183969. /* 0x20000000L unused */
  183970. /* 0x40000000L unused */
  183971. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183972. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183973. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183974. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183975. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183976. PNG_FLAG_CRC_CRITICAL_MASK)
  183977. /* save typing and make code easier to understand */
  183978. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183979. abs((int)((c1).green) - (int)((c2).green)) + \
  183980. abs((int)((c1).blue) - (int)((c2).blue)))
  183981. /* Added to libpng-1.2.6 JB */
  183982. #define PNG_ROWBYTES(pixel_bits, width) \
  183983. ((pixel_bits) >= 8 ? \
  183984. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183985. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183986. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183987. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183988. "ideal" and "delta" should be constants, normally simple
  183989. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183990. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183991. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183992. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183993. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183994. /* place to hold the signature string for a PNG file. */
  183995. #ifdef PNG_USE_GLOBAL_ARRAYS
  183996. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183997. #else
  183998. #endif
  183999. #endif /* PNG_NO_EXTERN */
  184000. /* Constant strings for known chunk types. If you need to add a chunk,
  184001. * define the name here, and add an invocation of the macro in png.c and
  184002. * wherever it's needed.
  184003. */
  184004. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184005. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184006. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184007. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184008. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184009. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184010. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184011. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184012. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184013. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184014. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184015. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184016. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184017. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184018. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184019. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184020. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184021. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184022. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184023. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184024. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184025. #ifdef PNG_USE_GLOBAL_ARRAYS
  184026. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184027. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184028. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184029. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184030. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184031. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184032. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184033. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184034. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184035. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184036. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184037. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184038. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184039. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184040. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184041. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184042. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184043. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184044. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184045. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184046. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184047. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184048. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184049. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184050. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184051. */
  184052. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184053. #undef png_read_init
  184054. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184055. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184056. #endif
  184057. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184058. png_const_charp user_png_ver, png_size_t png_struct_size));
  184059. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184060. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184061. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184062. png_info_size));
  184063. #endif
  184064. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184065. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184066. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184067. */
  184068. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184069. #undef png_write_init
  184070. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184071. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184072. #endif
  184073. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184074. png_const_charp user_png_ver, png_size_t png_struct_size));
  184075. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184076. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184077. png_info_size));
  184078. /* Allocate memory for an internal libpng struct */
  184079. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184080. /* Free memory from internal libpng struct */
  184081. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184082. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184083. malloc_fn, png_voidp mem_ptr));
  184084. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184085. png_free_ptr free_fn, png_voidp mem_ptr));
  184086. /* Free any memory that info_ptr points to and reset struct. */
  184087. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184088. png_infop info_ptr));
  184089. #ifndef PNG_1_0_X
  184090. /* Function to allocate memory for zlib. */
  184091. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184092. /* Function to free memory for zlib */
  184093. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184094. #ifdef PNG_SIZE_T
  184095. /* Function to convert a sizeof an item to png_sizeof item */
  184096. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184097. #endif
  184098. /* Next four functions are used internally as callbacks. PNGAPI is required
  184099. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184100. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184101. png_bytep data, png_size_t length));
  184102. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184103. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184104. png_bytep buffer, png_size_t length));
  184105. #endif
  184106. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184107. png_bytep data, png_size_t length));
  184108. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184109. #if !defined(PNG_NO_STDIO)
  184110. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184111. #endif
  184112. #endif
  184113. #else /* PNG_1_0_X */
  184114. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184115. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184116. png_bytep buffer, png_size_t length));
  184117. #endif
  184118. #endif /* PNG_1_0_X */
  184119. /* Reset the CRC variable */
  184120. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184121. /* Write the "data" buffer to whatever output you are using. */
  184122. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184123. png_size_t length));
  184124. /* Read data from whatever input you are using into the "data" buffer */
  184125. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184126. png_size_t length));
  184127. /* Read bytes into buf, and update png_ptr->crc */
  184128. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184129. png_size_t length));
  184130. /* Decompress data in a chunk that uses compression */
  184131. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184132. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184133. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184134. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184135. png_size_t prefix_length, png_size_t *data_length));
  184136. #endif
  184137. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184138. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184139. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184140. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184141. /* Calculate the CRC over a section of data. Note that we are only
  184142. * passing a maximum of 64K on systems that have this as a memory limit,
  184143. * since this is the maximum buffer size we can specify.
  184144. */
  184145. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184146. png_size_t length));
  184147. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184148. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184149. #endif
  184150. /* simple function to write the signature */
  184151. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184152. /* write various chunks */
  184153. /* Write the IHDR chunk, and update the png_struct with the necessary
  184154. * information.
  184155. */
  184156. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184157. png_uint_32 height,
  184158. int bit_depth, int color_type, int compression_method, int filter_method,
  184159. int interlace_method));
  184160. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184161. png_uint_32 num_pal));
  184162. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184163. png_size_t length));
  184164. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184165. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184166. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184167. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184168. #endif
  184169. #ifdef PNG_FIXED_POINT_SUPPORTED
  184170. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184171. file_gamma));
  184172. #endif
  184173. #endif
  184174. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184175. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184176. int color_type));
  184177. #endif
  184178. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184179. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184180. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184181. double white_x, double white_y,
  184182. double red_x, double red_y, double green_x, double green_y,
  184183. double blue_x, double blue_y));
  184184. #endif
  184185. #ifdef PNG_FIXED_POINT_SUPPORTED
  184186. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184187. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184188. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184189. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184190. png_fixed_point int_blue_y));
  184191. #endif
  184192. #endif
  184193. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184194. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184195. int intent));
  184196. #endif
  184197. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184198. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184199. png_charp name, int compression_type,
  184200. png_charp profile, int proflen));
  184201. /* Note to maintainer: profile should be png_bytep */
  184202. #endif
  184203. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184204. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184205. png_sPLT_tp palette));
  184206. #endif
  184207. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184208. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184209. png_color_16p values, int number, int color_type));
  184210. #endif
  184211. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184212. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184213. png_color_16p values, int color_type));
  184214. #endif
  184215. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184216. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184217. int num_hist));
  184218. #endif
  184219. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184220. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184221. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184222. png_charp key, png_charpp new_key));
  184223. #endif
  184224. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184225. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184226. png_charp text, png_size_t text_len));
  184227. #endif
  184228. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184229. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184230. png_charp text, png_size_t text_len, int compression));
  184231. #endif
  184232. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184233. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184234. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184235. png_charp text));
  184236. #endif
  184237. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184238. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184239. png_infop info_ptr, png_textp text_ptr, int num_text));
  184240. #endif
  184241. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184242. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184243. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184244. #endif
  184245. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184246. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184247. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184248. png_charp units, png_charpp params));
  184249. #endif
  184250. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184251. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184252. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184253. int unit_type));
  184254. #endif
  184255. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184256. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184257. png_timep mod_time));
  184258. #endif
  184259. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184260. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184261. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184262. int unit, double width, double height));
  184263. #else
  184264. #ifdef PNG_FIXED_POINT_SUPPORTED
  184265. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184266. int unit, png_charp width, png_charp height));
  184267. #endif
  184268. #endif
  184269. #endif
  184270. /* Called when finished processing a row of data */
  184271. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184272. /* Internal use only. Called before first row of data */
  184273. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184274. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184275. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184276. #endif
  184277. /* combine a row of data, dealing with alpha, etc. if requested */
  184278. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184279. int mask));
  184280. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184281. /* expand an interlaced row */
  184282. /* OLD pre-1.0.9 interface:
  184283. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184284. png_bytep row, int pass, png_uint_32 transformations));
  184285. */
  184286. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184287. #endif
  184288. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184289. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184290. /* grab pixels out of a row for an interlaced pass */
  184291. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184292. png_bytep row, int pass));
  184293. #endif
  184294. /* unfilter a row */
  184295. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184296. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184297. /* Choose the best filter to use and filter the row data */
  184298. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184299. png_row_infop row_info));
  184300. /* Write out the filtered row. */
  184301. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184302. png_bytep filtered_row));
  184303. /* finish a row while reading, dealing with interlacing passes, etc. */
  184304. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184305. /* initialize the row buffers, etc. */
  184306. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184307. /* optional call to update the users info structure */
  184308. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184309. png_infop info_ptr));
  184310. /* these are the functions that do the transformations */
  184311. #if defined(PNG_READ_FILLER_SUPPORTED)
  184312. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184313. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184314. #endif
  184315. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184316. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184317. png_bytep row));
  184318. #endif
  184319. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184320. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184321. png_bytep row));
  184322. #endif
  184323. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184324. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184325. png_bytep row));
  184326. #endif
  184327. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184328. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184329. png_bytep row));
  184330. #endif
  184331. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184332. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184333. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184334. png_bytep row, png_uint_32 flags));
  184335. #endif
  184336. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184337. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184338. #endif
  184339. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184340. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184341. #endif
  184342. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184343. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184344. row_info, png_bytep row));
  184345. #endif
  184346. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184347. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184348. png_bytep row));
  184349. #endif
  184350. #if defined(PNG_READ_PACK_SUPPORTED)
  184351. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184352. #endif
  184353. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184354. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184355. png_color_8p sig_bits));
  184356. #endif
  184357. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184358. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184359. #endif
  184360. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184361. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184362. #endif
  184363. #if defined(PNG_READ_DITHER_SUPPORTED)
  184364. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184365. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184366. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184367. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184368. png_colorp palette, int num_palette));
  184369. # endif
  184370. #endif
  184371. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184372. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184373. #endif
  184374. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184375. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184376. png_bytep row, png_uint_32 bit_depth));
  184377. #endif
  184378. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184379. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184380. png_color_8p bit_depth));
  184381. #endif
  184382. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184383. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184384. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184385. png_color_16p trans_values, png_color_16p background,
  184386. png_color_16p background_1,
  184387. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184388. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184389. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184390. #else
  184391. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184392. png_color_16p trans_values, png_color_16p background));
  184393. #endif
  184394. #endif
  184395. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184396. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184397. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184398. int gamma_shift));
  184399. #endif
  184400. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184401. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184402. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184403. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184404. png_bytep row, png_color_16p trans_value));
  184405. #endif
  184406. /* The following decodes the appropriate chunks, and does error correction,
  184407. * then calls the appropriate callback for the chunk if it is valid.
  184408. */
  184409. /* decode the IHDR chunk */
  184410. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184411. png_uint_32 length));
  184412. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184413. png_uint_32 length));
  184414. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184415. png_uint_32 length));
  184416. #if defined(PNG_READ_bKGD_SUPPORTED)
  184417. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184418. png_uint_32 length));
  184419. #endif
  184420. #if defined(PNG_READ_cHRM_SUPPORTED)
  184421. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184422. png_uint_32 length));
  184423. #endif
  184424. #if defined(PNG_READ_gAMA_SUPPORTED)
  184425. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184426. png_uint_32 length));
  184427. #endif
  184428. #if defined(PNG_READ_hIST_SUPPORTED)
  184429. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184430. png_uint_32 length));
  184431. #endif
  184432. #if defined(PNG_READ_iCCP_SUPPORTED)
  184433. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184434. png_uint_32 length));
  184435. #endif /* PNG_READ_iCCP_SUPPORTED */
  184436. #if defined(PNG_READ_iTXt_SUPPORTED)
  184437. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184438. png_uint_32 length));
  184439. #endif
  184440. #if defined(PNG_READ_oFFs_SUPPORTED)
  184441. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184442. png_uint_32 length));
  184443. #endif
  184444. #if defined(PNG_READ_pCAL_SUPPORTED)
  184445. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184446. png_uint_32 length));
  184447. #endif
  184448. #if defined(PNG_READ_pHYs_SUPPORTED)
  184449. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184450. png_uint_32 length));
  184451. #endif
  184452. #if defined(PNG_READ_sBIT_SUPPORTED)
  184453. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184454. png_uint_32 length));
  184455. #endif
  184456. #if defined(PNG_READ_sCAL_SUPPORTED)
  184457. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184458. png_uint_32 length));
  184459. #endif
  184460. #if defined(PNG_READ_sPLT_SUPPORTED)
  184461. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184462. png_uint_32 length));
  184463. #endif /* PNG_READ_sPLT_SUPPORTED */
  184464. #if defined(PNG_READ_sRGB_SUPPORTED)
  184465. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184466. png_uint_32 length));
  184467. #endif
  184468. #if defined(PNG_READ_tEXt_SUPPORTED)
  184469. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184470. png_uint_32 length));
  184471. #endif
  184472. #if defined(PNG_READ_tIME_SUPPORTED)
  184473. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184474. png_uint_32 length));
  184475. #endif
  184476. #if defined(PNG_READ_tRNS_SUPPORTED)
  184477. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184478. png_uint_32 length));
  184479. #endif
  184480. #if defined(PNG_READ_zTXt_SUPPORTED)
  184481. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184482. png_uint_32 length));
  184483. #endif
  184484. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184485. png_infop info_ptr, png_uint_32 length));
  184486. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184487. png_bytep chunk_name));
  184488. /* handle the transformations for reading and writing */
  184489. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184490. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184491. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184492. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184493. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184494. png_infop info_ptr));
  184495. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184496. png_infop info_ptr));
  184497. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184498. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184499. png_uint_32 length));
  184500. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184501. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184502. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184503. png_bytep buffer, png_size_t buffer_length));
  184504. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184505. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184506. png_bytep buffer, png_size_t buffer_length));
  184507. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184508. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184509. png_infop info_ptr, png_uint_32 length));
  184510. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184511. png_infop info_ptr));
  184512. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184513. png_infop info_ptr));
  184514. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184515. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184516. png_infop info_ptr));
  184517. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184518. png_infop info_ptr));
  184519. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184520. #if defined(PNG_READ_tEXt_SUPPORTED)
  184521. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184522. png_infop info_ptr, png_uint_32 length));
  184523. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184524. png_infop info_ptr));
  184525. #endif
  184526. #if defined(PNG_READ_zTXt_SUPPORTED)
  184527. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184528. png_infop info_ptr, png_uint_32 length));
  184529. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184530. png_infop info_ptr));
  184531. #endif
  184532. #if defined(PNG_READ_iTXt_SUPPORTED)
  184533. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184534. png_infop info_ptr, png_uint_32 length));
  184535. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184536. png_infop info_ptr));
  184537. #endif
  184538. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184539. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184540. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184541. png_bytep row));
  184542. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184543. png_bytep row));
  184544. #endif
  184545. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184546. #if defined(PNG_MMX_CODE_SUPPORTED)
  184547. /* png.c */ /* PRIVATE */
  184548. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184549. #endif
  184550. #endif
  184551. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184552. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184553. png_infop info_ptr));
  184554. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184555. png_infop info_ptr));
  184556. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184557. png_infop info_ptr));
  184558. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184559. png_infop info_ptr));
  184560. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184561. png_infop info_ptr));
  184562. #if defined(PNG_pHYs_SUPPORTED)
  184563. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184564. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184565. #endif /* PNG_pHYs_SUPPORTED */
  184566. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184567. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184568. #endif /* PNG_INTERNAL */
  184569. #ifdef __cplusplus
  184570. //}
  184571. #endif
  184572. #endif /* PNG_VERSION_INFO_ONLY */
  184573. /* do not put anything past this line */
  184574. #endif /* PNG_H */
  184575. /*** End of inlined file: png.h ***/
  184576. #define PNG_NO_EXTERN
  184577. /*** Start of inlined file: png.c ***/
  184578. /* png.c - location for general purpose libpng functions
  184579. *
  184580. * Last changed in libpng 1.2.21 [October 4, 2007]
  184581. * For conditions of distribution and use, see copyright notice in png.h
  184582. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184583. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184584. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184585. */
  184586. #define PNG_INTERNAL
  184587. #define PNG_NO_EXTERN
  184588. /* Generate a compiler error if there is an old png.h in the search path. */
  184589. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184590. /* Version information for C files. This had better match the version
  184591. * string defined in png.h. */
  184592. #ifdef PNG_USE_GLOBAL_ARRAYS
  184593. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184594. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184595. #ifdef PNG_READ_SUPPORTED
  184596. /* png_sig was changed to a function in version 1.0.5c */
  184597. /* Place to hold the signature string for a PNG file. */
  184598. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184599. #endif /* PNG_READ_SUPPORTED */
  184600. /* Invoke global declarations for constant strings for known chunk types */
  184601. PNG_IHDR;
  184602. PNG_IDAT;
  184603. PNG_IEND;
  184604. PNG_PLTE;
  184605. PNG_bKGD;
  184606. PNG_cHRM;
  184607. PNG_gAMA;
  184608. PNG_hIST;
  184609. PNG_iCCP;
  184610. PNG_iTXt;
  184611. PNG_oFFs;
  184612. PNG_pCAL;
  184613. PNG_sCAL;
  184614. PNG_pHYs;
  184615. PNG_sBIT;
  184616. PNG_sPLT;
  184617. PNG_sRGB;
  184618. PNG_tEXt;
  184619. PNG_tIME;
  184620. PNG_tRNS;
  184621. PNG_zTXt;
  184622. #ifdef PNG_READ_SUPPORTED
  184623. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184624. /* start of interlace block */
  184625. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184626. /* offset to next interlace block */
  184627. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184628. /* start of interlace block in the y direction */
  184629. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184630. /* offset to next interlace block in the y direction */
  184631. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184632. /* Height of interlace block. This is not currently used - if you need
  184633. * it, uncomment it here and in png.h
  184634. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184635. */
  184636. /* Mask to determine which pixels are valid in a pass */
  184637. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184638. /* Mask to determine which pixels to overwrite while displaying */
  184639. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184640. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184641. #endif /* PNG_READ_SUPPORTED */
  184642. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184643. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184644. * of the PNG file signature. If the PNG data is embedded into another
  184645. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184646. * or write any of the magic bytes before it starts on the IHDR.
  184647. */
  184648. #ifdef PNG_READ_SUPPORTED
  184649. void PNGAPI
  184650. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184651. {
  184652. if(png_ptr == NULL) return;
  184653. png_debug(1, "in png_set_sig_bytes\n");
  184654. if (num_bytes > 8)
  184655. png_error(png_ptr, "Too many bytes for PNG signature.");
  184656. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184657. }
  184658. /* Checks whether the supplied bytes match the PNG signature. We allow
  184659. * checking less than the full 8-byte signature so that those apps that
  184660. * already read the first few bytes of a file to determine the file type
  184661. * can simply check the remaining bytes for extra assurance. Returns
  184662. * an integer less than, equal to, or greater than zero if sig is found,
  184663. * respectively, to be less than, to match, or be greater than the correct
  184664. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184665. */
  184666. int PNGAPI
  184667. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184668. {
  184669. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184670. if (num_to_check > 8)
  184671. num_to_check = 8;
  184672. else if (num_to_check < 1)
  184673. return (-1);
  184674. if (start > 7)
  184675. return (-1);
  184676. if (start + num_to_check > 8)
  184677. num_to_check = 8 - start;
  184678. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184679. }
  184680. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184681. /* (Obsolete) function to check signature bytes. It does not allow one
  184682. * to check a partial signature. This function might be removed in the
  184683. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184684. */
  184685. int PNGAPI
  184686. png_check_sig(png_bytep sig, int num)
  184687. {
  184688. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184689. }
  184690. #endif
  184691. #endif /* PNG_READ_SUPPORTED */
  184692. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184693. /* Function to allocate memory for zlib and clear it to 0. */
  184694. #ifdef PNG_1_0_X
  184695. voidpf PNGAPI
  184696. #else
  184697. voidpf /* private */
  184698. #endif
  184699. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184700. {
  184701. png_voidp ptr;
  184702. png_structp p=(png_structp)png_ptr;
  184703. png_uint_32 save_flags=p->flags;
  184704. png_uint_32 num_bytes;
  184705. if(png_ptr == NULL) return (NULL);
  184706. if (items > PNG_UINT_32_MAX/size)
  184707. {
  184708. png_warning (p, "Potential overflow in png_zalloc()");
  184709. return (NULL);
  184710. }
  184711. num_bytes = (png_uint_32)items * size;
  184712. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184713. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184714. p->flags=save_flags;
  184715. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184716. if (ptr == NULL)
  184717. return ((voidpf)ptr);
  184718. if (num_bytes > (png_uint_32)0x8000L)
  184719. {
  184720. png_memset(ptr, 0, (png_size_t)0x8000L);
  184721. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184722. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184723. }
  184724. else
  184725. {
  184726. png_memset(ptr, 0, (png_size_t)num_bytes);
  184727. }
  184728. #endif
  184729. return ((voidpf)ptr);
  184730. }
  184731. /* function to free memory for zlib */
  184732. #ifdef PNG_1_0_X
  184733. void PNGAPI
  184734. #else
  184735. void /* private */
  184736. #endif
  184737. png_zfree(voidpf png_ptr, voidpf ptr)
  184738. {
  184739. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184740. }
  184741. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184742. * in case CRC is > 32 bits to leave the top bits 0.
  184743. */
  184744. void /* PRIVATE */
  184745. png_reset_crc(png_structp png_ptr)
  184746. {
  184747. png_ptr->crc = crc32(0, Z_NULL, 0);
  184748. }
  184749. /* Calculate the CRC over a section of data. We can only pass as
  184750. * much data to this routine as the largest single buffer size. We
  184751. * also check that this data will actually be used before going to the
  184752. * trouble of calculating it.
  184753. */
  184754. void /* PRIVATE */
  184755. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184756. {
  184757. int need_crc = 1;
  184758. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184759. {
  184760. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184761. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184762. need_crc = 0;
  184763. }
  184764. else /* critical */
  184765. {
  184766. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184767. need_crc = 0;
  184768. }
  184769. if (need_crc)
  184770. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184771. }
  184772. /* Allocate the memory for an info_struct for the application. We don't
  184773. * really need the png_ptr, but it could potentially be useful in the
  184774. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184775. * and png_info_init() so that applications that want to use a shared
  184776. * libpng don't have to be recompiled if png_info changes size.
  184777. */
  184778. png_infop PNGAPI
  184779. png_create_info_struct(png_structp png_ptr)
  184780. {
  184781. png_infop info_ptr;
  184782. png_debug(1, "in png_create_info_struct\n");
  184783. if(png_ptr == NULL) return (NULL);
  184784. #ifdef PNG_USER_MEM_SUPPORTED
  184785. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184786. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184787. #else
  184788. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184789. #endif
  184790. if (info_ptr != NULL)
  184791. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184792. return (info_ptr);
  184793. }
  184794. /* This function frees the memory associated with a single info struct.
  184795. * Normally, one would use either png_destroy_read_struct() or
  184796. * png_destroy_write_struct() to free an info struct, but this may be
  184797. * useful for some applications.
  184798. */
  184799. void PNGAPI
  184800. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184801. {
  184802. png_infop info_ptr = NULL;
  184803. if(png_ptr == NULL) return;
  184804. png_debug(1, "in png_destroy_info_struct\n");
  184805. if (info_ptr_ptr != NULL)
  184806. info_ptr = *info_ptr_ptr;
  184807. if (info_ptr != NULL)
  184808. {
  184809. png_info_destroy(png_ptr, info_ptr);
  184810. #ifdef PNG_USER_MEM_SUPPORTED
  184811. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184812. png_ptr->mem_ptr);
  184813. #else
  184814. png_destroy_struct((png_voidp)info_ptr);
  184815. #endif
  184816. *info_ptr_ptr = NULL;
  184817. }
  184818. }
  184819. /* Initialize the info structure. This is now an internal function (0.89)
  184820. * and applications using it are urged to use png_create_info_struct()
  184821. * instead.
  184822. */
  184823. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184824. #undef png_info_init
  184825. void PNGAPI
  184826. png_info_init(png_infop info_ptr)
  184827. {
  184828. /* We only come here via pre-1.0.12-compiled applications */
  184829. png_info_init_3(&info_ptr, 0);
  184830. }
  184831. #endif
  184832. void PNGAPI
  184833. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184834. {
  184835. png_infop info_ptr = *ptr_ptr;
  184836. if(info_ptr == NULL) return;
  184837. png_debug(1, "in png_info_init_3\n");
  184838. if(png_sizeof(png_info) > png_info_struct_size)
  184839. {
  184840. png_destroy_struct(info_ptr);
  184841. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184842. *ptr_ptr = info_ptr;
  184843. }
  184844. /* set everything to 0 */
  184845. png_memset(info_ptr, 0, png_sizeof (png_info));
  184846. }
  184847. #ifdef PNG_FREE_ME_SUPPORTED
  184848. void PNGAPI
  184849. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184850. int freer, png_uint_32 mask)
  184851. {
  184852. png_debug(1, "in png_data_freer\n");
  184853. if (png_ptr == NULL || info_ptr == NULL)
  184854. return;
  184855. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184856. info_ptr->free_me |= mask;
  184857. else if(freer == PNG_USER_WILL_FREE_DATA)
  184858. info_ptr->free_me &= ~mask;
  184859. else
  184860. png_warning(png_ptr,
  184861. "Unknown freer parameter in png_data_freer.");
  184862. }
  184863. #endif
  184864. void PNGAPI
  184865. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184866. int num)
  184867. {
  184868. png_debug(1, "in png_free_data\n");
  184869. if (png_ptr == NULL || info_ptr == NULL)
  184870. return;
  184871. #if defined(PNG_TEXT_SUPPORTED)
  184872. /* free text item num or (if num == -1) all text items */
  184873. #ifdef PNG_FREE_ME_SUPPORTED
  184874. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184875. #else
  184876. if (mask & PNG_FREE_TEXT)
  184877. #endif
  184878. {
  184879. if (num != -1)
  184880. {
  184881. if (info_ptr->text && info_ptr->text[num].key)
  184882. {
  184883. png_free(png_ptr, info_ptr->text[num].key);
  184884. info_ptr->text[num].key = NULL;
  184885. }
  184886. }
  184887. else
  184888. {
  184889. int i;
  184890. for (i = 0; i < info_ptr->num_text; i++)
  184891. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184892. png_free(png_ptr, info_ptr->text);
  184893. info_ptr->text = NULL;
  184894. info_ptr->num_text=0;
  184895. }
  184896. }
  184897. #endif
  184898. #if defined(PNG_tRNS_SUPPORTED)
  184899. /* free any tRNS entry */
  184900. #ifdef PNG_FREE_ME_SUPPORTED
  184901. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184902. #else
  184903. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184904. #endif
  184905. {
  184906. png_free(png_ptr, info_ptr->trans);
  184907. info_ptr->valid &= ~PNG_INFO_tRNS;
  184908. #ifndef PNG_FREE_ME_SUPPORTED
  184909. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184910. #endif
  184911. info_ptr->trans = NULL;
  184912. }
  184913. #endif
  184914. #if defined(PNG_sCAL_SUPPORTED)
  184915. /* free any sCAL entry */
  184916. #ifdef PNG_FREE_ME_SUPPORTED
  184917. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184918. #else
  184919. if (mask & PNG_FREE_SCAL)
  184920. #endif
  184921. {
  184922. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184923. png_free(png_ptr, info_ptr->scal_s_width);
  184924. png_free(png_ptr, info_ptr->scal_s_height);
  184925. info_ptr->scal_s_width = NULL;
  184926. info_ptr->scal_s_height = NULL;
  184927. #endif
  184928. info_ptr->valid &= ~PNG_INFO_sCAL;
  184929. }
  184930. #endif
  184931. #if defined(PNG_pCAL_SUPPORTED)
  184932. /* free any pCAL entry */
  184933. #ifdef PNG_FREE_ME_SUPPORTED
  184934. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184935. #else
  184936. if (mask & PNG_FREE_PCAL)
  184937. #endif
  184938. {
  184939. png_free(png_ptr, info_ptr->pcal_purpose);
  184940. png_free(png_ptr, info_ptr->pcal_units);
  184941. info_ptr->pcal_purpose = NULL;
  184942. info_ptr->pcal_units = NULL;
  184943. if (info_ptr->pcal_params != NULL)
  184944. {
  184945. int i;
  184946. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184947. {
  184948. png_free(png_ptr, info_ptr->pcal_params[i]);
  184949. info_ptr->pcal_params[i]=NULL;
  184950. }
  184951. png_free(png_ptr, info_ptr->pcal_params);
  184952. info_ptr->pcal_params = NULL;
  184953. }
  184954. info_ptr->valid &= ~PNG_INFO_pCAL;
  184955. }
  184956. #endif
  184957. #if defined(PNG_iCCP_SUPPORTED)
  184958. /* free any iCCP entry */
  184959. #ifdef PNG_FREE_ME_SUPPORTED
  184960. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184961. #else
  184962. if (mask & PNG_FREE_ICCP)
  184963. #endif
  184964. {
  184965. png_free(png_ptr, info_ptr->iccp_name);
  184966. png_free(png_ptr, info_ptr->iccp_profile);
  184967. info_ptr->iccp_name = NULL;
  184968. info_ptr->iccp_profile = NULL;
  184969. info_ptr->valid &= ~PNG_INFO_iCCP;
  184970. }
  184971. #endif
  184972. #if defined(PNG_sPLT_SUPPORTED)
  184973. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184974. #ifdef PNG_FREE_ME_SUPPORTED
  184975. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184976. #else
  184977. if (mask & PNG_FREE_SPLT)
  184978. #endif
  184979. {
  184980. if (num != -1)
  184981. {
  184982. if(info_ptr->splt_palettes)
  184983. {
  184984. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184985. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184986. info_ptr->splt_palettes[num].name = NULL;
  184987. info_ptr->splt_palettes[num].entries = NULL;
  184988. }
  184989. }
  184990. else
  184991. {
  184992. if(info_ptr->splt_palettes_num)
  184993. {
  184994. int i;
  184995. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184996. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184997. png_free(png_ptr, info_ptr->splt_palettes);
  184998. info_ptr->splt_palettes = NULL;
  184999. info_ptr->splt_palettes_num = 0;
  185000. }
  185001. info_ptr->valid &= ~PNG_INFO_sPLT;
  185002. }
  185003. }
  185004. #endif
  185005. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185006. if(png_ptr->unknown_chunk.data)
  185007. {
  185008. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185009. png_ptr->unknown_chunk.data = NULL;
  185010. }
  185011. #ifdef PNG_FREE_ME_SUPPORTED
  185012. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185013. #else
  185014. if (mask & PNG_FREE_UNKN)
  185015. #endif
  185016. {
  185017. if (num != -1)
  185018. {
  185019. if(info_ptr->unknown_chunks)
  185020. {
  185021. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185022. info_ptr->unknown_chunks[num].data = NULL;
  185023. }
  185024. }
  185025. else
  185026. {
  185027. int i;
  185028. if(info_ptr->unknown_chunks_num)
  185029. {
  185030. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185031. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185032. png_free(png_ptr, info_ptr->unknown_chunks);
  185033. info_ptr->unknown_chunks = NULL;
  185034. info_ptr->unknown_chunks_num = 0;
  185035. }
  185036. }
  185037. }
  185038. #endif
  185039. #if defined(PNG_hIST_SUPPORTED)
  185040. /* free any hIST entry */
  185041. #ifdef PNG_FREE_ME_SUPPORTED
  185042. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185043. #else
  185044. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185045. #endif
  185046. {
  185047. png_free(png_ptr, info_ptr->hist);
  185048. info_ptr->hist = NULL;
  185049. info_ptr->valid &= ~PNG_INFO_hIST;
  185050. #ifndef PNG_FREE_ME_SUPPORTED
  185051. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185052. #endif
  185053. }
  185054. #endif
  185055. /* free any PLTE entry that was internally allocated */
  185056. #ifdef PNG_FREE_ME_SUPPORTED
  185057. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185058. #else
  185059. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185060. #endif
  185061. {
  185062. png_zfree(png_ptr, info_ptr->palette);
  185063. info_ptr->palette = NULL;
  185064. info_ptr->valid &= ~PNG_INFO_PLTE;
  185065. #ifndef PNG_FREE_ME_SUPPORTED
  185066. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185067. #endif
  185068. info_ptr->num_palette = 0;
  185069. }
  185070. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185071. /* free any image bits attached to the info structure */
  185072. #ifdef PNG_FREE_ME_SUPPORTED
  185073. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185074. #else
  185075. if (mask & PNG_FREE_ROWS)
  185076. #endif
  185077. {
  185078. if(info_ptr->row_pointers)
  185079. {
  185080. int row;
  185081. for (row = 0; row < (int)info_ptr->height; row++)
  185082. {
  185083. png_free(png_ptr, info_ptr->row_pointers[row]);
  185084. info_ptr->row_pointers[row]=NULL;
  185085. }
  185086. png_free(png_ptr, info_ptr->row_pointers);
  185087. info_ptr->row_pointers=NULL;
  185088. }
  185089. info_ptr->valid &= ~PNG_INFO_IDAT;
  185090. }
  185091. #endif
  185092. #ifdef PNG_FREE_ME_SUPPORTED
  185093. if(num == -1)
  185094. info_ptr->free_me &= ~mask;
  185095. else
  185096. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185097. #endif
  185098. }
  185099. /* This is an internal routine to free any memory that the info struct is
  185100. * pointing to before re-using it or freeing the struct itself. Recall
  185101. * that png_free() checks for NULL pointers for us.
  185102. */
  185103. void /* PRIVATE */
  185104. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185105. {
  185106. png_debug(1, "in png_info_destroy\n");
  185107. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185108. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185109. if (png_ptr->num_chunk_list)
  185110. {
  185111. png_free(png_ptr, png_ptr->chunk_list);
  185112. png_ptr->chunk_list=NULL;
  185113. png_ptr->num_chunk_list=0;
  185114. }
  185115. #endif
  185116. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185117. }
  185118. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185119. /* This function returns a pointer to the io_ptr associated with the user
  185120. * functions. The application should free any memory associated with this
  185121. * pointer before png_write_destroy() or png_read_destroy() are called.
  185122. */
  185123. png_voidp PNGAPI
  185124. png_get_io_ptr(png_structp png_ptr)
  185125. {
  185126. if(png_ptr == NULL) return (NULL);
  185127. return (png_ptr->io_ptr);
  185128. }
  185129. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185130. #if !defined(PNG_NO_STDIO)
  185131. /* Initialize the default input/output functions for the PNG file. If you
  185132. * use your own read or write routines, you can call either png_set_read_fn()
  185133. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185134. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185135. * necessarily available.
  185136. */
  185137. void PNGAPI
  185138. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185139. {
  185140. png_debug(1, "in png_init_io\n");
  185141. if(png_ptr == NULL) return;
  185142. png_ptr->io_ptr = (png_voidp)fp;
  185143. }
  185144. #endif
  185145. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185146. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185147. * a "Creation Time" or other text-based time string.
  185148. */
  185149. png_charp PNGAPI
  185150. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185151. {
  185152. static PNG_CONST char short_months[12][4] =
  185153. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185154. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185155. if(png_ptr == NULL) return (NULL);
  185156. if (png_ptr->time_buffer == NULL)
  185157. {
  185158. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185159. png_sizeof(char)));
  185160. }
  185161. #if defined(_WIN32_WCE)
  185162. {
  185163. wchar_t time_buf[29];
  185164. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185165. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185166. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185167. ptime->second % 61);
  185168. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185169. NULL, NULL);
  185170. }
  185171. #else
  185172. #ifdef USE_FAR_KEYWORD
  185173. {
  185174. char near_time_buf[29];
  185175. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185176. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185177. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185178. ptime->second % 61);
  185179. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185180. 29*png_sizeof(char));
  185181. }
  185182. #else
  185183. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185184. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185185. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185186. ptime->second % 61);
  185187. #endif
  185188. #endif /* _WIN32_WCE */
  185189. return ((png_charp)png_ptr->time_buffer);
  185190. }
  185191. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185192. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185193. png_charp PNGAPI
  185194. png_get_copyright(png_structp png_ptr)
  185195. {
  185196. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185197. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185198. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185199. Copyright (c) 1996-1997 Andreas Dilger\n\
  185200. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185201. }
  185202. /* The following return the library version as a short string in the
  185203. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185204. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185205. * is defined in png.h.
  185206. * Note: now there is no difference between png_get_libpng_ver() and
  185207. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185208. * it is guaranteed that png.c uses the correct version of png.h.
  185209. */
  185210. png_charp PNGAPI
  185211. png_get_libpng_ver(png_structp png_ptr)
  185212. {
  185213. /* Version of *.c files used when building libpng */
  185214. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185215. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185216. }
  185217. png_charp PNGAPI
  185218. png_get_header_ver(png_structp png_ptr)
  185219. {
  185220. /* Version of *.h files used when building libpng */
  185221. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185222. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185223. }
  185224. png_charp PNGAPI
  185225. png_get_header_version(png_structp png_ptr)
  185226. {
  185227. /* Returns longer string containing both version and date */
  185228. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185229. return ((png_charp) PNG_HEADER_VERSION_STRING
  185230. #ifndef PNG_READ_SUPPORTED
  185231. " (NO READ SUPPORT)"
  185232. #endif
  185233. "\n");
  185234. }
  185235. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185236. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185237. int PNGAPI
  185238. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185239. {
  185240. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185241. int i;
  185242. png_bytep p;
  185243. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185244. return 0;
  185245. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185246. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185247. if (!png_memcmp(chunk_name, p, 4))
  185248. return ((int)*(p+4));
  185249. return 0;
  185250. }
  185251. #endif
  185252. /* This function, added to libpng-1.0.6g, is untested. */
  185253. int PNGAPI
  185254. png_reset_zstream(png_structp png_ptr)
  185255. {
  185256. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185257. return (inflateReset(&png_ptr->zstream));
  185258. }
  185259. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185260. /* This function was added to libpng-1.0.7 */
  185261. png_uint_32 PNGAPI
  185262. png_access_version_number(void)
  185263. {
  185264. /* Version of *.c files used when building libpng */
  185265. return((png_uint_32) PNG_LIBPNG_VER);
  185266. }
  185267. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185268. #if !defined(PNG_1_0_X)
  185269. /* this function was added to libpng 1.2.0 */
  185270. int PNGAPI
  185271. png_mmx_support(void)
  185272. {
  185273. /* obsolete, to be removed from libpng-1.4.0 */
  185274. return -1;
  185275. }
  185276. #endif /* PNG_1_0_X */
  185277. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185278. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185279. #ifdef PNG_SIZE_T
  185280. /* Added at libpng version 1.2.6 */
  185281. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185282. png_size_t PNGAPI
  185283. png_convert_size(size_t size)
  185284. {
  185285. if (size > (png_size_t)-1)
  185286. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185287. return ((png_size_t)size);
  185288. }
  185289. #endif /* PNG_SIZE_T */
  185290. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185291. /*** End of inlined file: png.c ***/
  185292. /*** Start of inlined file: pngerror.c ***/
  185293. /* pngerror.c - stub functions for i/o and memory allocation
  185294. *
  185295. * Last changed in libpng 1.2.20 October 4, 2007
  185296. * For conditions of distribution and use, see copyright notice in png.h
  185297. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185298. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185299. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185300. *
  185301. * This file provides a location for all error handling. Users who
  185302. * need special error handling are expected to write replacement functions
  185303. * and use png_set_error_fn() to use those functions. See the instructions
  185304. * at each function.
  185305. */
  185306. #define PNG_INTERNAL
  185307. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185308. static void /* PRIVATE */
  185309. png_default_error PNGARG((png_structp png_ptr,
  185310. png_const_charp error_message));
  185311. #ifndef PNG_NO_WARNINGS
  185312. static void /* PRIVATE */
  185313. png_default_warning PNGARG((png_structp png_ptr,
  185314. png_const_charp warning_message));
  185315. #endif /* PNG_NO_WARNINGS */
  185316. /* This function is called whenever there is a fatal error. This function
  185317. * should not be changed. If there is a need to handle errors differently,
  185318. * you should supply a replacement error function and use png_set_error_fn()
  185319. * to replace the error function at run-time.
  185320. */
  185321. #ifndef PNG_NO_ERROR_TEXT
  185322. void PNGAPI
  185323. png_error(png_structp png_ptr, png_const_charp error_message)
  185324. {
  185325. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185326. char msg[16];
  185327. if (png_ptr != NULL)
  185328. {
  185329. if (png_ptr->flags&
  185330. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185331. {
  185332. if (*error_message == '#')
  185333. {
  185334. int offset;
  185335. for (offset=1; offset<15; offset++)
  185336. if (*(error_message+offset) == ' ')
  185337. break;
  185338. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185339. {
  185340. int i;
  185341. for (i=0; i<offset-1; i++)
  185342. msg[i]=error_message[i+1];
  185343. msg[i]='\0';
  185344. error_message=msg;
  185345. }
  185346. else
  185347. error_message+=offset;
  185348. }
  185349. else
  185350. {
  185351. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185352. {
  185353. msg[0]='0';
  185354. msg[1]='\0';
  185355. error_message=msg;
  185356. }
  185357. }
  185358. }
  185359. }
  185360. #endif
  185361. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185362. (*(png_ptr->error_fn))(png_ptr, error_message);
  185363. /* If the custom handler doesn't exist, or if it returns,
  185364. use the default handler, which will not return. */
  185365. png_default_error(png_ptr, error_message);
  185366. }
  185367. #else
  185368. void PNGAPI
  185369. png_err(png_structp png_ptr)
  185370. {
  185371. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185372. (*(png_ptr->error_fn))(png_ptr, '\0');
  185373. /* If the custom handler doesn't exist, or if it returns,
  185374. use the default handler, which will not return. */
  185375. png_default_error(png_ptr, '\0');
  185376. }
  185377. #endif /* PNG_NO_ERROR_TEXT */
  185378. #ifndef PNG_NO_WARNINGS
  185379. /* This function is called whenever there is a non-fatal error. This function
  185380. * should not be changed. If there is a need to handle warnings differently,
  185381. * you should supply a replacement warning function and use
  185382. * png_set_error_fn() to replace the warning function at run-time.
  185383. */
  185384. void PNGAPI
  185385. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185386. {
  185387. int offset = 0;
  185388. if (png_ptr != NULL)
  185389. {
  185390. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185391. if (png_ptr->flags&
  185392. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185393. #endif
  185394. {
  185395. if (*warning_message == '#')
  185396. {
  185397. for (offset=1; offset<15; offset++)
  185398. if (*(warning_message+offset) == ' ')
  185399. break;
  185400. }
  185401. }
  185402. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185403. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185404. }
  185405. else
  185406. png_default_warning(png_ptr, warning_message+offset);
  185407. }
  185408. #endif /* PNG_NO_WARNINGS */
  185409. /* These utilities are used internally to build an error message that relates
  185410. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185411. * this is used to prefix the message. The message is limited in length
  185412. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185413. * if the character is invalid.
  185414. */
  185415. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185416. /*static PNG_CONST char png_digit[16] = {
  185417. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185418. 'A', 'B', 'C', 'D', 'E', 'F'
  185419. };*/
  185420. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185421. static void /* PRIVATE */
  185422. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185423. error_message)
  185424. {
  185425. int iout = 0, iin = 0;
  185426. while (iin < 4)
  185427. {
  185428. int c = png_ptr->chunk_name[iin++];
  185429. if (isnonalpha(c))
  185430. {
  185431. buffer[iout++] = '[';
  185432. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185433. buffer[iout++] = png_digit[c & 0x0f];
  185434. buffer[iout++] = ']';
  185435. }
  185436. else
  185437. {
  185438. buffer[iout++] = (png_byte)c;
  185439. }
  185440. }
  185441. if (error_message == NULL)
  185442. buffer[iout] = 0;
  185443. else
  185444. {
  185445. buffer[iout++] = ':';
  185446. buffer[iout++] = ' ';
  185447. png_strncpy(buffer+iout, error_message, 63);
  185448. buffer[iout+63] = 0;
  185449. }
  185450. }
  185451. #ifdef PNG_READ_SUPPORTED
  185452. void PNGAPI
  185453. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185454. {
  185455. char msg[18+64];
  185456. if (png_ptr == NULL)
  185457. png_error(png_ptr, error_message);
  185458. else
  185459. {
  185460. png_format_buffer(png_ptr, msg, error_message);
  185461. png_error(png_ptr, msg);
  185462. }
  185463. }
  185464. #endif /* PNG_READ_SUPPORTED */
  185465. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185466. #ifndef PNG_NO_WARNINGS
  185467. void PNGAPI
  185468. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185469. {
  185470. char msg[18+64];
  185471. if (png_ptr == NULL)
  185472. png_warning(png_ptr, warning_message);
  185473. else
  185474. {
  185475. png_format_buffer(png_ptr, msg, warning_message);
  185476. png_warning(png_ptr, msg);
  185477. }
  185478. }
  185479. #endif /* PNG_NO_WARNINGS */
  185480. /* This is the default error handling function. Note that replacements for
  185481. * this function MUST NOT RETURN, or the program will likely crash. This
  185482. * function is used by default, or if the program supplies NULL for the
  185483. * error function pointer in png_set_error_fn().
  185484. */
  185485. static void /* PRIVATE */
  185486. png_default_error(png_structp, png_const_charp error_message)
  185487. {
  185488. #ifndef PNG_NO_CONSOLE_IO
  185489. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185490. if (*error_message == '#')
  185491. {
  185492. int offset;
  185493. char error_number[16];
  185494. for (offset=0; offset<15; offset++)
  185495. {
  185496. error_number[offset] = *(error_message+offset+1);
  185497. if (*(error_message+offset) == ' ')
  185498. break;
  185499. }
  185500. if((offset > 1) && (offset < 15))
  185501. {
  185502. error_number[offset-1]='\0';
  185503. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185504. error_message+offset);
  185505. }
  185506. else
  185507. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185508. }
  185509. else
  185510. #endif
  185511. fprintf(stderr, "libpng error: %s\n", error_message);
  185512. #endif
  185513. #ifdef PNG_SETJMP_SUPPORTED
  185514. if (png_ptr)
  185515. {
  185516. # ifdef USE_FAR_KEYWORD
  185517. {
  185518. jmp_buf jmpbuf;
  185519. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185520. longjmp(jmpbuf, 1);
  185521. }
  185522. # else
  185523. longjmp(png_ptr->jmpbuf, 1);
  185524. # endif
  185525. }
  185526. #else
  185527. PNG_ABORT();
  185528. #endif
  185529. #ifdef PNG_NO_CONSOLE_IO
  185530. error_message = error_message; /* make compiler happy */
  185531. #endif
  185532. }
  185533. #ifndef PNG_NO_WARNINGS
  185534. /* This function is called when there is a warning, but the library thinks
  185535. * it can continue anyway. Replacement functions don't have to do anything
  185536. * here if you don't want them to. In the default configuration, png_ptr is
  185537. * not used, but it is passed in case it may be useful.
  185538. */
  185539. static void /* PRIVATE */
  185540. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185541. {
  185542. #ifndef PNG_NO_CONSOLE_IO
  185543. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185544. if (*warning_message == '#')
  185545. {
  185546. int offset;
  185547. char warning_number[16];
  185548. for (offset=0; offset<15; offset++)
  185549. {
  185550. warning_number[offset]=*(warning_message+offset+1);
  185551. if (*(warning_message+offset) == ' ')
  185552. break;
  185553. }
  185554. if((offset > 1) && (offset < 15))
  185555. {
  185556. warning_number[offset-1]='\0';
  185557. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185558. warning_message+offset);
  185559. }
  185560. else
  185561. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185562. }
  185563. else
  185564. # endif
  185565. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185566. #else
  185567. warning_message = warning_message; /* make compiler happy */
  185568. #endif
  185569. png_ptr = png_ptr; /* make compiler happy */
  185570. }
  185571. #endif /* PNG_NO_WARNINGS */
  185572. /* This function is called when the application wants to use another method
  185573. * of handling errors and warnings. Note that the error function MUST NOT
  185574. * return to the calling routine or serious problems will occur. The return
  185575. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185576. */
  185577. void PNGAPI
  185578. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185579. png_error_ptr error_fn, png_error_ptr warning_fn)
  185580. {
  185581. if (png_ptr == NULL)
  185582. return;
  185583. png_ptr->error_ptr = error_ptr;
  185584. png_ptr->error_fn = error_fn;
  185585. png_ptr->warning_fn = warning_fn;
  185586. }
  185587. /* This function returns a pointer to the error_ptr associated with the user
  185588. * functions. The application should free any memory associated with this
  185589. * pointer before png_write_destroy and png_read_destroy are called.
  185590. */
  185591. png_voidp PNGAPI
  185592. png_get_error_ptr(png_structp png_ptr)
  185593. {
  185594. if (png_ptr == NULL)
  185595. return NULL;
  185596. return ((png_voidp)png_ptr->error_ptr);
  185597. }
  185598. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185599. void PNGAPI
  185600. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185601. {
  185602. if(png_ptr != NULL)
  185603. {
  185604. png_ptr->flags &=
  185605. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185606. }
  185607. }
  185608. #endif
  185609. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185610. /*** End of inlined file: pngerror.c ***/
  185611. /*** Start of inlined file: pngget.c ***/
  185612. /* pngget.c - retrieval of values from info struct
  185613. *
  185614. * Last changed in libpng 1.2.15 January 5, 2007
  185615. * For conditions of distribution and use, see copyright notice in png.h
  185616. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185617. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185618. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185619. */
  185620. #define PNG_INTERNAL
  185621. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185622. png_uint_32 PNGAPI
  185623. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185624. {
  185625. if (png_ptr != NULL && info_ptr != NULL)
  185626. return(info_ptr->valid & flag);
  185627. else
  185628. return(0);
  185629. }
  185630. png_uint_32 PNGAPI
  185631. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185632. {
  185633. if (png_ptr != NULL && info_ptr != NULL)
  185634. return(info_ptr->rowbytes);
  185635. else
  185636. return(0);
  185637. }
  185638. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185639. png_bytepp PNGAPI
  185640. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185641. {
  185642. if (png_ptr != NULL && info_ptr != NULL)
  185643. return(info_ptr->row_pointers);
  185644. else
  185645. return(0);
  185646. }
  185647. #endif
  185648. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185649. /* easy access to info, added in libpng-0.99 */
  185650. png_uint_32 PNGAPI
  185651. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185652. {
  185653. if (png_ptr != NULL && info_ptr != NULL)
  185654. {
  185655. return info_ptr->width;
  185656. }
  185657. return (0);
  185658. }
  185659. png_uint_32 PNGAPI
  185660. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185661. {
  185662. if (png_ptr != NULL && info_ptr != NULL)
  185663. {
  185664. return info_ptr->height;
  185665. }
  185666. return (0);
  185667. }
  185668. png_byte PNGAPI
  185669. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185670. {
  185671. if (png_ptr != NULL && info_ptr != NULL)
  185672. {
  185673. return info_ptr->bit_depth;
  185674. }
  185675. return (0);
  185676. }
  185677. png_byte PNGAPI
  185678. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185679. {
  185680. if (png_ptr != NULL && info_ptr != NULL)
  185681. {
  185682. return info_ptr->color_type;
  185683. }
  185684. return (0);
  185685. }
  185686. png_byte PNGAPI
  185687. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185688. {
  185689. if (png_ptr != NULL && info_ptr != NULL)
  185690. {
  185691. return info_ptr->filter_type;
  185692. }
  185693. return (0);
  185694. }
  185695. png_byte PNGAPI
  185696. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185697. {
  185698. if (png_ptr != NULL && info_ptr != NULL)
  185699. {
  185700. return info_ptr->interlace_type;
  185701. }
  185702. return (0);
  185703. }
  185704. png_byte PNGAPI
  185705. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185706. {
  185707. if (png_ptr != NULL && info_ptr != NULL)
  185708. {
  185709. return info_ptr->compression_type;
  185710. }
  185711. return (0);
  185712. }
  185713. png_uint_32 PNGAPI
  185714. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185715. {
  185716. if (png_ptr != NULL && info_ptr != NULL)
  185717. #if defined(PNG_pHYs_SUPPORTED)
  185718. if (info_ptr->valid & PNG_INFO_pHYs)
  185719. {
  185720. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185721. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185722. return (0);
  185723. else return (info_ptr->x_pixels_per_unit);
  185724. }
  185725. #else
  185726. return (0);
  185727. #endif
  185728. return (0);
  185729. }
  185730. png_uint_32 PNGAPI
  185731. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185732. {
  185733. if (png_ptr != NULL && info_ptr != NULL)
  185734. #if defined(PNG_pHYs_SUPPORTED)
  185735. if (info_ptr->valid & PNG_INFO_pHYs)
  185736. {
  185737. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185738. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185739. return (0);
  185740. else return (info_ptr->y_pixels_per_unit);
  185741. }
  185742. #else
  185743. return (0);
  185744. #endif
  185745. return (0);
  185746. }
  185747. png_uint_32 PNGAPI
  185748. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185749. {
  185750. if (png_ptr != NULL && info_ptr != NULL)
  185751. #if defined(PNG_pHYs_SUPPORTED)
  185752. if (info_ptr->valid & PNG_INFO_pHYs)
  185753. {
  185754. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185755. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185756. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185757. return (0);
  185758. else return (info_ptr->x_pixels_per_unit);
  185759. }
  185760. #else
  185761. return (0);
  185762. #endif
  185763. return (0);
  185764. }
  185765. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185766. float PNGAPI
  185767. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185768. {
  185769. if (png_ptr != NULL && info_ptr != NULL)
  185770. #if defined(PNG_pHYs_SUPPORTED)
  185771. if (info_ptr->valid & PNG_INFO_pHYs)
  185772. {
  185773. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185774. if (info_ptr->x_pixels_per_unit == 0)
  185775. return ((float)0.0);
  185776. else
  185777. return ((float)((float)info_ptr->y_pixels_per_unit
  185778. /(float)info_ptr->x_pixels_per_unit));
  185779. }
  185780. #else
  185781. return (0.0);
  185782. #endif
  185783. return ((float)0.0);
  185784. }
  185785. #endif
  185786. png_int_32 PNGAPI
  185787. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185788. {
  185789. if (png_ptr != NULL && info_ptr != NULL)
  185790. #if defined(PNG_oFFs_SUPPORTED)
  185791. if (info_ptr->valid & PNG_INFO_oFFs)
  185792. {
  185793. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185794. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185795. return (0);
  185796. else return (info_ptr->x_offset);
  185797. }
  185798. #else
  185799. return (0);
  185800. #endif
  185801. return (0);
  185802. }
  185803. png_int_32 PNGAPI
  185804. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185805. {
  185806. if (png_ptr != NULL && info_ptr != NULL)
  185807. #if defined(PNG_oFFs_SUPPORTED)
  185808. if (info_ptr->valid & PNG_INFO_oFFs)
  185809. {
  185810. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185811. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185812. return (0);
  185813. else return (info_ptr->y_offset);
  185814. }
  185815. #else
  185816. return (0);
  185817. #endif
  185818. return (0);
  185819. }
  185820. png_int_32 PNGAPI
  185821. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185822. {
  185823. if (png_ptr != NULL && info_ptr != NULL)
  185824. #if defined(PNG_oFFs_SUPPORTED)
  185825. if (info_ptr->valid & PNG_INFO_oFFs)
  185826. {
  185827. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185828. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185829. return (0);
  185830. else return (info_ptr->x_offset);
  185831. }
  185832. #else
  185833. return (0);
  185834. #endif
  185835. return (0);
  185836. }
  185837. png_int_32 PNGAPI
  185838. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185839. {
  185840. if (png_ptr != NULL && info_ptr != NULL)
  185841. #if defined(PNG_oFFs_SUPPORTED)
  185842. if (info_ptr->valid & PNG_INFO_oFFs)
  185843. {
  185844. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185845. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185846. return (0);
  185847. else return (info_ptr->y_offset);
  185848. }
  185849. #else
  185850. return (0);
  185851. #endif
  185852. return (0);
  185853. }
  185854. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185855. png_uint_32 PNGAPI
  185856. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185857. {
  185858. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185859. *.0254 +.5));
  185860. }
  185861. png_uint_32 PNGAPI
  185862. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185863. {
  185864. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185865. *.0254 +.5));
  185866. }
  185867. png_uint_32 PNGAPI
  185868. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185869. {
  185870. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185871. *.0254 +.5));
  185872. }
  185873. float PNGAPI
  185874. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185875. {
  185876. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185877. *.00003937);
  185878. }
  185879. float PNGAPI
  185880. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185881. {
  185882. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185883. *.00003937);
  185884. }
  185885. #if defined(PNG_pHYs_SUPPORTED)
  185886. png_uint_32 PNGAPI
  185887. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185888. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185889. {
  185890. png_uint_32 retval = 0;
  185891. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185892. {
  185893. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185894. if (res_x != NULL)
  185895. {
  185896. *res_x = info_ptr->x_pixels_per_unit;
  185897. retval |= PNG_INFO_pHYs;
  185898. }
  185899. if (res_y != NULL)
  185900. {
  185901. *res_y = info_ptr->y_pixels_per_unit;
  185902. retval |= PNG_INFO_pHYs;
  185903. }
  185904. if (unit_type != NULL)
  185905. {
  185906. *unit_type = (int)info_ptr->phys_unit_type;
  185907. retval |= PNG_INFO_pHYs;
  185908. if(*unit_type == 1)
  185909. {
  185910. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185911. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185912. }
  185913. }
  185914. }
  185915. return (retval);
  185916. }
  185917. #endif /* PNG_pHYs_SUPPORTED */
  185918. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185919. /* png_get_channels really belongs in here, too, but it's been around longer */
  185920. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185921. png_byte PNGAPI
  185922. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185923. {
  185924. if (png_ptr != NULL && info_ptr != NULL)
  185925. return(info_ptr->channels);
  185926. else
  185927. return (0);
  185928. }
  185929. png_bytep PNGAPI
  185930. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185931. {
  185932. if (png_ptr != NULL && info_ptr != NULL)
  185933. return(info_ptr->signature);
  185934. else
  185935. return (NULL);
  185936. }
  185937. #if defined(PNG_bKGD_SUPPORTED)
  185938. png_uint_32 PNGAPI
  185939. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185940. png_color_16p *background)
  185941. {
  185942. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185943. && background != NULL)
  185944. {
  185945. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185946. *background = &(info_ptr->background);
  185947. return (PNG_INFO_bKGD);
  185948. }
  185949. return (0);
  185950. }
  185951. #endif
  185952. #if defined(PNG_cHRM_SUPPORTED)
  185953. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185954. png_uint_32 PNGAPI
  185955. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185956. double *white_x, double *white_y, double *red_x, double *red_y,
  185957. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185958. {
  185959. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185960. {
  185961. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185962. if (white_x != NULL)
  185963. *white_x = (double)info_ptr->x_white;
  185964. if (white_y != NULL)
  185965. *white_y = (double)info_ptr->y_white;
  185966. if (red_x != NULL)
  185967. *red_x = (double)info_ptr->x_red;
  185968. if (red_y != NULL)
  185969. *red_y = (double)info_ptr->y_red;
  185970. if (green_x != NULL)
  185971. *green_x = (double)info_ptr->x_green;
  185972. if (green_y != NULL)
  185973. *green_y = (double)info_ptr->y_green;
  185974. if (blue_x != NULL)
  185975. *blue_x = (double)info_ptr->x_blue;
  185976. if (blue_y != NULL)
  185977. *blue_y = (double)info_ptr->y_blue;
  185978. return (PNG_INFO_cHRM);
  185979. }
  185980. return (0);
  185981. }
  185982. #endif
  185983. #ifdef PNG_FIXED_POINT_SUPPORTED
  185984. png_uint_32 PNGAPI
  185985. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185986. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185987. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185988. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185989. {
  185990. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185991. {
  185992. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185993. if (white_x != NULL)
  185994. *white_x = info_ptr->int_x_white;
  185995. if (white_y != NULL)
  185996. *white_y = info_ptr->int_y_white;
  185997. if (red_x != NULL)
  185998. *red_x = info_ptr->int_x_red;
  185999. if (red_y != NULL)
  186000. *red_y = info_ptr->int_y_red;
  186001. if (green_x != NULL)
  186002. *green_x = info_ptr->int_x_green;
  186003. if (green_y != NULL)
  186004. *green_y = info_ptr->int_y_green;
  186005. if (blue_x != NULL)
  186006. *blue_x = info_ptr->int_x_blue;
  186007. if (blue_y != NULL)
  186008. *blue_y = info_ptr->int_y_blue;
  186009. return (PNG_INFO_cHRM);
  186010. }
  186011. return (0);
  186012. }
  186013. #endif
  186014. #endif
  186015. #if defined(PNG_gAMA_SUPPORTED)
  186016. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186017. png_uint_32 PNGAPI
  186018. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186019. {
  186020. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186021. && file_gamma != NULL)
  186022. {
  186023. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186024. *file_gamma = (double)info_ptr->gamma;
  186025. return (PNG_INFO_gAMA);
  186026. }
  186027. return (0);
  186028. }
  186029. #endif
  186030. #ifdef PNG_FIXED_POINT_SUPPORTED
  186031. png_uint_32 PNGAPI
  186032. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186033. png_fixed_point *int_file_gamma)
  186034. {
  186035. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186036. && int_file_gamma != NULL)
  186037. {
  186038. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186039. *int_file_gamma = info_ptr->int_gamma;
  186040. return (PNG_INFO_gAMA);
  186041. }
  186042. return (0);
  186043. }
  186044. #endif
  186045. #endif
  186046. #if defined(PNG_sRGB_SUPPORTED)
  186047. png_uint_32 PNGAPI
  186048. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186049. {
  186050. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186051. && file_srgb_intent != NULL)
  186052. {
  186053. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186054. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186055. return (PNG_INFO_sRGB);
  186056. }
  186057. return (0);
  186058. }
  186059. #endif
  186060. #if defined(PNG_iCCP_SUPPORTED)
  186061. png_uint_32 PNGAPI
  186062. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186063. png_charpp name, int *compression_type,
  186064. png_charpp profile, png_uint_32 *proflen)
  186065. {
  186066. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186067. && name != NULL && profile != NULL && proflen != NULL)
  186068. {
  186069. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186070. *name = info_ptr->iccp_name;
  186071. *profile = info_ptr->iccp_profile;
  186072. /* compression_type is a dummy so the API won't have to change
  186073. if we introduce multiple compression types later. */
  186074. *proflen = (int)info_ptr->iccp_proflen;
  186075. *compression_type = (int)info_ptr->iccp_compression;
  186076. return (PNG_INFO_iCCP);
  186077. }
  186078. return (0);
  186079. }
  186080. #endif
  186081. #if defined(PNG_sPLT_SUPPORTED)
  186082. png_uint_32 PNGAPI
  186083. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186084. png_sPLT_tpp spalettes)
  186085. {
  186086. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186087. {
  186088. *spalettes = info_ptr->splt_palettes;
  186089. return ((png_uint_32)info_ptr->splt_palettes_num);
  186090. }
  186091. return (0);
  186092. }
  186093. #endif
  186094. #if defined(PNG_hIST_SUPPORTED)
  186095. png_uint_32 PNGAPI
  186096. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186097. {
  186098. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186099. && hist != NULL)
  186100. {
  186101. png_debug1(1, "in %s retrieval function\n", "hIST");
  186102. *hist = info_ptr->hist;
  186103. return (PNG_INFO_hIST);
  186104. }
  186105. return (0);
  186106. }
  186107. #endif
  186108. png_uint_32 PNGAPI
  186109. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186110. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186111. int *color_type, int *interlace_type, int *compression_type,
  186112. int *filter_type)
  186113. {
  186114. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186115. bit_depth != NULL && color_type != NULL)
  186116. {
  186117. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186118. *width = info_ptr->width;
  186119. *height = info_ptr->height;
  186120. *bit_depth = info_ptr->bit_depth;
  186121. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186122. png_error(png_ptr, "Invalid bit depth");
  186123. *color_type = info_ptr->color_type;
  186124. if (info_ptr->color_type > 6)
  186125. png_error(png_ptr, "Invalid color type");
  186126. if (compression_type != NULL)
  186127. *compression_type = info_ptr->compression_type;
  186128. if (filter_type != NULL)
  186129. *filter_type = info_ptr->filter_type;
  186130. if (interlace_type != NULL)
  186131. *interlace_type = info_ptr->interlace_type;
  186132. /* check for potential overflow of rowbytes */
  186133. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186134. png_error(png_ptr, "Invalid image width");
  186135. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186136. png_error(png_ptr, "Invalid image height");
  186137. if (info_ptr->width > (PNG_UINT_32_MAX
  186138. >> 3) /* 8-byte RGBA pixels */
  186139. - 64 /* bigrowbuf hack */
  186140. - 1 /* filter byte */
  186141. - 7*8 /* rounding of width to multiple of 8 pixels */
  186142. - 8) /* extra max_pixel_depth pad */
  186143. {
  186144. png_warning(png_ptr,
  186145. "Width too large for libpng to process image data.");
  186146. }
  186147. return (1);
  186148. }
  186149. return (0);
  186150. }
  186151. #if defined(PNG_oFFs_SUPPORTED)
  186152. png_uint_32 PNGAPI
  186153. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186154. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186155. {
  186156. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186157. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186158. {
  186159. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186160. *offset_x = info_ptr->x_offset;
  186161. *offset_y = info_ptr->y_offset;
  186162. *unit_type = (int)info_ptr->offset_unit_type;
  186163. return (PNG_INFO_oFFs);
  186164. }
  186165. return (0);
  186166. }
  186167. #endif
  186168. #if defined(PNG_pCAL_SUPPORTED)
  186169. png_uint_32 PNGAPI
  186170. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186171. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186172. png_charp *units, png_charpp *params)
  186173. {
  186174. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186175. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186176. nparams != NULL && units != NULL && params != NULL)
  186177. {
  186178. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186179. *purpose = info_ptr->pcal_purpose;
  186180. *X0 = info_ptr->pcal_X0;
  186181. *X1 = info_ptr->pcal_X1;
  186182. *type = (int)info_ptr->pcal_type;
  186183. *nparams = (int)info_ptr->pcal_nparams;
  186184. *units = info_ptr->pcal_units;
  186185. *params = info_ptr->pcal_params;
  186186. return (PNG_INFO_pCAL);
  186187. }
  186188. return (0);
  186189. }
  186190. #endif
  186191. #if defined(PNG_sCAL_SUPPORTED)
  186192. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186193. png_uint_32 PNGAPI
  186194. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186195. int *unit, double *width, double *height)
  186196. {
  186197. if (png_ptr != NULL && info_ptr != NULL &&
  186198. (info_ptr->valid & PNG_INFO_sCAL))
  186199. {
  186200. *unit = info_ptr->scal_unit;
  186201. *width = info_ptr->scal_pixel_width;
  186202. *height = info_ptr->scal_pixel_height;
  186203. return (PNG_INFO_sCAL);
  186204. }
  186205. return(0);
  186206. }
  186207. #else
  186208. #ifdef PNG_FIXED_POINT_SUPPORTED
  186209. png_uint_32 PNGAPI
  186210. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186211. int *unit, png_charpp width, png_charpp height)
  186212. {
  186213. if (png_ptr != NULL && info_ptr != NULL &&
  186214. (info_ptr->valid & PNG_INFO_sCAL))
  186215. {
  186216. *unit = info_ptr->scal_unit;
  186217. *width = info_ptr->scal_s_width;
  186218. *height = info_ptr->scal_s_height;
  186219. return (PNG_INFO_sCAL);
  186220. }
  186221. return(0);
  186222. }
  186223. #endif
  186224. #endif
  186225. #endif
  186226. #if defined(PNG_pHYs_SUPPORTED)
  186227. png_uint_32 PNGAPI
  186228. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186229. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186230. {
  186231. png_uint_32 retval = 0;
  186232. if (png_ptr != NULL && info_ptr != NULL &&
  186233. (info_ptr->valid & PNG_INFO_pHYs))
  186234. {
  186235. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186236. if (res_x != NULL)
  186237. {
  186238. *res_x = info_ptr->x_pixels_per_unit;
  186239. retval |= PNG_INFO_pHYs;
  186240. }
  186241. if (res_y != NULL)
  186242. {
  186243. *res_y = info_ptr->y_pixels_per_unit;
  186244. retval |= PNG_INFO_pHYs;
  186245. }
  186246. if (unit_type != NULL)
  186247. {
  186248. *unit_type = (int)info_ptr->phys_unit_type;
  186249. retval |= PNG_INFO_pHYs;
  186250. }
  186251. }
  186252. return (retval);
  186253. }
  186254. #endif
  186255. png_uint_32 PNGAPI
  186256. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186257. int *num_palette)
  186258. {
  186259. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186260. && palette != NULL)
  186261. {
  186262. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186263. *palette = info_ptr->palette;
  186264. *num_palette = info_ptr->num_palette;
  186265. png_debug1(3, "num_palette = %d\n", *num_palette);
  186266. return (PNG_INFO_PLTE);
  186267. }
  186268. return (0);
  186269. }
  186270. #if defined(PNG_sBIT_SUPPORTED)
  186271. png_uint_32 PNGAPI
  186272. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186273. {
  186274. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186275. && sig_bit != NULL)
  186276. {
  186277. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186278. *sig_bit = &(info_ptr->sig_bit);
  186279. return (PNG_INFO_sBIT);
  186280. }
  186281. return (0);
  186282. }
  186283. #endif
  186284. #if defined(PNG_TEXT_SUPPORTED)
  186285. png_uint_32 PNGAPI
  186286. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186287. int *num_text)
  186288. {
  186289. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186290. {
  186291. png_debug1(1, "in %s retrieval function\n",
  186292. (png_ptr->chunk_name[0] == '\0' ? "text"
  186293. : (png_const_charp)png_ptr->chunk_name));
  186294. if (text_ptr != NULL)
  186295. *text_ptr = info_ptr->text;
  186296. if (num_text != NULL)
  186297. *num_text = info_ptr->num_text;
  186298. return ((png_uint_32)info_ptr->num_text);
  186299. }
  186300. if (num_text != NULL)
  186301. *num_text = 0;
  186302. return(0);
  186303. }
  186304. #endif
  186305. #if defined(PNG_tIME_SUPPORTED)
  186306. png_uint_32 PNGAPI
  186307. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186308. {
  186309. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186310. && mod_time != NULL)
  186311. {
  186312. png_debug1(1, "in %s retrieval function\n", "tIME");
  186313. *mod_time = &(info_ptr->mod_time);
  186314. return (PNG_INFO_tIME);
  186315. }
  186316. return (0);
  186317. }
  186318. #endif
  186319. #if defined(PNG_tRNS_SUPPORTED)
  186320. png_uint_32 PNGAPI
  186321. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186322. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186323. {
  186324. png_uint_32 retval = 0;
  186325. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186326. {
  186327. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186328. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186329. {
  186330. if (trans != NULL)
  186331. {
  186332. *trans = info_ptr->trans;
  186333. retval |= PNG_INFO_tRNS;
  186334. }
  186335. if (trans_values != NULL)
  186336. *trans_values = &(info_ptr->trans_values);
  186337. }
  186338. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186339. {
  186340. if (trans_values != NULL)
  186341. {
  186342. *trans_values = &(info_ptr->trans_values);
  186343. retval |= PNG_INFO_tRNS;
  186344. }
  186345. if(trans != NULL)
  186346. *trans = NULL;
  186347. }
  186348. if(num_trans != NULL)
  186349. {
  186350. *num_trans = info_ptr->num_trans;
  186351. retval |= PNG_INFO_tRNS;
  186352. }
  186353. }
  186354. return (retval);
  186355. }
  186356. #endif
  186357. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186358. png_uint_32 PNGAPI
  186359. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186360. png_unknown_chunkpp unknowns)
  186361. {
  186362. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186363. {
  186364. *unknowns = info_ptr->unknown_chunks;
  186365. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186366. }
  186367. return (0);
  186368. }
  186369. #endif
  186370. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186371. png_byte PNGAPI
  186372. png_get_rgb_to_gray_status (png_structp png_ptr)
  186373. {
  186374. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186375. }
  186376. #endif
  186377. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186378. png_voidp PNGAPI
  186379. png_get_user_chunk_ptr(png_structp png_ptr)
  186380. {
  186381. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186382. }
  186383. #endif
  186384. #ifdef PNG_WRITE_SUPPORTED
  186385. png_uint_32 PNGAPI
  186386. png_get_compression_buffer_size(png_structp png_ptr)
  186387. {
  186388. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186389. }
  186390. #endif
  186391. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186392. #ifndef PNG_1_0_X
  186393. /* this function was added to libpng 1.2.0 and should exist by default */
  186394. png_uint_32 PNGAPI
  186395. png_get_asm_flags (png_structp png_ptr)
  186396. {
  186397. /* obsolete, to be removed from libpng-1.4.0 */
  186398. return (png_ptr? 0L: 0L);
  186399. }
  186400. /* this function was added to libpng 1.2.0 and should exist by default */
  186401. png_uint_32 PNGAPI
  186402. png_get_asm_flagmask (int flag_select)
  186403. {
  186404. /* obsolete, to be removed from libpng-1.4.0 */
  186405. flag_select=flag_select;
  186406. return 0L;
  186407. }
  186408. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186409. /* this function was added to libpng 1.2.0 */
  186410. png_uint_32 PNGAPI
  186411. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186412. {
  186413. /* obsolete, to be removed from libpng-1.4.0 */
  186414. flag_select=flag_select;
  186415. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186416. return 0L;
  186417. }
  186418. /* this function was added to libpng 1.2.0 */
  186419. png_byte PNGAPI
  186420. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186421. {
  186422. /* obsolete, to be removed from libpng-1.4.0 */
  186423. return (png_ptr? 0: 0);
  186424. }
  186425. /* this function was added to libpng 1.2.0 */
  186426. png_uint_32 PNGAPI
  186427. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186428. {
  186429. /* obsolete, to be removed from libpng-1.4.0 */
  186430. return (png_ptr? 0L: 0L);
  186431. }
  186432. #endif /* ?PNG_1_0_X */
  186433. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186434. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186435. /* these functions were added to libpng 1.2.6 */
  186436. png_uint_32 PNGAPI
  186437. png_get_user_width_max (png_structp png_ptr)
  186438. {
  186439. return (png_ptr? png_ptr->user_width_max : 0);
  186440. }
  186441. png_uint_32 PNGAPI
  186442. png_get_user_height_max (png_structp png_ptr)
  186443. {
  186444. return (png_ptr? png_ptr->user_height_max : 0);
  186445. }
  186446. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186447. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186448. /*** End of inlined file: pngget.c ***/
  186449. /*** Start of inlined file: pngmem.c ***/
  186450. /* pngmem.c - stub functions for memory allocation
  186451. *
  186452. * Last changed in libpng 1.2.13 November 13, 2006
  186453. * For conditions of distribution and use, see copyright notice in png.h
  186454. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186455. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186456. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186457. *
  186458. * This file provides a location for all memory allocation. Users who
  186459. * need special memory handling are expected to supply replacement
  186460. * functions for png_malloc() and png_free(), and to use
  186461. * png_create_read_struct_2() and png_create_write_struct_2() to
  186462. * identify the replacement functions.
  186463. */
  186464. #define PNG_INTERNAL
  186465. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186466. /* Borland DOS special memory handler */
  186467. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186468. /* if you change this, be sure to change the one in png.h also */
  186469. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186470. by a single call to calloc() if this is thought to improve performance. */
  186471. png_voidp /* PRIVATE */
  186472. png_create_struct(int type)
  186473. {
  186474. #ifdef PNG_USER_MEM_SUPPORTED
  186475. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186476. }
  186477. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186478. png_voidp /* PRIVATE */
  186479. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186480. {
  186481. #endif /* PNG_USER_MEM_SUPPORTED */
  186482. png_size_t size;
  186483. png_voidp struct_ptr;
  186484. if (type == PNG_STRUCT_INFO)
  186485. size = png_sizeof(png_info);
  186486. else if (type == PNG_STRUCT_PNG)
  186487. size = png_sizeof(png_struct);
  186488. else
  186489. return (png_get_copyright(NULL));
  186490. #ifdef PNG_USER_MEM_SUPPORTED
  186491. if(malloc_fn != NULL)
  186492. {
  186493. png_struct dummy_struct;
  186494. png_structp png_ptr = &dummy_struct;
  186495. png_ptr->mem_ptr=mem_ptr;
  186496. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186497. }
  186498. else
  186499. #endif /* PNG_USER_MEM_SUPPORTED */
  186500. struct_ptr = (png_voidp)farmalloc(size);
  186501. if (struct_ptr != NULL)
  186502. png_memset(struct_ptr, 0, size);
  186503. return (struct_ptr);
  186504. }
  186505. /* Free memory allocated by a png_create_struct() call */
  186506. void /* PRIVATE */
  186507. png_destroy_struct(png_voidp struct_ptr)
  186508. {
  186509. #ifdef PNG_USER_MEM_SUPPORTED
  186510. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186511. }
  186512. /* Free memory allocated by a png_create_struct() call */
  186513. void /* PRIVATE */
  186514. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186515. png_voidp mem_ptr)
  186516. {
  186517. #endif
  186518. if (struct_ptr != NULL)
  186519. {
  186520. #ifdef PNG_USER_MEM_SUPPORTED
  186521. if(free_fn != NULL)
  186522. {
  186523. png_struct dummy_struct;
  186524. png_structp png_ptr = &dummy_struct;
  186525. png_ptr->mem_ptr=mem_ptr;
  186526. (*(free_fn))(png_ptr, struct_ptr);
  186527. return;
  186528. }
  186529. #endif /* PNG_USER_MEM_SUPPORTED */
  186530. farfree (struct_ptr);
  186531. }
  186532. }
  186533. /* Allocate memory. For reasonable files, size should never exceed
  186534. * 64K. However, zlib may allocate more then 64K if you don't tell
  186535. * it not to. See zconf.h and png.h for more information. zlib does
  186536. * need to allocate exactly 64K, so whatever you call here must
  186537. * have the ability to do that.
  186538. *
  186539. * Borland seems to have a problem in DOS mode for exactly 64K.
  186540. * It gives you a segment with an offset of 8 (perhaps to store its
  186541. * memory stuff). zlib doesn't like this at all, so we have to
  186542. * detect and deal with it. This code should not be needed in
  186543. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186544. * been updated by Alexander Lehmann for version 0.89 to waste less
  186545. * memory.
  186546. *
  186547. * Note that we can't use png_size_t for the "size" declaration,
  186548. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186549. * result, we would be truncating potentially larger memory requests
  186550. * (which should cause a fatal error) and introducing major problems.
  186551. */
  186552. png_voidp PNGAPI
  186553. png_malloc(png_structp png_ptr, png_uint_32 size)
  186554. {
  186555. png_voidp ret;
  186556. if (png_ptr == NULL || size == 0)
  186557. return (NULL);
  186558. #ifdef PNG_USER_MEM_SUPPORTED
  186559. if(png_ptr->malloc_fn != NULL)
  186560. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186561. else
  186562. ret = (png_malloc_default(png_ptr, size));
  186563. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186564. png_error(png_ptr, "Out of memory!");
  186565. return (ret);
  186566. }
  186567. png_voidp PNGAPI
  186568. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186569. {
  186570. png_voidp ret;
  186571. #endif /* PNG_USER_MEM_SUPPORTED */
  186572. if (png_ptr == NULL || size == 0)
  186573. return (NULL);
  186574. #ifdef PNG_MAX_MALLOC_64K
  186575. if (size > (png_uint_32)65536L)
  186576. {
  186577. png_warning(png_ptr, "Cannot Allocate > 64K");
  186578. ret = NULL;
  186579. }
  186580. else
  186581. #endif
  186582. if (size != (size_t)size)
  186583. ret = NULL;
  186584. else if (size == (png_uint_32)65536L)
  186585. {
  186586. if (png_ptr->offset_table == NULL)
  186587. {
  186588. /* try to see if we need to do any of this fancy stuff */
  186589. ret = farmalloc(size);
  186590. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186591. {
  186592. int num_blocks;
  186593. png_uint_32 total_size;
  186594. png_bytep table;
  186595. int i;
  186596. png_byte huge * hptr;
  186597. if (ret != NULL)
  186598. {
  186599. farfree(ret);
  186600. ret = NULL;
  186601. }
  186602. if(png_ptr->zlib_window_bits > 14)
  186603. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186604. else
  186605. num_blocks = 1;
  186606. if (png_ptr->zlib_mem_level >= 7)
  186607. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186608. else
  186609. num_blocks++;
  186610. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186611. table = farmalloc(total_size);
  186612. if (table == NULL)
  186613. {
  186614. #ifndef PNG_USER_MEM_SUPPORTED
  186615. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186616. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186617. else
  186618. png_warning(png_ptr, "Out Of Memory.");
  186619. #endif
  186620. return (NULL);
  186621. }
  186622. if ((png_size_t)table & 0xfff0)
  186623. {
  186624. #ifndef PNG_USER_MEM_SUPPORTED
  186625. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186626. png_error(png_ptr,
  186627. "Farmalloc didn't return normalized pointer");
  186628. else
  186629. png_warning(png_ptr,
  186630. "Farmalloc didn't return normalized pointer");
  186631. #endif
  186632. return (NULL);
  186633. }
  186634. png_ptr->offset_table = table;
  186635. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186636. png_sizeof (png_bytep));
  186637. if (png_ptr->offset_table_ptr == NULL)
  186638. {
  186639. #ifndef PNG_USER_MEM_SUPPORTED
  186640. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186641. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186642. else
  186643. png_warning(png_ptr, "Out Of memory.");
  186644. #endif
  186645. return (NULL);
  186646. }
  186647. hptr = (png_byte huge *)table;
  186648. if ((png_size_t)hptr & 0xf)
  186649. {
  186650. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186651. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186652. }
  186653. for (i = 0; i < num_blocks; i++)
  186654. {
  186655. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186656. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186657. }
  186658. png_ptr->offset_table_number = num_blocks;
  186659. png_ptr->offset_table_count = 0;
  186660. png_ptr->offset_table_count_free = 0;
  186661. }
  186662. }
  186663. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186664. {
  186665. #ifndef PNG_USER_MEM_SUPPORTED
  186666. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186667. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186668. else
  186669. png_warning(png_ptr, "Out of Memory.");
  186670. #endif
  186671. return (NULL);
  186672. }
  186673. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186674. }
  186675. else
  186676. ret = farmalloc(size);
  186677. #ifndef PNG_USER_MEM_SUPPORTED
  186678. if (ret == NULL)
  186679. {
  186680. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186681. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186682. else
  186683. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186684. }
  186685. #endif
  186686. return (ret);
  186687. }
  186688. /* free a pointer allocated by png_malloc(). In the default
  186689. configuration, png_ptr is not used, but is passed in case it
  186690. is needed. If ptr is NULL, return without taking any action. */
  186691. void PNGAPI
  186692. png_free(png_structp png_ptr, png_voidp ptr)
  186693. {
  186694. if (png_ptr == NULL || ptr == NULL)
  186695. return;
  186696. #ifdef PNG_USER_MEM_SUPPORTED
  186697. if (png_ptr->free_fn != NULL)
  186698. {
  186699. (*(png_ptr->free_fn))(png_ptr, ptr);
  186700. return;
  186701. }
  186702. else png_free_default(png_ptr, ptr);
  186703. }
  186704. void PNGAPI
  186705. png_free_default(png_structp png_ptr, png_voidp ptr)
  186706. {
  186707. #endif /* PNG_USER_MEM_SUPPORTED */
  186708. if(png_ptr == NULL) return;
  186709. if (png_ptr->offset_table != NULL)
  186710. {
  186711. int i;
  186712. for (i = 0; i < png_ptr->offset_table_count; i++)
  186713. {
  186714. if (ptr == png_ptr->offset_table_ptr[i])
  186715. {
  186716. ptr = NULL;
  186717. png_ptr->offset_table_count_free++;
  186718. break;
  186719. }
  186720. }
  186721. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186722. {
  186723. farfree(png_ptr->offset_table);
  186724. farfree(png_ptr->offset_table_ptr);
  186725. png_ptr->offset_table = NULL;
  186726. png_ptr->offset_table_ptr = NULL;
  186727. }
  186728. }
  186729. if (ptr != NULL)
  186730. {
  186731. farfree(ptr);
  186732. }
  186733. }
  186734. #else /* Not the Borland DOS special memory handler */
  186735. /* Allocate memory for a png_struct or a png_info. The malloc and
  186736. memset can be replaced by a single call to calloc() if this is thought
  186737. to improve performance noticably. */
  186738. png_voidp /* PRIVATE */
  186739. png_create_struct(int type)
  186740. {
  186741. #ifdef PNG_USER_MEM_SUPPORTED
  186742. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186743. }
  186744. /* Allocate memory for a png_struct or a png_info. The malloc and
  186745. memset can be replaced by a single call to calloc() if this is thought
  186746. to improve performance noticably. */
  186747. png_voidp /* PRIVATE */
  186748. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186749. {
  186750. #endif /* PNG_USER_MEM_SUPPORTED */
  186751. png_size_t size;
  186752. png_voidp struct_ptr;
  186753. if (type == PNG_STRUCT_INFO)
  186754. size = png_sizeof(png_info);
  186755. else if (type == PNG_STRUCT_PNG)
  186756. size = png_sizeof(png_struct);
  186757. else
  186758. return (NULL);
  186759. #ifdef PNG_USER_MEM_SUPPORTED
  186760. if(malloc_fn != NULL)
  186761. {
  186762. png_struct dummy_struct;
  186763. png_structp png_ptr = &dummy_struct;
  186764. png_ptr->mem_ptr=mem_ptr;
  186765. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186766. if (struct_ptr != NULL)
  186767. png_memset(struct_ptr, 0, size);
  186768. return (struct_ptr);
  186769. }
  186770. #endif /* PNG_USER_MEM_SUPPORTED */
  186771. #if defined(__TURBOC__) && !defined(__FLAT__)
  186772. struct_ptr = (png_voidp)farmalloc(size);
  186773. #else
  186774. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186775. struct_ptr = (png_voidp)halloc(size,1);
  186776. # else
  186777. struct_ptr = (png_voidp)malloc(size);
  186778. # endif
  186779. #endif
  186780. if (struct_ptr != NULL)
  186781. png_memset(struct_ptr, 0, size);
  186782. return (struct_ptr);
  186783. }
  186784. /* Free memory allocated by a png_create_struct() call */
  186785. void /* PRIVATE */
  186786. png_destroy_struct(png_voidp struct_ptr)
  186787. {
  186788. #ifdef PNG_USER_MEM_SUPPORTED
  186789. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186790. }
  186791. /* Free memory allocated by a png_create_struct() call */
  186792. void /* PRIVATE */
  186793. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186794. png_voidp mem_ptr)
  186795. {
  186796. #endif /* PNG_USER_MEM_SUPPORTED */
  186797. if (struct_ptr != NULL)
  186798. {
  186799. #ifdef PNG_USER_MEM_SUPPORTED
  186800. if(free_fn != NULL)
  186801. {
  186802. png_struct dummy_struct;
  186803. png_structp png_ptr = &dummy_struct;
  186804. png_ptr->mem_ptr=mem_ptr;
  186805. (*(free_fn))(png_ptr, struct_ptr);
  186806. return;
  186807. }
  186808. #endif /* PNG_USER_MEM_SUPPORTED */
  186809. #if defined(__TURBOC__) && !defined(__FLAT__)
  186810. farfree(struct_ptr);
  186811. #else
  186812. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186813. hfree(struct_ptr);
  186814. # else
  186815. free(struct_ptr);
  186816. # endif
  186817. #endif
  186818. }
  186819. }
  186820. /* Allocate memory. For reasonable files, size should never exceed
  186821. 64K. However, zlib may allocate more then 64K if you don't tell
  186822. it not to. See zconf.h and png.h for more information. zlib does
  186823. need to allocate exactly 64K, so whatever you call here must
  186824. have the ability to do that. */
  186825. png_voidp PNGAPI
  186826. png_malloc(png_structp png_ptr, png_uint_32 size)
  186827. {
  186828. png_voidp ret;
  186829. #ifdef PNG_USER_MEM_SUPPORTED
  186830. if (png_ptr == NULL || size == 0)
  186831. return (NULL);
  186832. if(png_ptr->malloc_fn != NULL)
  186833. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186834. else
  186835. ret = (png_malloc_default(png_ptr, size));
  186836. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186837. png_error(png_ptr, "Out of Memory!");
  186838. return (ret);
  186839. }
  186840. png_voidp PNGAPI
  186841. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186842. {
  186843. png_voidp ret;
  186844. #endif /* PNG_USER_MEM_SUPPORTED */
  186845. if (png_ptr == NULL || size == 0)
  186846. return (NULL);
  186847. #ifdef PNG_MAX_MALLOC_64K
  186848. if (size > (png_uint_32)65536L)
  186849. {
  186850. #ifndef PNG_USER_MEM_SUPPORTED
  186851. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186852. png_error(png_ptr, "Cannot Allocate > 64K");
  186853. else
  186854. #endif
  186855. return NULL;
  186856. }
  186857. #endif
  186858. /* Check for overflow */
  186859. #if defined(__TURBOC__) && !defined(__FLAT__)
  186860. if (size != (unsigned long)size)
  186861. ret = NULL;
  186862. else
  186863. ret = farmalloc(size);
  186864. #else
  186865. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186866. if (size != (unsigned long)size)
  186867. ret = NULL;
  186868. else
  186869. ret = halloc(size, 1);
  186870. # else
  186871. if (size != (size_t)size)
  186872. ret = NULL;
  186873. else
  186874. ret = malloc((size_t)size);
  186875. # endif
  186876. #endif
  186877. #ifndef PNG_USER_MEM_SUPPORTED
  186878. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186879. png_error(png_ptr, "Out of Memory");
  186880. #endif
  186881. return (ret);
  186882. }
  186883. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186884. without taking any action. */
  186885. void PNGAPI
  186886. png_free(png_structp png_ptr, png_voidp ptr)
  186887. {
  186888. if (png_ptr == NULL || ptr == NULL)
  186889. return;
  186890. #ifdef PNG_USER_MEM_SUPPORTED
  186891. if (png_ptr->free_fn != NULL)
  186892. {
  186893. (*(png_ptr->free_fn))(png_ptr, ptr);
  186894. return;
  186895. }
  186896. else png_free_default(png_ptr, ptr);
  186897. }
  186898. void PNGAPI
  186899. png_free_default(png_structp png_ptr, png_voidp ptr)
  186900. {
  186901. if (png_ptr == NULL || ptr == NULL)
  186902. return;
  186903. #endif /* PNG_USER_MEM_SUPPORTED */
  186904. #if defined(__TURBOC__) && !defined(__FLAT__)
  186905. farfree(ptr);
  186906. #else
  186907. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186908. hfree(ptr);
  186909. # else
  186910. free(ptr);
  186911. # endif
  186912. #endif
  186913. }
  186914. #endif /* Not Borland DOS special memory handler */
  186915. #if defined(PNG_1_0_X)
  186916. # define png_malloc_warn png_malloc
  186917. #else
  186918. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186919. * function will set up png_malloc() to issue a png_warning and return NULL
  186920. * instead of issuing a png_error, if it fails to allocate the requested
  186921. * memory.
  186922. */
  186923. png_voidp PNGAPI
  186924. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186925. {
  186926. png_voidp ptr;
  186927. png_uint_32 save_flags;
  186928. if(png_ptr == NULL) return (NULL);
  186929. save_flags=png_ptr->flags;
  186930. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186931. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186932. png_ptr->flags=save_flags;
  186933. return(ptr);
  186934. }
  186935. #endif
  186936. png_voidp PNGAPI
  186937. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186938. png_uint_32 length)
  186939. {
  186940. png_size_t size;
  186941. size = (png_size_t)length;
  186942. if ((png_uint_32)size != length)
  186943. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186944. return(png_memcpy (s1, s2, size));
  186945. }
  186946. png_voidp PNGAPI
  186947. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186948. png_uint_32 length)
  186949. {
  186950. png_size_t size;
  186951. size = (png_size_t)length;
  186952. if ((png_uint_32)size != length)
  186953. png_error(png_ptr,"Overflow in png_memset_check.");
  186954. return (png_memset (s1, value, size));
  186955. }
  186956. #ifdef PNG_USER_MEM_SUPPORTED
  186957. /* This function is called when the application wants to use another method
  186958. * of allocating and freeing memory.
  186959. */
  186960. void PNGAPI
  186961. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186962. malloc_fn, png_free_ptr free_fn)
  186963. {
  186964. if(png_ptr != NULL) {
  186965. png_ptr->mem_ptr = mem_ptr;
  186966. png_ptr->malloc_fn = malloc_fn;
  186967. png_ptr->free_fn = free_fn;
  186968. }
  186969. }
  186970. /* This function returns a pointer to the mem_ptr associated with the user
  186971. * functions. The application should free any memory associated with this
  186972. * pointer before png_write_destroy and png_read_destroy are called.
  186973. */
  186974. png_voidp PNGAPI
  186975. png_get_mem_ptr(png_structp png_ptr)
  186976. {
  186977. if(png_ptr == NULL) return (NULL);
  186978. return ((png_voidp)png_ptr->mem_ptr);
  186979. }
  186980. #endif /* PNG_USER_MEM_SUPPORTED */
  186981. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186982. /*** End of inlined file: pngmem.c ***/
  186983. /*** Start of inlined file: pngread.c ***/
  186984. /* pngread.c - read a PNG file
  186985. *
  186986. * Last changed in libpng 1.2.20 September 7, 2007
  186987. * For conditions of distribution and use, see copyright notice in png.h
  186988. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186989. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186990. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186991. *
  186992. * This file contains routines that an application calls directly to
  186993. * read a PNG file or stream.
  186994. */
  186995. #define PNG_INTERNAL
  186996. #if defined(PNG_READ_SUPPORTED)
  186997. /* Create a PNG structure for reading, and allocate any memory needed. */
  186998. png_structp PNGAPI
  186999. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187000. png_error_ptr error_fn, png_error_ptr warn_fn)
  187001. {
  187002. #ifdef PNG_USER_MEM_SUPPORTED
  187003. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187004. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187005. }
  187006. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187007. png_structp PNGAPI
  187008. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187009. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187010. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187011. {
  187012. #endif /* PNG_USER_MEM_SUPPORTED */
  187013. png_structp png_ptr;
  187014. #ifdef PNG_SETJMP_SUPPORTED
  187015. #ifdef USE_FAR_KEYWORD
  187016. jmp_buf jmpbuf;
  187017. #endif
  187018. #endif
  187019. int i;
  187020. png_debug(1, "in png_create_read_struct\n");
  187021. #ifdef PNG_USER_MEM_SUPPORTED
  187022. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187023. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187024. #else
  187025. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187026. #endif
  187027. if (png_ptr == NULL)
  187028. return (NULL);
  187029. /* added at libpng-1.2.6 */
  187030. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187031. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187032. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187033. #endif
  187034. #ifdef PNG_SETJMP_SUPPORTED
  187035. #ifdef USE_FAR_KEYWORD
  187036. if (setjmp(jmpbuf))
  187037. #else
  187038. if (setjmp(png_ptr->jmpbuf))
  187039. #endif
  187040. {
  187041. png_free(png_ptr, png_ptr->zbuf);
  187042. png_ptr->zbuf=NULL;
  187043. #ifdef PNG_USER_MEM_SUPPORTED
  187044. png_destroy_struct_2((png_voidp)png_ptr,
  187045. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187046. #else
  187047. png_destroy_struct((png_voidp)png_ptr);
  187048. #endif
  187049. return (NULL);
  187050. }
  187051. #ifdef USE_FAR_KEYWORD
  187052. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187053. #endif
  187054. #endif
  187055. #ifdef PNG_USER_MEM_SUPPORTED
  187056. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187057. #endif
  187058. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187059. i=0;
  187060. do
  187061. {
  187062. if(user_png_ver[i] != png_libpng_ver[i])
  187063. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187064. } while (png_libpng_ver[i++]);
  187065. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187066. {
  187067. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187068. * we must recompile any applications that use any older library version.
  187069. * For versions after libpng 1.0, we will be compatible, so we need
  187070. * only check the first digit.
  187071. */
  187072. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187073. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187074. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187075. {
  187076. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187077. char msg[80];
  187078. if (user_png_ver)
  187079. {
  187080. png_snprintf(msg, 80,
  187081. "Application was compiled with png.h from libpng-%.20s",
  187082. user_png_ver);
  187083. png_warning(png_ptr, msg);
  187084. }
  187085. png_snprintf(msg, 80,
  187086. "Application is running with png.c from libpng-%.20s",
  187087. png_libpng_ver);
  187088. png_warning(png_ptr, msg);
  187089. #endif
  187090. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187091. png_ptr->flags=0;
  187092. #endif
  187093. png_error(png_ptr,
  187094. "Incompatible libpng version in application and library");
  187095. }
  187096. }
  187097. /* initialize zbuf - compression buffer */
  187098. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187099. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187100. (png_uint_32)png_ptr->zbuf_size);
  187101. png_ptr->zstream.zalloc = png_zalloc;
  187102. png_ptr->zstream.zfree = png_zfree;
  187103. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187104. switch (inflateInit(&png_ptr->zstream))
  187105. {
  187106. case Z_OK: /* Do nothing */ break;
  187107. case Z_MEM_ERROR:
  187108. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187109. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187110. default: png_error(png_ptr, "Unknown zlib error");
  187111. }
  187112. png_ptr->zstream.next_out = png_ptr->zbuf;
  187113. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187114. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187115. #ifdef PNG_SETJMP_SUPPORTED
  187116. /* Applications that neglect to set up their own setjmp() and then encounter
  187117. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187118. abort instead of returning. */
  187119. #ifdef USE_FAR_KEYWORD
  187120. if (setjmp(jmpbuf))
  187121. PNG_ABORT();
  187122. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187123. #else
  187124. if (setjmp(png_ptr->jmpbuf))
  187125. PNG_ABORT();
  187126. #endif
  187127. #endif
  187128. return (png_ptr);
  187129. }
  187130. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187131. /* Initialize PNG structure for reading, and allocate any memory needed.
  187132. This interface is deprecated in favour of the png_create_read_struct(),
  187133. and it will disappear as of libpng-1.3.0. */
  187134. #undef png_read_init
  187135. void PNGAPI
  187136. png_read_init(png_structp png_ptr)
  187137. {
  187138. /* We only come here via pre-1.0.7-compiled applications */
  187139. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187140. }
  187141. void PNGAPI
  187142. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187143. png_size_t png_struct_size, png_size_t png_info_size)
  187144. {
  187145. /* We only come here via pre-1.0.12-compiled applications */
  187146. if(png_ptr == NULL) return;
  187147. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187148. if(png_sizeof(png_struct) > png_struct_size ||
  187149. png_sizeof(png_info) > png_info_size)
  187150. {
  187151. char msg[80];
  187152. png_ptr->warning_fn=NULL;
  187153. if (user_png_ver)
  187154. {
  187155. png_snprintf(msg, 80,
  187156. "Application was compiled with png.h from libpng-%.20s",
  187157. user_png_ver);
  187158. png_warning(png_ptr, msg);
  187159. }
  187160. png_snprintf(msg, 80,
  187161. "Application is running with png.c from libpng-%.20s",
  187162. png_libpng_ver);
  187163. png_warning(png_ptr, msg);
  187164. }
  187165. #endif
  187166. if(png_sizeof(png_struct) > png_struct_size)
  187167. {
  187168. png_ptr->error_fn=NULL;
  187169. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187170. png_ptr->flags=0;
  187171. #endif
  187172. png_error(png_ptr,
  187173. "The png struct allocated by the application for reading is too small.");
  187174. }
  187175. if(png_sizeof(png_info) > png_info_size)
  187176. {
  187177. png_ptr->error_fn=NULL;
  187178. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187179. png_ptr->flags=0;
  187180. #endif
  187181. png_error(png_ptr,
  187182. "The info struct allocated by application for reading is too small.");
  187183. }
  187184. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187185. }
  187186. #endif /* PNG_1_0_X || PNG_1_2_X */
  187187. void PNGAPI
  187188. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187189. png_size_t png_struct_size)
  187190. {
  187191. #ifdef PNG_SETJMP_SUPPORTED
  187192. jmp_buf tmp_jmp; /* to save current jump buffer */
  187193. #endif
  187194. int i=0;
  187195. png_structp png_ptr=*ptr_ptr;
  187196. if(png_ptr == NULL) return;
  187197. do
  187198. {
  187199. if(user_png_ver[i] != png_libpng_ver[i])
  187200. {
  187201. #ifdef PNG_LEGACY_SUPPORTED
  187202. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187203. #else
  187204. png_ptr->warning_fn=NULL;
  187205. png_warning(png_ptr,
  187206. "Application uses deprecated png_read_init() and should be recompiled.");
  187207. break;
  187208. #endif
  187209. }
  187210. } while (png_libpng_ver[i++]);
  187211. png_debug(1, "in png_read_init_3\n");
  187212. #ifdef PNG_SETJMP_SUPPORTED
  187213. /* save jump buffer and error functions */
  187214. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187215. #endif
  187216. if(png_sizeof(png_struct) > png_struct_size)
  187217. {
  187218. png_destroy_struct(png_ptr);
  187219. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187220. png_ptr = *ptr_ptr;
  187221. }
  187222. /* reset all variables to 0 */
  187223. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187224. #ifdef PNG_SETJMP_SUPPORTED
  187225. /* restore jump buffer */
  187226. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187227. #endif
  187228. /* added at libpng-1.2.6 */
  187229. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187230. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187231. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187232. #endif
  187233. /* initialize zbuf - compression buffer */
  187234. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187235. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187236. (png_uint_32)png_ptr->zbuf_size);
  187237. png_ptr->zstream.zalloc = png_zalloc;
  187238. png_ptr->zstream.zfree = png_zfree;
  187239. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187240. switch (inflateInit(&png_ptr->zstream))
  187241. {
  187242. case Z_OK: /* Do nothing */ break;
  187243. case Z_MEM_ERROR:
  187244. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187245. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187246. default: png_error(png_ptr, "Unknown zlib error");
  187247. }
  187248. png_ptr->zstream.next_out = png_ptr->zbuf;
  187249. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187250. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187251. }
  187252. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187253. /* Read the information before the actual image data. This has been
  187254. * changed in v0.90 to allow reading a file that already has the magic
  187255. * bytes read from the stream. You can tell libpng how many bytes have
  187256. * been read from the beginning of the stream (up to the maximum of 8)
  187257. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187258. * here. The application can then have access to the signature bytes we
  187259. * read if it is determined that this isn't a valid PNG file.
  187260. */
  187261. void PNGAPI
  187262. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187263. {
  187264. if(png_ptr == NULL) return;
  187265. png_debug(1, "in png_read_info\n");
  187266. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187267. if (png_ptr->sig_bytes < 8)
  187268. {
  187269. png_size_t num_checked = png_ptr->sig_bytes,
  187270. num_to_check = 8 - num_checked;
  187271. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187272. png_ptr->sig_bytes = 8;
  187273. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187274. {
  187275. if (num_checked < 4 &&
  187276. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187277. png_error(png_ptr, "Not a PNG file");
  187278. else
  187279. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187280. }
  187281. if (num_checked < 3)
  187282. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187283. }
  187284. for(;;)
  187285. {
  187286. #ifdef PNG_USE_LOCAL_ARRAYS
  187287. PNG_CONST PNG_IHDR;
  187288. PNG_CONST PNG_IDAT;
  187289. PNG_CONST PNG_IEND;
  187290. PNG_CONST PNG_PLTE;
  187291. #if defined(PNG_READ_bKGD_SUPPORTED)
  187292. PNG_CONST PNG_bKGD;
  187293. #endif
  187294. #if defined(PNG_READ_cHRM_SUPPORTED)
  187295. PNG_CONST PNG_cHRM;
  187296. #endif
  187297. #if defined(PNG_READ_gAMA_SUPPORTED)
  187298. PNG_CONST PNG_gAMA;
  187299. #endif
  187300. #if defined(PNG_READ_hIST_SUPPORTED)
  187301. PNG_CONST PNG_hIST;
  187302. #endif
  187303. #if defined(PNG_READ_iCCP_SUPPORTED)
  187304. PNG_CONST PNG_iCCP;
  187305. #endif
  187306. #if defined(PNG_READ_iTXt_SUPPORTED)
  187307. PNG_CONST PNG_iTXt;
  187308. #endif
  187309. #if defined(PNG_READ_oFFs_SUPPORTED)
  187310. PNG_CONST PNG_oFFs;
  187311. #endif
  187312. #if defined(PNG_READ_pCAL_SUPPORTED)
  187313. PNG_CONST PNG_pCAL;
  187314. #endif
  187315. #if defined(PNG_READ_pHYs_SUPPORTED)
  187316. PNG_CONST PNG_pHYs;
  187317. #endif
  187318. #if defined(PNG_READ_sBIT_SUPPORTED)
  187319. PNG_CONST PNG_sBIT;
  187320. #endif
  187321. #if defined(PNG_READ_sCAL_SUPPORTED)
  187322. PNG_CONST PNG_sCAL;
  187323. #endif
  187324. #if defined(PNG_READ_sPLT_SUPPORTED)
  187325. PNG_CONST PNG_sPLT;
  187326. #endif
  187327. #if defined(PNG_READ_sRGB_SUPPORTED)
  187328. PNG_CONST PNG_sRGB;
  187329. #endif
  187330. #if defined(PNG_READ_tEXt_SUPPORTED)
  187331. PNG_CONST PNG_tEXt;
  187332. #endif
  187333. #if defined(PNG_READ_tIME_SUPPORTED)
  187334. PNG_CONST PNG_tIME;
  187335. #endif
  187336. #if defined(PNG_READ_tRNS_SUPPORTED)
  187337. PNG_CONST PNG_tRNS;
  187338. #endif
  187339. #if defined(PNG_READ_zTXt_SUPPORTED)
  187340. PNG_CONST PNG_zTXt;
  187341. #endif
  187342. #endif /* PNG_USE_LOCAL_ARRAYS */
  187343. png_byte chunk_length[4];
  187344. png_uint_32 length;
  187345. png_read_data(png_ptr, chunk_length, 4);
  187346. length = png_get_uint_31(png_ptr,chunk_length);
  187347. png_reset_crc(png_ptr);
  187348. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187349. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187350. length);
  187351. /* This should be a binary subdivision search or a hash for
  187352. * matching the chunk name rather than a linear search.
  187353. */
  187354. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187355. if(png_ptr->mode & PNG_AFTER_IDAT)
  187356. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187357. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187358. png_handle_IHDR(png_ptr, info_ptr, length);
  187359. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187360. png_handle_IEND(png_ptr, info_ptr, length);
  187361. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187362. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187363. {
  187364. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187365. png_ptr->mode |= PNG_HAVE_IDAT;
  187366. png_handle_unknown(png_ptr, info_ptr, length);
  187367. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187368. png_ptr->mode |= PNG_HAVE_PLTE;
  187369. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187370. {
  187371. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187372. png_error(png_ptr, "Missing IHDR before IDAT");
  187373. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187374. !(png_ptr->mode & PNG_HAVE_PLTE))
  187375. png_error(png_ptr, "Missing PLTE before IDAT");
  187376. break;
  187377. }
  187378. }
  187379. #endif
  187380. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187381. png_handle_PLTE(png_ptr, info_ptr, length);
  187382. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187383. {
  187384. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187385. png_error(png_ptr, "Missing IHDR before IDAT");
  187386. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187387. !(png_ptr->mode & PNG_HAVE_PLTE))
  187388. png_error(png_ptr, "Missing PLTE before IDAT");
  187389. png_ptr->idat_size = length;
  187390. png_ptr->mode |= PNG_HAVE_IDAT;
  187391. break;
  187392. }
  187393. #if defined(PNG_READ_bKGD_SUPPORTED)
  187394. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187395. png_handle_bKGD(png_ptr, info_ptr, length);
  187396. #endif
  187397. #if defined(PNG_READ_cHRM_SUPPORTED)
  187398. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187399. png_handle_cHRM(png_ptr, info_ptr, length);
  187400. #endif
  187401. #if defined(PNG_READ_gAMA_SUPPORTED)
  187402. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187403. png_handle_gAMA(png_ptr, info_ptr, length);
  187404. #endif
  187405. #if defined(PNG_READ_hIST_SUPPORTED)
  187406. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187407. png_handle_hIST(png_ptr, info_ptr, length);
  187408. #endif
  187409. #if defined(PNG_READ_oFFs_SUPPORTED)
  187410. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187411. png_handle_oFFs(png_ptr, info_ptr, length);
  187412. #endif
  187413. #if defined(PNG_READ_pCAL_SUPPORTED)
  187414. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187415. png_handle_pCAL(png_ptr, info_ptr, length);
  187416. #endif
  187417. #if defined(PNG_READ_sCAL_SUPPORTED)
  187418. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187419. png_handle_sCAL(png_ptr, info_ptr, length);
  187420. #endif
  187421. #if defined(PNG_READ_pHYs_SUPPORTED)
  187422. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187423. png_handle_pHYs(png_ptr, info_ptr, length);
  187424. #endif
  187425. #if defined(PNG_READ_sBIT_SUPPORTED)
  187426. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187427. png_handle_sBIT(png_ptr, info_ptr, length);
  187428. #endif
  187429. #if defined(PNG_READ_sRGB_SUPPORTED)
  187430. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187431. png_handle_sRGB(png_ptr, info_ptr, length);
  187432. #endif
  187433. #if defined(PNG_READ_iCCP_SUPPORTED)
  187434. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187435. png_handle_iCCP(png_ptr, info_ptr, length);
  187436. #endif
  187437. #if defined(PNG_READ_sPLT_SUPPORTED)
  187438. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187439. png_handle_sPLT(png_ptr, info_ptr, length);
  187440. #endif
  187441. #if defined(PNG_READ_tEXt_SUPPORTED)
  187442. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187443. png_handle_tEXt(png_ptr, info_ptr, length);
  187444. #endif
  187445. #if defined(PNG_READ_tIME_SUPPORTED)
  187446. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187447. png_handle_tIME(png_ptr, info_ptr, length);
  187448. #endif
  187449. #if defined(PNG_READ_tRNS_SUPPORTED)
  187450. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187451. png_handle_tRNS(png_ptr, info_ptr, length);
  187452. #endif
  187453. #if defined(PNG_READ_zTXt_SUPPORTED)
  187454. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187455. png_handle_zTXt(png_ptr, info_ptr, length);
  187456. #endif
  187457. #if defined(PNG_READ_iTXt_SUPPORTED)
  187458. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187459. png_handle_iTXt(png_ptr, info_ptr, length);
  187460. #endif
  187461. else
  187462. png_handle_unknown(png_ptr, info_ptr, length);
  187463. }
  187464. }
  187465. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187466. /* optional call to update the users info_ptr structure */
  187467. void PNGAPI
  187468. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187469. {
  187470. png_debug(1, "in png_read_update_info\n");
  187471. if(png_ptr == NULL) return;
  187472. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187473. png_read_start_row(png_ptr);
  187474. else
  187475. png_warning(png_ptr,
  187476. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187477. png_read_transform_info(png_ptr, info_ptr);
  187478. }
  187479. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187480. /* Initialize palette, background, etc, after transformations
  187481. * are set, but before any reading takes place. This allows
  187482. * the user to obtain a gamma-corrected palette, for example.
  187483. * If the user doesn't call this, we will do it ourselves.
  187484. */
  187485. void PNGAPI
  187486. png_start_read_image(png_structp png_ptr)
  187487. {
  187488. png_debug(1, "in png_start_read_image\n");
  187489. if(png_ptr == NULL) return;
  187490. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187491. png_read_start_row(png_ptr);
  187492. }
  187493. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187494. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187495. void PNGAPI
  187496. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187497. {
  187498. #ifdef PNG_USE_LOCAL_ARRAYS
  187499. PNG_CONST PNG_IDAT;
  187500. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187501. 0xff};
  187502. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187503. #endif
  187504. int ret;
  187505. if(png_ptr == NULL) return;
  187506. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187507. png_ptr->row_number, png_ptr->pass);
  187508. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187509. png_read_start_row(png_ptr);
  187510. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187511. {
  187512. /* check for transforms that have been set but were defined out */
  187513. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187514. if (png_ptr->transformations & PNG_INVERT_MONO)
  187515. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187516. #endif
  187517. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187518. if (png_ptr->transformations & PNG_FILLER)
  187519. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187520. #endif
  187521. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187522. if (png_ptr->transformations & PNG_PACKSWAP)
  187523. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187524. #endif
  187525. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187526. if (png_ptr->transformations & PNG_PACK)
  187527. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187528. #endif
  187529. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187530. if (png_ptr->transformations & PNG_SHIFT)
  187531. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187532. #endif
  187533. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187534. if (png_ptr->transformations & PNG_BGR)
  187535. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187536. #endif
  187537. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187538. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187539. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187540. #endif
  187541. }
  187542. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187543. /* if interlaced and we do not need a new row, combine row and return */
  187544. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187545. {
  187546. switch (png_ptr->pass)
  187547. {
  187548. case 0:
  187549. if (png_ptr->row_number & 0x07)
  187550. {
  187551. if (dsp_row != NULL)
  187552. png_combine_row(png_ptr, dsp_row,
  187553. png_pass_dsp_mask[png_ptr->pass]);
  187554. png_read_finish_row(png_ptr);
  187555. return;
  187556. }
  187557. break;
  187558. case 1:
  187559. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187560. {
  187561. if (dsp_row != NULL)
  187562. png_combine_row(png_ptr, dsp_row,
  187563. png_pass_dsp_mask[png_ptr->pass]);
  187564. png_read_finish_row(png_ptr);
  187565. return;
  187566. }
  187567. break;
  187568. case 2:
  187569. if ((png_ptr->row_number & 0x07) != 4)
  187570. {
  187571. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187572. png_combine_row(png_ptr, dsp_row,
  187573. png_pass_dsp_mask[png_ptr->pass]);
  187574. png_read_finish_row(png_ptr);
  187575. return;
  187576. }
  187577. break;
  187578. case 3:
  187579. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187580. {
  187581. if (dsp_row != NULL)
  187582. png_combine_row(png_ptr, dsp_row,
  187583. png_pass_dsp_mask[png_ptr->pass]);
  187584. png_read_finish_row(png_ptr);
  187585. return;
  187586. }
  187587. break;
  187588. case 4:
  187589. if ((png_ptr->row_number & 3) != 2)
  187590. {
  187591. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187592. png_combine_row(png_ptr, dsp_row,
  187593. png_pass_dsp_mask[png_ptr->pass]);
  187594. png_read_finish_row(png_ptr);
  187595. return;
  187596. }
  187597. break;
  187598. case 5:
  187599. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187600. {
  187601. if (dsp_row != NULL)
  187602. png_combine_row(png_ptr, dsp_row,
  187603. png_pass_dsp_mask[png_ptr->pass]);
  187604. png_read_finish_row(png_ptr);
  187605. return;
  187606. }
  187607. break;
  187608. case 6:
  187609. if (!(png_ptr->row_number & 1))
  187610. {
  187611. png_read_finish_row(png_ptr);
  187612. return;
  187613. }
  187614. break;
  187615. }
  187616. }
  187617. #endif
  187618. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187619. png_error(png_ptr, "Invalid attempt to read row data");
  187620. png_ptr->zstream.next_out = png_ptr->row_buf;
  187621. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187622. do
  187623. {
  187624. if (!(png_ptr->zstream.avail_in))
  187625. {
  187626. while (!png_ptr->idat_size)
  187627. {
  187628. png_byte chunk_length[4];
  187629. png_crc_finish(png_ptr, 0);
  187630. png_read_data(png_ptr, chunk_length, 4);
  187631. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187632. png_reset_crc(png_ptr);
  187633. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187634. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187635. png_error(png_ptr, "Not enough image data");
  187636. }
  187637. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187638. png_ptr->zstream.next_in = png_ptr->zbuf;
  187639. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187640. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187641. png_crc_read(png_ptr, png_ptr->zbuf,
  187642. (png_size_t)png_ptr->zstream.avail_in);
  187643. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187644. }
  187645. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187646. if (ret == Z_STREAM_END)
  187647. {
  187648. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187649. png_ptr->idat_size)
  187650. png_error(png_ptr, "Extra compressed data");
  187651. png_ptr->mode |= PNG_AFTER_IDAT;
  187652. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187653. break;
  187654. }
  187655. if (ret != Z_OK)
  187656. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187657. "Decompression error");
  187658. } while (png_ptr->zstream.avail_out);
  187659. png_ptr->row_info.color_type = png_ptr->color_type;
  187660. png_ptr->row_info.width = png_ptr->iwidth;
  187661. png_ptr->row_info.channels = png_ptr->channels;
  187662. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187663. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187664. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187665. png_ptr->row_info.width);
  187666. if(png_ptr->row_buf[0])
  187667. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187668. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187669. (int)(png_ptr->row_buf[0]));
  187670. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187671. png_ptr->rowbytes + 1);
  187672. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187673. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187674. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187675. {
  187676. /* Intrapixel differencing */
  187677. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187678. }
  187679. #endif
  187680. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187681. png_do_read_transformations(png_ptr);
  187682. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187683. /* blow up interlaced rows to full size */
  187684. if (png_ptr->interlaced &&
  187685. (png_ptr->transformations & PNG_INTERLACE))
  187686. {
  187687. if (png_ptr->pass < 6)
  187688. /* old interface (pre-1.0.9):
  187689. png_do_read_interlace(&(png_ptr->row_info),
  187690. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187691. */
  187692. png_do_read_interlace(png_ptr);
  187693. if (dsp_row != NULL)
  187694. png_combine_row(png_ptr, dsp_row,
  187695. png_pass_dsp_mask[png_ptr->pass]);
  187696. if (row != NULL)
  187697. png_combine_row(png_ptr, row,
  187698. png_pass_mask[png_ptr->pass]);
  187699. }
  187700. else
  187701. #endif
  187702. {
  187703. if (row != NULL)
  187704. png_combine_row(png_ptr, row, 0xff);
  187705. if (dsp_row != NULL)
  187706. png_combine_row(png_ptr, dsp_row, 0xff);
  187707. }
  187708. png_read_finish_row(png_ptr);
  187709. if (png_ptr->read_row_fn != NULL)
  187710. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187711. }
  187712. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187713. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187714. /* Read one or more rows of image data. If the image is interlaced,
  187715. * and png_set_interlace_handling() has been called, the rows need to
  187716. * contain the contents of the rows from the previous pass. If the
  187717. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187718. * called, the rows contents must be initialized to the contents of the
  187719. * screen.
  187720. *
  187721. * "row" holds the actual image, and pixels are placed in it
  187722. * as they arrive. If the image is displayed after each pass, it will
  187723. * appear to "sparkle" in. "display_row" can be used to display a
  187724. * "chunky" progressive image, with finer detail added as it becomes
  187725. * available. If you do not want this "chunky" display, you may pass
  187726. * NULL for display_row. If you do not want the sparkle display, and
  187727. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187728. * If you have called png_handle_alpha(), and the image has either an
  187729. * alpha channel or a transparency chunk, you must provide a buffer for
  187730. * rows. In this case, you do not have to provide a display_row buffer
  187731. * also, but you may. If the image is not interlaced, or if you have
  187732. * not called png_set_interlace_handling(), the display_row buffer will
  187733. * be ignored, so pass NULL to it.
  187734. *
  187735. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187736. */
  187737. void PNGAPI
  187738. png_read_rows(png_structp png_ptr, png_bytepp row,
  187739. png_bytepp display_row, png_uint_32 num_rows)
  187740. {
  187741. png_uint_32 i;
  187742. png_bytepp rp;
  187743. png_bytepp dp;
  187744. png_debug(1, "in png_read_rows\n");
  187745. if(png_ptr == NULL) return;
  187746. rp = row;
  187747. dp = display_row;
  187748. if (rp != NULL && dp != NULL)
  187749. for (i = 0; i < num_rows; i++)
  187750. {
  187751. png_bytep rptr = *rp++;
  187752. png_bytep dptr = *dp++;
  187753. png_read_row(png_ptr, rptr, dptr);
  187754. }
  187755. else if(rp != NULL)
  187756. for (i = 0; i < num_rows; i++)
  187757. {
  187758. png_bytep rptr = *rp;
  187759. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187760. rp++;
  187761. }
  187762. else if(dp != NULL)
  187763. for (i = 0; i < num_rows; i++)
  187764. {
  187765. png_bytep dptr = *dp;
  187766. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187767. dp++;
  187768. }
  187769. }
  187770. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187771. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187772. /* Read the entire image. If the image has an alpha channel or a tRNS
  187773. * chunk, and you have called png_handle_alpha()[*], you will need to
  187774. * initialize the image to the current image that PNG will be overlaying.
  187775. * We set the num_rows again here, in case it was incorrectly set in
  187776. * png_read_start_row() by a call to png_read_update_info() or
  187777. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187778. * prior to either of these functions like it should have been. You can
  187779. * only call this function once. If you desire to have an image for
  187780. * each pass of a interlaced image, use png_read_rows() instead.
  187781. *
  187782. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187783. */
  187784. void PNGAPI
  187785. png_read_image(png_structp png_ptr, png_bytepp image)
  187786. {
  187787. png_uint_32 i,image_height;
  187788. int pass, j;
  187789. png_bytepp rp;
  187790. png_debug(1, "in png_read_image\n");
  187791. if(png_ptr == NULL) return;
  187792. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187793. pass = png_set_interlace_handling(png_ptr);
  187794. #else
  187795. if (png_ptr->interlaced)
  187796. png_error(png_ptr,
  187797. "Cannot read interlaced image -- interlace handler disabled.");
  187798. pass = 1;
  187799. #endif
  187800. image_height=png_ptr->height;
  187801. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187802. for (j = 0; j < pass; j++)
  187803. {
  187804. rp = image;
  187805. for (i = 0; i < image_height; i++)
  187806. {
  187807. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187808. rp++;
  187809. }
  187810. }
  187811. }
  187812. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187813. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187814. /* Read the end of the PNG file. Will not read past the end of the
  187815. * file, will verify the end is accurate, and will read any comments
  187816. * or time information at the end of the file, if info is not NULL.
  187817. */
  187818. void PNGAPI
  187819. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187820. {
  187821. png_byte chunk_length[4];
  187822. png_uint_32 length;
  187823. png_debug(1, "in png_read_end\n");
  187824. if(png_ptr == NULL) return;
  187825. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187826. do
  187827. {
  187828. #ifdef PNG_USE_LOCAL_ARRAYS
  187829. PNG_CONST PNG_IHDR;
  187830. PNG_CONST PNG_IDAT;
  187831. PNG_CONST PNG_IEND;
  187832. PNG_CONST PNG_PLTE;
  187833. #if defined(PNG_READ_bKGD_SUPPORTED)
  187834. PNG_CONST PNG_bKGD;
  187835. #endif
  187836. #if defined(PNG_READ_cHRM_SUPPORTED)
  187837. PNG_CONST PNG_cHRM;
  187838. #endif
  187839. #if defined(PNG_READ_gAMA_SUPPORTED)
  187840. PNG_CONST PNG_gAMA;
  187841. #endif
  187842. #if defined(PNG_READ_hIST_SUPPORTED)
  187843. PNG_CONST PNG_hIST;
  187844. #endif
  187845. #if defined(PNG_READ_iCCP_SUPPORTED)
  187846. PNG_CONST PNG_iCCP;
  187847. #endif
  187848. #if defined(PNG_READ_iTXt_SUPPORTED)
  187849. PNG_CONST PNG_iTXt;
  187850. #endif
  187851. #if defined(PNG_READ_oFFs_SUPPORTED)
  187852. PNG_CONST PNG_oFFs;
  187853. #endif
  187854. #if defined(PNG_READ_pCAL_SUPPORTED)
  187855. PNG_CONST PNG_pCAL;
  187856. #endif
  187857. #if defined(PNG_READ_pHYs_SUPPORTED)
  187858. PNG_CONST PNG_pHYs;
  187859. #endif
  187860. #if defined(PNG_READ_sBIT_SUPPORTED)
  187861. PNG_CONST PNG_sBIT;
  187862. #endif
  187863. #if defined(PNG_READ_sCAL_SUPPORTED)
  187864. PNG_CONST PNG_sCAL;
  187865. #endif
  187866. #if defined(PNG_READ_sPLT_SUPPORTED)
  187867. PNG_CONST PNG_sPLT;
  187868. #endif
  187869. #if defined(PNG_READ_sRGB_SUPPORTED)
  187870. PNG_CONST PNG_sRGB;
  187871. #endif
  187872. #if defined(PNG_READ_tEXt_SUPPORTED)
  187873. PNG_CONST PNG_tEXt;
  187874. #endif
  187875. #if defined(PNG_READ_tIME_SUPPORTED)
  187876. PNG_CONST PNG_tIME;
  187877. #endif
  187878. #if defined(PNG_READ_tRNS_SUPPORTED)
  187879. PNG_CONST PNG_tRNS;
  187880. #endif
  187881. #if defined(PNG_READ_zTXt_SUPPORTED)
  187882. PNG_CONST PNG_zTXt;
  187883. #endif
  187884. #endif /* PNG_USE_LOCAL_ARRAYS */
  187885. png_read_data(png_ptr, chunk_length, 4);
  187886. length = png_get_uint_31(png_ptr,chunk_length);
  187887. png_reset_crc(png_ptr);
  187888. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187889. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187890. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187891. png_handle_IHDR(png_ptr, info_ptr, length);
  187892. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187893. png_handle_IEND(png_ptr, info_ptr, length);
  187894. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187895. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187896. {
  187897. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187898. {
  187899. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187900. png_error(png_ptr, "Too many IDAT's found");
  187901. }
  187902. png_handle_unknown(png_ptr, info_ptr, length);
  187903. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187904. png_ptr->mode |= PNG_HAVE_PLTE;
  187905. }
  187906. #endif
  187907. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187908. {
  187909. /* Zero length IDATs are legal after the last IDAT has been
  187910. * read, but not after other chunks have been read.
  187911. */
  187912. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187913. png_error(png_ptr, "Too many IDAT's found");
  187914. png_crc_finish(png_ptr, length);
  187915. }
  187916. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187917. png_handle_PLTE(png_ptr, info_ptr, length);
  187918. #if defined(PNG_READ_bKGD_SUPPORTED)
  187919. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187920. png_handle_bKGD(png_ptr, info_ptr, length);
  187921. #endif
  187922. #if defined(PNG_READ_cHRM_SUPPORTED)
  187923. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187924. png_handle_cHRM(png_ptr, info_ptr, length);
  187925. #endif
  187926. #if defined(PNG_READ_gAMA_SUPPORTED)
  187927. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187928. png_handle_gAMA(png_ptr, info_ptr, length);
  187929. #endif
  187930. #if defined(PNG_READ_hIST_SUPPORTED)
  187931. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187932. png_handle_hIST(png_ptr, info_ptr, length);
  187933. #endif
  187934. #if defined(PNG_READ_oFFs_SUPPORTED)
  187935. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187936. png_handle_oFFs(png_ptr, info_ptr, length);
  187937. #endif
  187938. #if defined(PNG_READ_pCAL_SUPPORTED)
  187939. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187940. png_handle_pCAL(png_ptr, info_ptr, length);
  187941. #endif
  187942. #if defined(PNG_READ_sCAL_SUPPORTED)
  187943. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187944. png_handle_sCAL(png_ptr, info_ptr, length);
  187945. #endif
  187946. #if defined(PNG_READ_pHYs_SUPPORTED)
  187947. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187948. png_handle_pHYs(png_ptr, info_ptr, length);
  187949. #endif
  187950. #if defined(PNG_READ_sBIT_SUPPORTED)
  187951. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187952. png_handle_sBIT(png_ptr, info_ptr, length);
  187953. #endif
  187954. #if defined(PNG_READ_sRGB_SUPPORTED)
  187955. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187956. png_handle_sRGB(png_ptr, info_ptr, length);
  187957. #endif
  187958. #if defined(PNG_READ_iCCP_SUPPORTED)
  187959. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187960. png_handle_iCCP(png_ptr, info_ptr, length);
  187961. #endif
  187962. #if defined(PNG_READ_sPLT_SUPPORTED)
  187963. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187964. png_handle_sPLT(png_ptr, info_ptr, length);
  187965. #endif
  187966. #if defined(PNG_READ_tEXt_SUPPORTED)
  187967. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187968. png_handle_tEXt(png_ptr, info_ptr, length);
  187969. #endif
  187970. #if defined(PNG_READ_tIME_SUPPORTED)
  187971. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187972. png_handle_tIME(png_ptr, info_ptr, length);
  187973. #endif
  187974. #if defined(PNG_READ_tRNS_SUPPORTED)
  187975. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187976. png_handle_tRNS(png_ptr, info_ptr, length);
  187977. #endif
  187978. #if defined(PNG_READ_zTXt_SUPPORTED)
  187979. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187980. png_handle_zTXt(png_ptr, info_ptr, length);
  187981. #endif
  187982. #if defined(PNG_READ_iTXt_SUPPORTED)
  187983. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187984. png_handle_iTXt(png_ptr, info_ptr, length);
  187985. #endif
  187986. else
  187987. png_handle_unknown(png_ptr, info_ptr, length);
  187988. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187989. }
  187990. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187991. /* free all memory used by the read */
  187992. void PNGAPI
  187993. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187994. png_infopp end_info_ptr_ptr)
  187995. {
  187996. png_structp png_ptr = NULL;
  187997. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187998. #ifdef PNG_USER_MEM_SUPPORTED
  187999. png_free_ptr free_fn;
  188000. png_voidp mem_ptr;
  188001. #endif
  188002. png_debug(1, "in png_destroy_read_struct\n");
  188003. if (png_ptr_ptr != NULL)
  188004. png_ptr = *png_ptr_ptr;
  188005. if (info_ptr_ptr != NULL)
  188006. info_ptr = *info_ptr_ptr;
  188007. if (end_info_ptr_ptr != NULL)
  188008. end_info_ptr = *end_info_ptr_ptr;
  188009. #ifdef PNG_USER_MEM_SUPPORTED
  188010. free_fn = png_ptr->free_fn;
  188011. mem_ptr = png_ptr->mem_ptr;
  188012. #endif
  188013. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188014. if (info_ptr != NULL)
  188015. {
  188016. #if defined(PNG_TEXT_SUPPORTED)
  188017. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188018. #endif
  188019. #ifdef PNG_USER_MEM_SUPPORTED
  188020. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188021. (png_voidp)mem_ptr);
  188022. #else
  188023. png_destroy_struct((png_voidp)info_ptr);
  188024. #endif
  188025. *info_ptr_ptr = NULL;
  188026. }
  188027. if (end_info_ptr != NULL)
  188028. {
  188029. #if defined(PNG_READ_TEXT_SUPPORTED)
  188030. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188031. #endif
  188032. #ifdef PNG_USER_MEM_SUPPORTED
  188033. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188034. (png_voidp)mem_ptr);
  188035. #else
  188036. png_destroy_struct((png_voidp)end_info_ptr);
  188037. #endif
  188038. *end_info_ptr_ptr = NULL;
  188039. }
  188040. if (png_ptr != NULL)
  188041. {
  188042. #ifdef PNG_USER_MEM_SUPPORTED
  188043. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188044. (png_voidp)mem_ptr);
  188045. #else
  188046. png_destroy_struct((png_voidp)png_ptr);
  188047. #endif
  188048. *png_ptr_ptr = NULL;
  188049. }
  188050. }
  188051. /* free all memory used by the read (old method) */
  188052. void /* PRIVATE */
  188053. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188054. {
  188055. #ifdef PNG_SETJMP_SUPPORTED
  188056. jmp_buf tmp_jmp;
  188057. #endif
  188058. png_error_ptr error_fn;
  188059. png_error_ptr warning_fn;
  188060. png_voidp error_ptr;
  188061. #ifdef PNG_USER_MEM_SUPPORTED
  188062. png_free_ptr free_fn;
  188063. #endif
  188064. png_debug(1, "in png_read_destroy\n");
  188065. if (info_ptr != NULL)
  188066. png_info_destroy(png_ptr, info_ptr);
  188067. if (end_info_ptr != NULL)
  188068. png_info_destroy(png_ptr, end_info_ptr);
  188069. png_free(png_ptr, png_ptr->zbuf);
  188070. png_free(png_ptr, png_ptr->big_row_buf);
  188071. png_free(png_ptr, png_ptr->prev_row);
  188072. #if defined(PNG_READ_DITHER_SUPPORTED)
  188073. png_free(png_ptr, png_ptr->palette_lookup);
  188074. png_free(png_ptr, png_ptr->dither_index);
  188075. #endif
  188076. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188077. png_free(png_ptr, png_ptr->gamma_table);
  188078. #endif
  188079. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188080. png_free(png_ptr, png_ptr->gamma_from_1);
  188081. png_free(png_ptr, png_ptr->gamma_to_1);
  188082. #endif
  188083. #ifdef PNG_FREE_ME_SUPPORTED
  188084. if (png_ptr->free_me & PNG_FREE_PLTE)
  188085. png_zfree(png_ptr, png_ptr->palette);
  188086. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188087. #else
  188088. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188089. png_zfree(png_ptr, png_ptr->palette);
  188090. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188091. #endif
  188092. #if defined(PNG_tRNS_SUPPORTED) || \
  188093. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188094. #ifdef PNG_FREE_ME_SUPPORTED
  188095. if (png_ptr->free_me & PNG_FREE_TRNS)
  188096. png_free(png_ptr, png_ptr->trans);
  188097. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188098. #else
  188099. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188100. png_free(png_ptr, png_ptr->trans);
  188101. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188102. #endif
  188103. #endif
  188104. #if defined(PNG_READ_hIST_SUPPORTED)
  188105. #ifdef PNG_FREE_ME_SUPPORTED
  188106. if (png_ptr->free_me & PNG_FREE_HIST)
  188107. png_free(png_ptr, png_ptr->hist);
  188108. png_ptr->free_me &= ~PNG_FREE_HIST;
  188109. #else
  188110. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188111. png_free(png_ptr, png_ptr->hist);
  188112. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188113. #endif
  188114. #endif
  188115. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188116. if (png_ptr->gamma_16_table != NULL)
  188117. {
  188118. int i;
  188119. int istop = (1 << (8 - png_ptr->gamma_shift));
  188120. for (i = 0; i < istop; i++)
  188121. {
  188122. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188123. }
  188124. png_free(png_ptr, png_ptr->gamma_16_table);
  188125. }
  188126. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188127. if (png_ptr->gamma_16_from_1 != NULL)
  188128. {
  188129. int i;
  188130. int istop = (1 << (8 - png_ptr->gamma_shift));
  188131. for (i = 0; i < istop; i++)
  188132. {
  188133. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188134. }
  188135. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188136. }
  188137. if (png_ptr->gamma_16_to_1 != NULL)
  188138. {
  188139. int i;
  188140. int istop = (1 << (8 - png_ptr->gamma_shift));
  188141. for (i = 0; i < istop; i++)
  188142. {
  188143. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188144. }
  188145. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188146. }
  188147. #endif
  188148. #endif
  188149. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188150. png_free(png_ptr, png_ptr->time_buffer);
  188151. #endif
  188152. inflateEnd(&png_ptr->zstream);
  188153. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188154. png_free(png_ptr, png_ptr->save_buffer);
  188155. #endif
  188156. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188157. #ifdef PNG_TEXT_SUPPORTED
  188158. png_free(png_ptr, png_ptr->current_text);
  188159. #endif /* PNG_TEXT_SUPPORTED */
  188160. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188161. /* Save the important info out of the png_struct, in case it is
  188162. * being used again.
  188163. */
  188164. #ifdef PNG_SETJMP_SUPPORTED
  188165. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188166. #endif
  188167. error_fn = png_ptr->error_fn;
  188168. warning_fn = png_ptr->warning_fn;
  188169. error_ptr = png_ptr->error_ptr;
  188170. #ifdef PNG_USER_MEM_SUPPORTED
  188171. free_fn = png_ptr->free_fn;
  188172. #endif
  188173. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188174. png_ptr->error_fn = error_fn;
  188175. png_ptr->warning_fn = warning_fn;
  188176. png_ptr->error_ptr = error_ptr;
  188177. #ifdef PNG_USER_MEM_SUPPORTED
  188178. png_ptr->free_fn = free_fn;
  188179. #endif
  188180. #ifdef PNG_SETJMP_SUPPORTED
  188181. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188182. #endif
  188183. }
  188184. void PNGAPI
  188185. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188186. {
  188187. if(png_ptr == NULL) return;
  188188. png_ptr->read_row_fn = read_row_fn;
  188189. }
  188190. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188191. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188192. void PNGAPI
  188193. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188194. int transforms,
  188195. voidp params)
  188196. {
  188197. int row;
  188198. if(png_ptr == NULL) return;
  188199. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188200. /* invert the alpha channel from opacity to transparency
  188201. */
  188202. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188203. png_set_invert_alpha(png_ptr);
  188204. #endif
  188205. /* png_read_info() gives us all of the information from the
  188206. * PNG file before the first IDAT (image data chunk).
  188207. */
  188208. png_read_info(png_ptr, info_ptr);
  188209. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188210. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188211. /* -------------- image transformations start here ------------------- */
  188212. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188213. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188214. */
  188215. if (transforms & PNG_TRANSFORM_STRIP_16)
  188216. png_set_strip_16(png_ptr);
  188217. #endif
  188218. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188219. /* Strip alpha bytes from the input data without combining with
  188220. * the background (not recommended).
  188221. */
  188222. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188223. png_set_strip_alpha(png_ptr);
  188224. #endif
  188225. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188226. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188227. * byte into separate bytes (useful for paletted and grayscale images).
  188228. */
  188229. if (transforms & PNG_TRANSFORM_PACKING)
  188230. png_set_packing(png_ptr);
  188231. #endif
  188232. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188233. /* Change the order of packed pixels to least significant bit first
  188234. * (not useful if you are using png_set_packing).
  188235. */
  188236. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188237. png_set_packswap(png_ptr);
  188238. #endif
  188239. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188240. /* Expand paletted colors into true RGB triplets
  188241. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188242. * Expand paletted or RGB images with transparency to full alpha
  188243. * channels so the data will be available as RGBA quartets.
  188244. */
  188245. if (transforms & PNG_TRANSFORM_EXPAND)
  188246. if ((png_ptr->bit_depth < 8) ||
  188247. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188248. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188249. png_set_expand(png_ptr);
  188250. #endif
  188251. /* We don't handle background color or gamma transformation or dithering.
  188252. */
  188253. #if defined(PNG_READ_INVERT_SUPPORTED)
  188254. /* invert monochrome files to have 0 as white and 1 as black
  188255. */
  188256. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188257. png_set_invert_mono(png_ptr);
  188258. #endif
  188259. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188260. /* If you want to shift the pixel values from the range [0,255] or
  188261. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188262. * colors were originally in:
  188263. */
  188264. if ((transforms & PNG_TRANSFORM_SHIFT)
  188265. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188266. {
  188267. png_color_8p sig_bit;
  188268. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188269. png_set_shift(png_ptr, sig_bit);
  188270. }
  188271. #endif
  188272. #if defined(PNG_READ_BGR_SUPPORTED)
  188273. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188274. */
  188275. if (transforms & PNG_TRANSFORM_BGR)
  188276. png_set_bgr(png_ptr);
  188277. #endif
  188278. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188279. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188280. */
  188281. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188282. png_set_swap_alpha(png_ptr);
  188283. #endif
  188284. #if defined(PNG_READ_SWAP_SUPPORTED)
  188285. /* swap bytes of 16 bit files to least significant byte first
  188286. */
  188287. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188288. png_set_swap(png_ptr);
  188289. #endif
  188290. /* We don't handle adding filler bytes */
  188291. /* Optional call to gamma correct and add the background to the palette
  188292. * and update info structure. REQUIRED if you are expecting libpng to
  188293. * update the palette for you (i.e., you selected such a transform above).
  188294. */
  188295. png_read_update_info(png_ptr, info_ptr);
  188296. /* -------------- image transformations end here ------------------- */
  188297. #ifdef PNG_FREE_ME_SUPPORTED
  188298. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188299. #endif
  188300. if(info_ptr->row_pointers == NULL)
  188301. {
  188302. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188303. info_ptr->height * png_sizeof(png_bytep));
  188304. #ifdef PNG_FREE_ME_SUPPORTED
  188305. info_ptr->free_me |= PNG_FREE_ROWS;
  188306. #endif
  188307. for (row = 0; row < (int)info_ptr->height; row++)
  188308. {
  188309. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188310. png_get_rowbytes(png_ptr, info_ptr));
  188311. }
  188312. }
  188313. png_read_image(png_ptr, info_ptr->row_pointers);
  188314. info_ptr->valid |= PNG_INFO_IDAT;
  188315. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188316. png_read_end(png_ptr, info_ptr);
  188317. transforms = transforms; /* quiet compiler warnings */
  188318. params = params;
  188319. }
  188320. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188321. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188322. #endif /* PNG_READ_SUPPORTED */
  188323. /*** End of inlined file: pngread.c ***/
  188324. /*** Start of inlined file: pngpread.c ***/
  188325. /* pngpread.c - read a png file in push mode
  188326. *
  188327. * Last changed in libpng 1.2.21 October 4, 2007
  188328. * For conditions of distribution and use, see copyright notice in png.h
  188329. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188330. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188331. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188332. */
  188333. #define PNG_INTERNAL
  188334. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188335. /* push model modes */
  188336. #define PNG_READ_SIG_MODE 0
  188337. #define PNG_READ_CHUNK_MODE 1
  188338. #define PNG_READ_IDAT_MODE 2
  188339. #define PNG_SKIP_MODE 3
  188340. #define PNG_READ_tEXt_MODE 4
  188341. #define PNG_READ_zTXt_MODE 5
  188342. #define PNG_READ_DONE_MODE 6
  188343. #define PNG_READ_iTXt_MODE 7
  188344. #define PNG_ERROR_MODE 8
  188345. void PNGAPI
  188346. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188347. png_bytep buffer, png_size_t buffer_size)
  188348. {
  188349. if(png_ptr == NULL) return;
  188350. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188351. while (png_ptr->buffer_size)
  188352. {
  188353. png_process_some_data(png_ptr, info_ptr);
  188354. }
  188355. }
  188356. /* What we do with the incoming data depends on what we were previously
  188357. * doing before we ran out of data...
  188358. */
  188359. void /* PRIVATE */
  188360. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188361. {
  188362. if(png_ptr == NULL) return;
  188363. switch (png_ptr->process_mode)
  188364. {
  188365. case PNG_READ_SIG_MODE:
  188366. {
  188367. png_push_read_sig(png_ptr, info_ptr);
  188368. break;
  188369. }
  188370. case PNG_READ_CHUNK_MODE:
  188371. {
  188372. png_push_read_chunk(png_ptr, info_ptr);
  188373. break;
  188374. }
  188375. case PNG_READ_IDAT_MODE:
  188376. {
  188377. png_push_read_IDAT(png_ptr);
  188378. break;
  188379. }
  188380. #if defined(PNG_READ_tEXt_SUPPORTED)
  188381. case PNG_READ_tEXt_MODE:
  188382. {
  188383. png_push_read_tEXt(png_ptr, info_ptr);
  188384. break;
  188385. }
  188386. #endif
  188387. #if defined(PNG_READ_zTXt_SUPPORTED)
  188388. case PNG_READ_zTXt_MODE:
  188389. {
  188390. png_push_read_zTXt(png_ptr, info_ptr);
  188391. break;
  188392. }
  188393. #endif
  188394. #if defined(PNG_READ_iTXt_SUPPORTED)
  188395. case PNG_READ_iTXt_MODE:
  188396. {
  188397. png_push_read_iTXt(png_ptr, info_ptr);
  188398. break;
  188399. }
  188400. #endif
  188401. case PNG_SKIP_MODE:
  188402. {
  188403. png_push_crc_finish(png_ptr);
  188404. break;
  188405. }
  188406. default:
  188407. {
  188408. png_ptr->buffer_size = 0;
  188409. break;
  188410. }
  188411. }
  188412. }
  188413. /* Read any remaining signature bytes from the stream and compare them with
  188414. * the correct PNG signature. It is possible that this routine is called
  188415. * with bytes already read from the signature, either because they have been
  188416. * checked by the calling application, or because of multiple calls to this
  188417. * routine.
  188418. */
  188419. void /* PRIVATE */
  188420. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188421. {
  188422. png_size_t num_checked = png_ptr->sig_bytes,
  188423. num_to_check = 8 - num_checked;
  188424. if (png_ptr->buffer_size < num_to_check)
  188425. {
  188426. num_to_check = png_ptr->buffer_size;
  188427. }
  188428. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188429. num_to_check);
  188430. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188431. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188432. {
  188433. if (num_checked < 4 &&
  188434. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188435. png_error(png_ptr, "Not a PNG file");
  188436. else
  188437. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188438. }
  188439. else
  188440. {
  188441. if (png_ptr->sig_bytes >= 8)
  188442. {
  188443. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188444. }
  188445. }
  188446. }
  188447. void /* PRIVATE */
  188448. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188449. {
  188450. #ifdef PNG_USE_LOCAL_ARRAYS
  188451. PNG_CONST PNG_IHDR;
  188452. PNG_CONST PNG_IDAT;
  188453. PNG_CONST PNG_IEND;
  188454. PNG_CONST PNG_PLTE;
  188455. #if defined(PNG_READ_bKGD_SUPPORTED)
  188456. PNG_CONST PNG_bKGD;
  188457. #endif
  188458. #if defined(PNG_READ_cHRM_SUPPORTED)
  188459. PNG_CONST PNG_cHRM;
  188460. #endif
  188461. #if defined(PNG_READ_gAMA_SUPPORTED)
  188462. PNG_CONST PNG_gAMA;
  188463. #endif
  188464. #if defined(PNG_READ_hIST_SUPPORTED)
  188465. PNG_CONST PNG_hIST;
  188466. #endif
  188467. #if defined(PNG_READ_iCCP_SUPPORTED)
  188468. PNG_CONST PNG_iCCP;
  188469. #endif
  188470. #if defined(PNG_READ_iTXt_SUPPORTED)
  188471. PNG_CONST PNG_iTXt;
  188472. #endif
  188473. #if defined(PNG_READ_oFFs_SUPPORTED)
  188474. PNG_CONST PNG_oFFs;
  188475. #endif
  188476. #if defined(PNG_READ_pCAL_SUPPORTED)
  188477. PNG_CONST PNG_pCAL;
  188478. #endif
  188479. #if defined(PNG_READ_pHYs_SUPPORTED)
  188480. PNG_CONST PNG_pHYs;
  188481. #endif
  188482. #if defined(PNG_READ_sBIT_SUPPORTED)
  188483. PNG_CONST PNG_sBIT;
  188484. #endif
  188485. #if defined(PNG_READ_sCAL_SUPPORTED)
  188486. PNG_CONST PNG_sCAL;
  188487. #endif
  188488. #if defined(PNG_READ_sRGB_SUPPORTED)
  188489. PNG_CONST PNG_sRGB;
  188490. #endif
  188491. #if defined(PNG_READ_sPLT_SUPPORTED)
  188492. PNG_CONST PNG_sPLT;
  188493. #endif
  188494. #if defined(PNG_READ_tEXt_SUPPORTED)
  188495. PNG_CONST PNG_tEXt;
  188496. #endif
  188497. #if defined(PNG_READ_tIME_SUPPORTED)
  188498. PNG_CONST PNG_tIME;
  188499. #endif
  188500. #if defined(PNG_READ_tRNS_SUPPORTED)
  188501. PNG_CONST PNG_tRNS;
  188502. #endif
  188503. #if defined(PNG_READ_zTXt_SUPPORTED)
  188504. PNG_CONST PNG_zTXt;
  188505. #endif
  188506. #endif /* PNG_USE_LOCAL_ARRAYS */
  188507. /* First we make sure we have enough data for the 4 byte chunk name
  188508. * and the 4 byte chunk length before proceeding with decoding the
  188509. * chunk data. To fully decode each of these chunks, we also make
  188510. * sure we have enough data in the buffer for the 4 byte CRC at the
  188511. * end of every chunk (except IDAT, which is handled separately).
  188512. */
  188513. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188514. {
  188515. png_byte chunk_length[4];
  188516. if (png_ptr->buffer_size < 8)
  188517. {
  188518. png_push_save_buffer(png_ptr);
  188519. return;
  188520. }
  188521. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188522. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188523. png_reset_crc(png_ptr);
  188524. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188525. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188526. }
  188527. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188528. if(png_ptr->mode & PNG_AFTER_IDAT)
  188529. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188530. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188531. {
  188532. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188533. {
  188534. png_push_save_buffer(png_ptr);
  188535. return;
  188536. }
  188537. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188538. }
  188539. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188540. {
  188541. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188542. {
  188543. png_push_save_buffer(png_ptr);
  188544. return;
  188545. }
  188546. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188547. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188548. png_push_have_end(png_ptr, info_ptr);
  188549. }
  188550. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188551. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188552. {
  188553. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188554. {
  188555. png_push_save_buffer(png_ptr);
  188556. return;
  188557. }
  188558. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188559. png_ptr->mode |= PNG_HAVE_IDAT;
  188560. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188561. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188562. png_ptr->mode |= PNG_HAVE_PLTE;
  188563. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188564. {
  188565. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188566. png_error(png_ptr, "Missing IHDR before IDAT");
  188567. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188568. !(png_ptr->mode & PNG_HAVE_PLTE))
  188569. png_error(png_ptr, "Missing PLTE before IDAT");
  188570. }
  188571. }
  188572. #endif
  188573. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188574. {
  188575. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188576. {
  188577. png_push_save_buffer(png_ptr);
  188578. return;
  188579. }
  188580. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188581. }
  188582. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188583. {
  188584. /* If we reach an IDAT chunk, this means we have read all of the
  188585. * header chunks, and we can start reading the image (or if this
  188586. * is called after the image has been read - we have an error).
  188587. */
  188588. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188589. png_error(png_ptr, "Missing IHDR before IDAT");
  188590. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188591. !(png_ptr->mode & PNG_HAVE_PLTE))
  188592. png_error(png_ptr, "Missing PLTE before IDAT");
  188593. if (png_ptr->mode & PNG_HAVE_IDAT)
  188594. {
  188595. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188596. if (png_ptr->push_length == 0)
  188597. return;
  188598. if (png_ptr->mode & PNG_AFTER_IDAT)
  188599. png_error(png_ptr, "Too many IDAT's found");
  188600. }
  188601. png_ptr->idat_size = png_ptr->push_length;
  188602. png_ptr->mode |= PNG_HAVE_IDAT;
  188603. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188604. png_push_have_info(png_ptr, info_ptr);
  188605. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188606. png_ptr->zstream.next_out = png_ptr->row_buf;
  188607. return;
  188608. }
  188609. #if defined(PNG_READ_gAMA_SUPPORTED)
  188610. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188611. {
  188612. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188613. {
  188614. png_push_save_buffer(png_ptr);
  188615. return;
  188616. }
  188617. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188618. }
  188619. #endif
  188620. #if defined(PNG_READ_sBIT_SUPPORTED)
  188621. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188622. {
  188623. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188624. {
  188625. png_push_save_buffer(png_ptr);
  188626. return;
  188627. }
  188628. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188629. }
  188630. #endif
  188631. #if defined(PNG_READ_cHRM_SUPPORTED)
  188632. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188633. {
  188634. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188635. {
  188636. png_push_save_buffer(png_ptr);
  188637. return;
  188638. }
  188639. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188640. }
  188641. #endif
  188642. #if defined(PNG_READ_sRGB_SUPPORTED)
  188643. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188644. {
  188645. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188646. {
  188647. png_push_save_buffer(png_ptr);
  188648. return;
  188649. }
  188650. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188651. }
  188652. #endif
  188653. #if defined(PNG_READ_iCCP_SUPPORTED)
  188654. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188655. {
  188656. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188657. {
  188658. png_push_save_buffer(png_ptr);
  188659. return;
  188660. }
  188661. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188662. }
  188663. #endif
  188664. #if defined(PNG_READ_sPLT_SUPPORTED)
  188665. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188666. {
  188667. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188668. {
  188669. png_push_save_buffer(png_ptr);
  188670. return;
  188671. }
  188672. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188673. }
  188674. #endif
  188675. #if defined(PNG_READ_tRNS_SUPPORTED)
  188676. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188677. {
  188678. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188679. {
  188680. png_push_save_buffer(png_ptr);
  188681. return;
  188682. }
  188683. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188684. }
  188685. #endif
  188686. #if defined(PNG_READ_bKGD_SUPPORTED)
  188687. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188688. {
  188689. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188690. {
  188691. png_push_save_buffer(png_ptr);
  188692. return;
  188693. }
  188694. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188695. }
  188696. #endif
  188697. #if defined(PNG_READ_hIST_SUPPORTED)
  188698. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188699. {
  188700. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188701. {
  188702. png_push_save_buffer(png_ptr);
  188703. return;
  188704. }
  188705. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188706. }
  188707. #endif
  188708. #if defined(PNG_READ_pHYs_SUPPORTED)
  188709. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188710. {
  188711. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188712. {
  188713. png_push_save_buffer(png_ptr);
  188714. return;
  188715. }
  188716. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188717. }
  188718. #endif
  188719. #if defined(PNG_READ_oFFs_SUPPORTED)
  188720. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188721. {
  188722. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188723. {
  188724. png_push_save_buffer(png_ptr);
  188725. return;
  188726. }
  188727. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188728. }
  188729. #endif
  188730. #if defined(PNG_READ_pCAL_SUPPORTED)
  188731. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188732. {
  188733. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188734. {
  188735. png_push_save_buffer(png_ptr);
  188736. return;
  188737. }
  188738. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188739. }
  188740. #endif
  188741. #if defined(PNG_READ_sCAL_SUPPORTED)
  188742. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188743. {
  188744. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188745. {
  188746. png_push_save_buffer(png_ptr);
  188747. return;
  188748. }
  188749. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188750. }
  188751. #endif
  188752. #if defined(PNG_READ_tIME_SUPPORTED)
  188753. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188754. {
  188755. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188756. {
  188757. png_push_save_buffer(png_ptr);
  188758. return;
  188759. }
  188760. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188761. }
  188762. #endif
  188763. #if defined(PNG_READ_tEXt_SUPPORTED)
  188764. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188765. {
  188766. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188767. {
  188768. png_push_save_buffer(png_ptr);
  188769. return;
  188770. }
  188771. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188772. }
  188773. #endif
  188774. #if defined(PNG_READ_zTXt_SUPPORTED)
  188775. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188776. {
  188777. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188778. {
  188779. png_push_save_buffer(png_ptr);
  188780. return;
  188781. }
  188782. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188783. }
  188784. #endif
  188785. #if defined(PNG_READ_iTXt_SUPPORTED)
  188786. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188787. {
  188788. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188789. {
  188790. png_push_save_buffer(png_ptr);
  188791. return;
  188792. }
  188793. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188794. }
  188795. #endif
  188796. else
  188797. {
  188798. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188799. {
  188800. png_push_save_buffer(png_ptr);
  188801. return;
  188802. }
  188803. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188804. }
  188805. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188806. }
  188807. void /* PRIVATE */
  188808. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188809. {
  188810. png_ptr->process_mode = PNG_SKIP_MODE;
  188811. png_ptr->skip_length = skip;
  188812. }
  188813. void /* PRIVATE */
  188814. png_push_crc_finish(png_structp png_ptr)
  188815. {
  188816. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188817. {
  188818. png_size_t save_size;
  188819. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188820. save_size = (png_size_t)png_ptr->skip_length;
  188821. else
  188822. save_size = png_ptr->save_buffer_size;
  188823. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188824. png_ptr->skip_length -= save_size;
  188825. png_ptr->buffer_size -= save_size;
  188826. png_ptr->save_buffer_size -= save_size;
  188827. png_ptr->save_buffer_ptr += save_size;
  188828. }
  188829. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188830. {
  188831. png_size_t save_size;
  188832. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188833. save_size = (png_size_t)png_ptr->skip_length;
  188834. else
  188835. save_size = png_ptr->current_buffer_size;
  188836. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188837. png_ptr->skip_length -= save_size;
  188838. png_ptr->buffer_size -= save_size;
  188839. png_ptr->current_buffer_size -= save_size;
  188840. png_ptr->current_buffer_ptr += save_size;
  188841. }
  188842. if (!png_ptr->skip_length)
  188843. {
  188844. if (png_ptr->buffer_size < 4)
  188845. {
  188846. png_push_save_buffer(png_ptr);
  188847. return;
  188848. }
  188849. png_crc_finish(png_ptr, 0);
  188850. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188851. }
  188852. }
  188853. void PNGAPI
  188854. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188855. {
  188856. png_bytep ptr;
  188857. if(png_ptr == NULL) return;
  188858. ptr = buffer;
  188859. if (png_ptr->save_buffer_size)
  188860. {
  188861. png_size_t save_size;
  188862. if (length < png_ptr->save_buffer_size)
  188863. save_size = length;
  188864. else
  188865. save_size = png_ptr->save_buffer_size;
  188866. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188867. length -= save_size;
  188868. ptr += save_size;
  188869. png_ptr->buffer_size -= save_size;
  188870. png_ptr->save_buffer_size -= save_size;
  188871. png_ptr->save_buffer_ptr += save_size;
  188872. }
  188873. if (length && png_ptr->current_buffer_size)
  188874. {
  188875. png_size_t save_size;
  188876. if (length < png_ptr->current_buffer_size)
  188877. save_size = length;
  188878. else
  188879. save_size = png_ptr->current_buffer_size;
  188880. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188881. png_ptr->buffer_size -= save_size;
  188882. png_ptr->current_buffer_size -= save_size;
  188883. png_ptr->current_buffer_ptr += save_size;
  188884. }
  188885. }
  188886. void /* PRIVATE */
  188887. png_push_save_buffer(png_structp png_ptr)
  188888. {
  188889. if (png_ptr->save_buffer_size)
  188890. {
  188891. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188892. {
  188893. png_size_t i,istop;
  188894. png_bytep sp;
  188895. png_bytep dp;
  188896. istop = png_ptr->save_buffer_size;
  188897. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188898. i < istop; i++, sp++, dp++)
  188899. {
  188900. *dp = *sp;
  188901. }
  188902. }
  188903. }
  188904. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188905. png_ptr->save_buffer_max)
  188906. {
  188907. png_size_t new_max;
  188908. png_bytep old_buffer;
  188909. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188910. (png_ptr->current_buffer_size + 256))
  188911. {
  188912. png_error(png_ptr, "Potential overflow of save_buffer");
  188913. }
  188914. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188915. old_buffer = png_ptr->save_buffer;
  188916. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188917. (png_uint_32)new_max);
  188918. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188919. png_free(png_ptr, old_buffer);
  188920. png_ptr->save_buffer_max = new_max;
  188921. }
  188922. if (png_ptr->current_buffer_size)
  188923. {
  188924. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188925. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188926. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188927. png_ptr->current_buffer_size = 0;
  188928. }
  188929. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188930. png_ptr->buffer_size = 0;
  188931. }
  188932. void /* PRIVATE */
  188933. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188934. png_size_t buffer_length)
  188935. {
  188936. png_ptr->current_buffer = buffer;
  188937. png_ptr->current_buffer_size = buffer_length;
  188938. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188939. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188940. }
  188941. void /* PRIVATE */
  188942. png_push_read_IDAT(png_structp png_ptr)
  188943. {
  188944. #ifdef PNG_USE_LOCAL_ARRAYS
  188945. PNG_CONST PNG_IDAT;
  188946. #endif
  188947. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188948. {
  188949. png_byte chunk_length[4];
  188950. if (png_ptr->buffer_size < 8)
  188951. {
  188952. png_push_save_buffer(png_ptr);
  188953. return;
  188954. }
  188955. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188956. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188957. png_reset_crc(png_ptr);
  188958. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188959. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188960. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188961. {
  188962. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188963. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188964. png_error(png_ptr, "Not enough compressed data");
  188965. return;
  188966. }
  188967. png_ptr->idat_size = png_ptr->push_length;
  188968. }
  188969. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188970. {
  188971. png_size_t save_size;
  188972. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188973. {
  188974. save_size = (png_size_t)png_ptr->idat_size;
  188975. /* check for overflow */
  188976. if((png_uint_32)save_size != png_ptr->idat_size)
  188977. png_error(png_ptr, "save_size overflowed in pngpread");
  188978. }
  188979. else
  188980. save_size = png_ptr->save_buffer_size;
  188981. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188982. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188983. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188984. png_ptr->idat_size -= save_size;
  188985. png_ptr->buffer_size -= save_size;
  188986. png_ptr->save_buffer_size -= save_size;
  188987. png_ptr->save_buffer_ptr += save_size;
  188988. }
  188989. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188990. {
  188991. png_size_t save_size;
  188992. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188993. {
  188994. save_size = (png_size_t)png_ptr->idat_size;
  188995. /* check for overflow */
  188996. if((png_uint_32)save_size != png_ptr->idat_size)
  188997. png_error(png_ptr, "save_size overflowed in pngpread");
  188998. }
  188999. else
  189000. save_size = png_ptr->current_buffer_size;
  189001. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189002. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189003. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189004. png_ptr->idat_size -= save_size;
  189005. png_ptr->buffer_size -= save_size;
  189006. png_ptr->current_buffer_size -= save_size;
  189007. png_ptr->current_buffer_ptr += save_size;
  189008. }
  189009. if (!png_ptr->idat_size)
  189010. {
  189011. if (png_ptr->buffer_size < 4)
  189012. {
  189013. png_push_save_buffer(png_ptr);
  189014. return;
  189015. }
  189016. png_crc_finish(png_ptr, 0);
  189017. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189018. png_ptr->mode |= PNG_AFTER_IDAT;
  189019. }
  189020. }
  189021. void /* PRIVATE */
  189022. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189023. png_size_t buffer_length)
  189024. {
  189025. int ret;
  189026. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189027. png_error(png_ptr, "Extra compression data");
  189028. png_ptr->zstream.next_in = buffer;
  189029. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189030. for(;;)
  189031. {
  189032. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189033. if (ret != Z_OK)
  189034. {
  189035. if (ret == Z_STREAM_END)
  189036. {
  189037. if (png_ptr->zstream.avail_in)
  189038. png_error(png_ptr, "Extra compressed data");
  189039. if (!(png_ptr->zstream.avail_out))
  189040. {
  189041. png_push_process_row(png_ptr);
  189042. }
  189043. png_ptr->mode |= PNG_AFTER_IDAT;
  189044. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189045. break;
  189046. }
  189047. else if (ret == Z_BUF_ERROR)
  189048. break;
  189049. else
  189050. png_error(png_ptr, "Decompression Error");
  189051. }
  189052. if (!(png_ptr->zstream.avail_out))
  189053. {
  189054. if ((
  189055. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189056. png_ptr->interlaced && png_ptr->pass > 6) ||
  189057. (!png_ptr->interlaced &&
  189058. #endif
  189059. png_ptr->row_number == png_ptr->num_rows))
  189060. {
  189061. if (png_ptr->zstream.avail_in)
  189062. {
  189063. png_warning(png_ptr, "Too much data in IDAT chunks");
  189064. }
  189065. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189066. break;
  189067. }
  189068. png_push_process_row(png_ptr);
  189069. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189070. png_ptr->zstream.next_out = png_ptr->row_buf;
  189071. }
  189072. else
  189073. break;
  189074. }
  189075. }
  189076. void /* PRIVATE */
  189077. png_push_process_row(png_structp png_ptr)
  189078. {
  189079. png_ptr->row_info.color_type = png_ptr->color_type;
  189080. png_ptr->row_info.width = png_ptr->iwidth;
  189081. png_ptr->row_info.channels = png_ptr->channels;
  189082. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189083. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189084. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189085. png_ptr->row_info.width);
  189086. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189087. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189088. (int)(png_ptr->row_buf[0]));
  189089. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189090. png_ptr->rowbytes + 1);
  189091. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189092. png_do_read_transformations(png_ptr);
  189093. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189094. /* blow up interlaced rows to full size */
  189095. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189096. {
  189097. if (png_ptr->pass < 6)
  189098. /* old interface (pre-1.0.9):
  189099. png_do_read_interlace(&(png_ptr->row_info),
  189100. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189101. */
  189102. png_do_read_interlace(png_ptr);
  189103. switch (png_ptr->pass)
  189104. {
  189105. case 0:
  189106. {
  189107. int i;
  189108. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189109. {
  189110. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189111. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189112. }
  189113. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189114. {
  189115. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189116. {
  189117. png_push_have_row(png_ptr, png_bytep_NULL);
  189118. png_read_push_finish_row(png_ptr);
  189119. }
  189120. }
  189121. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189122. {
  189123. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189124. {
  189125. png_push_have_row(png_ptr, png_bytep_NULL);
  189126. png_read_push_finish_row(png_ptr);
  189127. }
  189128. }
  189129. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189130. {
  189131. png_push_have_row(png_ptr, png_bytep_NULL);
  189132. png_read_push_finish_row(png_ptr);
  189133. }
  189134. break;
  189135. }
  189136. case 1:
  189137. {
  189138. int i;
  189139. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189140. {
  189141. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189142. png_read_push_finish_row(png_ptr);
  189143. }
  189144. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189145. {
  189146. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189147. {
  189148. png_push_have_row(png_ptr, png_bytep_NULL);
  189149. png_read_push_finish_row(png_ptr);
  189150. }
  189151. }
  189152. break;
  189153. }
  189154. case 2:
  189155. {
  189156. int i;
  189157. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189158. {
  189159. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189160. png_read_push_finish_row(png_ptr);
  189161. }
  189162. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189163. {
  189164. png_push_have_row(png_ptr, png_bytep_NULL);
  189165. png_read_push_finish_row(png_ptr);
  189166. }
  189167. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189168. {
  189169. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189170. {
  189171. png_push_have_row(png_ptr, png_bytep_NULL);
  189172. png_read_push_finish_row(png_ptr);
  189173. }
  189174. }
  189175. break;
  189176. }
  189177. case 3:
  189178. {
  189179. int i;
  189180. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189181. {
  189182. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189183. png_read_push_finish_row(png_ptr);
  189184. }
  189185. if (png_ptr->pass == 4) /* skip top two generated rows */
  189186. {
  189187. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189188. {
  189189. png_push_have_row(png_ptr, png_bytep_NULL);
  189190. png_read_push_finish_row(png_ptr);
  189191. }
  189192. }
  189193. break;
  189194. }
  189195. case 4:
  189196. {
  189197. int i;
  189198. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189199. {
  189200. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189201. png_read_push_finish_row(png_ptr);
  189202. }
  189203. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189204. {
  189205. png_push_have_row(png_ptr, png_bytep_NULL);
  189206. png_read_push_finish_row(png_ptr);
  189207. }
  189208. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189209. {
  189210. png_push_have_row(png_ptr, png_bytep_NULL);
  189211. png_read_push_finish_row(png_ptr);
  189212. }
  189213. break;
  189214. }
  189215. case 5:
  189216. {
  189217. int i;
  189218. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189219. {
  189220. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189221. png_read_push_finish_row(png_ptr);
  189222. }
  189223. if (png_ptr->pass == 6) /* skip top generated row */
  189224. {
  189225. png_push_have_row(png_ptr, png_bytep_NULL);
  189226. png_read_push_finish_row(png_ptr);
  189227. }
  189228. break;
  189229. }
  189230. case 6:
  189231. {
  189232. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189233. png_read_push_finish_row(png_ptr);
  189234. if (png_ptr->pass != 6)
  189235. break;
  189236. png_push_have_row(png_ptr, png_bytep_NULL);
  189237. png_read_push_finish_row(png_ptr);
  189238. }
  189239. }
  189240. }
  189241. else
  189242. #endif
  189243. {
  189244. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189245. png_read_push_finish_row(png_ptr);
  189246. }
  189247. }
  189248. void /* PRIVATE */
  189249. png_read_push_finish_row(png_structp png_ptr)
  189250. {
  189251. #ifdef PNG_USE_LOCAL_ARRAYS
  189252. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189253. /* start of interlace block */
  189254. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189255. /* offset to next interlace block */
  189256. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189257. /* start of interlace block in the y direction */
  189258. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189259. /* offset to next interlace block in the y direction */
  189260. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189261. /* Height of interlace block. This is not currently used - if you need
  189262. * it, uncomment it here and in png.h
  189263. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189264. */
  189265. #endif
  189266. png_ptr->row_number++;
  189267. if (png_ptr->row_number < png_ptr->num_rows)
  189268. return;
  189269. if (png_ptr->interlaced)
  189270. {
  189271. png_ptr->row_number = 0;
  189272. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189273. png_ptr->rowbytes + 1);
  189274. do
  189275. {
  189276. png_ptr->pass++;
  189277. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189278. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189279. (png_ptr->pass == 5 && png_ptr->width < 2))
  189280. png_ptr->pass++;
  189281. if (png_ptr->pass > 7)
  189282. png_ptr->pass--;
  189283. if (png_ptr->pass >= 7)
  189284. break;
  189285. png_ptr->iwidth = (png_ptr->width +
  189286. png_pass_inc[png_ptr->pass] - 1 -
  189287. png_pass_start[png_ptr->pass]) /
  189288. png_pass_inc[png_ptr->pass];
  189289. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189290. png_ptr->iwidth) + 1;
  189291. if (png_ptr->transformations & PNG_INTERLACE)
  189292. break;
  189293. png_ptr->num_rows = (png_ptr->height +
  189294. png_pass_yinc[png_ptr->pass] - 1 -
  189295. png_pass_ystart[png_ptr->pass]) /
  189296. png_pass_yinc[png_ptr->pass];
  189297. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189298. }
  189299. }
  189300. #if defined(PNG_READ_tEXt_SUPPORTED)
  189301. void /* PRIVATE */
  189302. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189303. length)
  189304. {
  189305. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189306. {
  189307. png_error(png_ptr, "Out of place tEXt");
  189308. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189309. }
  189310. #ifdef PNG_MAX_MALLOC_64K
  189311. png_ptr->skip_length = 0; /* This may not be necessary */
  189312. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189313. {
  189314. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189315. png_ptr->skip_length = length - (png_uint_32)65535L;
  189316. length = (png_uint_32)65535L;
  189317. }
  189318. #endif
  189319. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189320. (png_uint_32)(length+1));
  189321. png_ptr->current_text[length] = '\0';
  189322. png_ptr->current_text_ptr = png_ptr->current_text;
  189323. png_ptr->current_text_size = (png_size_t)length;
  189324. png_ptr->current_text_left = (png_size_t)length;
  189325. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189326. }
  189327. void /* PRIVATE */
  189328. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189329. {
  189330. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189331. {
  189332. png_size_t text_size;
  189333. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189334. text_size = png_ptr->buffer_size;
  189335. else
  189336. text_size = png_ptr->current_text_left;
  189337. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189338. png_ptr->current_text_left -= text_size;
  189339. png_ptr->current_text_ptr += text_size;
  189340. }
  189341. if (!(png_ptr->current_text_left))
  189342. {
  189343. png_textp text_ptr;
  189344. png_charp text;
  189345. png_charp key;
  189346. int ret;
  189347. if (png_ptr->buffer_size < 4)
  189348. {
  189349. png_push_save_buffer(png_ptr);
  189350. return;
  189351. }
  189352. png_push_crc_finish(png_ptr);
  189353. #if defined(PNG_MAX_MALLOC_64K)
  189354. if (png_ptr->skip_length)
  189355. return;
  189356. #endif
  189357. key = png_ptr->current_text;
  189358. for (text = key; *text; text++)
  189359. /* empty loop */ ;
  189360. if (text < key + png_ptr->current_text_size)
  189361. text++;
  189362. text_ptr = (png_textp)png_malloc(png_ptr,
  189363. (png_uint_32)png_sizeof(png_text));
  189364. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189365. text_ptr->key = key;
  189366. #ifdef PNG_iTXt_SUPPORTED
  189367. text_ptr->lang = NULL;
  189368. text_ptr->lang_key = NULL;
  189369. #endif
  189370. text_ptr->text = text;
  189371. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189372. png_free(png_ptr, key);
  189373. png_free(png_ptr, text_ptr);
  189374. png_ptr->current_text = NULL;
  189375. if (ret)
  189376. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189377. }
  189378. }
  189379. #endif
  189380. #if defined(PNG_READ_zTXt_SUPPORTED)
  189381. void /* PRIVATE */
  189382. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189383. length)
  189384. {
  189385. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189386. {
  189387. png_error(png_ptr, "Out of place zTXt");
  189388. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189389. }
  189390. #ifdef PNG_MAX_MALLOC_64K
  189391. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189392. * to be able to store the uncompressed data. Actually, the threshold
  189393. * is probably around 32K, but it isn't as definite as 64K is.
  189394. */
  189395. if (length > (png_uint_32)65535L)
  189396. {
  189397. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189398. png_push_crc_skip(png_ptr, length);
  189399. return;
  189400. }
  189401. #endif
  189402. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189403. (png_uint_32)(length+1));
  189404. png_ptr->current_text[length] = '\0';
  189405. png_ptr->current_text_ptr = png_ptr->current_text;
  189406. png_ptr->current_text_size = (png_size_t)length;
  189407. png_ptr->current_text_left = (png_size_t)length;
  189408. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189409. }
  189410. void /* PRIVATE */
  189411. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189412. {
  189413. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189414. {
  189415. png_size_t text_size;
  189416. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189417. text_size = png_ptr->buffer_size;
  189418. else
  189419. text_size = png_ptr->current_text_left;
  189420. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189421. png_ptr->current_text_left -= text_size;
  189422. png_ptr->current_text_ptr += text_size;
  189423. }
  189424. if (!(png_ptr->current_text_left))
  189425. {
  189426. png_textp text_ptr;
  189427. png_charp text;
  189428. png_charp key;
  189429. int ret;
  189430. png_size_t text_size, key_size;
  189431. if (png_ptr->buffer_size < 4)
  189432. {
  189433. png_push_save_buffer(png_ptr);
  189434. return;
  189435. }
  189436. png_push_crc_finish(png_ptr);
  189437. key = png_ptr->current_text;
  189438. for (text = key; *text; text++)
  189439. /* empty loop */ ;
  189440. /* zTXt can't have zero text */
  189441. if (text >= key + png_ptr->current_text_size)
  189442. {
  189443. png_ptr->current_text = NULL;
  189444. png_free(png_ptr, key);
  189445. return;
  189446. }
  189447. text++;
  189448. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189449. {
  189450. png_ptr->current_text = NULL;
  189451. png_free(png_ptr, key);
  189452. return;
  189453. }
  189454. text++;
  189455. png_ptr->zstream.next_in = (png_bytep )text;
  189456. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189457. (text - key));
  189458. png_ptr->zstream.next_out = png_ptr->zbuf;
  189459. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189460. key_size = text - key;
  189461. text_size = 0;
  189462. text = NULL;
  189463. ret = Z_STREAM_END;
  189464. while (png_ptr->zstream.avail_in)
  189465. {
  189466. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189467. if (ret != Z_OK && ret != Z_STREAM_END)
  189468. {
  189469. inflateReset(&png_ptr->zstream);
  189470. png_ptr->zstream.avail_in = 0;
  189471. png_ptr->current_text = NULL;
  189472. png_free(png_ptr, key);
  189473. png_free(png_ptr, text);
  189474. return;
  189475. }
  189476. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189477. {
  189478. if (text == NULL)
  189479. {
  189480. text = (png_charp)png_malloc(png_ptr,
  189481. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189482. + key_size + 1));
  189483. png_memcpy(text + key_size, png_ptr->zbuf,
  189484. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189485. png_memcpy(text, key, key_size);
  189486. text_size = key_size + png_ptr->zbuf_size -
  189487. png_ptr->zstream.avail_out;
  189488. *(text + text_size) = '\0';
  189489. }
  189490. else
  189491. {
  189492. png_charp tmp;
  189493. tmp = text;
  189494. text = (png_charp)png_malloc(png_ptr, text_size +
  189495. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189496. + 1));
  189497. png_memcpy(text, tmp, text_size);
  189498. png_free(png_ptr, tmp);
  189499. png_memcpy(text + text_size, png_ptr->zbuf,
  189500. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189501. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189502. *(text + text_size) = '\0';
  189503. }
  189504. if (ret != Z_STREAM_END)
  189505. {
  189506. png_ptr->zstream.next_out = png_ptr->zbuf;
  189507. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189508. }
  189509. }
  189510. else
  189511. {
  189512. break;
  189513. }
  189514. if (ret == Z_STREAM_END)
  189515. break;
  189516. }
  189517. inflateReset(&png_ptr->zstream);
  189518. png_ptr->zstream.avail_in = 0;
  189519. if (ret != Z_STREAM_END)
  189520. {
  189521. png_ptr->current_text = NULL;
  189522. png_free(png_ptr, key);
  189523. png_free(png_ptr, text);
  189524. return;
  189525. }
  189526. png_ptr->current_text = NULL;
  189527. png_free(png_ptr, key);
  189528. key = text;
  189529. text += key_size;
  189530. text_ptr = (png_textp)png_malloc(png_ptr,
  189531. (png_uint_32)png_sizeof(png_text));
  189532. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189533. text_ptr->key = key;
  189534. #ifdef PNG_iTXt_SUPPORTED
  189535. text_ptr->lang = NULL;
  189536. text_ptr->lang_key = NULL;
  189537. #endif
  189538. text_ptr->text = text;
  189539. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189540. png_free(png_ptr, key);
  189541. png_free(png_ptr, text_ptr);
  189542. if (ret)
  189543. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189544. }
  189545. }
  189546. #endif
  189547. #if defined(PNG_READ_iTXt_SUPPORTED)
  189548. void /* PRIVATE */
  189549. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189550. length)
  189551. {
  189552. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189553. {
  189554. png_error(png_ptr, "Out of place iTXt");
  189555. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189556. }
  189557. #ifdef PNG_MAX_MALLOC_64K
  189558. png_ptr->skip_length = 0; /* This may not be necessary */
  189559. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189560. {
  189561. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189562. png_ptr->skip_length = length - (png_uint_32)65535L;
  189563. length = (png_uint_32)65535L;
  189564. }
  189565. #endif
  189566. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189567. (png_uint_32)(length+1));
  189568. png_ptr->current_text[length] = '\0';
  189569. png_ptr->current_text_ptr = png_ptr->current_text;
  189570. png_ptr->current_text_size = (png_size_t)length;
  189571. png_ptr->current_text_left = (png_size_t)length;
  189572. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189573. }
  189574. void /* PRIVATE */
  189575. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189576. {
  189577. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189578. {
  189579. png_size_t text_size;
  189580. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189581. text_size = png_ptr->buffer_size;
  189582. else
  189583. text_size = png_ptr->current_text_left;
  189584. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189585. png_ptr->current_text_left -= text_size;
  189586. png_ptr->current_text_ptr += text_size;
  189587. }
  189588. if (!(png_ptr->current_text_left))
  189589. {
  189590. png_textp text_ptr;
  189591. png_charp key;
  189592. int comp_flag;
  189593. png_charp lang;
  189594. png_charp lang_key;
  189595. png_charp text;
  189596. int ret;
  189597. if (png_ptr->buffer_size < 4)
  189598. {
  189599. png_push_save_buffer(png_ptr);
  189600. return;
  189601. }
  189602. png_push_crc_finish(png_ptr);
  189603. #if defined(PNG_MAX_MALLOC_64K)
  189604. if (png_ptr->skip_length)
  189605. return;
  189606. #endif
  189607. key = png_ptr->current_text;
  189608. for (lang = key; *lang; lang++)
  189609. /* empty loop */ ;
  189610. if (lang < key + png_ptr->current_text_size - 3)
  189611. lang++;
  189612. comp_flag = *lang++;
  189613. lang++; /* skip comp_type, always zero */
  189614. for (lang_key = lang; *lang_key; lang_key++)
  189615. /* empty loop */ ;
  189616. lang_key++; /* skip NUL separator */
  189617. text=lang_key;
  189618. if (lang_key < key + png_ptr->current_text_size - 1)
  189619. {
  189620. for (; *text; text++)
  189621. /* empty loop */ ;
  189622. }
  189623. if (text < key + png_ptr->current_text_size)
  189624. text++;
  189625. text_ptr = (png_textp)png_malloc(png_ptr,
  189626. (png_uint_32)png_sizeof(png_text));
  189627. text_ptr->compression = comp_flag + 2;
  189628. text_ptr->key = key;
  189629. text_ptr->lang = lang;
  189630. text_ptr->lang_key = lang_key;
  189631. text_ptr->text = text;
  189632. text_ptr->text_length = 0;
  189633. text_ptr->itxt_length = png_strlen(text);
  189634. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189635. png_ptr->current_text = NULL;
  189636. png_free(png_ptr, text_ptr);
  189637. if (ret)
  189638. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189639. }
  189640. }
  189641. #endif
  189642. /* This function is called when we haven't found a handler for this
  189643. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189644. * name or a critical chunk), the chunk is (currently) silently ignored.
  189645. */
  189646. void /* PRIVATE */
  189647. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189648. length)
  189649. {
  189650. png_uint_32 skip=0;
  189651. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189652. if (!(png_ptr->chunk_name[0] & 0x20))
  189653. {
  189654. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189655. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189656. PNG_HANDLE_CHUNK_ALWAYS
  189657. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189658. && png_ptr->read_user_chunk_fn == NULL
  189659. #endif
  189660. )
  189661. #endif
  189662. png_chunk_error(png_ptr, "unknown critical chunk");
  189663. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189664. }
  189665. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189666. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189667. {
  189668. #ifdef PNG_MAX_MALLOC_64K
  189669. if (length > (png_uint_32)65535L)
  189670. {
  189671. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189672. skip = length - (png_uint_32)65535L;
  189673. length = (png_uint_32)65535L;
  189674. }
  189675. #endif
  189676. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189677. (png_charp)png_ptr->chunk_name, 5);
  189678. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189679. png_ptr->unknown_chunk.size = (png_size_t)length;
  189680. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189681. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189682. if(png_ptr->read_user_chunk_fn != NULL)
  189683. {
  189684. /* callback to user unknown chunk handler */
  189685. int ret;
  189686. ret = (*(png_ptr->read_user_chunk_fn))
  189687. (png_ptr, &png_ptr->unknown_chunk);
  189688. if (ret < 0)
  189689. png_chunk_error(png_ptr, "error in user chunk");
  189690. if (ret == 0)
  189691. {
  189692. if (!(png_ptr->chunk_name[0] & 0x20))
  189693. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189694. PNG_HANDLE_CHUNK_ALWAYS)
  189695. png_chunk_error(png_ptr, "unknown critical chunk");
  189696. png_set_unknown_chunks(png_ptr, info_ptr,
  189697. &png_ptr->unknown_chunk, 1);
  189698. }
  189699. }
  189700. #else
  189701. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189702. #endif
  189703. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189704. png_ptr->unknown_chunk.data = NULL;
  189705. }
  189706. else
  189707. #endif
  189708. skip=length;
  189709. png_push_crc_skip(png_ptr, skip);
  189710. }
  189711. void /* PRIVATE */
  189712. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189713. {
  189714. if (png_ptr->info_fn != NULL)
  189715. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189716. }
  189717. void /* PRIVATE */
  189718. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189719. {
  189720. if (png_ptr->end_fn != NULL)
  189721. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189722. }
  189723. void /* PRIVATE */
  189724. png_push_have_row(png_structp png_ptr, png_bytep row)
  189725. {
  189726. if (png_ptr->row_fn != NULL)
  189727. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189728. (int)png_ptr->pass);
  189729. }
  189730. void PNGAPI
  189731. png_progressive_combine_row (png_structp png_ptr,
  189732. png_bytep old_row, png_bytep new_row)
  189733. {
  189734. #ifdef PNG_USE_LOCAL_ARRAYS
  189735. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189736. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189737. #endif
  189738. if(png_ptr == NULL) return;
  189739. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189740. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189741. }
  189742. void PNGAPI
  189743. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189744. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189745. png_progressive_end_ptr end_fn)
  189746. {
  189747. if(png_ptr == NULL) return;
  189748. png_ptr->info_fn = info_fn;
  189749. png_ptr->row_fn = row_fn;
  189750. png_ptr->end_fn = end_fn;
  189751. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189752. }
  189753. png_voidp PNGAPI
  189754. png_get_progressive_ptr(png_structp png_ptr)
  189755. {
  189756. if(png_ptr == NULL) return (NULL);
  189757. return png_ptr->io_ptr;
  189758. }
  189759. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189760. /*** End of inlined file: pngpread.c ***/
  189761. /*** Start of inlined file: pngrio.c ***/
  189762. /* pngrio.c - functions for data input
  189763. *
  189764. * Last changed in libpng 1.2.13 November 13, 2006
  189765. * For conditions of distribution and use, see copyright notice in png.h
  189766. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189767. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189768. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189769. *
  189770. * This file provides a location for all input. Users who need
  189771. * special handling are expected to write a function that has the same
  189772. * arguments as this and performs a similar function, but that possibly
  189773. * has a different input method. Note that you shouldn't change this
  189774. * function, but rather write a replacement function and then make
  189775. * libpng use it at run time with png_set_read_fn(...).
  189776. */
  189777. #define PNG_INTERNAL
  189778. #if defined(PNG_READ_SUPPORTED)
  189779. /* Read the data from whatever input you are using. The default routine
  189780. reads from a file pointer. Note that this routine sometimes gets called
  189781. with very small lengths, so you should implement some kind of simple
  189782. buffering if you are using unbuffered reads. This should never be asked
  189783. to read more then 64K on a 16 bit machine. */
  189784. void /* PRIVATE */
  189785. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189786. {
  189787. png_debug1(4,"reading %d bytes\n", (int)length);
  189788. if (png_ptr->read_data_fn != NULL)
  189789. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189790. else
  189791. png_error(png_ptr, "Call to NULL read function");
  189792. }
  189793. #if !defined(PNG_NO_STDIO)
  189794. /* This is the function that does the actual reading of data. If you are
  189795. not reading from a standard C stream, you should create a replacement
  189796. read_data function and use it at run time with png_set_read_fn(), rather
  189797. than changing the library. */
  189798. #ifndef USE_FAR_KEYWORD
  189799. void PNGAPI
  189800. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189801. {
  189802. png_size_t check;
  189803. if(png_ptr == NULL) return;
  189804. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189805. * instead of an int, which is what fread() actually returns.
  189806. */
  189807. #if defined(_WIN32_WCE)
  189808. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189809. check = 0;
  189810. #else
  189811. check = (png_size_t)fread(data, (png_size_t)1, length,
  189812. (png_FILE_p)png_ptr->io_ptr);
  189813. #endif
  189814. if (check != length)
  189815. png_error(png_ptr, "Read Error");
  189816. }
  189817. #else
  189818. /* this is the model-independent version. Since the standard I/O library
  189819. can't handle far buffers in the medium and small models, we have to copy
  189820. the data.
  189821. */
  189822. #define NEAR_BUF_SIZE 1024
  189823. #define MIN(a,b) (a <= b ? a : b)
  189824. static void PNGAPI
  189825. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189826. {
  189827. int check;
  189828. png_byte *n_data;
  189829. png_FILE_p io_ptr;
  189830. if(png_ptr == NULL) return;
  189831. /* Check if data really is near. If so, use usual code. */
  189832. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189833. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189834. if ((png_bytep)n_data == data)
  189835. {
  189836. #if defined(_WIN32_WCE)
  189837. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189838. check = 0;
  189839. #else
  189840. check = fread(n_data, 1, length, io_ptr);
  189841. #endif
  189842. }
  189843. else
  189844. {
  189845. png_byte buf[NEAR_BUF_SIZE];
  189846. png_size_t read, remaining, err;
  189847. check = 0;
  189848. remaining = length;
  189849. do
  189850. {
  189851. read = MIN(NEAR_BUF_SIZE, remaining);
  189852. #if defined(_WIN32_WCE)
  189853. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189854. err = 0;
  189855. #else
  189856. err = fread(buf, (png_size_t)1, read, io_ptr);
  189857. #endif
  189858. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189859. if(err != read)
  189860. break;
  189861. else
  189862. check += err;
  189863. data += read;
  189864. remaining -= read;
  189865. }
  189866. while (remaining != 0);
  189867. }
  189868. if ((png_uint_32)check != (png_uint_32)length)
  189869. png_error(png_ptr, "read Error");
  189870. }
  189871. #endif
  189872. #endif
  189873. /* This function allows the application to supply a new input function
  189874. for libpng if standard C streams aren't being used.
  189875. This function takes as its arguments:
  189876. png_ptr - pointer to a png input data structure
  189877. io_ptr - pointer to user supplied structure containing info about
  189878. the input functions. May be NULL.
  189879. read_data_fn - pointer to a new input function that takes as its
  189880. arguments a pointer to a png_struct, a pointer to
  189881. a location where input data can be stored, and a 32-bit
  189882. unsigned int that is the number of bytes to be read.
  189883. To exit and output any fatal error messages the new write
  189884. function should call png_error(png_ptr, "Error msg"). */
  189885. void PNGAPI
  189886. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189887. png_rw_ptr read_data_fn)
  189888. {
  189889. if(png_ptr == NULL) return;
  189890. png_ptr->io_ptr = io_ptr;
  189891. #if !defined(PNG_NO_STDIO)
  189892. if (read_data_fn != NULL)
  189893. png_ptr->read_data_fn = read_data_fn;
  189894. else
  189895. png_ptr->read_data_fn = png_default_read_data;
  189896. #else
  189897. png_ptr->read_data_fn = read_data_fn;
  189898. #endif
  189899. /* It is an error to write to a read device */
  189900. if (png_ptr->write_data_fn != NULL)
  189901. {
  189902. png_ptr->write_data_fn = NULL;
  189903. png_warning(png_ptr,
  189904. "It's an error to set both read_data_fn and write_data_fn in the ");
  189905. png_warning(png_ptr,
  189906. "same structure. Resetting write_data_fn to NULL.");
  189907. }
  189908. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189909. png_ptr->output_flush_fn = NULL;
  189910. #endif
  189911. }
  189912. #endif /* PNG_READ_SUPPORTED */
  189913. /*** End of inlined file: pngrio.c ***/
  189914. /*** Start of inlined file: pngrtran.c ***/
  189915. /* pngrtran.c - transforms the data in a row for PNG readers
  189916. *
  189917. * Last changed in libpng 1.2.21 [October 4, 2007]
  189918. * For conditions of distribution and use, see copyright notice in png.h
  189919. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189920. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189921. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189922. *
  189923. * This file contains functions optionally called by an application
  189924. * in order to tell libpng how to handle data when reading a PNG.
  189925. * Transformations that are used in both reading and writing are
  189926. * in pngtrans.c.
  189927. */
  189928. #define PNG_INTERNAL
  189929. #if defined(PNG_READ_SUPPORTED)
  189930. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189931. void PNGAPI
  189932. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189933. {
  189934. png_debug(1, "in png_set_crc_action\n");
  189935. /* Tell libpng how we react to CRC errors in critical chunks */
  189936. if(png_ptr == NULL) return;
  189937. switch (crit_action)
  189938. {
  189939. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189940. break;
  189941. case PNG_CRC_WARN_USE: /* warn/use data */
  189942. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189943. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189944. break;
  189945. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189946. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189947. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189948. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189949. break;
  189950. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189951. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189952. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189953. case PNG_CRC_DEFAULT:
  189954. default:
  189955. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189956. break;
  189957. }
  189958. switch (ancil_action)
  189959. {
  189960. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189961. break;
  189962. case PNG_CRC_WARN_USE: /* warn/use data */
  189963. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189964. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189965. break;
  189966. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189967. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189968. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189969. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189970. break;
  189971. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189972. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189973. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189974. break;
  189975. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189976. case PNG_CRC_DEFAULT:
  189977. default:
  189978. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189979. break;
  189980. }
  189981. }
  189982. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189983. defined(PNG_FLOATING_POINT_SUPPORTED)
  189984. /* handle alpha and tRNS via a background color */
  189985. void PNGAPI
  189986. png_set_background(png_structp png_ptr,
  189987. png_color_16p background_color, int background_gamma_code,
  189988. int need_expand, double background_gamma)
  189989. {
  189990. png_debug(1, "in png_set_background\n");
  189991. if(png_ptr == NULL) return;
  189992. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189993. {
  189994. png_warning(png_ptr, "Application must supply a known background gamma");
  189995. return;
  189996. }
  189997. png_ptr->transformations |= PNG_BACKGROUND;
  189998. png_memcpy(&(png_ptr->background), background_color,
  189999. png_sizeof(png_color_16));
  190000. png_ptr->background_gamma = (float)background_gamma;
  190001. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190002. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190003. }
  190004. #endif
  190005. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190006. /* strip 16 bit depth files to 8 bit depth */
  190007. void PNGAPI
  190008. png_set_strip_16(png_structp png_ptr)
  190009. {
  190010. png_debug(1, "in png_set_strip_16\n");
  190011. if(png_ptr == NULL) return;
  190012. png_ptr->transformations |= PNG_16_TO_8;
  190013. }
  190014. #endif
  190015. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190016. void PNGAPI
  190017. png_set_strip_alpha(png_structp png_ptr)
  190018. {
  190019. png_debug(1, "in png_set_strip_alpha\n");
  190020. if(png_ptr == NULL) return;
  190021. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190022. }
  190023. #endif
  190024. #if defined(PNG_READ_DITHER_SUPPORTED)
  190025. /* Dither file to 8 bit. Supply a palette, the current number
  190026. * of elements in the palette, the maximum number of elements
  190027. * allowed, and a histogram if possible. If the current number
  190028. * of colors is greater then the maximum number, the palette will be
  190029. * modified to fit in the maximum number. "full_dither" indicates
  190030. * whether we need a dithering cube set up for RGB images, or if we
  190031. * simply are reducing the number of colors in a paletted image.
  190032. */
  190033. typedef struct png_dsort_struct
  190034. {
  190035. struct png_dsort_struct FAR * next;
  190036. png_byte left;
  190037. png_byte right;
  190038. } png_dsort;
  190039. typedef png_dsort FAR * png_dsortp;
  190040. typedef png_dsort FAR * FAR * png_dsortpp;
  190041. void PNGAPI
  190042. png_set_dither(png_structp png_ptr, png_colorp palette,
  190043. int num_palette, int maximum_colors, png_uint_16p histogram,
  190044. int full_dither)
  190045. {
  190046. png_debug(1, "in png_set_dither\n");
  190047. if(png_ptr == NULL) return;
  190048. png_ptr->transformations |= PNG_DITHER;
  190049. if (!full_dither)
  190050. {
  190051. int i;
  190052. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190053. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190054. for (i = 0; i < num_palette; i++)
  190055. png_ptr->dither_index[i] = (png_byte)i;
  190056. }
  190057. if (num_palette > maximum_colors)
  190058. {
  190059. if (histogram != NULL)
  190060. {
  190061. /* This is easy enough, just throw out the least used colors.
  190062. Perhaps not the best solution, but good enough. */
  190063. int i;
  190064. /* initialize an array to sort colors */
  190065. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190066. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190067. /* initialize the dither_sort array */
  190068. for (i = 0; i < num_palette; i++)
  190069. png_ptr->dither_sort[i] = (png_byte)i;
  190070. /* Find the least used palette entries by starting a
  190071. bubble sort, and running it until we have sorted
  190072. out enough colors. Note that we don't care about
  190073. sorting all the colors, just finding which are
  190074. least used. */
  190075. for (i = num_palette - 1; i >= maximum_colors; i--)
  190076. {
  190077. int done; /* to stop early if the list is pre-sorted */
  190078. int j;
  190079. done = 1;
  190080. for (j = 0; j < i; j++)
  190081. {
  190082. if (histogram[png_ptr->dither_sort[j]]
  190083. < histogram[png_ptr->dither_sort[j + 1]])
  190084. {
  190085. png_byte t;
  190086. t = png_ptr->dither_sort[j];
  190087. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190088. png_ptr->dither_sort[j + 1] = t;
  190089. done = 0;
  190090. }
  190091. }
  190092. if (done)
  190093. break;
  190094. }
  190095. /* swap the palette around, and set up a table, if necessary */
  190096. if (full_dither)
  190097. {
  190098. int j = num_palette;
  190099. /* put all the useful colors within the max, but don't
  190100. move the others */
  190101. for (i = 0; i < maximum_colors; i++)
  190102. {
  190103. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190104. {
  190105. do
  190106. j--;
  190107. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190108. palette[i] = palette[j];
  190109. }
  190110. }
  190111. }
  190112. else
  190113. {
  190114. int j = num_palette;
  190115. /* move all the used colors inside the max limit, and
  190116. develop a translation table */
  190117. for (i = 0; i < maximum_colors; i++)
  190118. {
  190119. /* only move the colors we need to */
  190120. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190121. {
  190122. png_color tmp_color;
  190123. do
  190124. j--;
  190125. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190126. tmp_color = palette[j];
  190127. palette[j] = palette[i];
  190128. palette[i] = tmp_color;
  190129. /* indicate where the color went */
  190130. png_ptr->dither_index[j] = (png_byte)i;
  190131. png_ptr->dither_index[i] = (png_byte)j;
  190132. }
  190133. }
  190134. /* find closest color for those colors we are not using */
  190135. for (i = 0; i < num_palette; i++)
  190136. {
  190137. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190138. {
  190139. int min_d, k, min_k, d_index;
  190140. /* find the closest color to one we threw out */
  190141. d_index = png_ptr->dither_index[i];
  190142. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190143. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190144. {
  190145. int d;
  190146. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190147. if (d < min_d)
  190148. {
  190149. min_d = d;
  190150. min_k = k;
  190151. }
  190152. }
  190153. /* point to closest color */
  190154. png_ptr->dither_index[i] = (png_byte)min_k;
  190155. }
  190156. }
  190157. }
  190158. png_free(png_ptr, png_ptr->dither_sort);
  190159. png_ptr->dither_sort=NULL;
  190160. }
  190161. else
  190162. {
  190163. /* This is much harder to do simply (and quickly). Perhaps
  190164. we need to go through a median cut routine, but those
  190165. don't always behave themselves with only a few colors
  190166. as input. So we will just find the closest two colors,
  190167. and throw out one of them (chosen somewhat randomly).
  190168. [We don't understand this at all, so if someone wants to
  190169. work on improving it, be our guest - AED, GRP]
  190170. */
  190171. int i;
  190172. int max_d;
  190173. int num_new_palette;
  190174. png_dsortp t;
  190175. png_dsortpp hash;
  190176. t=NULL;
  190177. /* initialize palette index arrays */
  190178. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190179. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190180. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190181. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190182. /* initialize the sort array */
  190183. for (i = 0; i < num_palette; i++)
  190184. {
  190185. png_ptr->index_to_palette[i] = (png_byte)i;
  190186. png_ptr->palette_to_index[i] = (png_byte)i;
  190187. }
  190188. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190189. png_sizeof (png_dsortp)));
  190190. for (i = 0; i < 769; i++)
  190191. hash[i] = NULL;
  190192. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190193. num_new_palette = num_palette;
  190194. /* initial wild guess at how far apart the farthest pixel
  190195. pair we will be eliminating will be. Larger
  190196. numbers mean more areas will be allocated, Smaller
  190197. numbers run the risk of not saving enough data, and
  190198. having to do this all over again.
  190199. I have not done extensive checking on this number.
  190200. */
  190201. max_d = 96;
  190202. while (num_new_palette > maximum_colors)
  190203. {
  190204. for (i = 0; i < num_new_palette - 1; i++)
  190205. {
  190206. int j;
  190207. for (j = i + 1; j < num_new_palette; j++)
  190208. {
  190209. int d;
  190210. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190211. if (d <= max_d)
  190212. {
  190213. t = (png_dsortp)png_malloc_warn(png_ptr,
  190214. (png_uint_32)(png_sizeof(png_dsort)));
  190215. if (t == NULL)
  190216. break;
  190217. t->next = hash[d];
  190218. t->left = (png_byte)i;
  190219. t->right = (png_byte)j;
  190220. hash[d] = t;
  190221. }
  190222. }
  190223. if (t == NULL)
  190224. break;
  190225. }
  190226. if (t != NULL)
  190227. for (i = 0; i <= max_d; i++)
  190228. {
  190229. if (hash[i] != NULL)
  190230. {
  190231. png_dsortp p;
  190232. for (p = hash[i]; p; p = p->next)
  190233. {
  190234. if ((int)png_ptr->index_to_palette[p->left]
  190235. < num_new_palette &&
  190236. (int)png_ptr->index_to_palette[p->right]
  190237. < num_new_palette)
  190238. {
  190239. int j, next_j;
  190240. if (num_new_palette & 0x01)
  190241. {
  190242. j = p->left;
  190243. next_j = p->right;
  190244. }
  190245. else
  190246. {
  190247. j = p->right;
  190248. next_j = p->left;
  190249. }
  190250. num_new_palette--;
  190251. palette[png_ptr->index_to_palette[j]]
  190252. = palette[num_new_palette];
  190253. if (!full_dither)
  190254. {
  190255. int k;
  190256. for (k = 0; k < num_palette; k++)
  190257. {
  190258. if (png_ptr->dither_index[k] ==
  190259. png_ptr->index_to_palette[j])
  190260. png_ptr->dither_index[k] =
  190261. png_ptr->index_to_palette[next_j];
  190262. if ((int)png_ptr->dither_index[k] ==
  190263. num_new_palette)
  190264. png_ptr->dither_index[k] =
  190265. png_ptr->index_to_palette[j];
  190266. }
  190267. }
  190268. png_ptr->index_to_palette[png_ptr->palette_to_index
  190269. [num_new_palette]] = png_ptr->index_to_palette[j];
  190270. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190271. = png_ptr->palette_to_index[num_new_palette];
  190272. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190273. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190274. }
  190275. if (num_new_palette <= maximum_colors)
  190276. break;
  190277. }
  190278. if (num_new_palette <= maximum_colors)
  190279. break;
  190280. }
  190281. }
  190282. for (i = 0; i < 769; i++)
  190283. {
  190284. if (hash[i] != NULL)
  190285. {
  190286. png_dsortp p = hash[i];
  190287. while (p)
  190288. {
  190289. t = p->next;
  190290. png_free(png_ptr, p);
  190291. p = t;
  190292. }
  190293. }
  190294. hash[i] = 0;
  190295. }
  190296. max_d += 96;
  190297. }
  190298. png_free(png_ptr, hash);
  190299. png_free(png_ptr, png_ptr->palette_to_index);
  190300. png_free(png_ptr, png_ptr->index_to_palette);
  190301. png_ptr->palette_to_index=NULL;
  190302. png_ptr->index_to_palette=NULL;
  190303. }
  190304. num_palette = maximum_colors;
  190305. }
  190306. if (png_ptr->palette == NULL)
  190307. {
  190308. png_ptr->palette = palette;
  190309. }
  190310. png_ptr->num_palette = (png_uint_16)num_palette;
  190311. if (full_dither)
  190312. {
  190313. int i;
  190314. png_bytep distance;
  190315. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190316. PNG_DITHER_BLUE_BITS;
  190317. int num_red = (1 << PNG_DITHER_RED_BITS);
  190318. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190319. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190320. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190321. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190322. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190323. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190324. png_sizeof (png_byte));
  190325. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190326. png_sizeof(png_byte)));
  190327. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190328. for (i = 0; i < num_palette; i++)
  190329. {
  190330. int ir, ig, ib;
  190331. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190332. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190333. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190334. for (ir = 0; ir < num_red; ir++)
  190335. {
  190336. /* int dr = abs(ir - r); */
  190337. int dr = ((ir > r) ? ir - r : r - ir);
  190338. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190339. for (ig = 0; ig < num_green; ig++)
  190340. {
  190341. /* int dg = abs(ig - g); */
  190342. int dg = ((ig > g) ? ig - g : g - ig);
  190343. int dt = dr + dg;
  190344. int dm = ((dr > dg) ? dr : dg);
  190345. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190346. for (ib = 0; ib < num_blue; ib++)
  190347. {
  190348. int d_index = index_g | ib;
  190349. /* int db = abs(ib - b); */
  190350. int db = ((ib > b) ? ib - b : b - ib);
  190351. int dmax = ((dm > db) ? dm : db);
  190352. int d = dmax + dt + db;
  190353. if (d < (int)distance[d_index])
  190354. {
  190355. distance[d_index] = (png_byte)d;
  190356. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190357. }
  190358. }
  190359. }
  190360. }
  190361. }
  190362. png_free(png_ptr, distance);
  190363. }
  190364. }
  190365. #endif
  190366. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190367. /* Transform the image from the file_gamma to the screen_gamma. We
  190368. * only do transformations on images where the file_gamma and screen_gamma
  190369. * are not close reciprocals, otherwise it slows things down slightly, and
  190370. * also needlessly introduces small errors.
  190371. *
  190372. * We will turn off gamma transformation later if no semitransparent entries
  190373. * are present in the tRNS array for palette images. We can't do it here
  190374. * because we don't necessarily have the tRNS chunk yet.
  190375. */
  190376. void PNGAPI
  190377. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190378. {
  190379. png_debug(1, "in png_set_gamma\n");
  190380. if(png_ptr == NULL) return;
  190381. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190382. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190383. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190384. png_ptr->transformations |= PNG_GAMMA;
  190385. png_ptr->gamma = (float)file_gamma;
  190386. png_ptr->screen_gamma = (float)scrn_gamma;
  190387. }
  190388. #endif
  190389. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190390. /* Expand paletted images to RGB, expand grayscale images of
  190391. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190392. * to alpha channels.
  190393. */
  190394. void PNGAPI
  190395. png_set_expand(png_structp png_ptr)
  190396. {
  190397. png_debug(1, "in png_set_expand\n");
  190398. if(png_ptr == NULL) return;
  190399. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190400. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190401. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190402. #endif
  190403. }
  190404. /* GRR 19990627: the following three functions currently are identical
  190405. * to png_set_expand(). However, it is entirely reasonable that someone
  190406. * might wish to expand an indexed image to RGB but *not* expand a single,
  190407. * fully transparent palette entry to a full alpha channel--perhaps instead
  190408. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190409. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190410. * IOW, a future version of the library may make the transformations flag
  190411. * a bit more fine-grained, with separate bits for each of these three
  190412. * functions.
  190413. *
  190414. * More to the point, these functions make it obvious what libpng will be
  190415. * doing, whereas "expand" can (and does) mean any number of things.
  190416. *
  190417. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190418. * to expand only the sample depth but not to expand the tRNS to alpha.
  190419. */
  190420. /* Expand paletted images to RGB. */
  190421. void PNGAPI
  190422. png_set_palette_to_rgb(png_structp png_ptr)
  190423. {
  190424. png_debug(1, "in png_set_palette_to_rgb\n");
  190425. if(png_ptr == NULL) return;
  190426. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190427. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190428. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190429. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190430. #endif
  190431. }
  190432. #if !defined(PNG_1_0_X)
  190433. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190434. void PNGAPI
  190435. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190436. {
  190437. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190438. if(png_ptr == NULL) return;
  190439. png_ptr->transformations |= PNG_EXPAND;
  190440. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190441. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190442. #endif
  190443. }
  190444. #endif
  190445. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190446. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190447. /* Deprecated as of libpng-1.2.9 */
  190448. void PNGAPI
  190449. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190450. {
  190451. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190452. if(png_ptr == NULL) return;
  190453. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190454. }
  190455. #endif
  190456. /* Expand tRNS chunks to alpha channels. */
  190457. void PNGAPI
  190458. png_set_tRNS_to_alpha(png_structp png_ptr)
  190459. {
  190460. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190461. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190462. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190463. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190464. #endif
  190465. }
  190466. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190467. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190468. void PNGAPI
  190469. png_set_gray_to_rgb(png_structp png_ptr)
  190470. {
  190471. png_debug(1, "in png_set_gray_to_rgb\n");
  190472. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190473. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190474. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190475. #endif
  190476. }
  190477. #endif
  190478. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190479. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190480. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190481. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190482. */
  190483. void PNGAPI
  190484. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190485. double green)
  190486. {
  190487. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190488. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190489. if(png_ptr == NULL) return;
  190490. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190491. }
  190492. #endif
  190493. void PNGAPI
  190494. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190495. png_fixed_point red, png_fixed_point green)
  190496. {
  190497. png_debug(1, "in png_set_rgb_to_gray\n");
  190498. if(png_ptr == NULL) return;
  190499. switch(error_action)
  190500. {
  190501. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190502. break;
  190503. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190504. break;
  190505. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190506. }
  190507. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190508. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190509. png_ptr->transformations |= PNG_EXPAND;
  190510. #else
  190511. {
  190512. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190513. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190514. }
  190515. #endif
  190516. {
  190517. png_uint_16 red_int, green_int;
  190518. if(red < 0 || green < 0)
  190519. {
  190520. red_int = 6968; /* .212671 * 32768 + .5 */
  190521. green_int = 23434; /* .715160 * 32768 + .5 */
  190522. }
  190523. else if(red + green < 100000L)
  190524. {
  190525. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190526. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190527. }
  190528. else
  190529. {
  190530. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190531. red_int = 6968;
  190532. green_int = 23434;
  190533. }
  190534. png_ptr->rgb_to_gray_red_coeff = red_int;
  190535. png_ptr->rgb_to_gray_green_coeff = green_int;
  190536. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190537. }
  190538. }
  190539. #endif
  190540. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190541. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190542. defined(PNG_LEGACY_SUPPORTED)
  190543. void PNGAPI
  190544. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190545. read_user_transform_fn)
  190546. {
  190547. png_debug(1, "in png_set_read_user_transform_fn\n");
  190548. if(png_ptr == NULL) return;
  190549. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190550. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190551. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190552. #endif
  190553. #ifdef PNG_LEGACY_SUPPORTED
  190554. if(read_user_transform_fn)
  190555. png_warning(png_ptr,
  190556. "This version of libpng does not support user transforms");
  190557. #endif
  190558. }
  190559. #endif
  190560. /* Initialize everything needed for the read. This includes modifying
  190561. * the palette.
  190562. */
  190563. void /* PRIVATE */
  190564. png_init_read_transformations(png_structp png_ptr)
  190565. {
  190566. png_debug(1, "in png_init_read_transformations\n");
  190567. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190568. if(png_ptr != NULL)
  190569. #endif
  190570. {
  190571. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190572. || defined(PNG_READ_GAMMA_SUPPORTED)
  190573. int color_type = png_ptr->color_type;
  190574. #endif
  190575. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190576. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190577. /* Detect gray background and attempt to enable optimization
  190578. * for gray --> RGB case */
  190579. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190580. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190581. * background color might actually be gray yet not be flagged as such.
  190582. * This is not a problem for the current code, which uses
  190583. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190584. * png_do_gray_to_rgb() transformation.
  190585. */
  190586. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190587. !(color_type & PNG_COLOR_MASK_COLOR))
  190588. {
  190589. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190590. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190591. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190592. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190593. png_ptr->background.red == png_ptr->background.green &&
  190594. png_ptr->background.red == png_ptr->background.blue)
  190595. {
  190596. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190597. png_ptr->background.gray = png_ptr->background.red;
  190598. }
  190599. #endif
  190600. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190601. (png_ptr->transformations & PNG_EXPAND))
  190602. {
  190603. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190604. {
  190605. /* expand background and tRNS chunks */
  190606. switch (png_ptr->bit_depth)
  190607. {
  190608. case 1:
  190609. png_ptr->background.gray *= (png_uint_16)0xff;
  190610. png_ptr->background.red = png_ptr->background.green
  190611. = png_ptr->background.blue = png_ptr->background.gray;
  190612. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190613. {
  190614. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190615. png_ptr->trans_values.red = png_ptr->trans_values.green
  190616. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190617. }
  190618. break;
  190619. case 2:
  190620. png_ptr->background.gray *= (png_uint_16)0x55;
  190621. png_ptr->background.red = png_ptr->background.green
  190622. = png_ptr->background.blue = png_ptr->background.gray;
  190623. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190624. {
  190625. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190626. png_ptr->trans_values.red = png_ptr->trans_values.green
  190627. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190628. }
  190629. break;
  190630. case 4:
  190631. png_ptr->background.gray *= (png_uint_16)0x11;
  190632. png_ptr->background.red = png_ptr->background.green
  190633. = png_ptr->background.blue = png_ptr->background.gray;
  190634. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190635. {
  190636. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190637. png_ptr->trans_values.red = png_ptr->trans_values.green
  190638. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190639. }
  190640. break;
  190641. case 8:
  190642. case 16:
  190643. png_ptr->background.red = png_ptr->background.green
  190644. = png_ptr->background.blue = png_ptr->background.gray;
  190645. break;
  190646. }
  190647. }
  190648. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190649. {
  190650. png_ptr->background.red =
  190651. png_ptr->palette[png_ptr->background.index].red;
  190652. png_ptr->background.green =
  190653. png_ptr->palette[png_ptr->background.index].green;
  190654. png_ptr->background.blue =
  190655. png_ptr->palette[png_ptr->background.index].blue;
  190656. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190657. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190658. {
  190659. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190660. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190661. #endif
  190662. {
  190663. /* invert the alpha channel (in tRNS) unless the pixels are
  190664. going to be expanded, in which case leave it for later */
  190665. int i,istop;
  190666. istop=(int)png_ptr->num_trans;
  190667. for (i=0; i<istop; i++)
  190668. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190669. }
  190670. }
  190671. #endif
  190672. }
  190673. }
  190674. #endif
  190675. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190676. png_ptr->background_1 = png_ptr->background;
  190677. #endif
  190678. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190679. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190680. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190681. < PNG_GAMMA_THRESHOLD))
  190682. {
  190683. int i,k;
  190684. k=0;
  190685. for (i=0; i<png_ptr->num_trans; i++)
  190686. {
  190687. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190688. k=1; /* partial transparency is present */
  190689. }
  190690. if (k == 0)
  190691. png_ptr->transformations &= (~PNG_GAMMA);
  190692. }
  190693. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190694. png_ptr->gamma != 0.0)
  190695. {
  190696. png_build_gamma_table(png_ptr);
  190697. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190698. if (png_ptr->transformations & PNG_BACKGROUND)
  190699. {
  190700. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190701. {
  190702. /* could skip if no transparency and
  190703. */
  190704. png_color back, back_1;
  190705. png_colorp palette = png_ptr->palette;
  190706. int num_palette = png_ptr->num_palette;
  190707. int i;
  190708. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190709. {
  190710. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190711. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190712. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190713. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190714. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190715. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190716. }
  190717. else
  190718. {
  190719. double g, gs;
  190720. switch (png_ptr->background_gamma_type)
  190721. {
  190722. case PNG_BACKGROUND_GAMMA_SCREEN:
  190723. g = (png_ptr->screen_gamma);
  190724. gs = 1.0;
  190725. break;
  190726. case PNG_BACKGROUND_GAMMA_FILE:
  190727. g = 1.0 / (png_ptr->gamma);
  190728. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190729. break;
  190730. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190731. g = 1.0 / (png_ptr->background_gamma);
  190732. gs = 1.0 / (png_ptr->background_gamma *
  190733. png_ptr->screen_gamma);
  190734. break;
  190735. default:
  190736. g = 1.0; /* back_1 */
  190737. gs = 1.0; /* back */
  190738. }
  190739. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190740. {
  190741. back.red = (png_byte)png_ptr->background.red;
  190742. back.green = (png_byte)png_ptr->background.green;
  190743. back.blue = (png_byte)png_ptr->background.blue;
  190744. }
  190745. else
  190746. {
  190747. back.red = (png_byte)(pow(
  190748. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190749. back.green = (png_byte)(pow(
  190750. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190751. back.blue = (png_byte)(pow(
  190752. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190753. }
  190754. back_1.red = (png_byte)(pow(
  190755. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190756. back_1.green = (png_byte)(pow(
  190757. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190758. back_1.blue = (png_byte)(pow(
  190759. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190760. }
  190761. for (i = 0; i < num_palette; i++)
  190762. {
  190763. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190764. {
  190765. if (png_ptr->trans[i] == 0)
  190766. {
  190767. palette[i] = back;
  190768. }
  190769. else /* if (png_ptr->trans[i] != 0xff) */
  190770. {
  190771. png_byte v, w;
  190772. v = png_ptr->gamma_to_1[palette[i].red];
  190773. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190774. palette[i].red = png_ptr->gamma_from_1[w];
  190775. v = png_ptr->gamma_to_1[palette[i].green];
  190776. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190777. palette[i].green = png_ptr->gamma_from_1[w];
  190778. v = png_ptr->gamma_to_1[palette[i].blue];
  190779. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190780. palette[i].blue = png_ptr->gamma_from_1[w];
  190781. }
  190782. }
  190783. else
  190784. {
  190785. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190786. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190787. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190788. }
  190789. }
  190790. }
  190791. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190792. else
  190793. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190794. {
  190795. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190796. double g = 1.0;
  190797. double gs = 1.0;
  190798. switch (png_ptr->background_gamma_type)
  190799. {
  190800. case PNG_BACKGROUND_GAMMA_SCREEN:
  190801. g = (png_ptr->screen_gamma);
  190802. gs = 1.0;
  190803. break;
  190804. case PNG_BACKGROUND_GAMMA_FILE:
  190805. g = 1.0 / (png_ptr->gamma);
  190806. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190807. break;
  190808. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190809. g = 1.0 / (png_ptr->background_gamma);
  190810. gs = 1.0 / (png_ptr->background_gamma *
  190811. png_ptr->screen_gamma);
  190812. break;
  190813. }
  190814. png_ptr->background_1.gray = (png_uint_16)(pow(
  190815. (double)png_ptr->background.gray / m, g) * m + .5);
  190816. png_ptr->background.gray = (png_uint_16)(pow(
  190817. (double)png_ptr->background.gray / m, gs) * m + .5);
  190818. if ((png_ptr->background.red != png_ptr->background.green) ||
  190819. (png_ptr->background.red != png_ptr->background.blue) ||
  190820. (png_ptr->background.red != png_ptr->background.gray))
  190821. {
  190822. /* RGB or RGBA with color background */
  190823. png_ptr->background_1.red = (png_uint_16)(pow(
  190824. (double)png_ptr->background.red / m, g) * m + .5);
  190825. png_ptr->background_1.green = (png_uint_16)(pow(
  190826. (double)png_ptr->background.green / m, g) * m + .5);
  190827. png_ptr->background_1.blue = (png_uint_16)(pow(
  190828. (double)png_ptr->background.blue / m, g) * m + .5);
  190829. png_ptr->background.red = (png_uint_16)(pow(
  190830. (double)png_ptr->background.red / m, gs) * m + .5);
  190831. png_ptr->background.green = (png_uint_16)(pow(
  190832. (double)png_ptr->background.green / m, gs) * m + .5);
  190833. png_ptr->background.blue = (png_uint_16)(pow(
  190834. (double)png_ptr->background.blue / m, gs) * m + .5);
  190835. }
  190836. else
  190837. {
  190838. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190839. png_ptr->background_1.red = png_ptr->background_1.green
  190840. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190841. png_ptr->background.red = png_ptr->background.green
  190842. = png_ptr->background.blue = png_ptr->background.gray;
  190843. }
  190844. }
  190845. }
  190846. else
  190847. /* transformation does not include PNG_BACKGROUND */
  190848. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190849. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190850. {
  190851. png_colorp palette = png_ptr->palette;
  190852. int num_palette = png_ptr->num_palette;
  190853. int i;
  190854. for (i = 0; i < num_palette; i++)
  190855. {
  190856. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190857. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190858. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190859. }
  190860. }
  190861. }
  190862. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190863. else
  190864. #endif
  190865. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190866. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190867. /* No GAMMA transformation */
  190868. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190869. (color_type == PNG_COLOR_TYPE_PALETTE))
  190870. {
  190871. int i;
  190872. int istop = (int)png_ptr->num_trans;
  190873. png_color back;
  190874. png_colorp palette = png_ptr->palette;
  190875. back.red = (png_byte)png_ptr->background.red;
  190876. back.green = (png_byte)png_ptr->background.green;
  190877. back.blue = (png_byte)png_ptr->background.blue;
  190878. for (i = 0; i < istop; i++)
  190879. {
  190880. if (png_ptr->trans[i] == 0)
  190881. {
  190882. palette[i] = back;
  190883. }
  190884. else if (png_ptr->trans[i] != 0xff)
  190885. {
  190886. /* The png_composite() macro is defined in png.h */
  190887. png_composite(palette[i].red, palette[i].red,
  190888. png_ptr->trans[i], back.red);
  190889. png_composite(palette[i].green, palette[i].green,
  190890. png_ptr->trans[i], back.green);
  190891. png_composite(palette[i].blue, palette[i].blue,
  190892. png_ptr->trans[i], back.blue);
  190893. }
  190894. }
  190895. }
  190896. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190897. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190898. if ((png_ptr->transformations & PNG_SHIFT) &&
  190899. (color_type == PNG_COLOR_TYPE_PALETTE))
  190900. {
  190901. png_uint_16 i;
  190902. png_uint_16 istop = png_ptr->num_palette;
  190903. int sr = 8 - png_ptr->sig_bit.red;
  190904. int sg = 8 - png_ptr->sig_bit.green;
  190905. int sb = 8 - png_ptr->sig_bit.blue;
  190906. if (sr < 0 || sr > 8)
  190907. sr = 0;
  190908. if (sg < 0 || sg > 8)
  190909. sg = 0;
  190910. if (sb < 0 || sb > 8)
  190911. sb = 0;
  190912. for (i = 0; i < istop; i++)
  190913. {
  190914. png_ptr->palette[i].red >>= sr;
  190915. png_ptr->palette[i].green >>= sg;
  190916. png_ptr->palette[i].blue >>= sb;
  190917. }
  190918. }
  190919. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190920. }
  190921. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190922. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190923. if(png_ptr)
  190924. return;
  190925. #endif
  190926. }
  190927. /* Modify the info structure to reflect the transformations. The
  190928. * info should be updated so a PNG file could be written with it,
  190929. * assuming the transformations result in valid PNG data.
  190930. */
  190931. void /* PRIVATE */
  190932. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190933. {
  190934. png_debug(1, "in png_read_transform_info\n");
  190935. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190936. if (png_ptr->transformations & PNG_EXPAND)
  190937. {
  190938. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190939. {
  190940. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190941. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190942. else
  190943. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190944. info_ptr->bit_depth = 8;
  190945. info_ptr->num_trans = 0;
  190946. }
  190947. else
  190948. {
  190949. if (png_ptr->num_trans)
  190950. {
  190951. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190952. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190953. else
  190954. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190955. }
  190956. if (info_ptr->bit_depth < 8)
  190957. info_ptr->bit_depth = 8;
  190958. info_ptr->num_trans = 0;
  190959. }
  190960. }
  190961. #endif
  190962. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190963. if (png_ptr->transformations & PNG_BACKGROUND)
  190964. {
  190965. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190966. info_ptr->num_trans = 0;
  190967. info_ptr->background = png_ptr->background;
  190968. }
  190969. #endif
  190970. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190971. if (png_ptr->transformations & PNG_GAMMA)
  190972. {
  190973. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190974. info_ptr->gamma = png_ptr->gamma;
  190975. #endif
  190976. #ifdef PNG_FIXED_POINT_SUPPORTED
  190977. info_ptr->int_gamma = png_ptr->int_gamma;
  190978. #endif
  190979. }
  190980. #endif
  190981. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190982. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190983. info_ptr->bit_depth = 8;
  190984. #endif
  190985. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190986. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190987. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190988. #endif
  190989. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190990. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190991. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190992. #endif
  190993. #if defined(PNG_READ_DITHER_SUPPORTED)
  190994. if (png_ptr->transformations & PNG_DITHER)
  190995. {
  190996. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190997. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190998. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190999. {
  191000. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191001. }
  191002. }
  191003. #endif
  191004. #if defined(PNG_READ_PACK_SUPPORTED)
  191005. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191006. info_ptr->bit_depth = 8;
  191007. #endif
  191008. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191009. info_ptr->channels = 1;
  191010. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191011. info_ptr->channels = 3;
  191012. else
  191013. info_ptr->channels = 1;
  191014. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191015. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191016. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191017. #endif
  191018. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191019. info_ptr->channels++;
  191020. #if defined(PNG_READ_FILLER_SUPPORTED)
  191021. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191022. if ((png_ptr->transformations & PNG_FILLER) &&
  191023. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191024. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191025. {
  191026. info_ptr->channels++;
  191027. /* if adding a true alpha channel not just filler */
  191028. #if !defined(PNG_1_0_X)
  191029. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191030. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191031. #endif
  191032. }
  191033. #endif
  191034. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191035. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191036. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191037. {
  191038. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191039. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191040. if(info_ptr->channels < png_ptr->user_transform_channels)
  191041. info_ptr->channels = png_ptr->user_transform_channels;
  191042. }
  191043. #endif
  191044. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191045. info_ptr->bit_depth);
  191046. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191047. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191048. if(png_ptr)
  191049. return;
  191050. #endif
  191051. }
  191052. /* Transform the row. The order of transformations is significant,
  191053. * and is very touchy. If you add a transformation, take care to
  191054. * decide how it fits in with the other transformations here.
  191055. */
  191056. void /* PRIVATE */
  191057. png_do_read_transformations(png_structp png_ptr)
  191058. {
  191059. png_debug(1, "in png_do_read_transformations\n");
  191060. if (png_ptr->row_buf == NULL)
  191061. {
  191062. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191063. char msg[50];
  191064. png_snprintf2(msg, 50,
  191065. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191066. png_ptr->pass);
  191067. png_error(png_ptr, msg);
  191068. #else
  191069. png_error(png_ptr, "NULL row buffer");
  191070. #endif
  191071. }
  191072. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191073. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191074. /* Application has failed to call either png_read_start_image()
  191075. * or png_read_update_info() after setting transforms that expand
  191076. * pixels. This check added to libpng-1.2.19 */
  191077. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191078. png_error(png_ptr, "Uninitialized row");
  191079. #else
  191080. png_warning(png_ptr, "Uninitialized row");
  191081. #endif
  191082. #endif
  191083. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191084. if (png_ptr->transformations & PNG_EXPAND)
  191085. {
  191086. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191087. {
  191088. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191089. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191090. }
  191091. else
  191092. {
  191093. if (png_ptr->num_trans &&
  191094. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191095. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191096. &(png_ptr->trans_values));
  191097. else
  191098. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191099. NULL);
  191100. }
  191101. }
  191102. #endif
  191103. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191104. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191105. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191106. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191107. #endif
  191108. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191109. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191110. {
  191111. int rgb_error =
  191112. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191113. if(rgb_error)
  191114. {
  191115. png_ptr->rgb_to_gray_status=1;
  191116. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191117. PNG_RGB_TO_GRAY_WARN)
  191118. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191119. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191120. PNG_RGB_TO_GRAY_ERR)
  191121. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191122. }
  191123. }
  191124. #endif
  191125. /*
  191126. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191127. In most cases, the "simple transparency" should be done prior to doing
  191128. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191129. pixel is transparent. You would also need to make sure that the
  191130. transparency information is upgraded to RGB.
  191131. To summarize, the current flow is:
  191132. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191133. with background "in place" if transparent,
  191134. convert to RGB if necessary
  191135. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191136. convert to RGB if necessary
  191137. To support RGB backgrounds for gray images we need:
  191138. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191139. 3 or 6 bytes and composite with background
  191140. "in place" if transparent (3x compare/pixel
  191141. compared to doing composite with gray bkgrnd)
  191142. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191143. remove alpha bytes (3x float operations/pixel
  191144. compared with composite on gray background)
  191145. Greg's change will do this. The reason it wasn't done before is for
  191146. performance, as this increases the per-pixel operations. If we would check
  191147. in advance if the background was gray or RGB, and position the gray-to-RGB
  191148. transform appropriately, then it would save a lot of work/time.
  191149. */
  191150. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191151. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191152. * for performance reasons */
  191153. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191154. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191155. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191156. #endif
  191157. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191158. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191159. ((png_ptr->num_trans != 0 ) ||
  191160. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191161. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191162. &(png_ptr->trans_values), &(png_ptr->background)
  191163. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191164. , &(png_ptr->background_1),
  191165. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191166. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191167. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191168. png_ptr->gamma_shift
  191169. #endif
  191170. );
  191171. #endif
  191172. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191173. if ((png_ptr->transformations & PNG_GAMMA) &&
  191174. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191175. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191176. ((png_ptr->num_trans != 0) ||
  191177. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191178. #endif
  191179. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191180. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191181. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191182. png_ptr->gamma_shift);
  191183. #endif
  191184. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191185. if (png_ptr->transformations & PNG_16_TO_8)
  191186. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191187. #endif
  191188. #if defined(PNG_READ_DITHER_SUPPORTED)
  191189. if (png_ptr->transformations & PNG_DITHER)
  191190. {
  191191. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191192. png_ptr->palette_lookup, png_ptr->dither_index);
  191193. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191194. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191195. }
  191196. #endif
  191197. #if defined(PNG_READ_INVERT_SUPPORTED)
  191198. if (png_ptr->transformations & PNG_INVERT_MONO)
  191199. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191200. #endif
  191201. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191202. if (png_ptr->transformations & PNG_SHIFT)
  191203. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191204. &(png_ptr->shift));
  191205. #endif
  191206. #if defined(PNG_READ_PACK_SUPPORTED)
  191207. if (png_ptr->transformations & PNG_PACK)
  191208. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191209. #endif
  191210. #if defined(PNG_READ_BGR_SUPPORTED)
  191211. if (png_ptr->transformations & PNG_BGR)
  191212. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191213. #endif
  191214. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191215. if (png_ptr->transformations & PNG_PACKSWAP)
  191216. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191217. #endif
  191218. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191219. /* if gray -> RGB, do so now only if we did not do so above */
  191220. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191221. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191222. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191223. #endif
  191224. #if defined(PNG_READ_FILLER_SUPPORTED)
  191225. if (png_ptr->transformations & PNG_FILLER)
  191226. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191227. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191228. #endif
  191229. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191230. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191231. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191232. #endif
  191233. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191234. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191235. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191236. #endif
  191237. #if defined(PNG_READ_SWAP_SUPPORTED)
  191238. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191239. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191240. #endif
  191241. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191242. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191243. {
  191244. if(png_ptr->read_user_transform_fn != NULL)
  191245. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191246. (png_ptr, /* png_ptr */
  191247. &(png_ptr->row_info), /* row_info: */
  191248. /* png_uint_32 width; width of row */
  191249. /* png_uint_32 rowbytes; number of bytes in row */
  191250. /* png_byte color_type; color type of pixels */
  191251. /* png_byte bit_depth; bit depth of samples */
  191252. /* png_byte channels; number of channels (1-4) */
  191253. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191254. png_ptr->row_buf + 1); /* start of pixel data for row */
  191255. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191256. if(png_ptr->user_transform_depth)
  191257. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191258. if(png_ptr->user_transform_channels)
  191259. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191260. #endif
  191261. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191262. png_ptr->row_info.channels);
  191263. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191264. png_ptr->row_info.width);
  191265. }
  191266. #endif
  191267. }
  191268. #if defined(PNG_READ_PACK_SUPPORTED)
  191269. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191270. * without changing the actual values. Thus, if you had a row with
  191271. * a bit depth of 1, you would end up with bytes that only contained
  191272. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191273. * png_do_shift() after this.
  191274. */
  191275. void /* PRIVATE */
  191276. png_do_unpack(png_row_infop row_info, png_bytep row)
  191277. {
  191278. png_debug(1, "in png_do_unpack\n");
  191279. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191280. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191281. #else
  191282. if (row_info->bit_depth < 8)
  191283. #endif
  191284. {
  191285. png_uint_32 i;
  191286. png_uint_32 row_width=row_info->width;
  191287. switch (row_info->bit_depth)
  191288. {
  191289. case 1:
  191290. {
  191291. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191292. png_bytep dp = row + (png_size_t)row_width - 1;
  191293. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191294. for (i = 0; i < row_width; i++)
  191295. {
  191296. *dp = (png_byte)((*sp >> shift) & 0x01);
  191297. if (shift == 7)
  191298. {
  191299. shift = 0;
  191300. sp--;
  191301. }
  191302. else
  191303. shift++;
  191304. dp--;
  191305. }
  191306. break;
  191307. }
  191308. case 2:
  191309. {
  191310. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191311. png_bytep dp = row + (png_size_t)row_width - 1;
  191312. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191313. for (i = 0; i < row_width; i++)
  191314. {
  191315. *dp = (png_byte)((*sp >> shift) & 0x03);
  191316. if (shift == 6)
  191317. {
  191318. shift = 0;
  191319. sp--;
  191320. }
  191321. else
  191322. shift += 2;
  191323. dp--;
  191324. }
  191325. break;
  191326. }
  191327. case 4:
  191328. {
  191329. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191330. png_bytep dp = row + (png_size_t)row_width - 1;
  191331. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191332. for (i = 0; i < row_width; i++)
  191333. {
  191334. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191335. if (shift == 4)
  191336. {
  191337. shift = 0;
  191338. sp--;
  191339. }
  191340. else
  191341. shift = 4;
  191342. dp--;
  191343. }
  191344. break;
  191345. }
  191346. }
  191347. row_info->bit_depth = 8;
  191348. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191349. row_info->rowbytes = row_width * row_info->channels;
  191350. }
  191351. }
  191352. #endif
  191353. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191354. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191355. * pixels back to their significant bits values. Thus, if you have
  191356. * a row of bit depth 8, but only 5 are significant, this will shift
  191357. * the values back to 0 through 31.
  191358. */
  191359. void /* PRIVATE */
  191360. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191361. {
  191362. png_debug(1, "in png_do_unshift\n");
  191363. if (
  191364. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191365. row != NULL && row_info != NULL && sig_bits != NULL &&
  191366. #endif
  191367. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191368. {
  191369. int shift[4];
  191370. int channels = 0;
  191371. int c;
  191372. png_uint_16 value = 0;
  191373. png_uint_32 row_width = row_info->width;
  191374. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191375. {
  191376. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191377. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191378. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191379. }
  191380. else
  191381. {
  191382. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191383. }
  191384. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191385. {
  191386. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191387. }
  191388. for (c = 0; c < channels; c++)
  191389. {
  191390. if (shift[c] <= 0)
  191391. shift[c] = 0;
  191392. else
  191393. value = 1;
  191394. }
  191395. if (!value)
  191396. return;
  191397. switch (row_info->bit_depth)
  191398. {
  191399. case 2:
  191400. {
  191401. png_bytep bp;
  191402. png_uint_32 i;
  191403. png_uint_32 istop = row_info->rowbytes;
  191404. for (bp = row, i = 0; i < istop; i++)
  191405. {
  191406. *bp >>= 1;
  191407. *bp++ &= 0x55;
  191408. }
  191409. break;
  191410. }
  191411. case 4:
  191412. {
  191413. png_bytep bp = row;
  191414. png_uint_32 i;
  191415. png_uint_32 istop = row_info->rowbytes;
  191416. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191417. (png_byte)((int)0xf >> shift[0]));
  191418. for (i = 0; i < istop; i++)
  191419. {
  191420. *bp >>= shift[0];
  191421. *bp++ &= mask;
  191422. }
  191423. break;
  191424. }
  191425. case 8:
  191426. {
  191427. png_bytep bp = row;
  191428. png_uint_32 i;
  191429. png_uint_32 istop = row_width * channels;
  191430. for (i = 0; i < istop; i++)
  191431. {
  191432. *bp++ >>= shift[i%channels];
  191433. }
  191434. break;
  191435. }
  191436. case 16:
  191437. {
  191438. png_bytep bp = row;
  191439. png_uint_32 i;
  191440. png_uint_32 istop = channels * row_width;
  191441. for (i = 0; i < istop; i++)
  191442. {
  191443. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191444. value >>= shift[i%channels];
  191445. *bp++ = (png_byte)(value >> 8);
  191446. *bp++ = (png_byte)(value & 0xff);
  191447. }
  191448. break;
  191449. }
  191450. }
  191451. }
  191452. }
  191453. #endif
  191454. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191455. /* chop rows of bit depth 16 down to 8 */
  191456. void /* PRIVATE */
  191457. png_do_chop(png_row_infop row_info, png_bytep row)
  191458. {
  191459. png_debug(1, "in png_do_chop\n");
  191460. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191461. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191462. #else
  191463. if (row_info->bit_depth == 16)
  191464. #endif
  191465. {
  191466. png_bytep sp = row;
  191467. png_bytep dp = row;
  191468. png_uint_32 i;
  191469. png_uint_32 istop = row_info->width * row_info->channels;
  191470. for (i = 0; i<istop; i++, sp += 2, dp++)
  191471. {
  191472. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191473. /* This does a more accurate scaling of the 16-bit color
  191474. * value, rather than a simple low-byte truncation.
  191475. *
  191476. * What the ideal calculation should be:
  191477. * *dp = (((((png_uint_32)(*sp) << 8) |
  191478. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191479. *
  191480. * GRR: no, I think this is what it really should be:
  191481. * *dp = (((((png_uint_32)(*sp) << 8) |
  191482. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191483. *
  191484. * GRR: here's the exact calculation with shifts:
  191485. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191486. * *dp = (temp - (temp >> 8)) >> 8;
  191487. *
  191488. * Approximate calculation with shift/add instead of multiply/divide:
  191489. * *dp = ((((png_uint_32)(*sp) << 8) |
  191490. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191491. *
  191492. * What we actually do to avoid extra shifting and conversion:
  191493. */
  191494. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191495. #else
  191496. /* Simply discard the low order byte */
  191497. *dp = *sp;
  191498. #endif
  191499. }
  191500. row_info->bit_depth = 8;
  191501. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191502. row_info->rowbytes = row_info->width * row_info->channels;
  191503. }
  191504. }
  191505. #endif
  191506. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191507. void /* PRIVATE */
  191508. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191509. {
  191510. png_debug(1, "in png_do_read_swap_alpha\n");
  191511. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191512. if (row != NULL && row_info != NULL)
  191513. #endif
  191514. {
  191515. png_uint_32 row_width = row_info->width;
  191516. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191517. {
  191518. /* This converts from RGBA to ARGB */
  191519. if (row_info->bit_depth == 8)
  191520. {
  191521. png_bytep sp = row + row_info->rowbytes;
  191522. png_bytep dp = sp;
  191523. png_byte save;
  191524. png_uint_32 i;
  191525. for (i = 0; i < row_width; i++)
  191526. {
  191527. save = *(--sp);
  191528. *(--dp) = *(--sp);
  191529. *(--dp) = *(--sp);
  191530. *(--dp) = *(--sp);
  191531. *(--dp) = save;
  191532. }
  191533. }
  191534. /* This converts from RRGGBBAA to AARRGGBB */
  191535. else
  191536. {
  191537. png_bytep sp = row + row_info->rowbytes;
  191538. png_bytep dp = sp;
  191539. png_byte save[2];
  191540. png_uint_32 i;
  191541. for (i = 0; i < row_width; i++)
  191542. {
  191543. save[0] = *(--sp);
  191544. save[1] = *(--sp);
  191545. *(--dp) = *(--sp);
  191546. *(--dp) = *(--sp);
  191547. *(--dp) = *(--sp);
  191548. *(--dp) = *(--sp);
  191549. *(--dp) = *(--sp);
  191550. *(--dp) = *(--sp);
  191551. *(--dp) = save[0];
  191552. *(--dp) = save[1];
  191553. }
  191554. }
  191555. }
  191556. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191557. {
  191558. /* This converts from GA to AG */
  191559. if (row_info->bit_depth == 8)
  191560. {
  191561. png_bytep sp = row + row_info->rowbytes;
  191562. png_bytep dp = sp;
  191563. png_byte save;
  191564. png_uint_32 i;
  191565. for (i = 0; i < row_width; i++)
  191566. {
  191567. save = *(--sp);
  191568. *(--dp) = *(--sp);
  191569. *(--dp) = save;
  191570. }
  191571. }
  191572. /* This converts from GGAA to AAGG */
  191573. else
  191574. {
  191575. png_bytep sp = row + row_info->rowbytes;
  191576. png_bytep dp = sp;
  191577. png_byte save[2];
  191578. png_uint_32 i;
  191579. for (i = 0; i < row_width; i++)
  191580. {
  191581. save[0] = *(--sp);
  191582. save[1] = *(--sp);
  191583. *(--dp) = *(--sp);
  191584. *(--dp) = *(--sp);
  191585. *(--dp) = save[0];
  191586. *(--dp) = save[1];
  191587. }
  191588. }
  191589. }
  191590. }
  191591. }
  191592. #endif
  191593. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191594. void /* PRIVATE */
  191595. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191596. {
  191597. png_debug(1, "in png_do_read_invert_alpha\n");
  191598. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191599. if (row != NULL && row_info != NULL)
  191600. #endif
  191601. {
  191602. png_uint_32 row_width = row_info->width;
  191603. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191604. {
  191605. /* This inverts the alpha channel in RGBA */
  191606. if (row_info->bit_depth == 8)
  191607. {
  191608. png_bytep sp = row + row_info->rowbytes;
  191609. png_bytep dp = sp;
  191610. png_uint_32 i;
  191611. for (i = 0; i < row_width; i++)
  191612. {
  191613. *(--dp) = (png_byte)(255 - *(--sp));
  191614. /* This does nothing:
  191615. *(--dp) = *(--sp);
  191616. *(--dp) = *(--sp);
  191617. *(--dp) = *(--sp);
  191618. We can replace it with:
  191619. */
  191620. sp-=3;
  191621. dp=sp;
  191622. }
  191623. }
  191624. /* This inverts the alpha channel in RRGGBBAA */
  191625. else
  191626. {
  191627. png_bytep sp = row + row_info->rowbytes;
  191628. png_bytep dp = sp;
  191629. png_uint_32 i;
  191630. for (i = 0; i < row_width; i++)
  191631. {
  191632. *(--dp) = (png_byte)(255 - *(--sp));
  191633. *(--dp) = (png_byte)(255 - *(--sp));
  191634. /* This does nothing:
  191635. *(--dp) = *(--sp);
  191636. *(--dp) = *(--sp);
  191637. *(--dp) = *(--sp);
  191638. *(--dp) = *(--sp);
  191639. *(--dp) = *(--sp);
  191640. *(--dp) = *(--sp);
  191641. We can replace it with:
  191642. */
  191643. sp-=6;
  191644. dp=sp;
  191645. }
  191646. }
  191647. }
  191648. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191649. {
  191650. /* This inverts the alpha channel in GA */
  191651. if (row_info->bit_depth == 8)
  191652. {
  191653. png_bytep sp = row + row_info->rowbytes;
  191654. png_bytep dp = sp;
  191655. png_uint_32 i;
  191656. for (i = 0; i < row_width; i++)
  191657. {
  191658. *(--dp) = (png_byte)(255 - *(--sp));
  191659. *(--dp) = *(--sp);
  191660. }
  191661. }
  191662. /* This inverts the alpha channel in GGAA */
  191663. else
  191664. {
  191665. png_bytep sp = row + row_info->rowbytes;
  191666. png_bytep dp = sp;
  191667. png_uint_32 i;
  191668. for (i = 0; i < row_width; i++)
  191669. {
  191670. *(--dp) = (png_byte)(255 - *(--sp));
  191671. *(--dp) = (png_byte)(255 - *(--sp));
  191672. /*
  191673. *(--dp) = *(--sp);
  191674. *(--dp) = *(--sp);
  191675. */
  191676. sp-=2;
  191677. dp=sp;
  191678. }
  191679. }
  191680. }
  191681. }
  191682. }
  191683. #endif
  191684. #if defined(PNG_READ_FILLER_SUPPORTED)
  191685. /* Add filler channel if we have RGB color */
  191686. void /* PRIVATE */
  191687. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191688. png_uint_32 filler, png_uint_32 flags)
  191689. {
  191690. png_uint_32 i;
  191691. png_uint_32 row_width = row_info->width;
  191692. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191693. png_byte lo_filler = (png_byte)(filler & 0xff);
  191694. png_debug(1, "in png_do_read_filler\n");
  191695. if (
  191696. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191697. row != NULL && row_info != NULL &&
  191698. #endif
  191699. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191700. {
  191701. if(row_info->bit_depth == 8)
  191702. {
  191703. /* This changes the data from G to GX */
  191704. if (flags & PNG_FLAG_FILLER_AFTER)
  191705. {
  191706. png_bytep sp = row + (png_size_t)row_width;
  191707. png_bytep dp = sp + (png_size_t)row_width;
  191708. for (i = 1; i < row_width; i++)
  191709. {
  191710. *(--dp) = lo_filler;
  191711. *(--dp) = *(--sp);
  191712. }
  191713. *(--dp) = lo_filler;
  191714. row_info->channels = 2;
  191715. row_info->pixel_depth = 16;
  191716. row_info->rowbytes = row_width * 2;
  191717. }
  191718. /* This changes the data from G to XG */
  191719. else
  191720. {
  191721. png_bytep sp = row + (png_size_t)row_width;
  191722. png_bytep dp = sp + (png_size_t)row_width;
  191723. for (i = 0; i < row_width; i++)
  191724. {
  191725. *(--dp) = *(--sp);
  191726. *(--dp) = lo_filler;
  191727. }
  191728. row_info->channels = 2;
  191729. row_info->pixel_depth = 16;
  191730. row_info->rowbytes = row_width * 2;
  191731. }
  191732. }
  191733. else if(row_info->bit_depth == 16)
  191734. {
  191735. /* This changes the data from GG to GGXX */
  191736. if (flags & PNG_FLAG_FILLER_AFTER)
  191737. {
  191738. png_bytep sp = row + (png_size_t)row_width * 2;
  191739. png_bytep dp = sp + (png_size_t)row_width * 2;
  191740. for (i = 1; i < row_width; i++)
  191741. {
  191742. *(--dp) = hi_filler;
  191743. *(--dp) = lo_filler;
  191744. *(--dp) = *(--sp);
  191745. *(--dp) = *(--sp);
  191746. }
  191747. *(--dp) = hi_filler;
  191748. *(--dp) = lo_filler;
  191749. row_info->channels = 2;
  191750. row_info->pixel_depth = 32;
  191751. row_info->rowbytes = row_width * 4;
  191752. }
  191753. /* This changes the data from GG to XXGG */
  191754. else
  191755. {
  191756. png_bytep sp = row + (png_size_t)row_width * 2;
  191757. png_bytep dp = sp + (png_size_t)row_width * 2;
  191758. for (i = 0; i < row_width; i++)
  191759. {
  191760. *(--dp) = *(--sp);
  191761. *(--dp) = *(--sp);
  191762. *(--dp) = hi_filler;
  191763. *(--dp) = lo_filler;
  191764. }
  191765. row_info->channels = 2;
  191766. row_info->pixel_depth = 32;
  191767. row_info->rowbytes = row_width * 4;
  191768. }
  191769. }
  191770. } /* COLOR_TYPE == GRAY */
  191771. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191772. {
  191773. if(row_info->bit_depth == 8)
  191774. {
  191775. /* This changes the data from RGB to RGBX */
  191776. if (flags & PNG_FLAG_FILLER_AFTER)
  191777. {
  191778. png_bytep sp = row + (png_size_t)row_width * 3;
  191779. png_bytep dp = sp + (png_size_t)row_width;
  191780. for (i = 1; i < row_width; i++)
  191781. {
  191782. *(--dp) = lo_filler;
  191783. *(--dp) = *(--sp);
  191784. *(--dp) = *(--sp);
  191785. *(--dp) = *(--sp);
  191786. }
  191787. *(--dp) = lo_filler;
  191788. row_info->channels = 4;
  191789. row_info->pixel_depth = 32;
  191790. row_info->rowbytes = row_width * 4;
  191791. }
  191792. /* This changes the data from RGB to XRGB */
  191793. else
  191794. {
  191795. png_bytep sp = row + (png_size_t)row_width * 3;
  191796. png_bytep dp = sp + (png_size_t)row_width;
  191797. for (i = 0; i < row_width; i++)
  191798. {
  191799. *(--dp) = *(--sp);
  191800. *(--dp) = *(--sp);
  191801. *(--dp) = *(--sp);
  191802. *(--dp) = lo_filler;
  191803. }
  191804. row_info->channels = 4;
  191805. row_info->pixel_depth = 32;
  191806. row_info->rowbytes = row_width * 4;
  191807. }
  191808. }
  191809. else if(row_info->bit_depth == 16)
  191810. {
  191811. /* This changes the data from RRGGBB to RRGGBBXX */
  191812. if (flags & PNG_FLAG_FILLER_AFTER)
  191813. {
  191814. png_bytep sp = row + (png_size_t)row_width * 6;
  191815. png_bytep dp = sp + (png_size_t)row_width * 2;
  191816. for (i = 1; i < row_width; i++)
  191817. {
  191818. *(--dp) = hi_filler;
  191819. *(--dp) = lo_filler;
  191820. *(--dp) = *(--sp);
  191821. *(--dp) = *(--sp);
  191822. *(--dp) = *(--sp);
  191823. *(--dp) = *(--sp);
  191824. *(--dp) = *(--sp);
  191825. *(--dp) = *(--sp);
  191826. }
  191827. *(--dp) = hi_filler;
  191828. *(--dp) = lo_filler;
  191829. row_info->channels = 4;
  191830. row_info->pixel_depth = 64;
  191831. row_info->rowbytes = row_width * 8;
  191832. }
  191833. /* This changes the data from RRGGBB to XXRRGGBB */
  191834. else
  191835. {
  191836. png_bytep sp = row + (png_size_t)row_width * 6;
  191837. png_bytep dp = sp + (png_size_t)row_width * 2;
  191838. for (i = 0; i < row_width; i++)
  191839. {
  191840. *(--dp) = *(--sp);
  191841. *(--dp) = *(--sp);
  191842. *(--dp) = *(--sp);
  191843. *(--dp) = *(--sp);
  191844. *(--dp) = *(--sp);
  191845. *(--dp) = *(--sp);
  191846. *(--dp) = hi_filler;
  191847. *(--dp) = lo_filler;
  191848. }
  191849. row_info->channels = 4;
  191850. row_info->pixel_depth = 64;
  191851. row_info->rowbytes = row_width * 8;
  191852. }
  191853. }
  191854. } /* COLOR_TYPE == RGB */
  191855. }
  191856. #endif
  191857. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191858. /* expand grayscale files to RGB, with or without alpha */
  191859. void /* PRIVATE */
  191860. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191861. {
  191862. png_uint_32 i;
  191863. png_uint_32 row_width = row_info->width;
  191864. png_debug(1, "in png_do_gray_to_rgb\n");
  191865. if (row_info->bit_depth >= 8 &&
  191866. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191867. row != NULL && row_info != NULL &&
  191868. #endif
  191869. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191870. {
  191871. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191872. {
  191873. if (row_info->bit_depth == 8)
  191874. {
  191875. png_bytep sp = row + (png_size_t)row_width - 1;
  191876. png_bytep dp = sp + (png_size_t)row_width * 2;
  191877. for (i = 0; i < row_width; i++)
  191878. {
  191879. *(dp--) = *sp;
  191880. *(dp--) = *sp;
  191881. *(dp--) = *(sp--);
  191882. }
  191883. }
  191884. else
  191885. {
  191886. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191887. png_bytep dp = sp + (png_size_t)row_width * 4;
  191888. for (i = 0; i < row_width; i++)
  191889. {
  191890. *(dp--) = *sp;
  191891. *(dp--) = *(sp - 1);
  191892. *(dp--) = *sp;
  191893. *(dp--) = *(sp - 1);
  191894. *(dp--) = *(sp--);
  191895. *(dp--) = *(sp--);
  191896. }
  191897. }
  191898. }
  191899. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191900. {
  191901. if (row_info->bit_depth == 8)
  191902. {
  191903. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191904. png_bytep dp = sp + (png_size_t)row_width * 2;
  191905. for (i = 0; i < row_width; i++)
  191906. {
  191907. *(dp--) = *(sp--);
  191908. *(dp--) = *sp;
  191909. *(dp--) = *sp;
  191910. *(dp--) = *(sp--);
  191911. }
  191912. }
  191913. else
  191914. {
  191915. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191916. png_bytep dp = sp + (png_size_t)row_width * 4;
  191917. for (i = 0; i < row_width; i++)
  191918. {
  191919. *(dp--) = *(sp--);
  191920. *(dp--) = *(sp--);
  191921. *(dp--) = *sp;
  191922. *(dp--) = *(sp - 1);
  191923. *(dp--) = *sp;
  191924. *(dp--) = *(sp - 1);
  191925. *(dp--) = *(sp--);
  191926. *(dp--) = *(sp--);
  191927. }
  191928. }
  191929. }
  191930. row_info->channels += (png_byte)2;
  191931. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191932. row_info->pixel_depth = (png_byte)(row_info->channels *
  191933. row_info->bit_depth);
  191934. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191935. }
  191936. }
  191937. #endif
  191938. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191939. /* reduce RGB files to grayscale, with or without alpha
  191940. * using the equation given in Poynton's ColorFAQ at
  191941. * <http://www.inforamp.net/~poynton/>
  191942. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191943. *
  191944. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191945. *
  191946. * We approximate this with
  191947. *
  191948. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191949. *
  191950. * which can be expressed with integers as
  191951. *
  191952. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191953. *
  191954. * The calculation is to be done in a linear colorspace.
  191955. *
  191956. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191957. */
  191958. int /* PRIVATE */
  191959. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191960. {
  191961. png_uint_32 i;
  191962. png_uint_32 row_width = row_info->width;
  191963. int rgb_error = 0;
  191964. png_debug(1, "in png_do_rgb_to_gray\n");
  191965. if (
  191966. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191967. row != NULL && row_info != NULL &&
  191968. #endif
  191969. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191970. {
  191971. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191972. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191973. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191974. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191975. {
  191976. if (row_info->bit_depth == 8)
  191977. {
  191978. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191979. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191980. {
  191981. png_bytep sp = row;
  191982. png_bytep dp = row;
  191983. for (i = 0; i < row_width; i++)
  191984. {
  191985. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191986. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191987. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191988. if(red != green || red != blue)
  191989. {
  191990. rgb_error |= 1;
  191991. *(dp++) = png_ptr->gamma_from_1[
  191992. (rc*red+gc*green+bc*blue)>>15];
  191993. }
  191994. else
  191995. *(dp++) = *(sp-1);
  191996. }
  191997. }
  191998. else
  191999. #endif
  192000. {
  192001. png_bytep sp = row;
  192002. png_bytep dp = row;
  192003. for (i = 0; i < row_width; i++)
  192004. {
  192005. png_byte red = *(sp++);
  192006. png_byte green = *(sp++);
  192007. png_byte blue = *(sp++);
  192008. if(red != green || red != blue)
  192009. {
  192010. rgb_error |= 1;
  192011. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192012. }
  192013. else
  192014. *(dp++) = *(sp-1);
  192015. }
  192016. }
  192017. }
  192018. else /* RGB bit_depth == 16 */
  192019. {
  192020. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192021. if (png_ptr->gamma_16_to_1 != NULL &&
  192022. png_ptr->gamma_16_from_1 != NULL)
  192023. {
  192024. png_bytep sp = row;
  192025. png_bytep dp = row;
  192026. for (i = 0; i < row_width; i++)
  192027. {
  192028. png_uint_16 red, green, blue, w;
  192029. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192030. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192031. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192032. if(red == green && red == blue)
  192033. w = red;
  192034. else
  192035. {
  192036. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192037. png_ptr->gamma_shift][red>>8];
  192038. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192039. png_ptr->gamma_shift][green>>8];
  192040. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192041. png_ptr->gamma_shift][blue>>8];
  192042. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192043. + bc*blue_1)>>15);
  192044. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192045. png_ptr->gamma_shift][gray16 >> 8];
  192046. rgb_error |= 1;
  192047. }
  192048. *(dp++) = (png_byte)((w>>8) & 0xff);
  192049. *(dp++) = (png_byte)(w & 0xff);
  192050. }
  192051. }
  192052. else
  192053. #endif
  192054. {
  192055. png_bytep sp = row;
  192056. png_bytep dp = row;
  192057. for (i = 0; i < row_width; i++)
  192058. {
  192059. png_uint_16 red, green, blue, gray16;
  192060. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192061. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192062. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192063. if(red != green || red != blue)
  192064. rgb_error |= 1;
  192065. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192066. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192067. *(dp++) = (png_byte)(gray16 & 0xff);
  192068. }
  192069. }
  192070. }
  192071. }
  192072. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192073. {
  192074. if (row_info->bit_depth == 8)
  192075. {
  192076. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192077. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192078. {
  192079. png_bytep sp = row;
  192080. png_bytep dp = row;
  192081. for (i = 0; i < row_width; i++)
  192082. {
  192083. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192084. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192085. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192086. if(red != green || red != blue)
  192087. rgb_error |= 1;
  192088. *(dp++) = png_ptr->gamma_from_1
  192089. [(rc*red + gc*green + bc*blue)>>15];
  192090. *(dp++) = *(sp++); /* alpha */
  192091. }
  192092. }
  192093. else
  192094. #endif
  192095. {
  192096. png_bytep sp = row;
  192097. png_bytep dp = row;
  192098. for (i = 0; i < row_width; i++)
  192099. {
  192100. png_byte red = *(sp++);
  192101. png_byte green = *(sp++);
  192102. png_byte blue = *(sp++);
  192103. if(red != green || red != blue)
  192104. rgb_error |= 1;
  192105. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192106. *(dp++) = *(sp++); /* alpha */
  192107. }
  192108. }
  192109. }
  192110. else /* RGBA bit_depth == 16 */
  192111. {
  192112. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192113. if (png_ptr->gamma_16_to_1 != NULL &&
  192114. png_ptr->gamma_16_from_1 != NULL)
  192115. {
  192116. png_bytep sp = row;
  192117. png_bytep dp = row;
  192118. for (i = 0; i < row_width; i++)
  192119. {
  192120. png_uint_16 red, green, blue, w;
  192121. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192122. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192123. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192124. if(red == green && red == blue)
  192125. w = red;
  192126. else
  192127. {
  192128. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192129. png_ptr->gamma_shift][red>>8];
  192130. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192131. png_ptr->gamma_shift][green>>8];
  192132. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192133. png_ptr->gamma_shift][blue>>8];
  192134. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192135. + gc * green_1 + bc * blue_1)>>15);
  192136. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192137. png_ptr->gamma_shift][gray16 >> 8];
  192138. rgb_error |= 1;
  192139. }
  192140. *(dp++) = (png_byte)((w>>8) & 0xff);
  192141. *(dp++) = (png_byte)(w & 0xff);
  192142. *(dp++) = *(sp++); /* alpha */
  192143. *(dp++) = *(sp++);
  192144. }
  192145. }
  192146. else
  192147. #endif
  192148. {
  192149. png_bytep sp = row;
  192150. png_bytep dp = row;
  192151. for (i = 0; i < row_width; i++)
  192152. {
  192153. png_uint_16 red, green, blue, gray16;
  192154. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192155. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192156. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192157. if(red != green || red != blue)
  192158. rgb_error |= 1;
  192159. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192160. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192161. *(dp++) = (png_byte)(gray16 & 0xff);
  192162. *(dp++) = *(sp++); /* alpha */
  192163. *(dp++) = *(sp++);
  192164. }
  192165. }
  192166. }
  192167. }
  192168. row_info->channels -= (png_byte)2;
  192169. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192170. row_info->pixel_depth = (png_byte)(row_info->channels *
  192171. row_info->bit_depth);
  192172. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192173. }
  192174. return rgb_error;
  192175. }
  192176. #endif
  192177. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192178. * large of png_color. This lets grayscale images be treated as
  192179. * paletted. Most useful for gamma correction and simplification
  192180. * of code.
  192181. */
  192182. void PNGAPI
  192183. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192184. {
  192185. int num_palette;
  192186. int color_inc;
  192187. int i;
  192188. int v;
  192189. png_debug(1, "in png_do_build_grayscale_palette\n");
  192190. if (palette == NULL)
  192191. return;
  192192. switch (bit_depth)
  192193. {
  192194. case 1:
  192195. num_palette = 2;
  192196. color_inc = 0xff;
  192197. break;
  192198. case 2:
  192199. num_palette = 4;
  192200. color_inc = 0x55;
  192201. break;
  192202. case 4:
  192203. num_palette = 16;
  192204. color_inc = 0x11;
  192205. break;
  192206. case 8:
  192207. num_palette = 256;
  192208. color_inc = 1;
  192209. break;
  192210. default:
  192211. num_palette = 0;
  192212. color_inc = 0;
  192213. break;
  192214. }
  192215. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192216. {
  192217. palette[i].red = (png_byte)v;
  192218. palette[i].green = (png_byte)v;
  192219. palette[i].blue = (png_byte)v;
  192220. }
  192221. }
  192222. /* This function is currently unused. Do we really need it? */
  192223. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192224. void /* PRIVATE */
  192225. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192226. int num_palette)
  192227. {
  192228. png_debug(1, "in png_correct_palette\n");
  192229. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192230. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192231. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192232. {
  192233. png_color back, back_1;
  192234. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192235. {
  192236. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192237. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192238. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192239. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192240. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192241. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192242. }
  192243. else
  192244. {
  192245. double g;
  192246. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192247. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192248. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192249. {
  192250. back.red = png_ptr->background.red;
  192251. back.green = png_ptr->background.green;
  192252. back.blue = png_ptr->background.blue;
  192253. }
  192254. else
  192255. {
  192256. back.red =
  192257. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192258. 255.0 + 0.5);
  192259. back.green =
  192260. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192261. 255.0 + 0.5);
  192262. back.blue =
  192263. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192264. 255.0 + 0.5);
  192265. }
  192266. g = 1.0 / png_ptr->background_gamma;
  192267. back_1.red =
  192268. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192269. 255.0 + 0.5);
  192270. back_1.green =
  192271. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192272. 255.0 + 0.5);
  192273. back_1.blue =
  192274. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192275. 255.0 + 0.5);
  192276. }
  192277. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192278. {
  192279. png_uint_32 i;
  192280. for (i = 0; i < (png_uint_32)num_palette; i++)
  192281. {
  192282. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192283. {
  192284. palette[i] = back;
  192285. }
  192286. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192287. {
  192288. png_byte v, w;
  192289. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192290. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192291. palette[i].red = png_ptr->gamma_from_1[w];
  192292. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192293. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192294. palette[i].green = png_ptr->gamma_from_1[w];
  192295. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192296. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192297. palette[i].blue = png_ptr->gamma_from_1[w];
  192298. }
  192299. else
  192300. {
  192301. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192302. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192303. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192304. }
  192305. }
  192306. }
  192307. else
  192308. {
  192309. int i;
  192310. for (i = 0; i < num_palette; i++)
  192311. {
  192312. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192313. {
  192314. palette[i] = back;
  192315. }
  192316. else
  192317. {
  192318. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192319. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192320. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192321. }
  192322. }
  192323. }
  192324. }
  192325. else
  192326. #endif
  192327. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192328. if (png_ptr->transformations & PNG_GAMMA)
  192329. {
  192330. int i;
  192331. for (i = 0; i < num_palette; i++)
  192332. {
  192333. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192334. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192335. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192336. }
  192337. }
  192338. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192339. else
  192340. #endif
  192341. #endif
  192342. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192343. if (png_ptr->transformations & PNG_BACKGROUND)
  192344. {
  192345. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192346. {
  192347. png_color back;
  192348. back.red = (png_byte)png_ptr->background.red;
  192349. back.green = (png_byte)png_ptr->background.green;
  192350. back.blue = (png_byte)png_ptr->background.blue;
  192351. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192352. {
  192353. if (png_ptr->trans[i] == 0)
  192354. {
  192355. palette[i].red = back.red;
  192356. palette[i].green = back.green;
  192357. palette[i].blue = back.blue;
  192358. }
  192359. else if (png_ptr->trans[i] != 0xff)
  192360. {
  192361. png_composite(palette[i].red, png_ptr->palette[i].red,
  192362. png_ptr->trans[i], back.red);
  192363. png_composite(palette[i].green, png_ptr->palette[i].green,
  192364. png_ptr->trans[i], back.green);
  192365. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192366. png_ptr->trans[i], back.blue);
  192367. }
  192368. }
  192369. }
  192370. else /* assume grayscale palette (what else could it be?) */
  192371. {
  192372. int i;
  192373. for (i = 0; i < num_palette; i++)
  192374. {
  192375. if (i == (png_byte)png_ptr->trans_values.gray)
  192376. {
  192377. palette[i].red = (png_byte)png_ptr->background.red;
  192378. palette[i].green = (png_byte)png_ptr->background.green;
  192379. palette[i].blue = (png_byte)png_ptr->background.blue;
  192380. }
  192381. }
  192382. }
  192383. }
  192384. #endif
  192385. }
  192386. #endif
  192387. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192388. /* Replace any alpha or transparency with the supplied background color.
  192389. * "background" is already in the screen gamma, while "background_1" is
  192390. * at a gamma of 1.0. Paletted files have already been taken care of.
  192391. */
  192392. void /* PRIVATE */
  192393. png_do_background(png_row_infop row_info, png_bytep row,
  192394. png_color_16p trans_values, png_color_16p background
  192395. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192396. , png_color_16p background_1,
  192397. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192398. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192399. png_uint_16pp gamma_16_to_1, int gamma_shift
  192400. #endif
  192401. )
  192402. {
  192403. png_bytep sp, dp;
  192404. png_uint_32 i;
  192405. png_uint_32 row_width=row_info->width;
  192406. int shift;
  192407. png_debug(1, "in png_do_background\n");
  192408. if (background != NULL &&
  192409. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192410. row != NULL && row_info != NULL &&
  192411. #endif
  192412. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192413. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192414. {
  192415. switch (row_info->color_type)
  192416. {
  192417. case PNG_COLOR_TYPE_GRAY:
  192418. {
  192419. switch (row_info->bit_depth)
  192420. {
  192421. case 1:
  192422. {
  192423. sp = row;
  192424. shift = 7;
  192425. for (i = 0; i < row_width; i++)
  192426. {
  192427. if ((png_uint_16)((*sp >> shift) & 0x01)
  192428. == trans_values->gray)
  192429. {
  192430. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192431. *sp |= (png_byte)(background->gray << shift);
  192432. }
  192433. if (!shift)
  192434. {
  192435. shift = 7;
  192436. sp++;
  192437. }
  192438. else
  192439. shift--;
  192440. }
  192441. break;
  192442. }
  192443. case 2:
  192444. {
  192445. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192446. if (gamma_table != NULL)
  192447. {
  192448. sp = row;
  192449. shift = 6;
  192450. for (i = 0; i < row_width; i++)
  192451. {
  192452. if ((png_uint_16)((*sp >> shift) & 0x03)
  192453. == trans_values->gray)
  192454. {
  192455. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192456. *sp |= (png_byte)(background->gray << shift);
  192457. }
  192458. else
  192459. {
  192460. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192461. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192462. (p << 4) | (p << 6)] >> 6) & 0x03);
  192463. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192464. *sp |= (png_byte)(g << shift);
  192465. }
  192466. if (!shift)
  192467. {
  192468. shift = 6;
  192469. sp++;
  192470. }
  192471. else
  192472. shift -= 2;
  192473. }
  192474. }
  192475. else
  192476. #endif
  192477. {
  192478. sp = row;
  192479. shift = 6;
  192480. for (i = 0; i < row_width; i++)
  192481. {
  192482. if ((png_uint_16)((*sp >> shift) & 0x03)
  192483. == trans_values->gray)
  192484. {
  192485. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192486. *sp |= (png_byte)(background->gray << shift);
  192487. }
  192488. if (!shift)
  192489. {
  192490. shift = 6;
  192491. sp++;
  192492. }
  192493. else
  192494. shift -= 2;
  192495. }
  192496. }
  192497. break;
  192498. }
  192499. case 4:
  192500. {
  192501. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192502. if (gamma_table != NULL)
  192503. {
  192504. sp = row;
  192505. shift = 4;
  192506. for (i = 0; i < row_width; i++)
  192507. {
  192508. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192509. == trans_values->gray)
  192510. {
  192511. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192512. *sp |= (png_byte)(background->gray << shift);
  192513. }
  192514. else
  192515. {
  192516. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192517. png_byte g = (png_byte)((gamma_table[p |
  192518. (p << 4)] >> 4) & 0x0f);
  192519. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192520. *sp |= (png_byte)(g << shift);
  192521. }
  192522. if (!shift)
  192523. {
  192524. shift = 4;
  192525. sp++;
  192526. }
  192527. else
  192528. shift -= 4;
  192529. }
  192530. }
  192531. else
  192532. #endif
  192533. {
  192534. sp = row;
  192535. shift = 4;
  192536. for (i = 0; i < row_width; i++)
  192537. {
  192538. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192539. == trans_values->gray)
  192540. {
  192541. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192542. *sp |= (png_byte)(background->gray << shift);
  192543. }
  192544. if (!shift)
  192545. {
  192546. shift = 4;
  192547. sp++;
  192548. }
  192549. else
  192550. shift -= 4;
  192551. }
  192552. }
  192553. break;
  192554. }
  192555. case 8:
  192556. {
  192557. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192558. if (gamma_table != NULL)
  192559. {
  192560. sp = row;
  192561. for (i = 0; i < row_width; i++, sp++)
  192562. {
  192563. if (*sp == trans_values->gray)
  192564. {
  192565. *sp = (png_byte)background->gray;
  192566. }
  192567. else
  192568. {
  192569. *sp = gamma_table[*sp];
  192570. }
  192571. }
  192572. }
  192573. else
  192574. #endif
  192575. {
  192576. sp = row;
  192577. for (i = 0; i < row_width; i++, sp++)
  192578. {
  192579. if (*sp == trans_values->gray)
  192580. {
  192581. *sp = (png_byte)background->gray;
  192582. }
  192583. }
  192584. }
  192585. break;
  192586. }
  192587. case 16:
  192588. {
  192589. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192590. if (gamma_16 != NULL)
  192591. {
  192592. sp = row;
  192593. for (i = 0; i < row_width; i++, sp += 2)
  192594. {
  192595. png_uint_16 v;
  192596. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192597. if (v == trans_values->gray)
  192598. {
  192599. /* background is already in screen gamma */
  192600. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192601. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192602. }
  192603. else
  192604. {
  192605. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192606. *sp = (png_byte)((v >> 8) & 0xff);
  192607. *(sp + 1) = (png_byte)(v & 0xff);
  192608. }
  192609. }
  192610. }
  192611. else
  192612. #endif
  192613. {
  192614. sp = row;
  192615. for (i = 0; i < row_width; i++, sp += 2)
  192616. {
  192617. png_uint_16 v;
  192618. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192619. if (v == trans_values->gray)
  192620. {
  192621. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192622. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192623. }
  192624. }
  192625. }
  192626. break;
  192627. }
  192628. }
  192629. break;
  192630. }
  192631. case PNG_COLOR_TYPE_RGB:
  192632. {
  192633. if (row_info->bit_depth == 8)
  192634. {
  192635. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192636. if (gamma_table != NULL)
  192637. {
  192638. sp = row;
  192639. for (i = 0; i < row_width; i++, sp += 3)
  192640. {
  192641. if (*sp == trans_values->red &&
  192642. *(sp + 1) == trans_values->green &&
  192643. *(sp + 2) == trans_values->blue)
  192644. {
  192645. *sp = (png_byte)background->red;
  192646. *(sp + 1) = (png_byte)background->green;
  192647. *(sp + 2) = (png_byte)background->blue;
  192648. }
  192649. else
  192650. {
  192651. *sp = gamma_table[*sp];
  192652. *(sp + 1) = gamma_table[*(sp + 1)];
  192653. *(sp + 2) = gamma_table[*(sp + 2)];
  192654. }
  192655. }
  192656. }
  192657. else
  192658. #endif
  192659. {
  192660. sp = row;
  192661. for (i = 0; i < row_width; i++, sp += 3)
  192662. {
  192663. if (*sp == trans_values->red &&
  192664. *(sp + 1) == trans_values->green &&
  192665. *(sp + 2) == trans_values->blue)
  192666. {
  192667. *sp = (png_byte)background->red;
  192668. *(sp + 1) = (png_byte)background->green;
  192669. *(sp + 2) = (png_byte)background->blue;
  192670. }
  192671. }
  192672. }
  192673. }
  192674. else /* if (row_info->bit_depth == 16) */
  192675. {
  192676. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192677. if (gamma_16 != NULL)
  192678. {
  192679. sp = row;
  192680. for (i = 0; i < row_width; i++, sp += 6)
  192681. {
  192682. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192683. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192684. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192685. if (r == trans_values->red && g == trans_values->green &&
  192686. b == trans_values->blue)
  192687. {
  192688. /* background is already in screen gamma */
  192689. *sp = (png_byte)((background->red >> 8) & 0xff);
  192690. *(sp + 1) = (png_byte)(background->red & 0xff);
  192691. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192692. *(sp + 3) = (png_byte)(background->green & 0xff);
  192693. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192694. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192695. }
  192696. else
  192697. {
  192698. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192699. *sp = (png_byte)((v >> 8) & 0xff);
  192700. *(sp + 1) = (png_byte)(v & 0xff);
  192701. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192702. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192703. *(sp + 3) = (png_byte)(v & 0xff);
  192704. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192705. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192706. *(sp + 5) = (png_byte)(v & 0xff);
  192707. }
  192708. }
  192709. }
  192710. else
  192711. #endif
  192712. {
  192713. sp = row;
  192714. for (i = 0; i < row_width; i++, sp += 6)
  192715. {
  192716. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192717. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192718. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192719. if (r == trans_values->red && g == trans_values->green &&
  192720. b == trans_values->blue)
  192721. {
  192722. *sp = (png_byte)((background->red >> 8) & 0xff);
  192723. *(sp + 1) = (png_byte)(background->red & 0xff);
  192724. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192725. *(sp + 3) = (png_byte)(background->green & 0xff);
  192726. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192727. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192728. }
  192729. }
  192730. }
  192731. }
  192732. break;
  192733. }
  192734. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192735. {
  192736. if (row_info->bit_depth == 8)
  192737. {
  192738. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192739. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192740. gamma_table != NULL)
  192741. {
  192742. sp = row;
  192743. dp = row;
  192744. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192745. {
  192746. png_uint_16 a = *(sp + 1);
  192747. if (a == 0xff)
  192748. {
  192749. *dp = gamma_table[*sp];
  192750. }
  192751. else if (a == 0)
  192752. {
  192753. /* background is already in screen gamma */
  192754. *dp = (png_byte)background->gray;
  192755. }
  192756. else
  192757. {
  192758. png_byte v, w;
  192759. v = gamma_to_1[*sp];
  192760. png_composite(w, v, a, background_1->gray);
  192761. *dp = gamma_from_1[w];
  192762. }
  192763. }
  192764. }
  192765. else
  192766. #endif
  192767. {
  192768. sp = row;
  192769. dp = row;
  192770. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192771. {
  192772. png_byte a = *(sp + 1);
  192773. if (a == 0xff)
  192774. {
  192775. *dp = *sp;
  192776. }
  192777. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192778. else if (a == 0)
  192779. {
  192780. *dp = (png_byte)background->gray;
  192781. }
  192782. else
  192783. {
  192784. png_composite(*dp, *sp, a, background_1->gray);
  192785. }
  192786. #else
  192787. *dp = (png_byte)background->gray;
  192788. #endif
  192789. }
  192790. }
  192791. }
  192792. else /* if (png_ptr->bit_depth == 16) */
  192793. {
  192794. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192795. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192796. gamma_16_to_1 != NULL)
  192797. {
  192798. sp = row;
  192799. dp = row;
  192800. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192801. {
  192802. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192803. if (a == (png_uint_16)0xffff)
  192804. {
  192805. png_uint_16 v;
  192806. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192807. *dp = (png_byte)((v >> 8) & 0xff);
  192808. *(dp + 1) = (png_byte)(v & 0xff);
  192809. }
  192810. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192811. else if (a == 0)
  192812. #else
  192813. else
  192814. #endif
  192815. {
  192816. /* background is already in screen gamma */
  192817. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192818. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192819. }
  192820. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192821. else
  192822. {
  192823. png_uint_16 g, v, w;
  192824. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192825. png_composite_16(v, g, a, background_1->gray);
  192826. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192827. *dp = (png_byte)((w >> 8) & 0xff);
  192828. *(dp + 1) = (png_byte)(w & 0xff);
  192829. }
  192830. #endif
  192831. }
  192832. }
  192833. else
  192834. #endif
  192835. {
  192836. sp = row;
  192837. dp = row;
  192838. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192839. {
  192840. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192841. if (a == (png_uint_16)0xffff)
  192842. {
  192843. png_memcpy(dp, sp, 2);
  192844. }
  192845. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192846. else if (a == 0)
  192847. #else
  192848. else
  192849. #endif
  192850. {
  192851. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192852. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192853. }
  192854. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192855. else
  192856. {
  192857. png_uint_16 g, v;
  192858. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192859. png_composite_16(v, g, a, background_1->gray);
  192860. *dp = (png_byte)((v >> 8) & 0xff);
  192861. *(dp + 1) = (png_byte)(v & 0xff);
  192862. }
  192863. #endif
  192864. }
  192865. }
  192866. }
  192867. break;
  192868. }
  192869. case PNG_COLOR_TYPE_RGB_ALPHA:
  192870. {
  192871. if (row_info->bit_depth == 8)
  192872. {
  192873. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192874. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192875. gamma_table != NULL)
  192876. {
  192877. sp = row;
  192878. dp = row;
  192879. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192880. {
  192881. png_byte a = *(sp + 3);
  192882. if (a == 0xff)
  192883. {
  192884. *dp = gamma_table[*sp];
  192885. *(dp + 1) = gamma_table[*(sp + 1)];
  192886. *(dp + 2) = gamma_table[*(sp + 2)];
  192887. }
  192888. else if (a == 0)
  192889. {
  192890. /* background is already in screen gamma */
  192891. *dp = (png_byte)background->red;
  192892. *(dp + 1) = (png_byte)background->green;
  192893. *(dp + 2) = (png_byte)background->blue;
  192894. }
  192895. else
  192896. {
  192897. png_byte v, w;
  192898. v = gamma_to_1[*sp];
  192899. png_composite(w, v, a, background_1->red);
  192900. *dp = gamma_from_1[w];
  192901. v = gamma_to_1[*(sp + 1)];
  192902. png_composite(w, v, a, background_1->green);
  192903. *(dp + 1) = gamma_from_1[w];
  192904. v = gamma_to_1[*(sp + 2)];
  192905. png_composite(w, v, a, background_1->blue);
  192906. *(dp + 2) = gamma_from_1[w];
  192907. }
  192908. }
  192909. }
  192910. else
  192911. #endif
  192912. {
  192913. sp = row;
  192914. dp = row;
  192915. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192916. {
  192917. png_byte a = *(sp + 3);
  192918. if (a == 0xff)
  192919. {
  192920. *dp = *sp;
  192921. *(dp + 1) = *(sp + 1);
  192922. *(dp + 2) = *(sp + 2);
  192923. }
  192924. else if (a == 0)
  192925. {
  192926. *dp = (png_byte)background->red;
  192927. *(dp + 1) = (png_byte)background->green;
  192928. *(dp + 2) = (png_byte)background->blue;
  192929. }
  192930. else
  192931. {
  192932. png_composite(*dp, *sp, a, background->red);
  192933. png_composite(*(dp + 1), *(sp + 1), a,
  192934. background->green);
  192935. png_composite(*(dp + 2), *(sp + 2), a,
  192936. background->blue);
  192937. }
  192938. }
  192939. }
  192940. }
  192941. else /* if (row_info->bit_depth == 16) */
  192942. {
  192943. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192944. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192945. gamma_16_to_1 != NULL)
  192946. {
  192947. sp = row;
  192948. dp = row;
  192949. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192950. {
  192951. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192952. << 8) + (png_uint_16)(*(sp + 7)));
  192953. if (a == (png_uint_16)0xffff)
  192954. {
  192955. png_uint_16 v;
  192956. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192957. *dp = (png_byte)((v >> 8) & 0xff);
  192958. *(dp + 1) = (png_byte)(v & 0xff);
  192959. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192960. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192961. *(dp + 3) = (png_byte)(v & 0xff);
  192962. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192963. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192964. *(dp + 5) = (png_byte)(v & 0xff);
  192965. }
  192966. else if (a == 0)
  192967. {
  192968. /* background is already in screen gamma */
  192969. *dp = (png_byte)((background->red >> 8) & 0xff);
  192970. *(dp + 1) = (png_byte)(background->red & 0xff);
  192971. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192972. *(dp + 3) = (png_byte)(background->green & 0xff);
  192973. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192974. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192975. }
  192976. else
  192977. {
  192978. png_uint_16 v, w, x;
  192979. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192980. png_composite_16(w, v, a, background_1->red);
  192981. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192982. *dp = (png_byte)((x >> 8) & 0xff);
  192983. *(dp + 1) = (png_byte)(x & 0xff);
  192984. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192985. png_composite_16(w, v, a, background_1->green);
  192986. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192987. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192988. *(dp + 3) = (png_byte)(x & 0xff);
  192989. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192990. png_composite_16(w, v, a, background_1->blue);
  192991. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192992. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192993. *(dp + 5) = (png_byte)(x & 0xff);
  192994. }
  192995. }
  192996. }
  192997. else
  192998. #endif
  192999. {
  193000. sp = row;
  193001. dp = row;
  193002. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193003. {
  193004. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193005. << 8) + (png_uint_16)(*(sp + 7)));
  193006. if (a == (png_uint_16)0xffff)
  193007. {
  193008. png_memcpy(dp, sp, 6);
  193009. }
  193010. else if (a == 0)
  193011. {
  193012. *dp = (png_byte)((background->red >> 8) & 0xff);
  193013. *(dp + 1) = (png_byte)(background->red & 0xff);
  193014. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193015. *(dp + 3) = (png_byte)(background->green & 0xff);
  193016. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193017. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193018. }
  193019. else
  193020. {
  193021. png_uint_16 v;
  193022. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193023. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193024. + *(sp + 3));
  193025. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193026. + *(sp + 5));
  193027. png_composite_16(v, r, a, background->red);
  193028. *dp = (png_byte)((v >> 8) & 0xff);
  193029. *(dp + 1) = (png_byte)(v & 0xff);
  193030. png_composite_16(v, g, a, background->green);
  193031. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193032. *(dp + 3) = (png_byte)(v & 0xff);
  193033. png_composite_16(v, b, a, background->blue);
  193034. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193035. *(dp + 5) = (png_byte)(v & 0xff);
  193036. }
  193037. }
  193038. }
  193039. }
  193040. break;
  193041. }
  193042. }
  193043. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193044. {
  193045. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193046. row_info->channels--;
  193047. row_info->pixel_depth = (png_byte)(row_info->channels *
  193048. row_info->bit_depth);
  193049. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193050. }
  193051. }
  193052. }
  193053. #endif
  193054. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193055. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193056. * you do this after you deal with the transparency issue on grayscale
  193057. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193058. * is 16, use gamma_16_table and gamma_shift. Build these with
  193059. * build_gamma_table().
  193060. */
  193061. void /* PRIVATE */
  193062. png_do_gamma(png_row_infop row_info, png_bytep row,
  193063. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193064. int gamma_shift)
  193065. {
  193066. png_bytep sp;
  193067. png_uint_32 i;
  193068. png_uint_32 row_width=row_info->width;
  193069. png_debug(1, "in png_do_gamma\n");
  193070. if (
  193071. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193072. row != NULL && row_info != NULL &&
  193073. #endif
  193074. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193075. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193076. {
  193077. switch (row_info->color_type)
  193078. {
  193079. case PNG_COLOR_TYPE_RGB:
  193080. {
  193081. if (row_info->bit_depth == 8)
  193082. {
  193083. sp = row;
  193084. for (i = 0; i < row_width; i++)
  193085. {
  193086. *sp = gamma_table[*sp];
  193087. sp++;
  193088. *sp = gamma_table[*sp];
  193089. sp++;
  193090. *sp = gamma_table[*sp];
  193091. sp++;
  193092. }
  193093. }
  193094. else /* if (row_info->bit_depth == 16) */
  193095. {
  193096. sp = row;
  193097. for (i = 0; i < row_width; i++)
  193098. {
  193099. png_uint_16 v;
  193100. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193101. *sp = (png_byte)((v >> 8) & 0xff);
  193102. *(sp + 1) = (png_byte)(v & 0xff);
  193103. sp += 2;
  193104. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193105. *sp = (png_byte)((v >> 8) & 0xff);
  193106. *(sp + 1) = (png_byte)(v & 0xff);
  193107. sp += 2;
  193108. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193109. *sp = (png_byte)((v >> 8) & 0xff);
  193110. *(sp + 1) = (png_byte)(v & 0xff);
  193111. sp += 2;
  193112. }
  193113. }
  193114. break;
  193115. }
  193116. case PNG_COLOR_TYPE_RGB_ALPHA:
  193117. {
  193118. if (row_info->bit_depth == 8)
  193119. {
  193120. sp = row;
  193121. for (i = 0; i < row_width; i++)
  193122. {
  193123. *sp = gamma_table[*sp];
  193124. sp++;
  193125. *sp = gamma_table[*sp];
  193126. sp++;
  193127. *sp = gamma_table[*sp];
  193128. sp++;
  193129. sp++;
  193130. }
  193131. }
  193132. else /* if (row_info->bit_depth == 16) */
  193133. {
  193134. sp = row;
  193135. for (i = 0; i < row_width; i++)
  193136. {
  193137. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193138. *sp = (png_byte)((v >> 8) & 0xff);
  193139. *(sp + 1) = (png_byte)(v & 0xff);
  193140. sp += 2;
  193141. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193142. *sp = (png_byte)((v >> 8) & 0xff);
  193143. *(sp + 1) = (png_byte)(v & 0xff);
  193144. sp += 2;
  193145. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193146. *sp = (png_byte)((v >> 8) & 0xff);
  193147. *(sp + 1) = (png_byte)(v & 0xff);
  193148. sp += 4;
  193149. }
  193150. }
  193151. break;
  193152. }
  193153. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193154. {
  193155. if (row_info->bit_depth == 8)
  193156. {
  193157. sp = row;
  193158. for (i = 0; i < row_width; i++)
  193159. {
  193160. *sp = gamma_table[*sp];
  193161. sp += 2;
  193162. }
  193163. }
  193164. else /* if (row_info->bit_depth == 16) */
  193165. {
  193166. sp = row;
  193167. for (i = 0; i < row_width; i++)
  193168. {
  193169. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193170. *sp = (png_byte)((v >> 8) & 0xff);
  193171. *(sp + 1) = (png_byte)(v & 0xff);
  193172. sp += 4;
  193173. }
  193174. }
  193175. break;
  193176. }
  193177. case PNG_COLOR_TYPE_GRAY:
  193178. {
  193179. if (row_info->bit_depth == 2)
  193180. {
  193181. sp = row;
  193182. for (i = 0; i < row_width; i += 4)
  193183. {
  193184. int a = *sp & 0xc0;
  193185. int b = *sp & 0x30;
  193186. int c = *sp & 0x0c;
  193187. int d = *sp & 0x03;
  193188. *sp = (png_byte)(
  193189. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193190. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193191. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193192. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193193. sp++;
  193194. }
  193195. }
  193196. if (row_info->bit_depth == 4)
  193197. {
  193198. sp = row;
  193199. for (i = 0; i < row_width; i += 2)
  193200. {
  193201. int msb = *sp & 0xf0;
  193202. int lsb = *sp & 0x0f;
  193203. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193204. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193205. sp++;
  193206. }
  193207. }
  193208. else if (row_info->bit_depth == 8)
  193209. {
  193210. sp = row;
  193211. for (i = 0; i < row_width; i++)
  193212. {
  193213. *sp = gamma_table[*sp];
  193214. sp++;
  193215. }
  193216. }
  193217. else if (row_info->bit_depth == 16)
  193218. {
  193219. sp = row;
  193220. for (i = 0; i < row_width; i++)
  193221. {
  193222. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193223. *sp = (png_byte)((v >> 8) & 0xff);
  193224. *(sp + 1) = (png_byte)(v & 0xff);
  193225. sp += 2;
  193226. }
  193227. }
  193228. break;
  193229. }
  193230. }
  193231. }
  193232. }
  193233. #endif
  193234. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193235. /* Expands a palette row to an RGB or RGBA row depending
  193236. * upon whether you supply trans and num_trans.
  193237. */
  193238. void /* PRIVATE */
  193239. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193240. png_colorp palette, png_bytep trans, int num_trans)
  193241. {
  193242. int shift, value;
  193243. png_bytep sp, dp;
  193244. png_uint_32 i;
  193245. png_uint_32 row_width=row_info->width;
  193246. png_debug(1, "in png_do_expand_palette\n");
  193247. if (
  193248. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193249. row != NULL && row_info != NULL &&
  193250. #endif
  193251. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193252. {
  193253. if (row_info->bit_depth < 8)
  193254. {
  193255. switch (row_info->bit_depth)
  193256. {
  193257. case 1:
  193258. {
  193259. sp = row + (png_size_t)((row_width - 1) >> 3);
  193260. dp = row + (png_size_t)row_width - 1;
  193261. shift = 7 - (int)((row_width + 7) & 0x07);
  193262. for (i = 0; i < row_width; i++)
  193263. {
  193264. if ((*sp >> shift) & 0x01)
  193265. *dp = 1;
  193266. else
  193267. *dp = 0;
  193268. if (shift == 7)
  193269. {
  193270. shift = 0;
  193271. sp--;
  193272. }
  193273. else
  193274. shift++;
  193275. dp--;
  193276. }
  193277. break;
  193278. }
  193279. case 2:
  193280. {
  193281. sp = row + (png_size_t)((row_width - 1) >> 2);
  193282. dp = row + (png_size_t)row_width - 1;
  193283. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193284. for (i = 0; i < row_width; i++)
  193285. {
  193286. value = (*sp >> shift) & 0x03;
  193287. *dp = (png_byte)value;
  193288. if (shift == 6)
  193289. {
  193290. shift = 0;
  193291. sp--;
  193292. }
  193293. else
  193294. shift += 2;
  193295. dp--;
  193296. }
  193297. break;
  193298. }
  193299. case 4:
  193300. {
  193301. sp = row + (png_size_t)((row_width - 1) >> 1);
  193302. dp = row + (png_size_t)row_width - 1;
  193303. shift = (int)((row_width & 0x01) << 2);
  193304. for (i = 0; i < row_width; i++)
  193305. {
  193306. value = (*sp >> shift) & 0x0f;
  193307. *dp = (png_byte)value;
  193308. if (shift == 4)
  193309. {
  193310. shift = 0;
  193311. sp--;
  193312. }
  193313. else
  193314. shift += 4;
  193315. dp--;
  193316. }
  193317. break;
  193318. }
  193319. }
  193320. row_info->bit_depth = 8;
  193321. row_info->pixel_depth = 8;
  193322. row_info->rowbytes = row_width;
  193323. }
  193324. switch (row_info->bit_depth)
  193325. {
  193326. case 8:
  193327. {
  193328. if (trans != NULL)
  193329. {
  193330. sp = row + (png_size_t)row_width - 1;
  193331. dp = row + (png_size_t)(row_width << 2) - 1;
  193332. for (i = 0; i < row_width; i++)
  193333. {
  193334. if ((int)(*sp) >= num_trans)
  193335. *dp-- = 0xff;
  193336. else
  193337. *dp-- = trans[*sp];
  193338. *dp-- = palette[*sp].blue;
  193339. *dp-- = palette[*sp].green;
  193340. *dp-- = palette[*sp].red;
  193341. sp--;
  193342. }
  193343. row_info->bit_depth = 8;
  193344. row_info->pixel_depth = 32;
  193345. row_info->rowbytes = row_width * 4;
  193346. row_info->color_type = 6;
  193347. row_info->channels = 4;
  193348. }
  193349. else
  193350. {
  193351. sp = row + (png_size_t)row_width - 1;
  193352. dp = row + (png_size_t)(row_width * 3) - 1;
  193353. for (i = 0; i < row_width; i++)
  193354. {
  193355. *dp-- = palette[*sp].blue;
  193356. *dp-- = palette[*sp].green;
  193357. *dp-- = palette[*sp].red;
  193358. sp--;
  193359. }
  193360. row_info->bit_depth = 8;
  193361. row_info->pixel_depth = 24;
  193362. row_info->rowbytes = row_width * 3;
  193363. row_info->color_type = 2;
  193364. row_info->channels = 3;
  193365. }
  193366. break;
  193367. }
  193368. }
  193369. }
  193370. }
  193371. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193372. * expanded transparency value is supplied, an alpha channel is built.
  193373. */
  193374. void /* PRIVATE */
  193375. png_do_expand(png_row_infop row_info, png_bytep row,
  193376. png_color_16p trans_value)
  193377. {
  193378. int shift, value;
  193379. png_bytep sp, dp;
  193380. png_uint_32 i;
  193381. png_uint_32 row_width=row_info->width;
  193382. png_debug(1, "in png_do_expand\n");
  193383. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193384. if (row != NULL && row_info != NULL)
  193385. #endif
  193386. {
  193387. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193388. {
  193389. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193390. if (row_info->bit_depth < 8)
  193391. {
  193392. switch (row_info->bit_depth)
  193393. {
  193394. case 1:
  193395. {
  193396. gray = (png_uint_16)((gray&0x01)*0xff);
  193397. sp = row + (png_size_t)((row_width - 1) >> 3);
  193398. dp = row + (png_size_t)row_width - 1;
  193399. shift = 7 - (int)((row_width + 7) & 0x07);
  193400. for (i = 0; i < row_width; i++)
  193401. {
  193402. if ((*sp >> shift) & 0x01)
  193403. *dp = 0xff;
  193404. else
  193405. *dp = 0;
  193406. if (shift == 7)
  193407. {
  193408. shift = 0;
  193409. sp--;
  193410. }
  193411. else
  193412. shift++;
  193413. dp--;
  193414. }
  193415. break;
  193416. }
  193417. case 2:
  193418. {
  193419. gray = (png_uint_16)((gray&0x03)*0x55);
  193420. sp = row + (png_size_t)((row_width - 1) >> 2);
  193421. dp = row + (png_size_t)row_width - 1;
  193422. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193423. for (i = 0; i < row_width; i++)
  193424. {
  193425. value = (*sp >> shift) & 0x03;
  193426. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193427. (value << 6));
  193428. if (shift == 6)
  193429. {
  193430. shift = 0;
  193431. sp--;
  193432. }
  193433. else
  193434. shift += 2;
  193435. dp--;
  193436. }
  193437. break;
  193438. }
  193439. case 4:
  193440. {
  193441. gray = (png_uint_16)((gray&0x0f)*0x11);
  193442. sp = row + (png_size_t)((row_width - 1) >> 1);
  193443. dp = row + (png_size_t)row_width - 1;
  193444. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193445. for (i = 0; i < row_width; i++)
  193446. {
  193447. value = (*sp >> shift) & 0x0f;
  193448. *dp = (png_byte)(value | (value << 4));
  193449. if (shift == 4)
  193450. {
  193451. shift = 0;
  193452. sp--;
  193453. }
  193454. else
  193455. shift = 4;
  193456. dp--;
  193457. }
  193458. break;
  193459. }
  193460. }
  193461. row_info->bit_depth = 8;
  193462. row_info->pixel_depth = 8;
  193463. row_info->rowbytes = row_width;
  193464. }
  193465. if (trans_value != NULL)
  193466. {
  193467. if (row_info->bit_depth == 8)
  193468. {
  193469. gray = gray & 0xff;
  193470. sp = row + (png_size_t)row_width - 1;
  193471. dp = row + (png_size_t)(row_width << 1) - 1;
  193472. for (i = 0; i < row_width; i++)
  193473. {
  193474. if (*sp == gray)
  193475. *dp-- = 0;
  193476. else
  193477. *dp-- = 0xff;
  193478. *dp-- = *sp--;
  193479. }
  193480. }
  193481. else if (row_info->bit_depth == 16)
  193482. {
  193483. png_byte gray_high = (gray >> 8) & 0xff;
  193484. png_byte gray_low = gray & 0xff;
  193485. sp = row + row_info->rowbytes - 1;
  193486. dp = row + (row_info->rowbytes << 1) - 1;
  193487. for (i = 0; i < row_width; i++)
  193488. {
  193489. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193490. {
  193491. *dp-- = 0;
  193492. *dp-- = 0;
  193493. }
  193494. else
  193495. {
  193496. *dp-- = 0xff;
  193497. *dp-- = 0xff;
  193498. }
  193499. *dp-- = *sp--;
  193500. *dp-- = *sp--;
  193501. }
  193502. }
  193503. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193504. row_info->channels = 2;
  193505. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193506. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193507. row_width);
  193508. }
  193509. }
  193510. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193511. {
  193512. if (row_info->bit_depth == 8)
  193513. {
  193514. png_byte red = trans_value->red & 0xff;
  193515. png_byte green = trans_value->green & 0xff;
  193516. png_byte blue = trans_value->blue & 0xff;
  193517. sp = row + (png_size_t)row_info->rowbytes - 1;
  193518. dp = row + (png_size_t)(row_width << 2) - 1;
  193519. for (i = 0; i < row_width; i++)
  193520. {
  193521. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193522. *dp-- = 0;
  193523. else
  193524. *dp-- = 0xff;
  193525. *dp-- = *sp--;
  193526. *dp-- = *sp--;
  193527. *dp-- = *sp--;
  193528. }
  193529. }
  193530. else if (row_info->bit_depth == 16)
  193531. {
  193532. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193533. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193534. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193535. png_byte red_low = trans_value->red & 0xff;
  193536. png_byte green_low = trans_value->green & 0xff;
  193537. png_byte blue_low = trans_value->blue & 0xff;
  193538. sp = row + row_info->rowbytes - 1;
  193539. dp = row + (png_size_t)(row_width << 3) - 1;
  193540. for (i = 0; i < row_width; i++)
  193541. {
  193542. if (*(sp - 5) == red_high &&
  193543. *(sp - 4) == red_low &&
  193544. *(sp - 3) == green_high &&
  193545. *(sp - 2) == green_low &&
  193546. *(sp - 1) == blue_high &&
  193547. *(sp ) == blue_low)
  193548. {
  193549. *dp-- = 0;
  193550. *dp-- = 0;
  193551. }
  193552. else
  193553. {
  193554. *dp-- = 0xff;
  193555. *dp-- = 0xff;
  193556. }
  193557. *dp-- = *sp--;
  193558. *dp-- = *sp--;
  193559. *dp-- = *sp--;
  193560. *dp-- = *sp--;
  193561. *dp-- = *sp--;
  193562. *dp-- = *sp--;
  193563. }
  193564. }
  193565. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193566. row_info->channels = 4;
  193567. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193568. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193569. }
  193570. }
  193571. }
  193572. #endif
  193573. #if defined(PNG_READ_DITHER_SUPPORTED)
  193574. void /* PRIVATE */
  193575. png_do_dither(png_row_infop row_info, png_bytep row,
  193576. png_bytep palette_lookup, png_bytep dither_lookup)
  193577. {
  193578. png_bytep sp, dp;
  193579. png_uint_32 i;
  193580. png_uint_32 row_width=row_info->width;
  193581. png_debug(1, "in png_do_dither\n");
  193582. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193583. if (row != NULL && row_info != NULL)
  193584. #endif
  193585. {
  193586. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193587. palette_lookup && row_info->bit_depth == 8)
  193588. {
  193589. int r, g, b, p;
  193590. sp = row;
  193591. dp = row;
  193592. for (i = 0; i < row_width; i++)
  193593. {
  193594. r = *sp++;
  193595. g = *sp++;
  193596. b = *sp++;
  193597. /* this looks real messy, but the compiler will reduce
  193598. it down to a reasonable formula. For example, with
  193599. 5 bits per color, we get:
  193600. p = (((r >> 3) & 0x1f) << 10) |
  193601. (((g >> 3) & 0x1f) << 5) |
  193602. ((b >> 3) & 0x1f);
  193603. */
  193604. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193605. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193606. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193607. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193608. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193609. (PNG_DITHER_BLUE_BITS)) |
  193610. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193611. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193612. *dp++ = palette_lookup[p];
  193613. }
  193614. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193615. row_info->channels = 1;
  193616. row_info->pixel_depth = row_info->bit_depth;
  193617. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193618. }
  193619. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193620. palette_lookup != NULL && row_info->bit_depth == 8)
  193621. {
  193622. int r, g, b, p;
  193623. sp = row;
  193624. dp = row;
  193625. for (i = 0; i < row_width; i++)
  193626. {
  193627. r = *sp++;
  193628. g = *sp++;
  193629. b = *sp++;
  193630. sp++;
  193631. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193632. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193633. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193634. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193635. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193636. (PNG_DITHER_BLUE_BITS)) |
  193637. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193638. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193639. *dp++ = palette_lookup[p];
  193640. }
  193641. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193642. row_info->channels = 1;
  193643. row_info->pixel_depth = row_info->bit_depth;
  193644. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193645. }
  193646. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193647. dither_lookup && row_info->bit_depth == 8)
  193648. {
  193649. sp = row;
  193650. for (i = 0; i < row_width; i++, sp++)
  193651. {
  193652. *sp = dither_lookup[*sp];
  193653. }
  193654. }
  193655. }
  193656. }
  193657. #endif
  193658. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193659. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193660. static PNG_CONST int png_gamma_shift[] =
  193661. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193662. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193663. * tables, we don't make a full table if we are reducing to 8-bit in
  193664. * the future. Note also how the gamma_16 tables are segmented so that
  193665. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193666. */
  193667. void /* PRIVATE */
  193668. png_build_gamma_table(png_structp png_ptr)
  193669. {
  193670. png_debug(1, "in png_build_gamma_table\n");
  193671. if (png_ptr->bit_depth <= 8)
  193672. {
  193673. int i;
  193674. double g;
  193675. if (png_ptr->screen_gamma > .000001)
  193676. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193677. else
  193678. g = 1.0;
  193679. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193680. (png_uint_32)256);
  193681. for (i = 0; i < 256; i++)
  193682. {
  193683. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193684. g) * 255.0 + .5);
  193685. }
  193686. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193687. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193688. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193689. {
  193690. g = 1.0 / (png_ptr->gamma);
  193691. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193692. (png_uint_32)256);
  193693. for (i = 0; i < 256; i++)
  193694. {
  193695. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193696. g) * 255.0 + .5);
  193697. }
  193698. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193699. (png_uint_32)256);
  193700. if(png_ptr->screen_gamma > 0.000001)
  193701. g = 1.0 / png_ptr->screen_gamma;
  193702. else
  193703. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193704. for (i = 0; i < 256; i++)
  193705. {
  193706. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193707. g) * 255.0 + .5);
  193708. }
  193709. }
  193710. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193711. }
  193712. else
  193713. {
  193714. double g;
  193715. int i, j, shift, num;
  193716. int sig_bit;
  193717. png_uint_32 ig;
  193718. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193719. {
  193720. sig_bit = (int)png_ptr->sig_bit.red;
  193721. if ((int)png_ptr->sig_bit.green > sig_bit)
  193722. sig_bit = png_ptr->sig_bit.green;
  193723. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193724. sig_bit = png_ptr->sig_bit.blue;
  193725. }
  193726. else
  193727. {
  193728. sig_bit = (int)png_ptr->sig_bit.gray;
  193729. }
  193730. if (sig_bit > 0)
  193731. shift = 16 - sig_bit;
  193732. else
  193733. shift = 0;
  193734. if (png_ptr->transformations & PNG_16_TO_8)
  193735. {
  193736. if (shift < (16 - PNG_MAX_GAMMA_8))
  193737. shift = (16 - PNG_MAX_GAMMA_8);
  193738. }
  193739. if (shift > 8)
  193740. shift = 8;
  193741. if (shift < 0)
  193742. shift = 0;
  193743. png_ptr->gamma_shift = (png_byte)shift;
  193744. num = (1 << (8 - shift));
  193745. if (png_ptr->screen_gamma > .000001)
  193746. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193747. else
  193748. g = 1.0;
  193749. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193750. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193751. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193752. {
  193753. double fin, fout;
  193754. png_uint_32 last, max;
  193755. for (i = 0; i < num; i++)
  193756. {
  193757. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193758. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193759. }
  193760. g = 1.0 / g;
  193761. last = 0;
  193762. for (i = 0; i < 256; i++)
  193763. {
  193764. fout = ((double)i + 0.5) / 256.0;
  193765. fin = pow(fout, g);
  193766. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193767. while (last <= max)
  193768. {
  193769. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193770. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193771. (png_uint_16)i | ((png_uint_16)i << 8));
  193772. last++;
  193773. }
  193774. }
  193775. while (last < ((png_uint_32)num << 8))
  193776. {
  193777. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193778. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193779. last++;
  193780. }
  193781. }
  193782. else
  193783. {
  193784. for (i = 0; i < num; i++)
  193785. {
  193786. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193787. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193788. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193789. for (j = 0; j < 256; j++)
  193790. {
  193791. png_ptr->gamma_16_table[i][j] =
  193792. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193793. 65535.0, g) * 65535.0 + .5);
  193794. }
  193795. }
  193796. }
  193797. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193798. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193799. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193800. {
  193801. g = 1.0 / (png_ptr->gamma);
  193802. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193803. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193804. for (i = 0; i < num; i++)
  193805. {
  193806. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193807. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193808. ig = (((png_uint_32)i *
  193809. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193810. for (j = 0; j < 256; j++)
  193811. {
  193812. png_ptr->gamma_16_to_1[i][j] =
  193813. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193814. 65535.0, g) * 65535.0 + .5);
  193815. }
  193816. }
  193817. if(png_ptr->screen_gamma > 0.000001)
  193818. g = 1.0 / png_ptr->screen_gamma;
  193819. else
  193820. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193821. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193822. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193823. for (i = 0; i < num; i++)
  193824. {
  193825. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193826. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193827. ig = (((png_uint_32)i *
  193828. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193829. for (j = 0; j < 256; j++)
  193830. {
  193831. png_ptr->gamma_16_from_1[i][j] =
  193832. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193833. 65535.0, g) * 65535.0 + .5);
  193834. }
  193835. }
  193836. }
  193837. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193838. }
  193839. }
  193840. #endif
  193841. /* To do: install integer version of png_build_gamma_table here */
  193842. #endif
  193843. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193844. /* undoes intrapixel differencing */
  193845. void /* PRIVATE */
  193846. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193847. {
  193848. png_debug(1, "in png_do_read_intrapixel\n");
  193849. if (
  193850. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193851. row != NULL && row_info != NULL &&
  193852. #endif
  193853. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193854. {
  193855. int bytes_per_pixel;
  193856. png_uint_32 row_width = row_info->width;
  193857. if (row_info->bit_depth == 8)
  193858. {
  193859. png_bytep rp;
  193860. png_uint_32 i;
  193861. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193862. bytes_per_pixel = 3;
  193863. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193864. bytes_per_pixel = 4;
  193865. else
  193866. return;
  193867. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193868. {
  193869. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193870. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193871. }
  193872. }
  193873. else if (row_info->bit_depth == 16)
  193874. {
  193875. png_bytep rp;
  193876. png_uint_32 i;
  193877. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193878. bytes_per_pixel = 6;
  193879. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193880. bytes_per_pixel = 8;
  193881. else
  193882. return;
  193883. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193884. {
  193885. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193886. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193887. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193888. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193889. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193890. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193891. *(rp+1) = (png_byte)(red & 0xff);
  193892. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193893. *(rp+5) = (png_byte)(blue & 0xff);
  193894. }
  193895. }
  193896. }
  193897. }
  193898. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193899. #endif /* PNG_READ_SUPPORTED */
  193900. /*** End of inlined file: pngrtran.c ***/
  193901. /*** Start of inlined file: pngrutil.c ***/
  193902. /* pngrutil.c - utilities to read a PNG file
  193903. *
  193904. * Last changed in libpng 1.2.21 [October 4, 2007]
  193905. * For conditions of distribution and use, see copyright notice in png.h
  193906. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193907. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193908. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193909. *
  193910. * This file contains routines that are only called from within
  193911. * libpng itself during the course of reading an image.
  193912. */
  193913. #define PNG_INTERNAL
  193914. #if defined(PNG_READ_SUPPORTED)
  193915. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193916. # define WIN32_WCE_OLD
  193917. #endif
  193918. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193919. # if defined(WIN32_WCE_OLD)
  193920. /* strtod() function is not supported on WindowsCE */
  193921. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193922. {
  193923. double result = 0;
  193924. int len;
  193925. wchar_t *str, *end;
  193926. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193927. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193928. if ( NULL != str )
  193929. {
  193930. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193931. result = wcstod(str, &end);
  193932. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193933. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193934. png_free(png_ptr, str);
  193935. }
  193936. return result;
  193937. }
  193938. # else
  193939. # define png_strtod(p,a,b) strtod(a,b)
  193940. # endif
  193941. #endif
  193942. png_uint_32 PNGAPI
  193943. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193944. {
  193945. png_uint_32 i = png_get_uint_32(buf);
  193946. if (i > PNG_UINT_31_MAX)
  193947. png_error(png_ptr, "PNG unsigned integer out of range.");
  193948. return (i);
  193949. }
  193950. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193951. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193952. png_uint_32 PNGAPI
  193953. png_get_uint_32(png_bytep buf)
  193954. {
  193955. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193956. ((png_uint_32)(*(buf + 1)) << 16) +
  193957. ((png_uint_32)(*(buf + 2)) << 8) +
  193958. (png_uint_32)(*(buf + 3));
  193959. return (i);
  193960. }
  193961. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193962. * data is stored in the PNG file in two's complement format, and it is
  193963. * assumed that the machine format for signed integers is the same. */
  193964. png_int_32 PNGAPI
  193965. png_get_int_32(png_bytep buf)
  193966. {
  193967. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193968. ((png_int_32)(*(buf + 1)) << 16) +
  193969. ((png_int_32)(*(buf + 2)) << 8) +
  193970. (png_int_32)(*(buf + 3));
  193971. return (i);
  193972. }
  193973. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193974. png_uint_16 PNGAPI
  193975. png_get_uint_16(png_bytep buf)
  193976. {
  193977. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193978. (png_uint_16)(*(buf + 1)));
  193979. return (i);
  193980. }
  193981. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193982. /* Read data, and (optionally) run it through the CRC. */
  193983. void /* PRIVATE */
  193984. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193985. {
  193986. if(png_ptr == NULL) return;
  193987. png_read_data(png_ptr, buf, length);
  193988. png_calculate_crc(png_ptr, buf, length);
  193989. }
  193990. /* Optionally skip data and then check the CRC. Depending on whether we
  193991. are reading a ancillary or critical chunk, and how the program has set
  193992. things up, we may calculate the CRC on the data and print a message.
  193993. Returns '1' if there was a CRC error, '0' otherwise. */
  193994. int /* PRIVATE */
  193995. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193996. {
  193997. png_size_t i;
  193998. png_size_t istop = png_ptr->zbuf_size;
  193999. for (i = (png_size_t)skip; i > istop; i -= istop)
  194000. {
  194001. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194002. }
  194003. if (i)
  194004. {
  194005. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194006. }
  194007. if (png_crc_error(png_ptr))
  194008. {
  194009. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194010. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194011. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194012. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194013. {
  194014. png_chunk_warning(png_ptr, "CRC error");
  194015. }
  194016. else
  194017. {
  194018. png_chunk_error(png_ptr, "CRC error");
  194019. }
  194020. return (1);
  194021. }
  194022. return (0);
  194023. }
  194024. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194025. the data it has read thus far. */
  194026. int /* PRIVATE */
  194027. png_crc_error(png_structp png_ptr)
  194028. {
  194029. png_byte crc_bytes[4];
  194030. png_uint_32 crc;
  194031. int need_crc = 1;
  194032. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194033. {
  194034. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194035. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194036. need_crc = 0;
  194037. }
  194038. else /* critical */
  194039. {
  194040. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194041. need_crc = 0;
  194042. }
  194043. png_read_data(png_ptr, crc_bytes, 4);
  194044. if (need_crc)
  194045. {
  194046. crc = png_get_uint_32(crc_bytes);
  194047. return ((int)(crc != png_ptr->crc));
  194048. }
  194049. else
  194050. return (0);
  194051. }
  194052. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194053. defined(PNG_READ_iCCP_SUPPORTED)
  194054. /*
  194055. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194056. * points at an allocated area holding the contents of a chunk with a
  194057. * trailing compressed part. What we get back is an allocated area
  194058. * holding the original prefix part and an uncompressed version of the
  194059. * trailing part (the malloc area passed in is freed).
  194060. */
  194061. png_charp /* PRIVATE */
  194062. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194063. png_charp chunkdata, png_size_t chunklength,
  194064. png_size_t prefix_size, png_size_t *newlength)
  194065. {
  194066. static PNG_CONST char msg[] = "Error decoding compressed text";
  194067. png_charp text;
  194068. png_size_t text_size;
  194069. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194070. {
  194071. int ret = Z_OK;
  194072. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194073. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194074. png_ptr->zstream.next_out = png_ptr->zbuf;
  194075. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194076. text_size = 0;
  194077. text = NULL;
  194078. while (png_ptr->zstream.avail_in)
  194079. {
  194080. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194081. if (ret != Z_OK && ret != Z_STREAM_END)
  194082. {
  194083. if (png_ptr->zstream.msg != NULL)
  194084. png_warning(png_ptr, png_ptr->zstream.msg);
  194085. else
  194086. png_warning(png_ptr, msg);
  194087. inflateReset(&png_ptr->zstream);
  194088. png_ptr->zstream.avail_in = 0;
  194089. if (text == NULL)
  194090. {
  194091. text_size = prefix_size + png_sizeof(msg) + 1;
  194092. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194093. if (text == NULL)
  194094. {
  194095. png_free(png_ptr,chunkdata);
  194096. png_error(png_ptr,"Not enough memory to decompress chunk");
  194097. }
  194098. png_memcpy(text, chunkdata, prefix_size);
  194099. }
  194100. text[text_size - 1] = 0x00;
  194101. /* Copy what we can of the error message into the text chunk */
  194102. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194103. text_size = png_sizeof(msg) > text_size ? text_size :
  194104. png_sizeof(msg);
  194105. png_memcpy(text + prefix_size, msg, text_size + 1);
  194106. break;
  194107. }
  194108. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194109. {
  194110. if (text == NULL)
  194111. {
  194112. text_size = prefix_size +
  194113. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194114. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194115. if (text == NULL)
  194116. {
  194117. png_free(png_ptr,chunkdata);
  194118. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194119. }
  194120. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194121. text_size - prefix_size);
  194122. png_memcpy(text, chunkdata, prefix_size);
  194123. *(text + text_size) = 0x00;
  194124. }
  194125. else
  194126. {
  194127. png_charp tmp;
  194128. tmp = text;
  194129. text = (png_charp)png_malloc_warn(png_ptr,
  194130. (png_uint_32)(text_size +
  194131. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194132. if (text == NULL)
  194133. {
  194134. png_free(png_ptr, tmp);
  194135. png_free(png_ptr, chunkdata);
  194136. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194137. }
  194138. png_memcpy(text, tmp, text_size);
  194139. png_free(png_ptr, tmp);
  194140. png_memcpy(text + text_size, png_ptr->zbuf,
  194141. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194142. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194143. *(text + text_size) = 0x00;
  194144. }
  194145. if (ret == Z_STREAM_END)
  194146. break;
  194147. else
  194148. {
  194149. png_ptr->zstream.next_out = png_ptr->zbuf;
  194150. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194151. }
  194152. }
  194153. }
  194154. if (ret != Z_STREAM_END)
  194155. {
  194156. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194157. char umsg[52];
  194158. if (ret == Z_BUF_ERROR)
  194159. png_snprintf(umsg, 52,
  194160. "Buffer error in compressed datastream in %s chunk",
  194161. png_ptr->chunk_name);
  194162. else if (ret == Z_DATA_ERROR)
  194163. png_snprintf(umsg, 52,
  194164. "Data error in compressed datastream in %s chunk",
  194165. png_ptr->chunk_name);
  194166. else
  194167. png_snprintf(umsg, 52,
  194168. "Incomplete compressed datastream in %s chunk",
  194169. png_ptr->chunk_name);
  194170. png_warning(png_ptr, umsg);
  194171. #else
  194172. png_warning(png_ptr,
  194173. "Incomplete compressed datastream in chunk other than IDAT");
  194174. #endif
  194175. text_size=prefix_size;
  194176. if (text == NULL)
  194177. {
  194178. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194179. if (text == NULL)
  194180. {
  194181. png_free(png_ptr, chunkdata);
  194182. png_error(png_ptr,"Not enough memory for text.");
  194183. }
  194184. png_memcpy(text, chunkdata, prefix_size);
  194185. }
  194186. *(text + text_size) = 0x00;
  194187. }
  194188. inflateReset(&png_ptr->zstream);
  194189. png_ptr->zstream.avail_in = 0;
  194190. png_free(png_ptr, chunkdata);
  194191. chunkdata = text;
  194192. *newlength=text_size;
  194193. }
  194194. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194195. {
  194196. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194197. char umsg[50];
  194198. png_snprintf(umsg, 50,
  194199. "Unknown zTXt compression type %d", comp_type);
  194200. png_warning(png_ptr, umsg);
  194201. #else
  194202. png_warning(png_ptr, "Unknown zTXt compression type");
  194203. #endif
  194204. *(chunkdata + prefix_size) = 0x00;
  194205. *newlength=prefix_size;
  194206. }
  194207. return chunkdata;
  194208. }
  194209. #endif
  194210. /* read and check the IDHR chunk */
  194211. void /* PRIVATE */
  194212. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194213. {
  194214. png_byte buf[13];
  194215. png_uint_32 width, height;
  194216. int bit_depth, color_type, compression_type, filter_type;
  194217. int interlace_type;
  194218. png_debug(1, "in png_handle_IHDR\n");
  194219. if (png_ptr->mode & PNG_HAVE_IHDR)
  194220. png_error(png_ptr, "Out of place IHDR");
  194221. /* check the length */
  194222. if (length != 13)
  194223. png_error(png_ptr, "Invalid IHDR chunk");
  194224. png_ptr->mode |= PNG_HAVE_IHDR;
  194225. png_crc_read(png_ptr, buf, 13);
  194226. png_crc_finish(png_ptr, 0);
  194227. width = png_get_uint_31(png_ptr, buf);
  194228. height = png_get_uint_31(png_ptr, buf + 4);
  194229. bit_depth = buf[8];
  194230. color_type = buf[9];
  194231. compression_type = buf[10];
  194232. filter_type = buf[11];
  194233. interlace_type = buf[12];
  194234. /* set internal variables */
  194235. png_ptr->width = width;
  194236. png_ptr->height = height;
  194237. png_ptr->bit_depth = (png_byte)bit_depth;
  194238. png_ptr->interlaced = (png_byte)interlace_type;
  194239. png_ptr->color_type = (png_byte)color_type;
  194240. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194241. png_ptr->filter_type = (png_byte)filter_type;
  194242. #endif
  194243. png_ptr->compression_type = (png_byte)compression_type;
  194244. /* find number of channels */
  194245. switch (png_ptr->color_type)
  194246. {
  194247. case PNG_COLOR_TYPE_GRAY:
  194248. case PNG_COLOR_TYPE_PALETTE:
  194249. png_ptr->channels = 1;
  194250. break;
  194251. case PNG_COLOR_TYPE_RGB:
  194252. png_ptr->channels = 3;
  194253. break;
  194254. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194255. png_ptr->channels = 2;
  194256. break;
  194257. case PNG_COLOR_TYPE_RGB_ALPHA:
  194258. png_ptr->channels = 4;
  194259. break;
  194260. }
  194261. /* set up other useful info */
  194262. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194263. png_ptr->channels);
  194264. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194265. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194266. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194267. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194268. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194269. color_type, interlace_type, compression_type, filter_type);
  194270. }
  194271. /* read and check the palette */
  194272. void /* PRIVATE */
  194273. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194274. {
  194275. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194276. int num, i;
  194277. #ifndef PNG_NO_POINTER_INDEXING
  194278. png_colorp pal_ptr;
  194279. #endif
  194280. png_debug(1, "in png_handle_PLTE\n");
  194281. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194282. png_error(png_ptr, "Missing IHDR before PLTE");
  194283. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194284. {
  194285. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194286. png_crc_finish(png_ptr, length);
  194287. return;
  194288. }
  194289. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194290. png_error(png_ptr, "Duplicate PLTE chunk");
  194291. png_ptr->mode |= PNG_HAVE_PLTE;
  194292. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194293. {
  194294. png_warning(png_ptr,
  194295. "Ignoring PLTE chunk in grayscale PNG");
  194296. png_crc_finish(png_ptr, length);
  194297. return;
  194298. }
  194299. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194300. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194301. {
  194302. png_crc_finish(png_ptr, length);
  194303. return;
  194304. }
  194305. #endif
  194306. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194307. {
  194308. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194309. {
  194310. png_warning(png_ptr, "Invalid palette chunk");
  194311. png_crc_finish(png_ptr, length);
  194312. return;
  194313. }
  194314. else
  194315. {
  194316. png_error(png_ptr, "Invalid palette chunk");
  194317. }
  194318. }
  194319. num = (int)length / 3;
  194320. #ifndef PNG_NO_POINTER_INDEXING
  194321. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194322. {
  194323. png_byte buf[3];
  194324. png_crc_read(png_ptr, buf, 3);
  194325. pal_ptr->red = buf[0];
  194326. pal_ptr->green = buf[1];
  194327. pal_ptr->blue = buf[2];
  194328. }
  194329. #else
  194330. for (i = 0; i < num; i++)
  194331. {
  194332. png_byte buf[3];
  194333. png_crc_read(png_ptr, buf, 3);
  194334. /* don't depend upon png_color being any order */
  194335. palette[i].red = buf[0];
  194336. palette[i].green = buf[1];
  194337. palette[i].blue = buf[2];
  194338. }
  194339. #endif
  194340. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194341. whatever the normal CRC configuration tells us. However, if we
  194342. have an RGB image, the PLTE can be considered ancillary, so
  194343. we will act as though it is. */
  194344. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194345. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194346. #endif
  194347. {
  194348. png_crc_finish(png_ptr, 0);
  194349. }
  194350. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194351. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194352. {
  194353. /* If we don't want to use the data from an ancillary chunk,
  194354. we have two options: an error abort, or a warning and we
  194355. ignore the data in this chunk (which should be OK, since
  194356. it's considered ancillary for a RGB or RGBA image). */
  194357. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194358. {
  194359. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194360. {
  194361. png_chunk_error(png_ptr, "CRC error");
  194362. }
  194363. else
  194364. {
  194365. png_chunk_warning(png_ptr, "CRC error");
  194366. return;
  194367. }
  194368. }
  194369. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194370. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194371. {
  194372. png_chunk_warning(png_ptr, "CRC error");
  194373. }
  194374. }
  194375. #endif
  194376. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194377. #if defined(PNG_READ_tRNS_SUPPORTED)
  194378. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194379. {
  194380. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194381. {
  194382. if (png_ptr->num_trans > (png_uint_16)num)
  194383. {
  194384. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194385. png_ptr->num_trans = (png_uint_16)num;
  194386. }
  194387. if (info_ptr->num_trans > (png_uint_16)num)
  194388. {
  194389. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194390. info_ptr->num_trans = (png_uint_16)num;
  194391. }
  194392. }
  194393. }
  194394. #endif
  194395. }
  194396. void /* PRIVATE */
  194397. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194398. {
  194399. png_debug(1, "in png_handle_IEND\n");
  194400. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194401. {
  194402. png_error(png_ptr, "No image in file");
  194403. }
  194404. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194405. if (length != 0)
  194406. {
  194407. png_warning(png_ptr, "Incorrect IEND chunk length");
  194408. }
  194409. png_crc_finish(png_ptr, length);
  194410. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194411. }
  194412. #if defined(PNG_READ_gAMA_SUPPORTED)
  194413. void /* PRIVATE */
  194414. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194415. {
  194416. png_fixed_point igamma;
  194417. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194418. float file_gamma;
  194419. #endif
  194420. png_byte buf[4];
  194421. png_debug(1, "in png_handle_gAMA\n");
  194422. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194423. png_error(png_ptr, "Missing IHDR before gAMA");
  194424. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194425. {
  194426. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194427. png_crc_finish(png_ptr, length);
  194428. return;
  194429. }
  194430. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194431. /* Should be an error, but we can cope with it */
  194432. png_warning(png_ptr, "Out of place gAMA chunk");
  194433. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194434. #if defined(PNG_READ_sRGB_SUPPORTED)
  194435. && !(info_ptr->valid & PNG_INFO_sRGB)
  194436. #endif
  194437. )
  194438. {
  194439. png_warning(png_ptr, "Duplicate gAMA chunk");
  194440. png_crc_finish(png_ptr, length);
  194441. return;
  194442. }
  194443. if (length != 4)
  194444. {
  194445. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194446. png_crc_finish(png_ptr, length);
  194447. return;
  194448. }
  194449. png_crc_read(png_ptr, buf, 4);
  194450. if (png_crc_finish(png_ptr, 0))
  194451. return;
  194452. igamma = (png_fixed_point)png_get_uint_32(buf);
  194453. /* check for zero gamma */
  194454. if (igamma == 0)
  194455. {
  194456. png_warning(png_ptr,
  194457. "Ignoring gAMA chunk with gamma=0");
  194458. return;
  194459. }
  194460. #if defined(PNG_READ_sRGB_SUPPORTED)
  194461. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194462. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194463. {
  194464. png_warning(png_ptr,
  194465. "Ignoring incorrect gAMA value when sRGB is also present");
  194466. #ifndef PNG_NO_CONSOLE_IO
  194467. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194468. #endif
  194469. return;
  194470. }
  194471. #endif /* PNG_READ_sRGB_SUPPORTED */
  194472. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194473. file_gamma = (float)igamma / (float)100000.0;
  194474. # ifdef PNG_READ_GAMMA_SUPPORTED
  194475. png_ptr->gamma = file_gamma;
  194476. # endif
  194477. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194478. #endif
  194479. #ifdef PNG_FIXED_POINT_SUPPORTED
  194480. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194481. #endif
  194482. }
  194483. #endif
  194484. #if defined(PNG_READ_sBIT_SUPPORTED)
  194485. void /* PRIVATE */
  194486. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194487. {
  194488. png_size_t truelen;
  194489. png_byte buf[4];
  194490. png_debug(1, "in png_handle_sBIT\n");
  194491. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194492. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194493. png_error(png_ptr, "Missing IHDR before sBIT");
  194494. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194495. {
  194496. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194497. png_crc_finish(png_ptr, length);
  194498. return;
  194499. }
  194500. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194501. {
  194502. /* Should be an error, but we can cope with it */
  194503. png_warning(png_ptr, "Out of place sBIT chunk");
  194504. }
  194505. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194506. {
  194507. png_warning(png_ptr, "Duplicate sBIT chunk");
  194508. png_crc_finish(png_ptr, length);
  194509. return;
  194510. }
  194511. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194512. truelen = 3;
  194513. else
  194514. truelen = (png_size_t)png_ptr->channels;
  194515. if (length != truelen || length > 4)
  194516. {
  194517. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194518. png_crc_finish(png_ptr, length);
  194519. return;
  194520. }
  194521. png_crc_read(png_ptr, buf, truelen);
  194522. if (png_crc_finish(png_ptr, 0))
  194523. return;
  194524. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194525. {
  194526. png_ptr->sig_bit.red = buf[0];
  194527. png_ptr->sig_bit.green = buf[1];
  194528. png_ptr->sig_bit.blue = buf[2];
  194529. png_ptr->sig_bit.alpha = buf[3];
  194530. }
  194531. else
  194532. {
  194533. png_ptr->sig_bit.gray = buf[0];
  194534. png_ptr->sig_bit.red = buf[0];
  194535. png_ptr->sig_bit.green = buf[0];
  194536. png_ptr->sig_bit.blue = buf[0];
  194537. png_ptr->sig_bit.alpha = buf[1];
  194538. }
  194539. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194540. }
  194541. #endif
  194542. #if defined(PNG_READ_cHRM_SUPPORTED)
  194543. void /* PRIVATE */
  194544. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194545. {
  194546. png_byte buf[4];
  194547. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194548. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194549. #endif
  194550. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194551. int_y_green, int_x_blue, int_y_blue;
  194552. png_uint_32 uint_x, uint_y;
  194553. png_debug(1, "in png_handle_cHRM\n");
  194554. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194555. png_error(png_ptr, "Missing IHDR before cHRM");
  194556. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194557. {
  194558. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194559. png_crc_finish(png_ptr, length);
  194560. return;
  194561. }
  194562. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194563. /* Should be an error, but we can cope with it */
  194564. png_warning(png_ptr, "Missing PLTE before cHRM");
  194565. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194566. #if defined(PNG_READ_sRGB_SUPPORTED)
  194567. && !(info_ptr->valid & PNG_INFO_sRGB)
  194568. #endif
  194569. )
  194570. {
  194571. png_warning(png_ptr, "Duplicate cHRM chunk");
  194572. png_crc_finish(png_ptr, length);
  194573. return;
  194574. }
  194575. if (length != 32)
  194576. {
  194577. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194578. png_crc_finish(png_ptr, length);
  194579. return;
  194580. }
  194581. png_crc_read(png_ptr, buf, 4);
  194582. uint_x = png_get_uint_32(buf);
  194583. png_crc_read(png_ptr, buf, 4);
  194584. uint_y = png_get_uint_32(buf);
  194585. if (uint_x > 80000L || uint_y > 80000L ||
  194586. uint_x + uint_y > 100000L)
  194587. {
  194588. png_warning(png_ptr, "Invalid cHRM white point");
  194589. png_crc_finish(png_ptr, 24);
  194590. return;
  194591. }
  194592. int_x_white = (png_fixed_point)uint_x;
  194593. int_y_white = (png_fixed_point)uint_y;
  194594. png_crc_read(png_ptr, buf, 4);
  194595. uint_x = png_get_uint_32(buf);
  194596. png_crc_read(png_ptr, buf, 4);
  194597. uint_y = png_get_uint_32(buf);
  194598. if (uint_x + uint_y > 100000L)
  194599. {
  194600. png_warning(png_ptr, "Invalid cHRM red point");
  194601. png_crc_finish(png_ptr, 16);
  194602. return;
  194603. }
  194604. int_x_red = (png_fixed_point)uint_x;
  194605. int_y_red = (png_fixed_point)uint_y;
  194606. png_crc_read(png_ptr, buf, 4);
  194607. uint_x = png_get_uint_32(buf);
  194608. png_crc_read(png_ptr, buf, 4);
  194609. uint_y = png_get_uint_32(buf);
  194610. if (uint_x + uint_y > 100000L)
  194611. {
  194612. png_warning(png_ptr, "Invalid cHRM green point");
  194613. png_crc_finish(png_ptr, 8);
  194614. return;
  194615. }
  194616. int_x_green = (png_fixed_point)uint_x;
  194617. int_y_green = (png_fixed_point)uint_y;
  194618. png_crc_read(png_ptr, buf, 4);
  194619. uint_x = png_get_uint_32(buf);
  194620. png_crc_read(png_ptr, buf, 4);
  194621. uint_y = png_get_uint_32(buf);
  194622. if (uint_x + uint_y > 100000L)
  194623. {
  194624. png_warning(png_ptr, "Invalid cHRM blue point");
  194625. png_crc_finish(png_ptr, 0);
  194626. return;
  194627. }
  194628. int_x_blue = (png_fixed_point)uint_x;
  194629. int_y_blue = (png_fixed_point)uint_y;
  194630. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194631. white_x = (float)int_x_white / (float)100000.0;
  194632. white_y = (float)int_y_white / (float)100000.0;
  194633. red_x = (float)int_x_red / (float)100000.0;
  194634. red_y = (float)int_y_red / (float)100000.0;
  194635. green_x = (float)int_x_green / (float)100000.0;
  194636. green_y = (float)int_y_green / (float)100000.0;
  194637. blue_x = (float)int_x_blue / (float)100000.0;
  194638. blue_y = (float)int_y_blue / (float)100000.0;
  194639. #endif
  194640. #if defined(PNG_READ_sRGB_SUPPORTED)
  194641. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194642. {
  194643. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194644. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194645. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194646. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194647. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194648. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194649. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194650. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194651. {
  194652. png_warning(png_ptr,
  194653. "Ignoring incorrect cHRM value when sRGB is also present");
  194654. #ifndef PNG_NO_CONSOLE_IO
  194655. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194656. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194657. white_x, white_y, red_x, red_y);
  194658. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194659. green_x, green_y, blue_x, blue_y);
  194660. #else
  194661. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194662. int_x_white, int_y_white, int_x_red, int_y_red);
  194663. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194664. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194665. #endif
  194666. #endif /* PNG_NO_CONSOLE_IO */
  194667. }
  194668. png_crc_finish(png_ptr, 0);
  194669. return;
  194670. }
  194671. #endif /* PNG_READ_sRGB_SUPPORTED */
  194672. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194673. png_set_cHRM(png_ptr, info_ptr,
  194674. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194675. #endif
  194676. #ifdef PNG_FIXED_POINT_SUPPORTED
  194677. png_set_cHRM_fixed(png_ptr, info_ptr,
  194678. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194679. int_y_green, int_x_blue, int_y_blue);
  194680. #endif
  194681. if (png_crc_finish(png_ptr, 0))
  194682. return;
  194683. }
  194684. #endif
  194685. #if defined(PNG_READ_sRGB_SUPPORTED)
  194686. void /* PRIVATE */
  194687. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194688. {
  194689. int intent;
  194690. png_byte buf[1];
  194691. png_debug(1, "in png_handle_sRGB\n");
  194692. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194693. png_error(png_ptr, "Missing IHDR before sRGB");
  194694. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194695. {
  194696. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194697. png_crc_finish(png_ptr, length);
  194698. return;
  194699. }
  194700. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194701. /* Should be an error, but we can cope with it */
  194702. png_warning(png_ptr, "Out of place sRGB chunk");
  194703. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194704. {
  194705. png_warning(png_ptr, "Duplicate sRGB chunk");
  194706. png_crc_finish(png_ptr, length);
  194707. return;
  194708. }
  194709. if (length != 1)
  194710. {
  194711. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194712. png_crc_finish(png_ptr, length);
  194713. return;
  194714. }
  194715. png_crc_read(png_ptr, buf, 1);
  194716. if (png_crc_finish(png_ptr, 0))
  194717. return;
  194718. intent = buf[0];
  194719. /* check for bad intent */
  194720. if (intent >= PNG_sRGB_INTENT_LAST)
  194721. {
  194722. png_warning(png_ptr, "Unknown sRGB intent");
  194723. return;
  194724. }
  194725. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194726. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194727. {
  194728. png_fixed_point igamma;
  194729. #ifdef PNG_FIXED_POINT_SUPPORTED
  194730. igamma=info_ptr->int_gamma;
  194731. #else
  194732. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194733. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194734. # endif
  194735. #endif
  194736. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194737. {
  194738. png_warning(png_ptr,
  194739. "Ignoring incorrect gAMA value when sRGB is also present");
  194740. #ifndef PNG_NO_CONSOLE_IO
  194741. # ifdef PNG_FIXED_POINT_SUPPORTED
  194742. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194743. # else
  194744. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194745. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194746. # endif
  194747. # endif
  194748. #endif
  194749. }
  194750. }
  194751. #endif /* PNG_READ_gAMA_SUPPORTED */
  194752. #ifdef PNG_READ_cHRM_SUPPORTED
  194753. #ifdef PNG_FIXED_POINT_SUPPORTED
  194754. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194755. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194756. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194757. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194758. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194759. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194760. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194761. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194762. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194763. {
  194764. png_warning(png_ptr,
  194765. "Ignoring incorrect cHRM value when sRGB is also present");
  194766. }
  194767. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194768. #endif /* PNG_READ_cHRM_SUPPORTED */
  194769. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194770. }
  194771. #endif /* PNG_READ_sRGB_SUPPORTED */
  194772. #if defined(PNG_READ_iCCP_SUPPORTED)
  194773. void /* PRIVATE */
  194774. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194775. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194776. {
  194777. png_charp chunkdata;
  194778. png_byte compression_type;
  194779. png_bytep pC;
  194780. png_charp profile;
  194781. png_uint_32 skip = 0;
  194782. png_uint_32 profile_size, profile_length;
  194783. png_size_t slength, prefix_length, data_length;
  194784. png_debug(1, "in png_handle_iCCP\n");
  194785. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194786. png_error(png_ptr, "Missing IHDR before iCCP");
  194787. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194788. {
  194789. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194790. png_crc_finish(png_ptr, length);
  194791. return;
  194792. }
  194793. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194794. /* Should be an error, but we can cope with it */
  194795. png_warning(png_ptr, "Out of place iCCP chunk");
  194796. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194797. {
  194798. png_warning(png_ptr, "Duplicate iCCP chunk");
  194799. png_crc_finish(png_ptr, length);
  194800. return;
  194801. }
  194802. #ifdef PNG_MAX_MALLOC_64K
  194803. if (length > (png_uint_32)65535L)
  194804. {
  194805. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194806. skip = length - (png_uint_32)65535L;
  194807. length = (png_uint_32)65535L;
  194808. }
  194809. #endif
  194810. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194811. slength = (png_size_t)length;
  194812. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194813. if (png_crc_finish(png_ptr, skip))
  194814. {
  194815. png_free(png_ptr, chunkdata);
  194816. return;
  194817. }
  194818. chunkdata[slength] = 0x00;
  194819. for (profile = chunkdata; *profile; profile++)
  194820. /* empty loop to find end of name */ ;
  194821. ++profile;
  194822. /* there should be at least one zero (the compression type byte)
  194823. following the separator, and we should be on it */
  194824. if ( profile >= chunkdata + slength - 1)
  194825. {
  194826. png_free(png_ptr, chunkdata);
  194827. png_warning(png_ptr, "Malformed iCCP chunk");
  194828. return;
  194829. }
  194830. /* compression_type should always be zero */
  194831. compression_type = *profile++;
  194832. if (compression_type)
  194833. {
  194834. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194835. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194836. wrote nonzero) */
  194837. }
  194838. prefix_length = profile - chunkdata;
  194839. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194840. slength, prefix_length, &data_length);
  194841. profile_length = data_length - prefix_length;
  194842. if ( prefix_length > data_length || profile_length < 4)
  194843. {
  194844. png_free(png_ptr, chunkdata);
  194845. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194846. return;
  194847. }
  194848. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194849. pC = (png_bytep)(chunkdata+prefix_length);
  194850. profile_size = ((*(pC ))<<24) |
  194851. ((*(pC+1))<<16) |
  194852. ((*(pC+2))<< 8) |
  194853. ((*(pC+3)) );
  194854. if(profile_size < profile_length)
  194855. profile_length = profile_size;
  194856. if(profile_size > profile_length)
  194857. {
  194858. png_free(png_ptr, chunkdata);
  194859. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194860. return;
  194861. }
  194862. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194863. chunkdata + prefix_length, profile_length);
  194864. png_free(png_ptr, chunkdata);
  194865. }
  194866. #endif /* PNG_READ_iCCP_SUPPORTED */
  194867. #if defined(PNG_READ_sPLT_SUPPORTED)
  194868. void /* PRIVATE */
  194869. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194870. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194871. {
  194872. png_bytep chunkdata;
  194873. png_bytep entry_start;
  194874. png_sPLT_t new_palette;
  194875. #ifdef PNG_NO_POINTER_INDEXING
  194876. png_sPLT_entryp pp;
  194877. #endif
  194878. int data_length, entry_size, i;
  194879. png_uint_32 skip = 0;
  194880. png_size_t slength;
  194881. png_debug(1, "in png_handle_sPLT\n");
  194882. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194883. png_error(png_ptr, "Missing IHDR before sPLT");
  194884. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194885. {
  194886. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194887. png_crc_finish(png_ptr, length);
  194888. return;
  194889. }
  194890. #ifdef PNG_MAX_MALLOC_64K
  194891. if (length > (png_uint_32)65535L)
  194892. {
  194893. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194894. skip = length - (png_uint_32)65535L;
  194895. length = (png_uint_32)65535L;
  194896. }
  194897. #endif
  194898. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194899. slength = (png_size_t)length;
  194900. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194901. if (png_crc_finish(png_ptr, skip))
  194902. {
  194903. png_free(png_ptr, chunkdata);
  194904. return;
  194905. }
  194906. chunkdata[slength] = 0x00;
  194907. for (entry_start = chunkdata; *entry_start; entry_start++)
  194908. /* empty loop to find end of name */ ;
  194909. ++entry_start;
  194910. /* a sample depth should follow the separator, and we should be on it */
  194911. if (entry_start > chunkdata + slength - 2)
  194912. {
  194913. png_free(png_ptr, chunkdata);
  194914. png_warning(png_ptr, "malformed sPLT chunk");
  194915. return;
  194916. }
  194917. new_palette.depth = *entry_start++;
  194918. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194919. data_length = (slength - (entry_start - chunkdata));
  194920. /* integrity-check the data length */
  194921. if (data_length % entry_size)
  194922. {
  194923. png_free(png_ptr, chunkdata);
  194924. png_warning(png_ptr, "sPLT chunk has bad length");
  194925. return;
  194926. }
  194927. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194928. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194929. png_sizeof(png_sPLT_entry)))
  194930. {
  194931. png_warning(png_ptr, "sPLT chunk too long");
  194932. return;
  194933. }
  194934. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194935. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194936. if (new_palette.entries == NULL)
  194937. {
  194938. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194939. return;
  194940. }
  194941. #ifndef PNG_NO_POINTER_INDEXING
  194942. for (i = 0; i < new_palette.nentries; i++)
  194943. {
  194944. png_sPLT_entryp pp = new_palette.entries + i;
  194945. if (new_palette.depth == 8)
  194946. {
  194947. pp->red = *entry_start++;
  194948. pp->green = *entry_start++;
  194949. pp->blue = *entry_start++;
  194950. pp->alpha = *entry_start++;
  194951. }
  194952. else
  194953. {
  194954. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194955. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194956. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194957. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194958. }
  194959. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194960. }
  194961. #else
  194962. pp = new_palette.entries;
  194963. for (i = 0; i < new_palette.nentries; i++)
  194964. {
  194965. if (new_palette.depth == 8)
  194966. {
  194967. pp[i].red = *entry_start++;
  194968. pp[i].green = *entry_start++;
  194969. pp[i].blue = *entry_start++;
  194970. pp[i].alpha = *entry_start++;
  194971. }
  194972. else
  194973. {
  194974. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194975. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194976. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194977. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194978. }
  194979. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194980. }
  194981. #endif
  194982. /* discard all chunk data except the name and stash that */
  194983. new_palette.name = (png_charp)chunkdata;
  194984. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194985. png_free(png_ptr, chunkdata);
  194986. png_free(png_ptr, new_palette.entries);
  194987. }
  194988. #endif /* PNG_READ_sPLT_SUPPORTED */
  194989. #if defined(PNG_READ_tRNS_SUPPORTED)
  194990. void /* PRIVATE */
  194991. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194992. {
  194993. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194994. int bit_mask;
  194995. png_debug(1, "in png_handle_tRNS\n");
  194996. /* For non-indexed color, mask off any bits in the tRNS value that
  194997. * exceed the bit depth. Some creators were writing extra bits there.
  194998. * This is not needed for indexed color. */
  194999. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195000. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195001. png_error(png_ptr, "Missing IHDR before tRNS");
  195002. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195003. {
  195004. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195005. png_crc_finish(png_ptr, length);
  195006. return;
  195007. }
  195008. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195009. {
  195010. png_warning(png_ptr, "Duplicate tRNS chunk");
  195011. png_crc_finish(png_ptr, length);
  195012. return;
  195013. }
  195014. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195015. {
  195016. png_byte buf[2];
  195017. if (length != 2)
  195018. {
  195019. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195020. png_crc_finish(png_ptr, length);
  195021. return;
  195022. }
  195023. png_crc_read(png_ptr, buf, 2);
  195024. png_ptr->num_trans = 1;
  195025. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195026. }
  195027. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195028. {
  195029. png_byte buf[6];
  195030. if (length != 6)
  195031. {
  195032. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195033. png_crc_finish(png_ptr, length);
  195034. return;
  195035. }
  195036. png_crc_read(png_ptr, buf, (png_size_t)length);
  195037. png_ptr->num_trans = 1;
  195038. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195039. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195040. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195041. }
  195042. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195043. {
  195044. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195045. {
  195046. /* Should be an error, but we can cope with it. */
  195047. png_warning(png_ptr, "Missing PLTE before tRNS");
  195048. }
  195049. if (length > (png_uint_32)png_ptr->num_palette ||
  195050. length > PNG_MAX_PALETTE_LENGTH)
  195051. {
  195052. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195053. png_crc_finish(png_ptr, length);
  195054. return;
  195055. }
  195056. if (length == 0)
  195057. {
  195058. png_warning(png_ptr, "Zero length tRNS chunk");
  195059. png_crc_finish(png_ptr, length);
  195060. return;
  195061. }
  195062. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195063. png_ptr->num_trans = (png_uint_16)length;
  195064. }
  195065. else
  195066. {
  195067. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195068. png_crc_finish(png_ptr, length);
  195069. return;
  195070. }
  195071. if (png_crc_finish(png_ptr, 0))
  195072. {
  195073. png_ptr->num_trans = 0;
  195074. return;
  195075. }
  195076. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195077. &(png_ptr->trans_values));
  195078. }
  195079. #endif
  195080. #if defined(PNG_READ_bKGD_SUPPORTED)
  195081. void /* PRIVATE */
  195082. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195083. {
  195084. png_size_t truelen;
  195085. png_byte buf[6];
  195086. png_debug(1, "in png_handle_bKGD\n");
  195087. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195088. png_error(png_ptr, "Missing IHDR before bKGD");
  195089. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195090. {
  195091. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195092. png_crc_finish(png_ptr, length);
  195093. return;
  195094. }
  195095. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195096. !(png_ptr->mode & PNG_HAVE_PLTE))
  195097. {
  195098. png_warning(png_ptr, "Missing PLTE before bKGD");
  195099. png_crc_finish(png_ptr, length);
  195100. return;
  195101. }
  195102. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195103. {
  195104. png_warning(png_ptr, "Duplicate bKGD chunk");
  195105. png_crc_finish(png_ptr, length);
  195106. return;
  195107. }
  195108. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195109. truelen = 1;
  195110. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195111. truelen = 6;
  195112. else
  195113. truelen = 2;
  195114. if (length != truelen)
  195115. {
  195116. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195117. png_crc_finish(png_ptr, length);
  195118. return;
  195119. }
  195120. png_crc_read(png_ptr, buf, truelen);
  195121. if (png_crc_finish(png_ptr, 0))
  195122. return;
  195123. /* We convert the index value into RGB components so that we can allow
  195124. * arbitrary RGB values for background when we have transparency, and
  195125. * so it is easy to determine the RGB values of the background color
  195126. * from the info_ptr struct. */
  195127. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195128. {
  195129. png_ptr->background.index = buf[0];
  195130. if(info_ptr->num_palette)
  195131. {
  195132. if(buf[0] > info_ptr->num_palette)
  195133. {
  195134. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195135. return;
  195136. }
  195137. png_ptr->background.red =
  195138. (png_uint_16)png_ptr->palette[buf[0]].red;
  195139. png_ptr->background.green =
  195140. (png_uint_16)png_ptr->palette[buf[0]].green;
  195141. png_ptr->background.blue =
  195142. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195143. }
  195144. }
  195145. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195146. {
  195147. png_ptr->background.red =
  195148. png_ptr->background.green =
  195149. png_ptr->background.blue =
  195150. png_ptr->background.gray = png_get_uint_16(buf);
  195151. }
  195152. else
  195153. {
  195154. png_ptr->background.red = png_get_uint_16(buf);
  195155. png_ptr->background.green = png_get_uint_16(buf + 2);
  195156. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195157. }
  195158. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195159. }
  195160. #endif
  195161. #if defined(PNG_READ_hIST_SUPPORTED)
  195162. void /* PRIVATE */
  195163. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195164. {
  195165. unsigned int num, i;
  195166. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195167. png_debug(1, "in png_handle_hIST\n");
  195168. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195169. png_error(png_ptr, "Missing IHDR before hIST");
  195170. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195171. {
  195172. png_warning(png_ptr, "Invalid hIST after IDAT");
  195173. png_crc_finish(png_ptr, length);
  195174. return;
  195175. }
  195176. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195177. {
  195178. png_warning(png_ptr, "Missing PLTE before hIST");
  195179. png_crc_finish(png_ptr, length);
  195180. return;
  195181. }
  195182. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195183. {
  195184. png_warning(png_ptr, "Duplicate hIST chunk");
  195185. png_crc_finish(png_ptr, length);
  195186. return;
  195187. }
  195188. num = length / 2 ;
  195189. if (num != (unsigned int) png_ptr->num_palette || num >
  195190. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195191. {
  195192. png_warning(png_ptr, "Incorrect hIST chunk length");
  195193. png_crc_finish(png_ptr, length);
  195194. return;
  195195. }
  195196. for (i = 0; i < num; i++)
  195197. {
  195198. png_byte buf[2];
  195199. png_crc_read(png_ptr, buf, 2);
  195200. readbuf[i] = png_get_uint_16(buf);
  195201. }
  195202. if (png_crc_finish(png_ptr, 0))
  195203. return;
  195204. png_set_hIST(png_ptr, info_ptr, readbuf);
  195205. }
  195206. #endif
  195207. #if defined(PNG_READ_pHYs_SUPPORTED)
  195208. void /* PRIVATE */
  195209. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195210. {
  195211. png_byte buf[9];
  195212. png_uint_32 res_x, res_y;
  195213. int unit_type;
  195214. png_debug(1, "in png_handle_pHYs\n");
  195215. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195216. png_error(png_ptr, "Missing IHDR before pHYs");
  195217. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195218. {
  195219. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195220. png_crc_finish(png_ptr, length);
  195221. return;
  195222. }
  195223. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195224. {
  195225. png_warning(png_ptr, "Duplicate pHYs chunk");
  195226. png_crc_finish(png_ptr, length);
  195227. return;
  195228. }
  195229. if (length != 9)
  195230. {
  195231. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195232. png_crc_finish(png_ptr, length);
  195233. return;
  195234. }
  195235. png_crc_read(png_ptr, buf, 9);
  195236. if (png_crc_finish(png_ptr, 0))
  195237. return;
  195238. res_x = png_get_uint_32(buf);
  195239. res_y = png_get_uint_32(buf + 4);
  195240. unit_type = buf[8];
  195241. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195242. }
  195243. #endif
  195244. #if defined(PNG_READ_oFFs_SUPPORTED)
  195245. void /* PRIVATE */
  195246. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195247. {
  195248. png_byte buf[9];
  195249. png_int_32 offset_x, offset_y;
  195250. int unit_type;
  195251. png_debug(1, "in png_handle_oFFs\n");
  195252. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195253. png_error(png_ptr, "Missing IHDR before oFFs");
  195254. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195255. {
  195256. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195257. png_crc_finish(png_ptr, length);
  195258. return;
  195259. }
  195260. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195261. {
  195262. png_warning(png_ptr, "Duplicate oFFs chunk");
  195263. png_crc_finish(png_ptr, length);
  195264. return;
  195265. }
  195266. if (length != 9)
  195267. {
  195268. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195269. png_crc_finish(png_ptr, length);
  195270. return;
  195271. }
  195272. png_crc_read(png_ptr, buf, 9);
  195273. if (png_crc_finish(png_ptr, 0))
  195274. return;
  195275. offset_x = png_get_int_32(buf);
  195276. offset_y = png_get_int_32(buf + 4);
  195277. unit_type = buf[8];
  195278. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195279. }
  195280. #endif
  195281. #if defined(PNG_READ_pCAL_SUPPORTED)
  195282. /* read the pCAL chunk (described in the PNG Extensions document) */
  195283. void /* PRIVATE */
  195284. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195285. {
  195286. png_charp purpose;
  195287. png_int_32 X0, X1;
  195288. png_byte type, nparams;
  195289. png_charp buf, units, endptr;
  195290. png_charpp params;
  195291. png_size_t slength;
  195292. int i;
  195293. png_debug(1, "in png_handle_pCAL\n");
  195294. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195295. png_error(png_ptr, "Missing IHDR before pCAL");
  195296. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195297. {
  195298. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195299. png_crc_finish(png_ptr, length);
  195300. return;
  195301. }
  195302. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195303. {
  195304. png_warning(png_ptr, "Duplicate pCAL chunk");
  195305. png_crc_finish(png_ptr, length);
  195306. return;
  195307. }
  195308. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195309. length + 1);
  195310. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195311. if (purpose == NULL)
  195312. {
  195313. png_warning(png_ptr, "No memory for pCAL purpose.");
  195314. return;
  195315. }
  195316. slength = (png_size_t)length;
  195317. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195318. if (png_crc_finish(png_ptr, 0))
  195319. {
  195320. png_free(png_ptr, purpose);
  195321. return;
  195322. }
  195323. purpose[slength] = 0x00; /* null terminate the last string */
  195324. png_debug(3, "Finding end of pCAL purpose string\n");
  195325. for (buf = purpose; *buf; buf++)
  195326. /* empty loop */ ;
  195327. endptr = purpose + slength;
  195328. /* We need to have at least 12 bytes after the purpose string
  195329. in order to get the parameter information. */
  195330. if (endptr <= buf + 12)
  195331. {
  195332. png_warning(png_ptr, "Invalid pCAL data");
  195333. png_free(png_ptr, purpose);
  195334. return;
  195335. }
  195336. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195337. X0 = png_get_int_32((png_bytep)buf+1);
  195338. X1 = png_get_int_32((png_bytep)buf+5);
  195339. type = buf[9];
  195340. nparams = buf[10];
  195341. units = buf + 11;
  195342. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195343. /* Check that we have the right number of parameters for known
  195344. equation types. */
  195345. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195346. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195347. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195348. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195349. {
  195350. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195351. png_free(png_ptr, purpose);
  195352. return;
  195353. }
  195354. else if (type >= PNG_EQUATION_LAST)
  195355. {
  195356. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195357. }
  195358. for (buf = units; *buf; buf++)
  195359. /* Empty loop to move past the units string. */ ;
  195360. png_debug(3, "Allocating pCAL parameters array\n");
  195361. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195362. *png_sizeof(png_charp))) ;
  195363. if (params == NULL)
  195364. {
  195365. png_free(png_ptr, purpose);
  195366. png_warning(png_ptr, "No memory for pCAL params.");
  195367. return;
  195368. }
  195369. /* Get pointers to the start of each parameter string. */
  195370. for (i = 0; i < (int)nparams; i++)
  195371. {
  195372. buf++; /* Skip the null string terminator from previous parameter. */
  195373. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195374. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195375. /* Empty loop to move past each parameter string */ ;
  195376. /* Make sure we haven't run out of data yet */
  195377. if (buf > endptr)
  195378. {
  195379. png_warning(png_ptr, "Invalid pCAL data");
  195380. png_free(png_ptr, purpose);
  195381. png_free(png_ptr, params);
  195382. return;
  195383. }
  195384. }
  195385. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195386. units, params);
  195387. png_free(png_ptr, purpose);
  195388. png_free(png_ptr, params);
  195389. }
  195390. #endif
  195391. #if defined(PNG_READ_sCAL_SUPPORTED)
  195392. /* read the sCAL chunk */
  195393. void /* PRIVATE */
  195394. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195395. {
  195396. png_charp buffer, ep;
  195397. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195398. double width, height;
  195399. png_charp vp;
  195400. #else
  195401. #ifdef PNG_FIXED_POINT_SUPPORTED
  195402. png_charp swidth, sheight;
  195403. #endif
  195404. #endif
  195405. png_size_t slength;
  195406. png_debug(1, "in png_handle_sCAL\n");
  195407. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195408. png_error(png_ptr, "Missing IHDR before sCAL");
  195409. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195410. {
  195411. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195412. png_crc_finish(png_ptr, length);
  195413. return;
  195414. }
  195415. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195416. {
  195417. png_warning(png_ptr, "Duplicate sCAL chunk");
  195418. png_crc_finish(png_ptr, length);
  195419. return;
  195420. }
  195421. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195422. length + 1);
  195423. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195424. if (buffer == NULL)
  195425. {
  195426. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195427. return;
  195428. }
  195429. slength = (png_size_t)length;
  195430. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195431. if (png_crc_finish(png_ptr, 0))
  195432. {
  195433. png_free(png_ptr, buffer);
  195434. return;
  195435. }
  195436. buffer[slength] = 0x00; /* null terminate the last string */
  195437. ep = buffer + 1; /* skip unit byte */
  195438. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195439. width = png_strtod(png_ptr, ep, &vp);
  195440. if (*vp)
  195441. {
  195442. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195443. return;
  195444. }
  195445. #else
  195446. #ifdef PNG_FIXED_POINT_SUPPORTED
  195447. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195448. if (swidth == NULL)
  195449. {
  195450. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195451. return;
  195452. }
  195453. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195454. #endif
  195455. #endif
  195456. for (ep = buffer; *ep; ep++)
  195457. /* empty loop */ ;
  195458. ep++;
  195459. if (buffer + slength < ep)
  195460. {
  195461. png_warning(png_ptr, "Truncated sCAL chunk");
  195462. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195463. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195464. png_free(png_ptr, swidth);
  195465. #endif
  195466. png_free(png_ptr, buffer);
  195467. return;
  195468. }
  195469. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195470. height = png_strtod(png_ptr, ep, &vp);
  195471. if (*vp)
  195472. {
  195473. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195474. return;
  195475. }
  195476. #else
  195477. #ifdef PNG_FIXED_POINT_SUPPORTED
  195478. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195479. if (swidth == NULL)
  195480. {
  195481. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195482. return;
  195483. }
  195484. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195485. #endif
  195486. #endif
  195487. if (buffer + slength < ep
  195488. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195489. || width <= 0. || height <= 0.
  195490. #endif
  195491. )
  195492. {
  195493. png_warning(png_ptr, "Invalid sCAL data");
  195494. png_free(png_ptr, buffer);
  195495. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195496. png_free(png_ptr, swidth);
  195497. png_free(png_ptr, sheight);
  195498. #endif
  195499. return;
  195500. }
  195501. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195502. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195503. #else
  195504. #ifdef PNG_FIXED_POINT_SUPPORTED
  195505. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195506. #endif
  195507. #endif
  195508. png_free(png_ptr, buffer);
  195509. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195510. png_free(png_ptr, swidth);
  195511. png_free(png_ptr, sheight);
  195512. #endif
  195513. }
  195514. #endif
  195515. #if defined(PNG_READ_tIME_SUPPORTED)
  195516. void /* PRIVATE */
  195517. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195518. {
  195519. png_byte buf[7];
  195520. png_time mod_time;
  195521. png_debug(1, "in png_handle_tIME\n");
  195522. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195523. png_error(png_ptr, "Out of place tIME chunk");
  195524. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195525. {
  195526. png_warning(png_ptr, "Duplicate tIME chunk");
  195527. png_crc_finish(png_ptr, length);
  195528. return;
  195529. }
  195530. if (png_ptr->mode & PNG_HAVE_IDAT)
  195531. png_ptr->mode |= PNG_AFTER_IDAT;
  195532. if (length != 7)
  195533. {
  195534. png_warning(png_ptr, "Incorrect tIME chunk length");
  195535. png_crc_finish(png_ptr, length);
  195536. return;
  195537. }
  195538. png_crc_read(png_ptr, buf, 7);
  195539. if (png_crc_finish(png_ptr, 0))
  195540. return;
  195541. mod_time.second = buf[6];
  195542. mod_time.minute = buf[5];
  195543. mod_time.hour = buf[4];
  195544. mod_time.day = buf[3];
  195545. mod_time.month = buf[2];
  195546. mod_time.year = png_get_uint_16(buf);
  195547. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195548. }
  195549. #endif
  195550. #if defined(PNG_READ_tEXt_SUPPORTED)
  195551. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195552. void /* PRIVATE */
  195553. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195554. {
  195555. png_textp text_ptr;
  195556. png_charp key;
  195557. png_charp text;
  195558. png_uint_32 skip = 0;
  195559. png_size_t slength;
  195560. int ret;
  195561. png_debug(1, "in png_handle_tEXt\n");
  195562. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195563. png_error(png_ptr, "Missing IHDR before tEXt");
  195564. if (png_ptr->mode & PNG_HAVE_IDAT)
  195565. png_ptr->mode |= PNG_AFTER_IDAT;
  195566. #ifdef PNG_MAX_MALLOC_64K
  195567. if (length > (png_uint_32)65535L)
  195568. {
  195569. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195570. skip = length - (png_uint_32)65535L;
  195571. length = (png_uint_32)65535L;
  195572. }
  195573. #endif
  195574. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195575. if (key == NULL)
  195576. {
  195577. png_warning(png_ptr, "No memory to process text chunk.");
  195578. return;
  195579. }
  195580. slength = (png_size_t)length;
  195581. png_crc_read(png_ptr, (png_bytep)key, slength);
  195582. if (png_crc_finish(png_ptr, skip))
  195583. {
  195584. png_free(png_ptr, key);
  195585. return;
  195586. }
  195587. key[slength] = 0x00;
  195588. for (text = key; *text; text++)
  195589. /* empty loop to find end of key */ ;
  195590. if (text != key + slength)
  195591. text++;
  195592. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195593. (png_uint_32)png_sizeof(png_text));
  195594. if (text_ptr == NULL)
  195595. {
  195596. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195597. png_free(png_ptr, key);
  195598. return;
  195599. }
  195600. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195601. text_ptr->key = key;
  195602. #ifdef PNG_iTXt_SUPPORTED
  195603. text_ptr->lang = NULL;
  195604. text_ptr->lang_key = NULL;
  195605. text_ptr->itxt_length = 0;
  195606. #endif
  195607. text_ptr->text = text;
  195608. text_ptr->text_length = png_strlen(text);
  195609. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195610. png_free(png_ptr, key);
  195611. png_free(png_ptr, text_ptr);
  195612. if (ret)
  195613. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195614. }
  195615. #endif
  195616. #if defined(PNG_READ_zTXt_SUPPORTED)
  195617. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195618. void /* PRIVATE */
  195619. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195620. {
  195621. png_textp text_ptr;
  195622. png_charp chunkdata;
  195623. png_charp text;
  195624. int comp_type;
  195625. int ret;
  195626. png_size_t slength, prefix_len, data_len;
  195627. png_debug(1, "in png_handle_zTXt\n");
  195628. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195629. png_error(png_ptr, "Missing IHDR before zTXt");
  195630. if (png_ptr->mode & PNG_HAVE_IDAT)
  195631. png_ptr->mode |= PNG_AFTER_IDAT;
  195632. #ifdef PNG_MAX_MALLOC_64K
  195633. /* We will no doubt have problems with chunks even half this size, but
  195634. there is no hard and fast rule to tell us where to stop. */
  195635. if (length > (png_uint_32)65535L)
  195636. {
  195637. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195638. png_crc_finish(png_ptr, length);
  195639. return;
  195640. }
  195641. #endif
  195642. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195643. if (chunkdata == NULL)
  195644. {
  195645. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195646. return;
  195647. }
  195648. slength = (png_size_t)length;
  195649. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195650. if (png_crc_finish(png_ptr, 0))
  195651. {
  195652. png_free(png_ptr, chunkdata);
  195653. return;
  195654. }
  195655. chunkdata[slength] = 0x00;
  195656. for (text = chunkdata; *text; text++)
  195657. /* empty loop */ ;
  195658. /* zTXt must have some text after the chunkdataword */
  195659. if (text >= chunkdata + slength - 2)
  195660. {
  195661. png_warning(png_ptr, "Truncated zTXt chunk");
  195662. png_free(png_ptr, chunkdata);
  195663. return;
  195664. }
  195665. else
  195666. {
  195667. comp_type = *(++text);
  195668. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195669. {
  195670. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195671. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195672. }
  195673. text++; /* skip the compression_method byte */
  195674. }
  195675. prefix_len = text - chunkdata;
  195676. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195677. (png_size_t)length, prefix_len, &data_len);
  195678. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195679. (png_uint_32)png_sizeof(png_text));
  195680. if (text_ptr == NULL)
  195681. {
  195682. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195683. png_free(png_ptr, chunkdata);
  195684. return;
  195685. }
  195686. text_ptr->compression = comp_type;
  195687. text_ptr->key = chunkdata;
  195688. #ifdef PNG_iTXt_SUPPORTED
  195689. text_ptr->lang = NULL;
  195690. text_ptr->lang_key = NULL;
  195691. text_ptr->itxt_length = 0;
  195692. #endif
  195693. text_ptr->text = chunkdata + prefix_len;
  195694. text_ptr->text_length = data_len;
  195695. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195696. png_free(png_ptr, text_ptr);
  195697. png_free(png_ptr, chunkdata);
  195698. if (ret)
  195699. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195700. }
  195701. #endif
  195702. #if defined(PNG_READ_iTXt_SUPPORTED)
  195703. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195704. void /* PRIVATE */
  195705. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195706. {
  195707. png_textp text_ptr;
  195708. png_charp chunkdata;
  195709. png_charp key, lang, text, lang_key;
  195710. int comp_flag;
  195711. int comp_type = 0;
  195712. int ret;
  195713. png_size_t slength, prefix_len, data_len;
  195714. png_debug(1, "in png_handle_iTXt\n");
  195715. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195716. png_error(png_ptr, "Missing IHDR before iTXt");
  195717. if (png_ptr->mode & PNG_HAVE_IDAT)
  195718. png_ptr->mode |= PNG_AFTER_IDAT;
  195719. #ifdef PNG_MAX_MALLOC_64K
  195720. /* We will no doubt have problems with chunks even half this size, but
  195721. there is no hard and fast rule to tell us where to stop. */
  195722. if (length > (png_uint_32)65535L)
  195723. {
  195724. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195725. png_crc_finish(png_ptr, length);
  195726. return;
  195727. }
  195728. #endif
  195729. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195730. if (chunkdata == NULL)
  195731. {
  195732. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195733. return;
  195734. }
  195735. slength = (png_size_t)length;
  195736. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195737. if (png_crc_finish(png_ptr, 0))
  195738. {
  195739. png_free(png_ptr, chunkdata);
  195740. return;
  195741. }
  195742. chunkdata[slength] = 0x00;
  195743. for (lang = chunkdata; *lang; lang++)
  195744. /* empty loop */ ;
  195745. lang++; /* skip NUL separator */
  195746. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195747. translated keyword (possibly empty), and possibly some text after the
  195748. keyword */
  195749. if (lang >= chunkdata + slength - 3)
  195750. {
  195751. png_warning(png_ptr, "Truncated iTXt chunk");
  195752. png_free(png_ptr, chunkdata);
  195753. return;
  195754. }
  195755. else
  195756. {
  195757. comp_flag = *lang++;
  195758. comp_type = *lang++;
  195759. }
  195760. for (lang_key = lang; *lang_key; lang_key++)
  195761. /* empty loop */ ;
  195762. lang_key++; /* skip NUL separator */
  195763. if (lang_key >= chunkdata + slength)
  195764. {
  195765. png_warning(png_ptr, "Truncated iTXt chunk");
  195766. png_free(png_ptr, chunkdata);
  195767. return;
  195768. }
  195769. for (text = lang_key; *text; text++)
  195770. /* empty loop */ ;
  195771. text++; /* skip NUL separator */
  195772. if (text >= chunkdata + slength)
  195773. {
  195774. png_warning(png_ptr, "Malformed iTXt chunk");
  195775. png_free(png_ptr, chunkdata);
  195776. return;
  195777. }
  195778. prefix_len = text - chunkdata;
  195779. key=chunkdata;
  195780. if (comp_flag)
  195781. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195782. (size_t)length, prefix_len, &data_len);
  195783. else
  195784. data_len=png_strlen(chunkdata + prefix_len);
  195785. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195786. (png_uint_32)png_sizeof(png_text));
  195787. if (text_ptr == NULL)
  195788. {
  195789. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195790. png_free(png_ptr, chunkdata);
  195791. return;
  195792. }
  195793. text_ptr->compression = (int)comp_flag + 1;
  195794. text_ptr->lang_key = chunkdata+(lang_key-key);
  195795. text_ptr->lang = chunkdata+(lang-key);
  195796. text_ptr->itxt_length = data_len;
  195797. text_ptr->text_length = 0;
  195798. text_ptr->key = chunkdata;
  195799. text_ptr->text = chunkdata + prefix_len;
  195800. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195801. png_free(png_ptr, text_ptr);
  195802. png_free(png_ptr, chunkdata);
  195803. if (ret)
  195804. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195805. }
  195806. #endif
  195807. /* This function is called when we haven't found a handler for a
  195808. chunk. If there isn't a problem with the chunk itself (ie bad
  195809. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195810. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195811. case it will be saved away to be written out later. */
  195812. void /* PRIVATE */
  195813. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195814. {
  195815. png_uint_32 skip = 0;
  195816. png_debug(1, "in png_handle_unknown\n");
  195817. if (png_ptr->mode & PNG_HAVE_IDAT)
  195818. {
  195819. #ifdef PNG_USE_LOCAL_ARRAYS
  195820. PNG_CONST PNG_IDAT;
  195821. #endif
  195822. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195823. png_ptr->mode |= PNG_AFTER_IDAT;
  195824. }
  195825. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195826. if (!(png_ptr->chunk_name[0] & 0x20))
  195827. {
  195828. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195829. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195830. PNG_HANDLE_CHUNK_ALWAYS
  195831. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195832. && png_ptr->read_user_chunk_fn == NULL
  195833. #endif
  195834. )
  195835. #endif
  195836. png_chunk_error(png_ptr, "unknown critical chunk");
  195837. }
  195838. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195839. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195840. (png_ptr->read_user_chunk_fn != NULL))
  195841. {
  195842. #ifdef PNG_MAX_MALLOC_64K
  195843. if (length > (png_uint_32)65535L)
  195844. {
  195845. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195846. skip = length - (png_uint_32)65535L;
  195847. length = (png_uint_32)65535L;
  195848. }
  195849. #endif
  195850. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195851. (png_charp)png_ptr->chunk_name, 5);
  195852. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195853. png_ptr->unknown_chunk.size = (png_size_t)length;
  195854. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195855. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195856. if(png_ptr->read_user_chunk_fn != NULL)
  195857. {
  195858. /* callback to user unknown chunk handler */
  195859. int ret;
  195860. ret = (*(png_ptr->read_user_chunk_fn))
  195861. (png_ptr, &png_ptr->unknown_chunk);
  195862. if (ret < 0)
  195863. png_chunk_error(png_ptr, "error in user chunk");
  195864. if (ret == 0)
  195865. {
  195866. if (!(png_ptr->chunk_name[0] & 0x20))
  195867. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195868. PNG_HANDLE_CHUNK_ALWAYS)
  195869. png_chunk_error(png_ptr, "unknown critical chunk");
  195870. png_set_unknown_chunks(png_ptr, info_ptr,
  195871. &png_ptr->unknown_chunk, 1);
  195872. }
  195873. }
  195874. #else
  195875. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195876. #endif
  195877. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195878. png_ptr->unknown_chunk.data = NULL;
  195879. }
  195880. else
  195881. #endif
  195882. skip = length;
  195883. png_crc_finish(png_ptr, skip);
  195884. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195885. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195886. #endif
  195887. }
  195888. /* This function is called to verify that a chunk name is valid.
  195889. This function can't have the "critical chunk check" incorporated
  195890. into it, since in the future we will need to be able to call user
  195891. functions to handle unknown critical chunks after we check that
  195892. the chunk name itself is valid. */
  195893. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195894. void /* PRIVATE */
  195895. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195896. {
  195897. png_debug(1, "in png_check_chunk_name\n");
  195898. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195899. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195900. {
  195901. png_chunk_error(png_ptr, "invalid chunk type");
  195902. }
  195903. }
  195904. /* Combines the row recently read in with the existing pixels in the
  195905. row. This routine takes care of alpha and transparency if requested.
  195906. This routine also handles the two methods of progressive display
  195907. of interlaced images, depending on the mask value.
  195908. The mask value describes which pixels are to be combined with
  195909. the row. The pattern always repeats every 8 pixels, so just 8
  195910. bits are needed. A one indicates the pixel is to be combined,
  195911. a zero indicates the pixel is to be skipped. This is in addition
  195912. to any alpha or transparency value associated with the pixel. If
  195913. you want all pixels to be combined, pass 0xff (255) in mask. */
  195914. void /* PRIVATE */
  195915. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195916. {
  195917. png_debug(1,"in png_combine_row\n");
  195918. if (mask == 0xff)
  195919. {
  195920. png_memcpy(row, png_ptr->row_buf + 1,
  195921. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195922. }
  195923. else
  195924. {
  195925. switch (png_ptr->row_info.pixel_depth)
  195926. {
  195927. case 1:
  195928. {
  195929. png_bytep sp = png_ptr->row_buf + 1;
  195930. png_bytep dp = row;
  195931. int s_inc, s_start, s_end;
  195932. int m = 0x80;
  195933. int shift;
  195934. png_uint_32 i;
  195935. png_uint_32 row_width = png_ptr->width;
  195936. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195937. if (png_ptr->transformations & PNG_PACKSWAP)
  195938. {
  195939. s_start = 0;
  195940. s_end = 7;
  195941. s_inc = 1;
  195942. }
  195943. else
  195944. #endif
  195945. {
  195946. s_start = 7;
  195947. s_end = 0;
  195948. s_inc = -1;
  195949. }
  195950. shift = s_start;
  195951. for (i = 0; i < row_width; i++)
  195952. {
  195953. if (m & mask)
  195954. {
  195955. int value;
  195956. value = (*sp >> shift) & 0x01;
  195957. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195958. *dp |= (png_byte)(value << shift);
  195959. }
  195960. if (shift == s_end)
  195961. {
  195962. shift = s_start;
  195963. sp++;
  195964. dp++;
  195965. }
  195966. else
  195967. shift += s_inc;
  195968. if (m == 1)
  195969. m = 0x80;
  195970. else
  195971. m >>= 1;
  195972. }
  195973. break;
  195974. }
  195975. case 2:
  195976. {
  195977. png_bytep sp = png_ptr->row_buf + 1;
  195978. png_bytep dp = row;
  195979. int s_start, s_end, s_inc;
  195980. int m = 0x80;
  195981. int shift;
  195982. png_uint_32 i;
  195983. png_uint_32 row_width = png_ptr->width;
  195984. int value;
  195985. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195986. if (png_ptr->transformations & PNG_PACKSWAP)
  195987. {
  195988. s_start = 0;
  195989. s_end = 6;
  195990. s_inc = 2;
  195991. }
  195992. else
  195993. #endif
  195994. {
  195995. s_start = 6;
  195996. s_end = 0;
  195997. s_inc = -2;
  195998. }
  195999. shift = s_start;
  196000. for (i = 0; i < row_width; i++)
  196001. {
  196002. if (m & mask)
  196003. {
  196004. value = (*sp >> shift) & 0x03;
  196005. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196006. *dp |= (png_byte)(value << shift);
  196007. }
  196008. if (shift == s_end)
  196009. {
  196010. shift = s_start;
  196011. sp++;
  196012. dp++;
  196013. }
  196014. else
  196015. shift += s_inc;
  196016. if (m == 1)
  196017. m = 0x80;
  196018. else
  196019. m >>= 1;
  196020. }
  196021. break;
  196022. }
  196023. case 4:
  196024. {
  196025. png_bytep sp = png_ptr->row_buf + 1;
  196026. png_bytep dp = row;
  196027. int s_start, s_end, s_inc;
  196028. int m = 0x80;
  196029. int shift;
  196030. png_uint_32 i;
  196031. png_uint_32 row_width = png_ptr->width;
  196032. int value;
  196033. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196034. if (png_ptr->transformations & PNG_PACKSWAP)
  196035. {
  196036. s_start = 0;
  196037. s_end = 4;
  196038. s_inc = 4;
  196039. }
  196040. else
  196041. #endif
  196042. {
  196043. s_start = 4;
  196044. s_end = 0;
  196045. s_inc = -4;
  196046. }
  196047. shift = s_start;
  196048. for (i = 0; i < row_width; i++)
  196049. {
  196050. if (m & mask)
  196051. {
  196052. value = (*sp >> shift) & 0xf;
  196053. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196054. *dp |= (png_byte)(value << shift);
  196055. }
  196056. if (shift == s_end)
  196057. {
  196058. shift = s_start;
  196059. sp++;
  196060. dp++;
  196061. }
  196062. else
  196063. shift += s_inc;
  196064. if (m == 1)
  196065. m = 0x80;
  196066. else
  196067. m >>= 1;
  196068. }
  196069. break;
  196070. }
  196071. default:
  196072. {
  196073. png_bytep sp = png_ptr->row_buf + 1;
  196074. png_bytep dp = row;
  196075. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196076. png_uint_32 i;
  196077. png_uint_32 row_width = png_ptr->width;
  196078. png_byte m = 0x80;
  196079. for (i = 0; i < row_width; i++)
  196080. {
  196081. if (m & mask)
  196082. {
  196083. png_memcpy(dp, sp, pixel_bytes);
  196084. }
  196085. sp += pixel_bytes;
  196086. dp += pixel_bytes;
  196087. if (m == 1)
  196088. m = 0x80;
  196089. else
  196090. m >>= 1;
  196091. }
  196092. break;
  196093. }
  196094. }
  196095. }
  196096. }
  196097. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196098. /* OLD pre-1.0.9 interface:
  196099. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196100. png_uint_32 transformations)
  196101. */
  196102. void /* PRIVATE */
  196103. png_do_read_interlace(png_structp png_ptr)
  196104. {
  196105. png_row_infop row_info = &(png_ptr->row_info);
  196106. png_bytep row = png_ptr->row_buf + 1;
  196107. int pass = png_ptr->pass;
  196108. png_uint_32 transformations = png_ptr->transformations;
  196109. #ifdef PNG_USE_LOCAL_ARRAYS
  196110. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196111. /* offset to next interlace block */
  196112. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196113. #endif
  196114. png_debug(1,"in png_do_read_interlace\n");
  196115. if (row != NULL && row_info != NULL)
  196116. {
  196117. png_uint_32 final_width;
  196118. final_width = row_info->width * png_pass_inc[pass];
  196119. switch (row_info->pixel_depth)
  196120. {
  196121. case 1:
  196122. {
  196123. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196124. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196125. int sshift, dshift;
  196126. int s_start, s_end, s_inc;
  196127. int jstop = png_pass_inc[pass];
  196128. png_byte v;
  196129. png_uint_32 i;
  196130. int j;
  196131. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196132. if (transformations & PNG_PACKSWAP)
  196133. {
  196134. sshift = (int)((row_info->width + 7) & 0x07);
  196135. dshift = (int)((final_width + 7) & 0x07);
  196136. s_start = 7;
  196137. s_end = 0;
  196138. s_inc = -1;
  196139. }
  196140. else
  196141. #endif
  196142. {
  196143. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196144. dshift = 7 - (int)((final_width + 7) & 0x07);
  196145. s_start = 0;
  196146. s_end = 7;
  196147. s_inc = 1;
  196148. }
  196149. for (i = 0; i < row_info->width; i++)
  196150. {
  196151. v = (png_byte)((*sp >> sshift) & 0x01);
  196152. for (j = 0; j < jstop; j++)
  196153. {
  196154. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196155. *dp |= (png_byte)(v << dshift);
  196156. if (dshift == s_end)
  196157. {
  196158. dshift = s_start;
  196159. dp--;
  196160. }
  196161. else
  196162. dshift += s_inc;
  196163. }
  196164. if (sshift == s_end)
  196165. {
  196166. sshift = s_start;
  196167. sp--;
  196168. }
  196169. else
  196170. sshift += s_inc;
  196171. }
  196172. break;
  196173. }
  196174. case 2:
  196175. {
  196176. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196177. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196178. int sshift, dshift;
  196179. int s_start, s_end, s_inc;
  196180. int jstop = png_pass_inc[pass];
  196181. png_uint_32 i;
  196182. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196183. if (transformations & PNG_PACKSWAP)
  196184. {
  196185. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196186. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196187. s_start = 6;
  196188. s_end = 0;
  196189. s_inc = -2;
  196190. }
  196191. else
  196192. #endif
  196193. {
  196194. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196195. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196196. s_start = 0;
  196197. s_end = 6;
  196198. s_inc = 2;
  196199. }
  196200. for (i = 0; i < row_info->width; i++)
  196201. {
  196202. png_byte v;
  196203. int j;
  196204. v = (png_byte)((*sp >> sshift) & 0x03);
  196205. for (j = 0; j < jstop; j++)
  196206. {
  196207. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196208. *dp |= (png_byte)(v << dshift);
  196209. if (dshift == s_end)
  196210. {
  196211. dshift = s_start;
  196212. dp--;
  196213. }
  196214. else
  196215. dshift += s_inc;
  196216. }
  196217. if (sshift == s_end)
  196218. {
  196219. sshift = s_start;
  196220. sp--;
  196221. }
  196222. else
  196223. sshift += s_inc;
  196224. }
  196225. break;
  196226. }
  196227. case 4:
  196228. {
  196229. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196230. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196231. int sshift, dshift;
  196232. int s_start, s_end, s_inc;
  196233. png_uint_32 i;
  196234. int jstop = png_pass_inc[pass];
  196235. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196236. if (transformations & PNG_PACKSWAP)
  196237. {
  196238. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196239. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196240. s_start = 4;
  196241. s_end = 0;
  196242. s_inc = -4;
  196243. }
  196244. else
  196245. #endif
  196246. {
  196247. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196248. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196249. s_start = 0;
  196250. s_end = 4;
  196251. s_inc = 4;
  196252. }
  196253. for (i = 0; i < row_info->width; i++)
  196254. {
  196255. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196256. int j;
  196257. for (j = 0; j < jstop; j++)
  196258. {
  196259. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196260. *dp |= (png_byte)(v << dshift);
  196261. if (dshift == s_end)
  196262. {
  196263. dshift = s_start;
  196264. dp--;
  196265. }
  196266. else
  196267. dshift += s_inc;
  196268. }
  196269. if (sshift == s_end)
  196270. {
  196271. sshift = s_start;
  196272. sp--;
  196273. }
  196274. else
  196275. sshift += s_inc;
  196276. }
  196277. break;
  196278. }
  196279. default:
  196280. {
  196281. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196282. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196283. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196284. int jstop = png_pass_inc[pass];
  196285. png_uint_32 i;
  196286. for (i = 0; i < row_info->width; i++)
  196287. {
  196288. png_byte v[8];
  196289. int j;
  196290. png_memcpy(v, sp, pixel_bytes);
  196291. for (j = 0; j < jstop; j++)
  196292. {
  196293. png_memcpy(dp, v, pixel_bytes);
  196294. dp -= pixel_bytes;
  196295. }
  196296. sp -= pixel_bytes;
  196297. }
  196298. break;
  196299. }
  196300. }
  196301. row_info->width = final_width;
  196302. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196303. }
  196304. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196305. transformations = transformations; /* silence compiler warning */
  196306. #endif
  196307. }
  196308. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196309. void /* PRIVATE */
  196310. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196311. png_bytep prev_row, int filter)
  196312. {
  196313. png_debug(1, "in png_read_filter_row\n");
  196314. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196315. switch (filter)
  196316. {
  196317. case PNG_FILTER_VALUE_NONE:
  196318. break;
  196319. case PNG_FILTER_VALUE_SUB:
  196320. {
  196321. png_uint_32 i;
  196322. png_uint_32 istop = row_info->rowbytes;
  196323. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196324. png_bytep rp = row + bpp;
  196325. png_bytep lp = row;
  196326. for (i = bpp; i < istop; i++)
  196327. {
  196328. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196329. rp++;
  196330. }
  196331. break;
  196332. }
  196333. case PNG_FILTER_VALUE_UP:
  196334. {
  196335. png_uint_32 i;
  196336. png_uint_32 istop = row_info->rowbytes;
  196337. png_bytep rp = row;
  196338. png_bytep pp = prev_row;
  196339. for (i = 0; i < istop; i++)
  196340. {
  196341. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196342. rp++;
  196343. }
  196344. break;
  196345. }
  196346. case PNG_FILTER_VALUE_AVG:
  196347. {
  196348. png_uint_32 i;
  196349. png_bytep rp = row;
  196350. png_bytep pp = prev_row;
  196351. png_bytep lp = row;
  196352. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196353. png_uint_32 istop = row_info->rowbytes - bpp;
  196354. for (i = 0; i < bpp; i++)
  196355. {
  196356. *rp = (png_byte)(((int)(*rp) +
  196357. ((int)(*pp++) / 2 )) & 0xff);
  196358. rp++;
  196359. }
  196360. for (i = 0; i < istop; i++)
  196361. {
  196362. *rp = (png_byte)(((int)(*rp) +
  196363. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196364. rp++;
  196365. }
  196366. break;
  196367. }
  196368. case PNG_FILTER_VALUE_PAETH:
  196369. {
  196370. png_uint_32 i;
  196371. png_bytep rp = row;
  196372. png_bytep pp = prev_row;
  196373. png_bytep lp = row;
  196374. png_bytep cp = prev_row;
  196375. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196376. png_uint_32 istop=row_info->rowbytes - bpp;
  196377. for (i = 0; i < bpp; i++)
  196378. {
  196379. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196380. rp++;
  196381. }
  196382. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196383. {
  196384. int a, b, c, pa, pb, pc, p;
  196385. a = *lp++;
  196386. b = *pp++;
  196387. c = *cp++;
  196388. p = b - c;
  196389. pc = a - c;
  196390. #ifdef PNG_USE_ABS
  196391. pa = abs(p);
  196392. pb = abs(pc);
  196393. pc = abs(p + pc);
  196394. #else
  196395. pa = p < 0 ? -p : p;
  196396. pb = pc < 0 ? -pc : pc;
  196397. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196398. #endif
  196399. /*
  196400. if (pa <= pb && pa <= pc)
  196401. p = a;
  196402. else if (pb <= pc)
  196403. p = b;
  196404. else
  196405. p = c;
  196406. */
  196407. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196408. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196409. rp++;
  196410. }
  196411. break;
  196412. }
  196413. default:
  196414. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196415. *row=0;
  196416. break;
  196417. }
  196418. }
  196419. void /* PRIVATE */
  196420. png_read_finish_row(png_structp png_ptr)
  196421. {
  196422. #ifdef PNG_USE_LOCAL_ARRAYS
  196423. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196424. /* start of interlace block */
  196425. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196426. /* offset to next interlace block */
  196427. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196428. /* start of interlace block in the y direction */
  196429. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196430. /* offset to next interlace block in the y direction */
  196431. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196432. #endif
  196433. png_debug(1, "in png_read_finish_row\n");
  196434. png_ptr->row_number++;
  196435. if (png_ptr->row_number < png_ptr->num_rows)
  196436. return;
  196437. if (png_ptr->interlaced)
  196438. {
  196439. png_ptr->row_number = 0;
  196440. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196441. png_ptr->rowbytes + 1);
  196442. do
  196443. {
  196444. png_ptr->pass++;
  196445. if (png_ptr->pass >= 7)
  196446. break;
  196447. png_ptr->iwidth = (png_ptr->width +
  196448. png_pass_inc[png_ptr->pass] - 1 -
  196449. png_pass_start[png_ptr->pass]) /
  196450. png_pass_inc[png_ptr->pass];
  196451. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196452. png_ptr->iwidth) + 1;
  196453. if (!(png_ptr->transformations & PNG_INTERLACE))
  196454. {
  196455. png_ptr->num_rows = (png_ptr->height +
  196456. png_pass_yinc[png_ptr->pass] - 1 -
  196457. png_pass_ystart[png_ptr->pass]) /
  196458. png_pass_yinc[png_ptr->pass];
  196459. if (!(png_ptr->num_rows))
  196460. continue;
  196461. }
  196462. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196463. break;
  196464. } while (png_ptr->iwidth == 0);
  196465. if (png_ptr->pass < 7)
  196466. return;
  196467. }
  196468. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196469. {
  196470. #ifdef PNG_USE_LOCAL_ARRAYS
  196471. PNG_CONST PNG_IDAT;
  196472. #endif
  196473. char extra;
  196474. int ret;
  196475. png_ptr->zstream.next_out = (Bytef *)&extra;
  196476. png_ptr->zstream.avail_out = (uInt)1;
  196477. for(;;)
  196478. {
  196479. if (!(png_ptr->zstream.avail_in))
  196480. {
  196481. while (!png_ptr->idat_size)
  196482. {
  196483. png_byte chunk_length[4];
  196484. png_crc_finish(png_ptr, 0);
  196485. png_read_data(png_ptr, chunk_length, 4);
  196486. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196487. png_reset_crc(png_ptr);
  196488. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196489. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196490. png_error(png_ptr, "Not enough image data");
  196491. }
  196492. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196493. png_ptr->zstream.next_in = png_ptr->zbuf;
  196494. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196495. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196496. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196497. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196498. }
  196499. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196500. if (ret == Z_STREAM_END)
  196501. {
  196502. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196503. png_ptr->idat_size)
  196504. png_warning(png_ptr, "Extra compressed data");
  196505. png_ptr->mode |= PNG_AFTER_IDAT;
  196506. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196507. break;
  196508. }
  196509. if (ret != Z_OK)
  196510. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196511. "Decompression Error");
  196512. if (!(png_ptr->zstream.avail_out))
  196513. {
  196514. png_warning(png_ptr, "Extra compressed data.");
  196515. png_ptr->mode |= PNG_AFTER_IDAT;
  196516. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196517. break;
  196518. }
  196519. }
  196520. png_ptr->zstream.avail_out = 0;
  196521. }
  196522. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196523. png_warning(png_ptr, "Extra compression data");
  196524. inflateReset(&png_ptr->zstream);
  196525. png_ptr->mode |= PNG_AFTER_IDAT;
  196526. }
  196527. void /* PRIVATE */
  196528. png_read_start_row(png_structp png_ptr)
  196529. {
  196530. #ifdef PNG_USE_LOCAL_ARRAYS
  196531. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196532. /* start of interlace block */
  196533. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196534. /* offset to next interlace block */
  196535. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196536. /* start of interlace block in the y direction */
  196537. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196538. /* offset to next interlace block in the y direction */
  196539. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196540. #endif
  196541. int max_pixel_depth;
  196542. png_uint_32 row_bytes;
  196543. png_debug(1, "in png_read_start_row\n");
  196544. png_ptr->zstream.avail_in = 0;
  196545. png_init_read_transformations(png_ptr);
  196546. if (png_ptr->interlaced)
  196547. {
  196548. if (!(png_ptr->transformations & PNG_INTERLACE))
  196549. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196550. png_pass_ystart[0]) / png_pass_yinc[0];
  196551. else
  196552. png_ptr->num_rows = png_ptr->height;
  196553. png_ptr->iwidth = (png_ptr->width +
  196554. png_pass_inc[png_ptr->pass] - 1 -
  196555. png_pass_start[png_ptr->pass]) /
  196556. png_pass_inc[png_ptr->pass];
  196557. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196558. png_ptr->irowbytes = (png_size_t)row_bytes;
  196559. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196560. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196561. }
  196562. else
  196563. {
  196564. png_ptr->num_rows = png_ptr->height;
  196565. png_ptr->iwidth = png_ptr->width;
  196566. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196567. }
  196568. max_pixel_depth = png_ptr->pixel_depth;
  196569. #if defined(PNG_READ_PACK_SUPPORTED)
  196570. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196571. max_pixel_depth = 8;
  196572. #endif
  196573. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196574. if (png_ptr->transformations & PNG_EXPAND)
  196575. {
  196576. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196577. {
  196578. if (png_ptr->num_trans)
  196579. max_pixel_depth = 32;
  196580. else
  196581. max_pixel_depth = 24;
  196582. }
  196583. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196584. {
  196585. if (max_pixel_depth < 8)
  196586. max_pixel_depth = 8;
  196587. if (png_ptr->num_trans)
  196588. max_pixel_depth *= 2;
  196589. }
  196590. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196591. {
  196592. if (png_ptr->num_trans)
  196593. {
  196594. max_pixel_depth *= 4;
  196595. max_pixel_depth /= 3;
  196596. }
  196597. }
  196598. }
  196599. #endif
  196600. #if defined(PNG_READ_FILLER_SUPPORTED)
  196601. if (png_ptr->transformations & (PNG_FILLER))
  196602. {
  196603. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196604. max_pixel_depth = 32;
  196605. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196606. {
  196607. if (max_pixel_depth <= 8)
  196608. max_pixel_depth = 16;
  196609. else
  196610. max_pixel_depth = 32;
  196611. }
  196612. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196613. {
  196614. if (max_pixel_depth <= 32)
  196615. max_pixel_depth = 32;
  196616. else
  196617. max_pixel_depth = 64;
  196618. }
  196619. }
  196620. #endif
  196621. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196622. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196623. {
  196624. if (
  196625. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196626. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196627. #endif
  196628. #if defined(PNG_READ_FILLER_SUPPORTED)
  196629. (png_ptr->transformations & (PNG_FILLER)) ||
  196630. #endif
  196631. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196632. {
  196633. if (max_pixel_depth <= 16)
  196634. max_pixel_depth = 32;
  196635. else
  196636. max_pixel_depth = 64;
  196637. }
  196638. else
  196639. {
  196640. if (max_pixel_depth <= 8)
  196641. {
  196642. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196643. max_pixel_depth = 32;
  196644. else
  196645. max_pixel_depth = 24;
  196646. }
  196647. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196648. max_pixel_depth = 64;
  196649. else
  196650. max_pixel_depth = 48;
  196651. }
  196652. }
  196653. #endif
  196654. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196655. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196656. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196657. {
  196658. int user_pixel_depth=png_ptr->user_transform_depth*
  196659. png_ptr->user_transform_channels;
  196660. if(user_pixel_depth > max_pixel_depth)
  196661. max_pixel_depth=user_pixel_depth;
  196662. }
  196663. #endif
  196664. /* align the width on the next larger 8 pixels. Mainly used
  196665. for interlacing */
  196666. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196667. /* calculate the maximum bytes needed, adding a byte and a pixel
  196668. for safety's sake */
  196669. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196670. 1 + ((max_pixel_depth + 7) >> 3);
  196671. #ifdef PNG_MAX_MALLOC_64K
  196672. if (row_bytes > (png_uint_32)65536L)
  196673. png_error(png_ptr, "This image requires a row greater than 64KB");
  196674. #endif
  196675. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196676. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196677. #ifdef PNG_MAX_MALLOC_64K
  196678. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196679. png_error(png_ptr, "This image requires a row greater than 64KB");
  196680. #endif
  196681. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196682. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196683. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196684. png_ptr->rowbytes + 1));
  196685. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196686. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196687. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196688. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196689. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196690. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196691. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196692. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196693. }
  196694. #endif /* PNG_READ_SUPPORTED */
  196695. /*** End of inlined file: pngrutil.c ***/
  196696. /*** Start of inlined file: pngset.c ***/
  196697. /* pngset.c - storage of image information into info struct
  196698. *
  196699. * Last changed in libpng 1.2.21 [October 4, 2007]
  196700. * For conditions of distribution and use, see copyright notice in png.h
  196701. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196702. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196703. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196704. *
  196705. * The functions here are used during reads to store data from the file
  196706. * into the info struct, and during writes to store application data
  196707. * into the info struct for writing into the file. This abstracts the
  196708. * info struct and allows us to change the structure in the future.
  196709. */
  196710. #define PNG_INTERNAL
  196711. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196712. #if defined(PNG_bKGD_SUPPORTED)
  196713. void PNGAPI
  196714. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196715. {
  196716. png_debug1(1, "in %s storage function\n", "bKGD");
  196717. if (png_ptr == NULL || info_ptr == NULL)
  196718. return;
  196719. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196720. info_ptr->valid |= PNG_INFO_bKGD;
  196721. }
  196722. #endif
  196723. #if defined(PNG_cHRM_SUPPORTED)
  196724. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196725. void PNGAPI
  196726. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196727. double white_x, double white_y, double red_x, double red_y,
  196728. double green_x, double green_y, double blue_x, double blue_y)
  196729. {
  196730. png_debug1(1, "in %s storage function\n", "cHRM");
  196731. if (png_ptr == NULL || info_ptr == NULL)
  196732. return;
  196733. if (white_x < 0.0 || white_y < 0.0 ||
  196734. red_x < 0.0 || red_y < 0.0 ||
  196735. green_x < 0.0 || green_y < 0.0 ||
  196736. blue_x < 0.0 || blue_y < 0.0)
  196737. {
  196738. png_warning(png_ptr,
  196739. "Ignoring attempt to set negative chromaticity value");
  196740. return;
  196741. }
  196742. if (white_x > 21474.83 || white_y > 21474.83 ||
  196743. red_x > 21474.83 || red_y > 21474.83 ||
  196744. green_x > 21474.83 || green_y > 21474.83 ||
  196745. blue_x > 21474.83 || blue_y > 21474.83)
  196746. {
  196747. png_warning(png_ptr,
  196748. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196749. return;
  196750. }
  196751. info_ptr->x_white = (float)white_x;
  196752. info_ptr->y_white = (float)white_y;
  196753. info_ptr->x_red = (float)red_x;
  196754. info_ptr->y_red = (float)red_y;
  196755. info_ptr->x_green = (float)green_x;
  196756. info_ptr->y_green = (float)green_y;
  196757. info_ptr->x_blue = (float)blue_x;
  196758. info_ptr->y_blue = (float)blue_y;
  196759. #ifdef PNG_FIXED_POINT_SUPPORTED
  196760. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196761. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196762. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196763. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196764. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196765. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196766. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196767. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196768. #endif
  196769. info_ptr->valid |= PNG_INFO_cHRM;
  196770. }
  196771. #endif
  196772. #ifdef PNG_FIXED_POINT_SUPPORTED
  196773. void PNGAPI
  196774. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196775. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196776. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196777. png_fixed_point blue_x, png_fixed_point blue_y)
  196778. {
  196779. png_debug1(1, "in %s storage function\n", "cHRM");
  196780. if (png_ptr == NULL || info_ptr == NULL)
  196781. return;
  196782. if (white_x < 0 || white_y < 0 ||
  196783. red_x < 0 || red_y < 0 ||
  196784. green_x < 0 || green_y < 0 ||
  196785. blue_x < 0 || blue_y < 0)
  196786. {
  196787. png_warning(png_ptr,
  196788. "Ignoring attempt to set negative chromaticity value");
  196789. return;
  196790. }
  196791. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196792. if (white_x > (double) PNG_UINT_31_MAX ||
  196793. white_y > (double) PNG_UINT_31_MAX ||
  196794. red_x > (double) PNG_UINT_31_MAX ||
  196795. red_y > (double) PNG_UINT_31_MAX ||
  196796. green_x > (double) PNG_UINT_31_MAX ||
  196797. green_y > (double) PNG_UINT_31_MAX ||
  196798. blue_x > (double) PNG_UINT_31_MAX ||
  196799. blue_y > (double) PNG_UINT_31_MAX)
  196800. #else
  196801. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196802. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196803. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196804. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196805. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196806. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196807. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196808. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196809. #endif
  196810. {
  196811. png_warning(png_ptr,
  196812. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196813. return;
  196814. }
  196815. info_ptr->int_x_white = white_x;
  196816. info_ptr->int_y_white = white_y;
  196817. info_ptr->int_x_red = red_x;
  196818. info_ptr->int_y_red = red_y;
  196819. info_ptr->int_x_green = green_x;
  196820. info_ptr->int_y_green = green_y;
  196821. info_ptr->int_x_blue = blue_x;
  196822. info_ptr->int_y_blue = blue_y;
  196823. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196824. info_ptr->x_white = (float)(white_x/100000.);
  196825. info_ptr->y_white = (float)(white_y/100000.);
  196826. info_ptr->x_red = (float)( red_x/100000.);
  196827. info_ptr->y_red = (float)( red_y/100000.);
  196828. info_ptr->x_green = (float)(green_x/100000.);
  196829. info_ptr->y_green = (float)(green_y/100000.);
  196830. info_ptr->x_blue = (float)( blue_x/100000.);
  196831. info_ptr->y_blue = (float)( blue_y/100000.);
  196832. #endif
  196833. info_ptr->valid |= PNG_INFO_cHRM;
  196834. }
  196835. #endif
  196836. #endif
  196837. #if defined(PNG_gAMA_SUPPORTED)
  196838. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196839. void PNGAPI
  196840. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196841. {
  196842. double gamma;
  196843. png_debug1(1, "in %s storage function\n", "gAMA");
  196844. if (png_ptr == NULL || info_ptr == NULL)
  196845. return;
  196846. /* Check for overflow */
  196847. if (file_gamma > 21474.83)
  196848. {
  196849. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196850. gamma=21474.83;
  196851. }
  196852. else
  196853. gamma=file_gamma;
  196854. info_ptr->gamma = (float)gamma;
  196855. #ifdef PNG_FIXED_POINT_SUPPORTED
  196856. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196857. #endif
  196858. info_ptr->valid |= PNG_INFO_gAMA;
  196859. if(gamma == 0.0)
  196860. png_warning(png_ptr, "Setting gamma=0");
  196861. }
  196862. #endif
  196863. void PNGAPI
  196864. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196865. int_gamma)
  196866. {
  196867. png_fixed_point gamma;
  196868. png_debug1(1, "in %s storage function\n", "gAMA");
  196869. if (png_ptr == NULL || info_ptr == NULL)
  196870. return;
  196871. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196872. {
  196873. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196874. gamma=PNG_UINT_31_MAX;
  196875. }
  196876. else
  196877. {
  196878. if (int_gamma < 0)
  196879. {
  196880. png_warning(png_ptr, "Setting negative gamma to zero");
  196881. gamma=0;
  196882. }
  196883. else
  196884. gamma=int_gamma;
  196885. }
  196886. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196887. info_ptr->gamma = (float)(gamma/100000.);
  196888. #endif
  196889. #ifdef PNG_FIXED_POINT_SUPPORTED
  196890. info_ptr->int_gamma = gamma;
  196891. #endif
  196892. info_ptr->valid |= PNG_INFO_gAMA;
  196893. if(gamma == 0)
  196894. png_warning(png_ptr, "Setting gamma=0");
  196895. }
  196896. #endif
  196897. #if defined(PNG_hIST_SUPPORTED)
  196898. void PNGAPI
  196899. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196900. {
  196901. int i;
  196902. png_debug1(1, "in %s storage function\n", "hIST");
  196903. if (png_ptr == NULL || info_ptr == NULL)
  196904. return;
  196905. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196906. > PNG_MAX_PALETTE_LENGTH)
  196907. {
  196908. png_warning(png_ptr,
  196909. "Invalid palette size, hIST allocation skipped.");
  196910. return;
  196911. }
  196912. #ifdef PNG_FREE_ME_SUPPORTED
  196913. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196914. #endif
  196915. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196916. 1.2.1 */
  196917. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196918. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196919. if (png_ptr->hist == NULL)
  196920. {
  196921. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196922. return;
  196923. }
  196924. for (i = 0; i < info_ptr->num_palette; i++)
  196925. png_ptr->hist[i] = hist[i];
  196926. info_ptr->hist = png_ptr->hist;
  196927. info_ptr->valid |= PNG_INFO_hIST;
  196928. #ifdef PNG_FREE_ME_SUPPORTED
  196929. info_ptr->free_me |= PNG_FREE_HIST;
  196930. #else
  196931. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196932. #endif
  196933. }
  196934. #endif
  196935. void PNGAPI
  196936. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196937. png_uint_32 width, png_uint_32 height, int bit_depth,
  196938. int color_type, int interlace_type, int compression_type,
  196939. int filter_type)
  196940. {
  196941. png_debug1(1, "in %s storage function\n", "IHDR");
  196942. if (png_ptr == NULL || info_ptr == NULL)
  196943. return;
  196944. /* check for width and height valid values */
  196945. if (width == 0 || height == 0)
  196946. png_error(png_ptr, "Image width or height is zero in IHDR");
  196947. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196948. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196949. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196950. #else
  196951. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196952. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196953. #endif
  196954. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196955. png_error(png_ptr, "Invalid image size in IHDR");
  196956. if ( width > (PNG_UINT_32_MAX
  196957. >> 3) /* 8-byte RGBA pixels */
  196958. - 64 /* bigrowbuf hack */
  196959. - 1 /* filter byte */
  196960. - 7*8 /* rounding of width to multiple of 8 pixels */
  196961. - 8) /* extra max_pixel_depth pad */
  196962. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196963. /* check other values */
  196964. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196965. bit_depth != 8 && bit_depth != 16)
  196966. png_error(png_ptr, "Invalid bit depth in IHDR");
  196967. if (color_type < 0 || color_type == 1 ||
  196968. color_type == 5 || color_type > 6)
  196969. png_error(png_ptr, "Invalid color type in IHDR");
  196970. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196971. ((color_type == PNG_COLOR_TYPE_RGB ||
  196972. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196973. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196974. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196975. if (interlace_type >= PNG_INTERLACE_LAST)
  196976. png_error(png_ptr, "Unknown interlace method in IHDR");
  196977. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196978. png_error(png_ptr, "Unknown compression method in IHDR");
  196979. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196980. /* Accept filter_method 64 (intrapixel differencing) only if
  196981. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196982. * 2. Libpng did not read a PNG signature (this filter_method is only
  196983. * used in PNG datastreams that are embedded in MNG datastreams) and
  196984. * 3. The application called png_permit_mng_features with a mask that
  196985. * included PNG_FLAG_MNG_FILTER_64 and
  196986. * 4. The filter_method is 64 and
  196987. * 5. The color_type is RGB or RGBA
  196988. */
  196989. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196990. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196991. if(filter_type != PNG_FILTER_TYPE_BASE)
  196992. {
  196993. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196994. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196995. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196996. (color_type == PNG_COLOR_TYPE_RGB ||
  196997. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196998. png_error(png_ptr, "Unknown filter method in IHDR");
  196999. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197000. png_warning(png_ptr, "Invalid filter method in IHDR");
  197001. }
  197002. #else
  197003. if(filter_type != PNG_FILTER_TYPE_BASE)
  197004. png_error(png_ptr, "Unknown filter method in IHDR");
  197005. #endif
  197006. info_ptr->width = width;
  197007. info_ptr->height = height;
  197008. info_ptr->bit_depth = (png_byte)bit_depth;
  197009. info_ptr->color_type =(png_byte) color_type;
  197010. info_ptr->compression_type = (png_byte)compression_type;
  197011. info_ptr->filter_type = (png_byte)filter_type;
  197012. info_ptr->interlace_type = (png_byte)interlace_type;
  197013. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197014. info_ptr->channels = 1;
  197015. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197016. info_ptr->channels = 3;
  197017. else
  197018. info_ptr->channels = 1;
  197019. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197020. info_ptr->channels++;
  197021. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197022. /* check for potential overflow */
  197023. if (width > (PNG_UINT_32_MAX
  197024. >> 3) /* 8-byte RGBA pixels */
  197025. - 64 /* bigrowbuf hack */
  197026. - 1 /* filter byte */
  197027. - 7*8 /* rounding of width to multiple of 8 pixels */
  197028. - 8) /* extra max_pixel_depth pad */
  197029. info_ptr->rowbytes = (png_size_t)0;
  197030. else
  197031. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197032. }
  197033. #if defined(PNG_oFFs_SUPPORTED)
  197034. void PNGAPI
  197035. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197036. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197037. {
  197038. png_debug1(1, "in %s storage function\n", "oFFs");
  197039. if (png_ptr == NULL || info_ptr == NULL)
  197040. return;
  197041. info_ptr->x_offset = offset_x;
  197042. info_ptr->y_offset = offset_y;
  197043. info_ptr->offset_unit_type = (png_byte)unit_type;
  197044. info_ptr->valid |= PNG_INFO_oFFs;
  197045. }
  197046. #endif
  197047. #if defined(PNG_pCAL_SUPPORTED)
  197048. void PNGAPI
  197049. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197050. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197051. png_charp units, png_charpp params)
  197052. {
  197053. png_uint_32 length;
  197054. int i;
  197055. png_debug1(1, "in %s storage function\n", "pCAL");
  197056. if (png_ptr == NULL || info_ptr == NULL)
  197057. return;
  197058. length = png_strlen(purpose) + 1;
  197059. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197060. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197061. if (info_ptr->pcal_purpose == NULL)
  197062. {
  197063. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197064. return;
  197065. }
  197066. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197067. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197068. info_ptr->pcal_X0 = X0;
  197069. info_ptr->pcal_X1 = X1;
  197070. info_ptr->pcal_type = (png_byte)type;
  197071. info_ptr->pcal_nparams = (png_byte)nparams;
  197072. length = png_strlen(units) + 1;
  197073. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197074. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197075. if (info_ptr->pcal_units == NULL)
  197076. {
  197077. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197078. return;
  197079. }
  197080. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197081. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197082. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197083. if (info_ptr->pcal_params == NULL)
  197084. {
  197085. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197086. return;
  197087. }
  197088. info_ptr->pcal_params[nparams] = NULL;
  197089. for (i = 0; i < nparams; i++)
  197090. {
  197091. length = png_strlen(params[i]) + 1;
  197092. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197093. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197094. if (info_ptr->pcal_params[i] == NULL)
  197095. {
  197096. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197097. return;
  197098. }
  197099. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197100. }
  197101. info_ptr->valid |= PNG_INFO_pCAL;
  197102. #ifdef PNG_FREE_ME_SUPPORTED
  197103. info_ptr->free_me |= PNG_FREE_PCAL;
  197104. #endif
  197105. }
  197106. #endif
  197107. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197108. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197109. void PNGAPI
  197110. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197111. int unit, double width, double height)
  197112. {
  197113. png_debug1(1, "in %s storage function\n", "sCAL");
  197114. if (png_ptr == NULL || info_ptr == NULL)
  197115. return;
  197116. info_ptr->scal_unit = (png_byte)unit;
  197117. info_ptr->scal_pixel_width = width;
  197118. info_ptr->scal_pixel_height = height;
  197119. info_ptr->valid |= PNG_INFO_sCAL;
  197120. }
  197121. #else
  197122. #ifdef PNG_FIXED_POINT_SUPPORTED
  197123. void PNGAPI
  197124. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197125. int unit, png_charp swidth, png_charp sheight)
  197126. {
  197127. png_uint_32 length;
  197128. png_debug1(1, "in %s storage function\n", "sCAL");
  197129. if (png_ptr == NULL || info_ptr == NULL)
  197130. return;
  197131. info_ptr->scal_unit = (png_byte)unit;
  197132. length = png_strlen(swidth) + 1;
  197133. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197134. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197135. if (info_ptr->scal_s_width == NULL)
  197136. {
  197137. png_warning(png_ptr,
  197138. "Memory allocation failed while processing sCAL.");
  197139. }
  197140. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197141. length = png_strlen(sheight) + 1;
  197142. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197143. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197144. if (info_ptr->scal_s_height == NULL)
  197145. {
  197146. png_free (png_ptr, info_ptr->scal_s_width);
  197147. png_warning(png_ptr,
  197148. "Memory allocation failed while processing sCAL.");
  197149. }
  197150. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197151. info_ptr->valid |= PNG_INFO_sCAL;
  197152. #ifdef PNG_FREE_ME_SUPPORTED
  197153. info_ptr->free_me |= PNG_FREE_SCAL;
  197154. #endif
  197155. }
  197156. #endif
  197157. #endif
  197158. #endif
  197159. #if defined(PNG_pHYs_SUPPORTED)
  197160. void PNGAPI
  197161. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197162. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197163. {
  197164. png_debug1(1, "in %s storage function\n", "pHYs");
  197165. if (png_ptr == NULL || info_ptr == NULL)
  197166. return;
  197167. info_ptr->x_pixels_per_unit = res_x;
  197168. info_ptr->y_pixels_per_unit = res_y;
  197169. info_ptr->phys_unit_type = (png_byte)unit_type;
  197170. info_ptr->valid |= PNG_INFO_pHYs;
  197171. }
  197172. #endif
  197173. void PNGAPI
  197174. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197175. png_colorp palette, int num_palette)
  197176. {
  197177. png_debug1(1, "in %s storage function\n", "PLTE");
  197178. if (png_ptr == NULL || info_ptr == NULL)
  197179. return;
  197180. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197181. {
  197182. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197183. png_error(png_ptr, "Invalid palette length");
  197184. else
  197185. {
  197186. png_warning(png_ptr, "Invalid palette length");
  197187. return;
  197188. }
  197189. }
  197190. /*
  197191. * It may not actually be necessary to set png_ptr->palette here;
  197192. * we do it for backward compatibility with the way the png_handle_tRNS
  197193. * function used to do the allocation.
  197194. */
  197195. #ifdef PNG_FREE_ME_SUPPORTED
  197196. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197197. #endif
  197198. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197199. of num_palette entries,
  197200. in case of an invalid PNG file that has too-large sample values. */
  197201. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197202. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197203. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197204. png_sizeof(png_color));
  197205. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197206. info_ptr->palette = png_ptr->palette;
  197207. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197208. #ifdef PNG_FREE_ME_SUPPORTED
  197209. info_ptr->free_me |= PNG_FREE_PLTE;
  197210. #else
  197211. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197212. #endif
  197213. info_ptr->valid |= PNG_INFO_PLTE;
  197214. }
  197215. #if defined(PNG_sBIT_SUPPORTED)
  197216. void PNGAPI
  197217. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197218. png_color_8p sig_bit)
  197219. {
  197220. png_debug1(1, "in %s storage function\n", "sBIT");
  197221. if (png_ptr == NULL || info_ptr == NULL)
  197222. return;
  197223. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197224. info_ptr->valid |= PNG_INFO_sBIT;
  197225. }
  197226. #endif
  197227. #if defined(PNG_sRGB_SUPPORTED)
  197228. void PNGAPI
  197229. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197230. {
  197231. png_debug1(1, "in %s storage function\n", "sRGB");
  197232. if (png_ptr == NULL || info_ptr == NULL)
  197233. return;
  197234. info_ptr->srgb_intent = (png_byte)intent;
  197235. info_ptr->valid |= PNG_INFO_sRGB;
  197236. }
  197237. void PNGAPI
  197238. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197239. int intent)
  197240. {
  197241. #if defined(PNG_gAMA_SUPPORTED)
  197242. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197243. float file_gamma;
  197244. #endif
  197245. #ifdef PNG_FIXED_POINT_SUPPORTED
  197246. png_fixed_point int_file_gamma;
  197247. #endif
  197248. #endif
  197249. #if defined(PNG_cHRM_SUPPORTED)
  197250. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197251. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197252. #endif
  197253. #ifdef PNG_FIXED_POINT_SUPPORTED
  197254. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197255. int_green_y, int_blue_x, int_blue_y;
  197256. #endif
  197257. #endif
  197258. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197259. if (png_ptr == NULL || info_ptr == NULL)
  197260. return;
  197261. png_set_sRGB(png_ptr, info_ptr, intent);
  197262. #if defined(PNG_gAMA_SUPPORTED)
  197263. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197264. file_gamma = (float).45455;
  197265. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197266. #endif
  197267. #ifdef PNG_FIXED_POINT_SUPPORTED
  197268. int_file_gamma = 45455L;
  197269. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197270. #endif
  197271. #endif
  197272. #if defined(PNG_cHRM_SUPPORTED)
  197273. #ifdef PNG_FIXED_POINT_SUPPORTED
  197274. int_white_x = 31270L;
  197275. int_white_y = 32900L;
  197276. int_red_x = 64000L;
  197277. int_red_y = 33000L;
  197278. int_green_x = 30000L;
  197279. int_green_y = 60000L;
  197280. int_blue_x = 15000L;
  197281. int_blue_y = 6000L;
  197282. png_set_cHRM_fixed(png_ptr, info_ptr,
  197283. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197284. int_blue_x, int_blue_y);
  197285. #endif
  197286. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197287. white_x = (float).3127;
  197288. white_y = (float).3290;
  197289. red_x = (float).64;
  197290. red_y = (float).33;
  197291. green_x = (float).30;
  197292. green_y = (float).60;
  197293. blue_x = (float).15;
  197294. blue_y = (float).06;
  197295. png_set_cHRM(png_ptr, info_ptr,
  197296. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197297. #endif
  197298. #endif
  197299. }
  197300. #endif
  197301. #if defined(PNG_iCCP_SUPPORTED)
  197302. void PNGAPI
  197303. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197304. png_charp name, int compression_type,
  197305. png_charp profile, png_uint_32 proflen)
  197306. {
  197307. png_charp new_iccp_name;
  197308. png_charp new_iccp_profile;
  197309. png_debug1(1, "in %s storage function\n", "iCCP");
  197310. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197311. return;
  197312. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197313. if (new_iccp_name == NULL)
  197314. {
  197315. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197316. return;
  197317. }
  197318. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197319. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197320. if (new_iccp_profile == NULL)
  197321. {
  197322. png_free (png_ptr, new_iccp_name);
  197323. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197324. return;
  197325. }
  197326. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197327. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197328. info_ptr->iccp_proflen = proflen;
  197329. info_ptr->iccp_name = new_iccp_name;
  197330. info_ptr->iccp_profile = new_iccp_profile;
  197331. /* Compression is always zero but is here so the API and info structure
  197332. * does not have to change if we introduce multiple compression types */
  197333. info_ptr->iccp_compression = (png_byte)compression_type;
  197334. #ifdef PNG_FREE_ME_SUPPORTED
  197335. info_ptr->free_me |= PNG_FREE_ICCP;
  197336. #endif
  197337. info_ptr->valid |= PNG_INFO_iCCP;
  197338. }
  197339. #endif
  197340. #if defined(PNG_TEXT_SUPPORTED)
  197341. void PNGAPI
  197342. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197343. int num_text)
  197344. {
  197345. int ret;
  197346. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197347. if (ret)
  197348. png_error(png_ptr, "Insufficient memory to store text");
  197349. }
  197350. int /* PRIVATE */
  197351. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197352. int num_text)
  197353. {
  197354. int i;
  197355. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197356. "text" : (png_const_charp)png_ptr->chunk_name));
  197357. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197358. return(0);
  197359. /* Make sure we have enough space in the "text" array in info_struct
  197360. * to hold all of the incoming text_ptr objects.
  197361. */
  197362. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197363. {
  197364. if (info_ptr->text != NULL)
  197365. {
  197366. png_textp old_text;
  197367. int old_max;
  197368. old_max = info_ptr->max_text;
  197369. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197370. old_text = info_ptr->text;
  197371. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197372. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197373. if (info_ptr->text == NULL)
  197374. {
  197375. png_free(png_ptr, old_text);
  197376. return(1);
  197377. }
  197378. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197379. png_sizeof(png_text)));
  197380. png_free(png_ptr, old_text);
  197381. }
  197382. else
  197383. {
  197384. info_ptr->max_text = num_text + 8;
  197385. info_ptr->num_text = 0;
  197386. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197387. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197388. if (info_ptr->text == NULL)
  197389. return(1);
  197390. #ifdef PNG_FREE_ME_SUPPORTED
  197391. info_ptr->free_me |= PNG_FREE_TEXT;
  197392. #endif
  197393. }
  197394. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197395. info_ptr->max_text);
  197396. }
  197397. for (i = 0; i < num_text; i++)
  197398. {
  197399. png_size_t text_length,key_len;
  197400. png_size_t lang_len,lang_key_len;
  197401. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197402. if (text_ptr[i].key == NULL)
  197403. continue;
  197404. key_len = png_strlen(text_ptr[i].key);
  197405. if(text_ptr[i].compression <= 0)
  197406. {
  197407. lang_len = 0;
  197408. lang_key_len = 0;
  197409. }
  197410. else
  197411. #ifdef PNG_iTXt_SUPPORTED
  197412. {
  197413. /* set iTXt data */
  197414. if (text_ptr[i].lang != NULL)
  197415. lang_len = png_strlen(text_ptr[i].lang);
  197416. else
  197417. lang_len = 0;
  197418. if (text_ptr[i].lang_key != NULL)
  197419. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197420. else
  197421. lang_key_len = 0;
  197422. }
  197423. #else
  197424. {
  197425. png_warning(png_ptr, "iTXt chunk not supported.");
  197426. continue;
  197427. }
  197428. #endif
  197429. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197430. {
  197431. text_length = 0;
  197432. #ifdef PNG_iTXt_SUPPORTED
  197433. if(text_ptr[i].compression > 0)
  197434. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197435. else
  197436. #endif
  197437. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197438. }
  197439. else
  197440. {
  197441. text_length = png_strlen(text_ptr[i].text);
  197442. textp->compression = text_ptr[i].compression;
  197443. }
  197444. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197445. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197446. if (textp->key == NULL)
  197447. return(1);
  197448. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197449. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197450. (int)textp->key);
  197451. png_memcpy(textp->key, text_ptr[i].key,
  197452. (png_size_t)(key_len));
  197453. *(textp->key+key_len) = '\0';
  197454. #ifdef PNG_iTXt_SUPPORTED
  197455. if (text_ptr[i].compression > 0)
  197456. {
  197457. textp->lang=textp->key + key_len + 1;
  197458. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197459. *(textp->lang+lang_len) = '\0';
  197460. textp->lang_key=textp->lang + lang_len + 1;
  197461. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197462. *(textp->lang_key+lang_key_len) = '\0';
  197463. textp->text=textp->lang_key + lang_key_len + 1;
  197464. }
  197465. else
  197466. #endif
  197467. {
  197468. #ifdef PNG_iTXt_SUPPORTED
  197469. textp->lang=NULL;
  197470. textp->lang_key=NULL;
  197471. #endif
  197472. textp->text=textp->key + key_len + 1;
  197473. }
  197474. if(text_length)
  197475. png_memcpy(textp->text, text_ptr[i].text,
  197476. (png_size_t)(text_length));
  197477. *(textp->text+text_length) = '\0';
  197478. #ifdef PNG_iTXt_SUPPORTED
  197479. if(textp->compression > 0)
  197480. {
  197481. textp->text_length = 0;
  197482. textp->itxt_length = text_length;
  197483. }
  197484. else
  197485. #endif
  197486. {
  197487. textp->text_length = text_length;
  197488. #ifdef PNG_iTXt_SUPPORTED
  197489. textp->itxt_length = 0;
  197490. #endif
  197491. }
  197492. info_ptr->num_text++;
  197493. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197494. }
  197495. return(0);
  197496. }
  197497. #endif
  197498. #if defined(PNG_tIME_SUPPORTED)
  197499. void PNGAPI
  197500. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197501. {
  197502. png_debug1(1, "in %s storage function\n", "tIME");
  197503. if (png_ptr == NULL || info_ptr == NULL ||
  197504. (png_ptr->mode & PNG_WROTE_tIME))
  197505. return;
  197506. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197507. info_ptr->valid |= PNG_INFO_tIME;
  197508. }
  197509. #endif
  197510. #if defined(PNG_tRNS_SUPPORTED)
  197511. void PNGAPI
  197512. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197513. png_bytep trans, int num_trans, png_color_16p trans_values)
  197514. {
  197515. png_debug1(1, "in %s storage function\n", "tRNS");
  197516. if (png_ptr == NULL || info_ptr == NULL)
  197517. return;
  197518. if (trans != NULL)
  197519. {
  197520. /*
  197521. * It may not actually be necessary to set png_ptr->trans here;
  197522. * we do it for backward compatibility with the way the png_handle_tRNS
  197523. * function used to do the allocation.
  197524. */
  197525. #ifdef PNG_FREE_ME_SUPPORTED
  197526. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197527. #endif
  197528. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197529. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197530. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197531. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197532. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197533. #ifdef PNG_FREE_ME_SUPPORTED
  197534. info_ptr->free_me |= PNG_FREE_TRNS;
  197535. #else
  197536. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197537. #endif
  197538. }
  197539. if (trans_values != NULL)
  197540. {
  197541. png_memcpy(&(info_ptr->trans_values), trans_values,
  197542. png_sizeof(png_color_16));
  197543. if (num_trans == 0)
  197544. num_trans = 1;
  197545. }
  197546. info_ptr->num_trans = (png_uint_16)num_trans;
  197547. info_ptr->valid |= PNG_INFO_tRNS;
  197548. }
  197549. #endif
  197550. #if defined(PNG_sPLT_SUPPORTED)
  197551. void PNGAPI
  197552. png_set_sPLT(png_structp png_ptr,
  197553. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197554. {
  197555. png_sPLT_tp np;
  197556. int i;
  197557. if (png_ptr == NULL || info_ptr == NULL)
  197558. return;
  197559. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197560. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197561. if (np == NULL)
  197562. {
  197563. png_warning(png_ptr, "No memory for sPLT palettes.");
  197564. return;
  197565. }
  197566. png_memcpy(np, info_ptr->splt_palettes,
  197567. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197568. png_free(png_ptr, info_ptr->splt_palettes);
  197569. info_ptr->splt_palettes=NULL;
  197570. for (i = 0; i < nentries; i++)
  197571. {
  197572. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197573. png_sPLT_tp from = entries + i;
  197574. to->name = (png_charp)png_malloc_warn(png_ptr,
  197575. png_strlen(from->name) + 1);
  197576. if (to->name == NULL)
  197577. {
  197578. png_warning(png_ptr,
  197579. "Out of memory while processing sPLT chunk");
  197580. }
  197581. /* TODO: use png_malloc_warn */
  197582. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197583. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197584. from->nentries * png_sizeof(png_sPLT_entry));
  197585. /* TODO: use png_malloc_warn */
  197586. png_memcpy(to->entries, from->entries,
  197587. from->nentries * png_sizeof(png_sPLT_entry));
  197588. if (to->entries == NULL)
  197589. {
  197590. png_warning(png_ptr,
  197591. "Out of memory while processing sPLT chunk");
  197592. png_free(png_ptr,to->name);
  197593. to->name = NULL;
  197594. }
  197595. to->nentries = from->nentries;
  197596. to->depth = from->depth;
  197597. }
  197598. info_ptr->splt_palettes = np;
  197599. info_ptr->splt_palettes_num += nentries;
  197600. info_ptr->valid |= PNG_INFO_sPLT;
  197601. #ifdef PNG_FREE_ME_SUPPORTED
  197602. info_ptr->free_me |= PNG_FREE_SPLT;
  197603. #endif
  197604. }
  197605. #endif /* PNG_sPLT_SUPPORTED */
  197606. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197607. void PNGAPI
  197608. png_set_unknown_chunks(png_structp png_ptr,
  197609. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197610. {
  197611. png_unknown_chunkp np;
  197612. int i;
  197613. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197614. return;
  197615. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197616. (info_ptr->unknown_chunks_num + num_unknowns) *
  197617. png_sizeof(png_unknown_chunk));
  197618. if (np == NULL)
  197619. {
  197620. png_warning(png_ptr,
  197621. "Out of memory while processing unknown chunk.");
  197622. return;
  197623. }
  197624. png_memcpy(np, info_ptr->unknown_chunks,
  197625. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197626. png_free(png_ptr, info_ptr->unknown_chunks);
  197627. info_ptr->unknown_chunks=NULL;
  197628. for (i = 0; i < num_unknowns; i++)
  197629. {
  197630. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197631. png_unknown_chunkp from = unknowns + i;
  197632. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197633. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197634. if (to->data == NULL)
  197635. {
  197636. png_warning(png_ptr,
  197637. "Out of memory while processing unknown chunk.");
  197638. }
  197639. else
  197640. {
  197641. png_memcpy(to->data, from->data, from->size);
  197642. to->size = from->size;
  197643. /* note our location in the read or write sequence */
  197644. to->location = (png_byte)(png_ptr->mode & 0xff);
  197645. }
  197646. }
  197647. info_ptr->unknown_chunks = np;
  197648. info_ptr->unknown_chunks_num += num_unknowns;
  197649. #ifdef PNG_FREE_ME_SUPPORTED
  197650. info_ptr->free_me |= PNG_FREE_UNKN;
  197651. #endif
  197652. }
  197653. void PNGAPI
  197654. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197655. int chunk, int location)
  197656. {
  197657. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197658. (int)info_ptr->unknown_chunks_num)
  197659. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197660. }
  197661. #endif
  197662. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197663. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197664. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197665. void PNGAPI
  197666. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197667. {
  197668. /* This function is deprecated in favor of png_permit_mng_features()
  197669. and will be removed from libpng-1.3.0 */
  197670. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197671. if (png_ptr == NULL)
  197672. return;
  197673. png_ptr->mng_features_permitted = (png_byte)
  197674. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197675. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197676. }
  197677. #endif
  197678. #endif
  197679. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197680. png_uint_32 PNGAPI
  197681. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197682. {
  197683. png_debug(1, "in png_permit_mng_features\n");
  197684. if (png_ptr == NULL)
  197685. return (png_uint_32)0;
  197686. png_ptr->mng_features_permitted =
  197687. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197688. return (png_uint_32)png_ptr->mng_features_permitted;
  197689. }
  197690. #endif
  197691. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197692. void PNGAPI
  197693. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197694. chunk_list, int num_chunks)
  197695. {
  197696. png_bytep new_list, p;
  197697. int i, old_num_chunks;
  197698. if (png_ptr == NULL)
  197699. return;
  197700. if (num_chunks == 0)
  197701. {
  197702. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197703. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197704. else
  197705. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197706. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197707. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197708. else
  197709. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197710. return;
  197711. }
  197712. if (chunk_list == NULL)
  197713. return;
  197714. old_num_chunks=png_ptr->num_chunk_list;
  197715. new_list=(png_bytep)png_malloc(png_ptr,
  197716. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197717. if(png_ptr->chunk_list != NULL)
  197718. {
  197719. png_memcpy(new_list, png_ptr->chunk_list,
  197720. (png_size_t)(5*old_num_chunks));
  197721. png_free(png_ptr, png_ptr->chunk_list);
  197722. png_ptr->chunk_list=NULL;
  197723. }
  197724. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197725. (png_size_t)(5*num_chunks));
  197726. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197727. *p=(png_byte)keep;
  197728. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197729. png_ptr->chunk_list=new_list;
  197730. #ifdef PNG_FREE_ME_SUPPORTED
  197731. png_ptr->free_me |= PNG_FREE_LIST;
  197732. #endif
  197733. }
  197734. #endif
  197735. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197736. void PNGAPI
  197737. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197738. png_user_chunk_ptr read_user_chunk_fn)
  197739. {
  197740. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197741. if (png_ptr == NULL)
  197742. return;
  197743. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197744. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197745. }
  197746. #endif
  197747. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197748. void PNGAPI
  197749. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197750. {
  197751. png_debug1(1, "in %s storage function\n", "rows");
  197752. if (png_ptr == NULL || info_ptr == NULL)
  197753. return;
  197754. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197755. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197756. info_ptr->row_pointers = row_pointers;
  197757. if(row_pointers)
  197758. info_ptr->valid |= PNG_INFO_IDAT;
  197759. }
  197760. #endif
  197761. #ifdef PNG_WRITE_SUPPORTED
  197762. void PNGAPI
  197763. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197764. {
  197765. if (png_ptr == NULL)
  197766. return;
  197767. if(png_ptr->zbuf)
  197768. png_free(png_ptr, png_ptr->zbuf);
  197769. png_ptr->zbuf_size = (png_size_t)size;
  197770. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197771. png_ptr->zstream.next_out = png_ptr->zbuf;
  197772. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197773. }
  197774. #endif
  197775. void PNGAPI
  197776. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197777. {
  197778. if (png_ptr && info_ptr)
  197779. info_ptr->valid &= ~(mask);
  197780. }
  197781. #ifndef PNG_1_0_X
  197782. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197783. /* function was added to libpng 1.2.0 and should always exist by default */
  197784. void PNGAPI
  197785. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197786. {
  197787. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197788. if (png_ptr != NULL)
  197789. png_ptr->asm_flags = 0;
  197790. }
  197791. /* this function was added to libpng 1.2.0 */
  197792. void PNGAPI
  197793. png_set_mmx_thresholds (png_structp png_ptr,
  197794. png_byte,
  197795. png_uint_32)
  197796. {
  197797. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197798. if (png_ptr == NULL)
  197799. return;
  197800. }
  197801. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197802. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197803. /* this function was added to libpng 1.2.6 */
  197804. void PNGAPI
  197805. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197806. png_uint_32 user_height_max)
  197807. {
  197808. /* Images with dimensions larger than these limits will be
  197809. * rejected by png_set_IHDR(). To accept any PNG datastream
  197810. * regardless of dimensions, set both limits to 0x7ffffffL.
  197811. */
  197812. if(png_ptr == NULL) return;
  197813. png_ptr->user_width_max = user_width_max;
  197814. png_ptr->user_height_max = user_height_max;
  197815. }
  197816. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197817. #endif /* ?PNG_1_0_X */
  197818. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197819. /*** End of inlined file: pngset.c ***/
  197820. /*** Start of inlined file: pngtrans.c ***/
  197821. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197822. *
  197823. * Last changed in libpng 1.2.17 May 15, 2007
  197824. * For conditions of distribution and use, see copyright notice in png.h
  197825. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197826. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197827. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197828. */
  197829. #define PNG_INTERNAL
  197830. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197831. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197832. /* turn on BGR-to-RGB mapping */
  197833. void PNGAPI
  197834. png_set_bgr(png_structp png_ptr)
  197835. {
  197836. png_debug(1, "in png_set_bgr\n");
  197837. if(png_ptr == NULL) return;
  197838. png_ptr->transformations |= PNG_BGR;
  197839. }
  197840. #endif
  197841. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197842. /* turn on 16 bit byte swapping */
  197843. void PNGAPI
  197844. png_set_swap(png_structp png_ptr)
  197845. {
  197846. png_debug(1, "in png_set_swap\n");
  197847. if(png_ptr == NULL) return;
  197848. if (png_ptr->bit_depth == 16)
  197849. png_ptr->transformations |= PNG_SWAP_BYTES;
  197850. }
  197851. #endif
  197852. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197853. /* turn on pixel packing */
  197854. void PNGAPI
  197855. png_set_packing(png_structp png_ptr)
  197856. {
  197857. png_debug(1, "in png_set_packing\n");
  197858. if(png_ptr == NULL) return;
  197859. if (png_ptr->bit_depth < 8)
  197860. {
  197861. png_ptr->transformations |= PNG_PACK;
  197862. png_ptr->usr_bit_depth = 8;
  197863. }
  197864. }
  197865. #endif
  197866. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197867. /* turn on packed pixel swapping */
  197868. void PNGAPI
  197869. png_set_packswap(png_structp png_ptr)
  197870. {
  197871. png_debug(1, "in png_set_packswap\n");
  197872. if(png_ptr == NULL) return;
  197873. if (png_ptr->bit_depth < 8)
  197874. png_ptr->transformations |= PNG_PACKSWAP;
  197875. }
  197876. #endif
  197877. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197878. void PNGAPI
  197879. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197880. {
  197881. png_debug(1, "in png_set_shift\n");
  197882. if(png_ptr == NULL) return;
  197883. png_ptr->transformations |= PNG_SHIFT;
  197884. png_ptr->shift = *true_bits;
  197885. }
  197886. #endif
  197887. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197888. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197889. int PNGAPI
  197890. png_set_interlace_handling(png_structp png_ptr)
  197891. {
  197892. png_debug(1, "in png_set_interlace handling\n");
  197893. if (png_ptr && png_ptr->interlaced)
  197894. {
  197895. png_ptr->transformations |= PNG_INTERLACE;
  197896. return (7);
  197897. }
  197898. return (1);
  197899. }
  197900. #endif
  197901. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197902. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197903. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197904. * for 48-bit input data, as well as to avoid problems with some compilers
  197905. * that don't like bytes as parameters.
  197906. */
  197907. void PNGAPI
  197908. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197909. {
  197910. png_debug(1, "in png_set_filler\n");
  197911. if(png_ptr == NULL) return;
  197912. png_ptr->transformations |= PNG_FILLER;
  197913. png_ptr->filler = (png_byte)filler;
  197914. if (filler_loc == PNG_FILLER_AFTER)
  197915. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197916. else
  197917. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197918. /* This should probably go in the "do_read_filler" routine.
  197919. * I attempted to do that in libpng-1.0.1a but that caused problems
  197920. * so I restored it in libpng-1.0.2a
  197921. */
  197922. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197923. {
  197924. png_ptr->usr_channels = 4;
  197925. }
  197926. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197927. * a less-than-8-bit grayscale to GA? */
  197928. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197929. {
  197930. png_ptr->usr_channels = 2;
  197931. }
  197932. }
  197933. #if !defined(PNG_1_0_X)
  197934. /* Added to libpng-1.2.7 */
  197935. void PNGAPI
  197936. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197937. {
  197938. png_debug(1, "in png_set_add_alpha\n");
  197939. if(png_ptr == NULL) return;
  197940. png_set_filler(png_ptr, filler, filler_loc);
  197941. png_ptr->transformations |= PNG_ADD_ALPHA;
  197942. }
  197943. #endif
  197944. #endif
  197945. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197946. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197947. void PNGAPI
  197948. png_set_swap_alpha(png_structp png_ptr)
  197949. {
  197950. png_debug(1, "in png_set_swap_alpha\n");
  197951. if(png_ptr == NULL) return;
  197952. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197953. }
  197954. #endif
  197955. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197956. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197957. void PNGAPI
  197958. png_set_invert_alpha(png_structp png_ptr)
  197959. {
  197960. png_debug(1, "in png_set_invert_alpha\n");
  197961. if(png_ptr == NULL) return;
  197962. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197963. }
  197964. #endif
  197965. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197966. void PNGAPI
  197967. png_set_invert_mono(png_structp png_ptr)
  197968. {
  197969. png_debug(1, "in png_set_invert_mono\n");
  197970. if(png_ptr == NULL) return;
  197971. png_ptr->transformations |= PNG_INVERT_MONO;
  197972. }
  197973. /* invert monochrome grayscale data */
  197974. void /* PRIVATE */
  197975. png_do_invert(png_row_infop row_info, png_bytep row)
  197976. {
  197977. png_debug(1, "in png_do_invert\n");
  197978. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197979. * if (row_info->bit_depth == 1 &&
  197980. */
  197981. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197982. if (row == NULL || row_info == NULL)
  197983. return;
  197984. #endif
  197985. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197986. {
  197987. png_bytep rp = row;
  197988. png_uint_32 i;
  197989. png_uint_32 istop = row_info->rowbytes;
  197990. for (i = 0; i < istop; i++)
  197991. {
  197992. *rp = (png_byte)(~(*rp));
  197993. rp++;
  197994. }
  197995. }
  197996. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197997. row_info->bit_depth == 8)
  197998. {
  197999. png_bytep rp = row;
  198000. png_uint_32 i;
  198001. png_uint_32 istop = row_info->rowbytes;
  198002. for (i = 0; i < istop; i+=2)
  198003. {
  198004. *rp = (png_byte)(~(*rp));
  198005. rp+=2;
  198006. }
  198007. }
  198008. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198009. row_info->bit_depth == 16)
  198010. {
  198011. png_bytep rp = row;
  198012. png_uint_32 i;
  198013. png_uint_32 istop = row_info->rowbytes;
  198014. for (i = 0; i < istop; i+=4)
  198015. {
  198016. *rp = (png_byte)(~(*rp));
  198017. *(rp+1) = (png_byte)(~(*(rp+1)));
  198018. rp+=4;
  198019. }
  198020. }
  198021. }
  198022. #endif
  198023. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198024. /* swaps byte order on 16 bit depth images */
  198025. void /* PRIVATE */
  198026. png_do_swap(png_row_infop row_info, png_bytep row)
  198027. {
  198028. png_debug(1, "in png_do_swap\n");
  198029. if (
  198030. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198031. row != NULL && row_info != NULL &&
  198032. #endif
  198033. row_info->bit_depth == 16)
  198034. {
  198035. png_bytep rp = row;
  198036. png_uint_32 i;
  198037. png_uint_32 istop= row_info->width * row_info->channels;
  198038. for (i = 0; i < istop; i++, rp += 2)
  198039. {
  198040. png_byte t = *rp;
  198041. *rp = *(rp + 1);
  198042. *(rp + 1) = t;
  198043. }
  198044. }
  198045. }
  198046. #endif
  198047. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198048. static PNG_CONST png_byte onebppswaptable[256] = {
  198049. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198050. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198051. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198052. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198053. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198054. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198055. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198056. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198057. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198058. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198059. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198060. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198061. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198062. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198063. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198064. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198065. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198066. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198067. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198068. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198069. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198070. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198071. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198072. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198073. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198074. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198075. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198076. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198077. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198078. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198079. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198080. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198081. };
  198082. static PNG_CONST png_byte twobppswaptable[256] = {
  198083. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198084. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198085. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198086. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198087. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198088. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198089. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198090. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198091. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198092. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198093. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198094. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198095. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198096. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198097. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198098. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198099. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198100. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198101. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198102. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198103. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198104. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198105. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198106. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198107. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198108. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198109. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198110. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198111. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198112. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198113. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198114. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198115. };
  198116. static PNG_CONST png_byte fourbppswaptable[256] = {
  198117. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198118. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198119. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198120. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198121. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198122. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198123. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198124. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198125. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198126. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198127. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198128. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198129. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198130. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198131. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198132. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198133. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198134. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198135. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198136. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198137. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198138. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198139. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198140. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198141. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198142. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198143. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198144. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198145. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198146. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198147. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198148. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198149. };
  198150. /* swaps pixel packing order within bytes */
  198151. void /* PRIVATE */
  198152. png_do_packswap(png_row_infop row_info, png_bytep row)
  198153. {
  198154. png_debug(1, "in png_do_packswap\n");
  198155. if (
  198156. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198157. row != NULL && row_info != NULL &&
  198158. #endif
  198159. row_info->bit_depth < 8)
  198160. {
  198161. png_bytep rp, end, table;
  198162. end = row + row_info->rowbytes;
  198163. if (row_info->bit_depth == 1)
  198164. table = (png_bytep)onebppswaptable;
  198165. else if (row_info->bit_depth == 2)
  198166. table = (png_bytep)twobppswaptable;
  198167. else if (row_info->bit_depth == 4)
  198168. table = (png_bytep)fourbppswaptable;
  198169. else
  198170. return;
  198171. for (rp = row; rp < end; rp++)
  198172. *rp = table[*rp];
  198173. }
  198174. }
  198175. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198176. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198177. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198178. /* remove filler or alpha byte(s) */
  198179. void /* PRIVATE */
  198180. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198181. {
  198182. png_debug(1, "in png_do_strip_filler\n");
  198183. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198184. if (row != NULL && row_info != NULL)
  198185. #endif
  198186. {
  198187. png_bytep sp=row;
  198188. png_bytep dp=row;
  198189. png_uint_32 row_width=row_info->width;
  198190. png_uint_32 i;
  198191. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198192. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198193. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198194. row_info->channels == 4)
  198195. {
  198196. if (row_info->bit_depth == 8)
  198197. {
  198198. /* This converts from RGBX or RGBA to RGB */
  198199. if (flags & PNG_FLAG_FILLER_AFTER)
  198200. {
  198201. dp+=3; sp+=4;
  198202. for (i = 1; i < row_width; i++)
  198203. {
  198204. *dp++ = *sp++;
  198205. *dp++ = *sp++;
  198206. *dp++ = *sp++;
  198207. sp++;
  198208. }
  198209. }
  198210. /* This converts from XRGB or ARGB to RGB */
  198211. else
  198212. {
  198213. for (i = 0; i < row_width; i++)
  198214. {
  198215. sp++;
  198216. *dp++ = *sp++;
  198217. *dp++ = *sp++;
  198218. *dp++ = *sp++;
  198219. }
  198220. }
  198221. row_info->pixel_depth = 24;
  198222. row_info->rowbytes = row_width * 3;
  198223. }
  198224. else /* if (row_info->bit_depth == 16) */
  198225. {
  198226. if (flags & PNG_FLAG_FILLER_AFTER)
  198227. {
  198228. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198229. sp += 8; dp += 6;
  198230. for (i = 1; i < row_width; i++)
  198231. {
  198232. /* This could be (although png_memcpy is probably slower):
  198233. png_memcpy(dp, sp, 6);
  198234. sp += 8;
  198235. dp += 6;
  198236. */
  198237. *dp++ = *sp++;
  198238. *dp++ = *sp++;
  198239. *dp++ = *sp++;
  198240. *dp++ = *sp++;
  198241. *dp++ = *sp++;
  198242. *dp++ = *sp++;
  198243. sp += 2;
  198244. }
  198245. }
  198246. else
  198247. {
  198248. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198249. for (i = 0; i < row_width; i++)
  198250. {
  198251. /* This could be (although png_memcpy is probably slower):
  198252. png_memcpy(dp, sp, 6);
  198253. sp += 8;
  198254. dp += 6;
  198255. */
  198256. sp+=2;
  198257. *dp++ = *sp++;
  198258. *dp++ = *sp++;
  198259. *dp++ = *sp++;
  198260. *dp++ = *sp++;
  198261. *dp++ = *sp++;
  198262. *dp++ = *sp++;
  198263. }
  198264. }
  198265. row_info->pixel_depth = 48;
  198266. row_info->rowbytes = row_width * 6;
  198267. }
  198268. row_info->channels = 3;
  198269. }
  198270. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198271. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198272. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198273. row_info->channels == 2)
  198274. {
  198275. if (row_info->bit_depth == 8)
  198276. {
  198277. /* This converts from GX or GA to G */
  198278. if (flags & PNG_FLAG_FILLER_AFTER)
  198279. {
  198280. for (i = 0; i < row_width; i++)
  198281. {
  198282. *dp++ = *sp++;
  198283. sp++;
  198284. }
  198285. }
  198286. /* This converts from XG or AG to G */
  198287. else
  198288. {
  198289. for (i = 0; i < row_width; i++)
  198290. {
  198291. sp++;
  198292. *dp++ = *sp++;
  198293. }
  198294. }
  198295. row_info->pixel_depth = 8;
  198296. row_info->rowbytes = row_width;
  198297. }
  198298. else /* if (row_info->bit_depth == 16) */
  198299. {
  198300. if (flags & PNG_FLAG_FILLER_AFTER)
  198301. {
  198302. /* This converts from GGXX or GGAA to GG */
  198303. sp += 4; dp += 2;
  198304. for (i = 1; i < row_width; i++)
  198305. {
  198306. *dp++ = *sp++;
  198307. *dp++ = *sp++;
  198308. sp += 2;
  198309. }
  198310. }
  198311. else
  198312. {
  198313. /* This converts from XXGG or AAGG to GG */
  198314. for (i = 0; i < row_width; i++)
  198315. {
  198316. sp += 2;
  198317. *dp++ = *sp++;
  198318. *dp++ = *sp++;
  198319. }
  198320. }
  198321. row_info->pixel_depth = 16;
  198322. row_info->rowbytes = row_width * 2;
  198323. }
  198324. row_info->channels = 1;
  198325. }
  198326. if (flags & PNG_FLAG_STRIP_ALPHA)
  198327. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198328. }
  198329. }
  198330. #endif
  198331. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198332. /* swaps red and blue bytes within a pixel */
  198333. void /* PRIVATE */
  198334. png_do_bgr(png_row_infop row_info, png_bytep row)
  198335. {
  198336. png_debug(1, "in png_do_bgr\n");
  198337. if (
  198338. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198339. row != NULL && row_info != NULL &&
  198340. #endif
  198341. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198342. {
  198343. png_uint_32 row_width = row_info->width;
  198344. if (row_info->bit_depth == 8)
  198345. {
  198346. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198347. {
  198348. png_bytep rp;
  198349. png_uint_32 i;
  198350. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198351. {
  198352. png_byte save = *rp;
  198353. *rp = *(rp + 2);
  198354. *(rp + 2) = save;
  198355. }
  198356. }
  198357. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198358. {
  198359. png_bytep rp;
  198360. png_uint_32 i;
  198361. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198362. {
  198363. png_byte save = *rp;
  198364. *rp = *(rp + 2);
  198365. *(rp + 2) = save;
  198366. }
  198367. }
  198368. }
  198369. else if (row_info->bit_depth == 16)
  198370. {
  198371. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198372. {
  198373. png_bytep rp;
  198374. png_uint_32 i;
  198375. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198376. {
  198377. png_byte save = *rp;
  198378. *rp = *(rp + 4);
  198379. *(rp + 4) = save;
  198380. save = *(rp + 1);
  198381. *(rp + 1) = *(rp + 5);
  198382. *(rp + 5) = save;
  198383. }
  198384. }
  198385. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198386. {
  198387. png_bytep rp;
  198388. png_uint_32 i;
  198389. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198390. {
  198391. png_byte save = *rp;
  198392. *rp = *(rp + 4);
  198393. *(rp + 4) = save;
  198394. save = *(rp + 1);
  198395. *(rp + 1) = *(rp + 5);
  198396. *(rp + 5) = save;
  198397. }
  198398. }
  198399. }
  198400. }
  198401. }
  198402. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198403. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198404. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198405. defined(PNG_LEGACY_SUPPORTED)
  198406. void PNGAPI
  198407. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198408. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198409. {
  198410. png_debug(1, "in png_set_user_transform_info\n");
  198411. if(png_ptr == NULL) return;
  198412. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198413. png_ptr->user_transform_ptr = user_transform_ptr;
  198414. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198415. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198416. #else
  198417. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198418. png_warning(png_ptr,
  198419. "This version of libpng does not support user transform info");
  198420. #endif
  198421. }
  198422. #endif
  198423. /* This function returns a pointer to the user_transform_ptr associated with
  198424. * the user transform functions. The application should free any memory
  198425. * associated with this pointer before png_write_destroy and png_read_destroy
  198426. * are called.
  198427. */
  198428. png_voidp PNGAPI
  198429. png_get_user_transform_ptr(png_structp png_ptr)
  198430. {
  198431. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198432. if (png_ptr == NULL) return (NULL);
  198433. return ((png_voidp)png_ptr->user_transform_ptr);
  198434. #else
  198435. return (NULL);
  198436. #endif
  198437. }
  198438. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198439. /*** End of inlined file: pngtrans.c ***/
  198440. /*** Start of inlined file: pngwio.c ***/
  198441. /* pngwio.c - functions for data output
  198442. *
  198443. * Last changed in libpng 1.2.13 November 13, 2006
  198444. * For conditions of distribution and use, see copyright notice in png.h
  198445. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198446. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198447. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198448. *
  198449. * This file provides a location for all output. Users who need
  198450. * special handling are expected to write functions that have the same
  198451. * arguments as these and perform similar functions, but that possibly
  198452. * use different output methods. Note that you shouldn't change these
  198453. * functions, but rather write replacement functions and then change
  198454. * them at run time with png_set_write_fn(...).
  198455. */
  198456. #define PNG_INTERNAL
  198457. #ifdef PNG_WRITE_SUPPORTED
  198458. /* Write the data to whatever output you are using. The default routine
  198459. writes to a file pointer. Note that this routine sometimes gets called
  198460. with very small lengths, so you should implement some kind of simple
  198461. buffering if you are using unbuffered writes. This should never be asked
  198462. to write more than 64K on a 16 bit machine. */
  198463. void /* PRIVATE */
  198464. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198465. {
  198466. if (png_ptr->write_data_fn != NULL )
  198467. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198468. else
  198469. png_error(png_ptr, "Call to NULL write function");
  198470. }
  198471. #if !defined(PNG_NO_STDIO)
  198472. /* This is the function that does the actual writing of data. If you are
  198473. not writing to a standard C stream, you should create a replacement
  198474. write_data function and use it at run time with png_set_write_fn(), rather
  198475. than changing the library. */
  198476. #ifndef USE_FAR_KEYWORD
  198477. void PNGAPI
  198478. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198479. {
  198480. png_uint_32 check;
  198481. if(png_ptr == NULL) return;
  198482. #if defined(_WIN32_WCE)
  198483. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198484. check = 0;
  198485. #else
  198486. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198487. #endif
  198488. if (check != length)
  198489. png_error(png_ptr, "Write Error");
  198490. }
  198491. #else
  198492. /* this is the model-independent version. Since the standard I/O library
  198493. can't handle far buffers in the medium and small models, we have to copy
  198494. the data.
  198495. */
  198496. #define NEAR_BUF_SIZE 1024
  198497. #define MIN(a,b) (a <= b ? a : b)
  198498. void PNGAPI
  198499. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198500. {
  198501. png_uint_32 check;
  198502. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198503. png_FILE_p io_ptr;
  198504. if(png_ptr == NULL) return;
  198505. /* Check if data really is near. If so, use usual code. */
  198506. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198507. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198508. if ((png_bytep)near_data == data)
  198509. {
  198510. #if defined(_WIN32_WCE)
  198511. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198512. check = 0;
  198513. #else
  198514. check = fwrite(near_data, 1, length, io_ptr);
  198515. #endif
  198516. }
  198517. else
  198518. {
  198519. png_byte buf[NEAR_BUF_SIZE];
  198520. png_size_t written, remaining, err;
  198521. check = 0;
  198522. remaining = length;
  198523. do
  198524. {
  198525. written = MIN(NEAR_BUF_SIZE, remaining);
  198526. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198527. #if defined(_WIN32_WCE)
  198528. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198529. err = 0;
  198530. #else
  198531. err = fwrite(buf, 1, written, io_ptr);
  198532. #endif
  198533. if (err != written)
  198534. break;
  198535. else
  198536. check += err;
  198537. data += written;
  198538. remaining -= written;
  198539. }
  198540. while (remaining != 0);
  198541. }
  198542. if (check != length)
  198543. png_error(png_ptr, "Write Error");
  198544. }
  198545. #endif
  198546. #endif
  198547. /* This function is called to output any data pending writing (normally
  198548. to disk). After png_flush is called, there should be no data pending
  198549. writing in any buffers. */
  198550. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198551. void /* PRIVATE */
  198552. png_flush(png_structp png_ptr)
  198553. {
  198554. if (png_ptr->output_flush_fn != NULL)
  198555. (*(png_ptr->output_flush_fn))(png_ptr);
  198556. }
  198557. #if !defined(PNG_NO_STDIO)
  198558. void PNGAPI
  198559. png_default_flush(png_structp png_ptr)
  198560. {
  198561. #if !defined(_WIN32_WCE)
  198562. png_FILE_p io_ptr;
  198563. #endif
  198564. if(png_ptr == NULL) return;
  198565. #if !defined(_WIN32_WCE)
  198566. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198567. if (io_ptr != NULL)
  198568. fflush(io_ptr);
  198569. #endif
  198570. }
  198571. #endif
  198572. #endif
  198573. /* This function allows the application to supply new output functions for
  198574. libpng if standard C streams aren't being used.
  198575. This function takes as its arguments:
  198576. png_ptr - pointer to a png output data structure
  198577. io_ptr - pointer to user supplied structure containing info about
  198578. the output functions. May be NULL.
  198579. write_data_fn - pointer to a new output function that takes as its
  198580. arguments a pointer to a png_struct, a pointer to
  198581. data to be written, and a 32-bit unsigned int that is
  198582. the number of bytes to be written. The new write
  198583. function should call png_error(png_ptr, "Error msg")
  198584. to exit and output any fatal error messages.
  198585. flush_data_fn - pointer to a new flush function that takes as its
  198586. arguments a pointer to a png_struct. After a call to
  198587. the flush function, there should be no data in any buffers
  198588. or pending transmission. If the output method doesn't do
  198589. any buffering of ouput, a function prototype must still be
  198590. supplied although it doesn't have to do anything. If
  198591. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198592. time, output_flush_fn will be ignored, although it must be
  198593. supplied for compatibility. */
  198594. void PNGAPI
  198595. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198596. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198597. {
  198598. if(png_ptr == NULL) return;
  198599. png_ptr->io_ptr = io_ptr;
  198600. #if !defined(PNG_NO_STDIO)
  198601. if (write_data_fn != NULL)
  198602. png_ptr->write_data_fn = write_data_fn;
  198603. else
  198604. png_ptr->write_data_fn = png_default_write_data;
  198605. #else
  198606. png_ptr->write_data_fn = write_data_fn;
  198607. #endif
  198608. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198609. #if !defined(PNG_NO_STDIO)
  198610. if (output_flush_fn != NULL)
  198611. png_ptr->output_flush_fn = output_flush_fn;
  198612. else
  198613. png_ptr->output_flush_fn = png_default_flush;
  198614. #else
  198615. png_ptr->output_flush_fn = output_flush_fn;
  198616. #endif
  198617. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198618. /* It is an error to read while writing a png file */
  198619. if (png_ptr->read_data_fn != NULL)
  198620. {
  198621. png_ptr->read_data_fn = NULL;
  198622. png_warning(png_ptr,
  198623. "Attempted to set both read_data_fn and write_data_fn in");
  198624. png_warning(png_ptr,
  198625. "the same structure. Resetting read_data_fn to NULL.");
  198626. }
  198627. }
  198628. #if defined(USE_FAR_KEYWORD)
  198629. #if defined(_MSC_VER)
  198630. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198631. {
  198632. void *near_ptr;
  198633. void FAR *far_ptr;
  198634. FP_OFF(near_ptr) = FP_OFF(ptr);
  198635. far_ptr = (void FAR *)near_ptr;
  198636. if(check != 0)
  198637. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198638. png_error(png_ptr,"segment lost in conversion");
  198639. return(near_ptr);
  198640. }
  198641. # else
  198642. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198643. {
  198644. void *near_ptr;
  198645. void FAR *far_ptr;
  198646. near_ptr = (void FAR *)ptr;
  198647. far_ptr = (void FAR *)near_ptr;
  198648. if(check != 0)
  198649. if(far_ptr != ptr)
  198650. png_error(png_ptr,"segment lost in conversion");
  198651. return(near_ptr);
  198652. }
  198653. # endif
  198654. # endif
  198655. #endif /* PNG_WRITE_SUPPORTED */
  198656. /*** End of inlined file: pngwio.c ***/
  198657. /*** Start of inlined file: pngwrite.c ***/
  198658. /* pngwrite.c - general routines to write a PNG file
  198659. *
  198660. * Last changed in libpng 1.2.15 January 5, 2007
  198661. * For conditions of distribution and use, see copyright notice in png.h
  198662. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198663. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198664. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198665. */
  198666. /* get internal access to png.h */
  198667. #define PNG_INTERNAL
  198668. #ifdef PNG_WRITE_SUPPORTED
  198669. /* Writes all the PNG information. This is the suggested way to use the
  198670. * library. If you have a new chunk to add, make a function to write it,
  198671. * and put it in the correct location here. If you want the chunk written
  198672. * after the image data, put it in png_write_end(). I strongly encourage
  198673. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198674. * the chunk, as that will keep the code from breaking if you want to just
  198675. * write a plain PNG file. If you have long comments, I suggest writing
  198676. * them in png_write_end(), and compressing them.
  198677. */
  198678. void PNGAPI
  198679. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198680. {
  198681. png_debug(1, "in png_write_info_before_PLTE\n");
  198682. if (png_ptr == NULL || info_ptr == NULL)
  198683. return;
  198684. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198685. {
  198686. png_write_sig(png_ptr); /* write PNG signature */
  198687. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198688. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198689. {
  198690. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198691. png_ptr->mng_features_permitted=0;
  198692. }
  198693. #endif
  198694. /* write IHDR information. */
  198695. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198696. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198697. info_ptr->filter_type,
  198698. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198699. info_ptr->interlace_type);
  198700. #else
  198701. 0);
  198702. #endif
  198703. /* the rest of these check to see if the valid field has the appropriate
  198704. flag set, and if it does, writes the chunk. */
  198705. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198706. if (info_ptr->valid & PNG_INFO_gAMA)
  198707. {
  198708. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198709. png_write_gAMA(png_ptr, info_ptr->gamma);
  198710. #else
  198711. #ifdef PNG_FIXED_POINT_SUPPORTED
  198712. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198713. # endif
  198714. #endif
  198715. }
  198716. #endif
  198717. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198718. if (info_ptr->valid & PNG_INFO_sRGB)
  198719. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198720. #endif
  198721. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198722. if (info_ptr->valid & PNG_INFO_iCCP)
  198723. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198724. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198725. #endif
  198726. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198727. if (info_ptr->valid & PNG_INFO_sBIT)
  198728. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198729. #endif
  198730. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198731. if (info_ptr->valid & PNG_INFO_cHRM)
  198732. {
  198733. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198734. png_write_cHRM(png_ptr,
  198735. info_ptr->x_white, info_ptr->y_white,
  198736. info_ptr->x_red, info_ptr->y_red,
  198737. info_ptr->x_green, info_ptr->y_green,
  198738. info_ptr->x_blue, info_ptr->y_blue);
  198739. #else
  198740. # ifdef PNG_FIXED_POINT_SUPPORTED
  198741. png_write_cHRM_fixed(png_ptr,
  198742. info_ptr->int_x_white, info_ptr->int_y_white,
  198743. info_ptr->int_x_red, info_ptr->int_y_red,
  198744. info_ptr->int_x_green, info_ptr->int_y_green,
  198745. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198746. # endif
  198747. #endif
  198748. }
  198749. #endif
  198750. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198751. if (info_ptr->unknown_chunks_num)
  198752. {
  198753. png_unknown_chunk *up;
  198754. png_debug(5, "writing extra chunks\n");
  198755. for (up = info_ptr->unknown_chunks;
  198756. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198757. up++)
  198758. {
  198759. int keep=png_handle_as_unknown(png_ptr, up->name);
  198760. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198761. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198762. !(up->location & PNG_HAVE_IDAT) &&
  198763. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198764. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198765. {
  198766. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198767. }
  198768. }
  198769. }
  198770. #endif
  198771. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198772. }
  198773. }
  198774. void PNGAPI
  198775. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198776. {
  198777. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198778. int i;
  198779. #endif
  198780. png_debug(1, "in png_write_info\n");
  198781. if (png_ptr == NULL || info_ptr == NULL)
  198782. return;
  198783. png_write_info_before_PLTE(png_ptr, info_ptr);
  198784. if (info_ptr->valid & PNG_INFO_PLTE)
  198785. png_write_PLTE(png_ptr, info_ptr->palette,
  198786. (png_uint_32)info_ptr->num_palette);
  198787. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198788. png_error(png_ptr, "Valid palette required for paletted images");
  198789. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198790. if (info_ptr->valid & PNG_INFO_tRNS)
  198791. {
  198792. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198793. /* invert the alpha channel (in tRNS) */
  198794. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198795. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198796. {
  198797. int j;
  198798. for (j=0; j<(int)info_ptr->num_trans; j++)
  198799. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198800. }
  198801. #endif
  198802. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198803. info_ptr->num_trans, info_ptr->color_type);
  198804. }
  198805. #endif
  198806. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198807. if (info_ptr->valid & PNG_INFO_bKGD)
  198808. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198809. #endif
  198810. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198811. if (info_ptr->valid & PNG_INFO_hIST)
  198812. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198813. #endif
  198814. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198815. if (info_ptr->valid & PNG_INFO_oFFs)
  198816. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198817. info_ptr->offset_unit_type);
  198818. #endif
  198819. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198820. if (info_ptr->valid & PNG_INFO_pCAL)
  198821. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198822. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198823. info_ptr->pcal_units, info_ptr->pcal_params);
  198824. #endif
  198825. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198826. if (info_ptr->valid & PNG_INFO_sCAL)
  198827. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198828. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198829. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198830. #else
  198831. #ifdef PNG_FIXED_POINT_SUPPORTED
  198832. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198833. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198834. #else
  198835. png_warning(png_ptr,
  198836. "png_write_sCAL not supported; sCAL chunk not written.");
  198837. #endif
  198838. #endif
  198839. #endif
  198840. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198841. if (info_ptr->valid & PNG_INFO_pHYs)
  198842. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198843. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198844. #endif
  198845. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198846. if (info_ptr->valid & PNG_INFO_tIME)
  198847. {
  198848. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198849. png_ptr->mode |= PNG_WROTE_tIME;
  198850. }
  198851. #endif
  198852. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198853. if (info_ptr->valid & PNG_INFO_sPLT)
  198854. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198855. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198856. #endif
  198857. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198858. /* Check to see if we need to write text chunks */
  198859. for (i = 0; i < info_ptr->num_text; i++)
  198860. {
  198861. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198862. info_ptr->text[i].compression);
  198863. /* an internationalized chunk? */
  198864. if (info_ptr->text[i].compression > 0)
  198865. {
  198866. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198867. /* write international chunk */
  198868. png_write_iTXt(png_ptr,
  198869. info_ptr->text[i].compression,
  198870. info_ptr->text[i].key,
  198871. info_ptr->text[i].lang,
  198872. info_ptr->text[i].lang_key,
  198873. info_ptr->text[i].text);
  198874. #else
  198875. png_warning(png_ptr, "Unable to write international text");
  198876. #endif
  198877. /* Mark this chunk as written */
  198878. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198879. }
  198880. /* If we want a compressed text chunk */
  198881. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198882. {
  198883. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198884. /* write compressed chunk */
  198885. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198886. info_ptr->text[i].text, 0,
  198887. info_ptr->text[i].compression);
  198888. #else
  198889. png_warning(png_ptr, "Unable to write compressed text");
  198890. #endif
  198891. /* Mark this chunk as written */
  198892. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198893. }
  198894. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198895. {
  198896. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198897. /* write uncompressed chunk */
  198898. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198899. info_ptr->text[i].text,
  198900. 0);
  198901. #else
  198902. png_warning(png_ptr, "Unable to write uncompressed text");
  198903. #endif
  198904. /* Mark this chunk as written */
  198905. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198906. }
  198907. }
  198908. #endif
  198909. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198910. if (info_ptr->unknown_chunks_num)
  198911. {
  198912. png_unknown_chunk *up;
  198913. png_debug(5, "writing extra chunks\n");
  198914. for (up = info_ptr->unknown_chunks;
  198915. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198916. up++)
  198917. {
  198918. int keep=png_handle_as_unknown(png_ptr, up->name);
  198919. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198920. up->location && (up->location & PNG_HAVE_PLTE) &&
  198921. !(up->location & PNG_HAVE_IDAT) &&
  198922. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198923. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198924. {
  198925. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198926. }
  198927. }
  198928. }
  198929. #endif
  198930. }
  198931. /* Writes the end of the PNG file. If you don't want to write comments or
  198932. * time information, you can pass NULL for info. If you already wrote these
  198933. * in png_write_info(), do not write them again here. If you have long
  198934. * comments, I suggest writing them here, and compressing them.
  198935. */
  198936. void PNGAPI
  198937. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198938. {
  198939. png_debug(1, "in png_write_end\n");
  198940. if (png_ptr == NULL)
  198941. return;
  198942. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198943. png_error(png_ptr, "No IDATs written into file");
  198944. /* see if user wants us to write information chunks */
  198945. if (info_ptr != NULL)
  198946. {
  198947. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198948. int i; /* local index variable */
  198949. #endif
  198950. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198951. /* check to see if user has supplied a time chunk */
  198952. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198953. !(png_ptr->mode & PNG_WROTE_tIME))
  198954. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198955. #endif
  198956. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198957. /* loop through comment chunks */
  198958. for (i = 0; i < info_ptr->num_text; i++)
  198959. {
  198960. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198961. info_ptr->text[i].compression);
  198962. /* an internationalized chunk? */
  198963. if (info_ptr->text[i].compression > 0)
  198964. {
  198965. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198966. /* write international chunk */
  198967. png_write_iTXt(png_ptr,
  198968. info_ptr->text[i].compression,
  198969. info_ptr->text[i].key,
  198970. info_ptr->text[i].lang,
  198971. info_ptr->text[i].lang_key,
  198972. info_ptr->text[i].text);
  198973. #else
  198974. png_warning(png_ptr, "Unable to write international text");
  198975. #endif
  198976. /* Mark this chunk as written */
  198977. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198978. }
  198979. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198980. {
  198981. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198982. /* write compressed chunk */
  198983. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198984. info_ptr->text[i].text, 0,
  198985. info_ptr->text[i].compression);
  198986. #else
  198987. png_warning(png_ptr, "Unable to write compressed text");
  198988. #endif
  198989. /* Mark this chunk as written */
  198990. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198991. }
  198992. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198993. {
  198994. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198995. /* write uncompressed chunk */
  198996. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198997. info_ptr->text[i].text, 0);
  198998. #else
  198999. png_warning(png_ptr, "Unable to write uncompressed text");
  199000. #endif
  199001. /* Mark this chunk as written */
  199002. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199003. }
  199004. }
  199005. #endif
  199006. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199007. if (info_ptr->unknown_chunks_num)
  199008. {
  199009. png_unknown_chunk *up;
  199010. png_debug(5, "writing extra chunks\n");
  199011. for (up = info_ptr->unknown_chunks;
  199012. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199013. up++)
  199014. {
  199015. int keep=png_handle_as_unknown(png_ptr, up->name);
  199016. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199017. up->location && (up->location & PNG_AFTER_IDAT) &&
  199018. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199019. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199020. {
  199021. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199022. }
  199023. }
  199024. }
  199025. #endif
  199026. }
  199027. png_ptr->mode |= PNG_AFTER_IDAT;
  199028. /* write end of PNG file */
  199029. png_write_IEND(png_ptr);
  199030. }
  199031. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199032. #if !defined(_WIN32_WCE)
  199033. /* "time.h" functions are not supported on WindowsCE */
  199034. void PNGAPI
  199035. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199036. {
  199037. png_debug(1, "in png_convert_from_struct_tm\n");
  199038. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199039. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199040. ptime->day = (png_byte)ttime->tm_mday;
  199041. ptime->hour = (png_byte)ttime->tm_hour;
  199042. ptime->minute = (png_byte)ttime->tm_min;
  199043. ptime->second = (png_byte)ttime->tm_sec;
  199044. }
  199045. void PNGAPI
  199046. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199047. {
  199048. struct tm *tbuf;
  199049. png_debug(1, "in png_convert_from_time_t\n");
  199050. tbuf = gmtime(&ttime);
  199051. png_convert_from_struct_tm(ptime, tbuf);
  199052. }
  199053. #endif
  199054. #endif
  199055. /* Initialize png_ptr structure, and allocate any memory needed */
  199056. png_structp PNGAPI
  199057. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199058. png_error_ptr error_fn, png_error_ptr warn_fn)
  199059. {
  199060. #ifdef PNG_USER_MEM_SUPPORTED
  199061. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199062. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199063. }
  199064. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199065. png_structp PNGAPI
  199066. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199067. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199068. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199069. {
  199070. #endif /* PNG_USER_MEM_SUPPORTED */
  199071. png_structp png_ptr;
  199072. #ifdef PNG_SETJMP_SUPPORTED
  199073. #ifdef USE_FAR_KEYWORD
  199074. jmp_buf jmpbuf;
  199075. #endif
  199076. #endif
  199077. int i;
  199078. png_debug(1, "in png_create_write_struct\n");
  199079. #ifdef PNG_USER_MEM_SUPPORTED
  199080. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199081. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199082. #else
  199083. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199084. #endif /* PNG_USER_MEM_SUPPORTED */
  199085. if (png_ptr == NULL)
  199086. return (NULL);
  199087. /* added at libpng-1.2.6 */
  199088. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199089. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199090. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199091. #endif
  199092. #ifdef PNG_SETJMP_SUPPORTED
  199093. #ifdef USE_FAR_KEYWORD
  199094. if (setjmp(jmpbuf))
  199095. #else
  199096. if (setjmp(png_ptr->jmpbuf))
  199097. #endif
  199098. {
  199099. png_free(png_ptr, png_ptr->zbuf);
  199100. png_ptr->zbuf=NULL;
  199101. png_destroy_struct(png_ptr);
  199102. return (NULL);
  199103. }
  199104. #ifdef USE_FAR_KEYWORD
  199105. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199106. #endif
  199107. #endif
  199108. #ifdef PNG_USER_MEM_SUPPORTED
  199109. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199110. #endif /* PNG_USER_MEM_SUPPORTED */
  199111. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199112. i=0;
  199113. do
  199114. {
  199115. if(user_png_ver[i] != png_libpng_ver[i])
  199116. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199117. } while (png_libpng_ver[i++]);
  199118. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199119. {
  199120. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199121. * we must recompile any applications that use any older library version.
  199122. * For versions after libpng 1.0, we will be compatible, so we need
  199123. * only check the first digit.
  199124. */
  199125. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199126. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199127. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199128. {
  199129. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199130. char msg[80];
  199131. if (user_png_ver)
  199132. {
  199133. png_snprintf(msg, 80,
  199134. "Application was compiled with png.h from libpng-%.20s",
  199135. user_png_ver);
  199136. png_warning(png_ptr, msg);
  199137. }
  199138. png_snprintf(msg, 80,
  199139. "Application is running with png.c from libpng-%.20s",
  199140. png_libpng_ver);
  199141. png_warning(png_ptr, msg);
  199142. #endif
  199143. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199144. png_ptr->flags=0;
  199145. #endif
  199146. png_error(png_ptr,
  199147. "Incompatible libpng version in application and library");
  199148. }
  199149. }
  199150. /* initialize zbuf - compression buffer */
  199151. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199152. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199153. (png_uint_32)png_ptr->zbuf_size);
  199154. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199155. png_flush_ptr_NULL);
  199156. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199157. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199158. 1, png_doublep_NULL, png_doublep_NULL);
  199159. #endif
  199160. #ifdef PNG_SETJMP_SUPPORTED
  199161. /* Applications that neglect to set up their own setjmp() and then encounter
  199162. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199163. abort instead of returning. */
  199164. #ifdef USE_FAR_KEYWORD
  199165. if (setjmp(jmpbuf))
  199166. PNG_ABORT();
  199167. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199168. #else
  199169. if (setjmp(png_ptr->jmpbuf))
  199170. PNG_ABORT();
  199171. #endif
  199172. #endif
  199173. return (png_ptr);
  199174. }
  199175. /* Initialize png_ptr structure, and allocate any memory needed */
  199176. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199177. /* Deprecated. */
  199178. #undef png_write_init
  199179. void PNGAPI
  199180. png_write_init(png_structp png_ptr)
  199181. {
  199182. /* We only come here via pre-1.0.7-compiled applications */
  199183. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199184. }
  199185. void PNGAPI
  199186. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199187. png_size_t png_struct_size, png_size_t png_info_size)
  199188. {
  199189. /* We only come here via pre-1.0.12-compiled applications */
  199190. if(png_ptr == NULL) return;
  199191. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199192. if(png_sizeof(png_struct) > png_struct_size ||
  199193. png_sizeof(png_info) > png_info_size)
  199194. {
  199195. char msg[80];
  199196. png_ptr->warning_fn=NULL;
  199197. if (user_png_ver)
  199198. {
  199199. png_snprintf(msg, 80,
  199200. "Application was compiled with png.h from libpng-%.20s",
  199201. user_png_ver);
  199202. png_warning(png_ptr, msg);
  199203. }
  199204. png_snprintf(msg, 80,
  199205. "Application is running with png.c from libpng-%.20s",
  199206. png_libpng_ver);
  199207. png_warning(png_ptr, msg);
  199208. }
  199209. #endif
  199210. if(png_sizeof(png_struct) > png_struct_size)
  199211. {
  199212. png_ptr->error_fn=NULL;
  199213. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199214. png_ptr->flags=0;
  199215. #endif
  199216. png_error(png_ptr,
  199217. "The png struct allocated by the application for writing is too small.");
  199218. }
  199219. if(png_sizeof(png_info) > png_info_size)
  199220. {
  199221. png_ptr->error_fn=NULL;
  199222. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199223. png_ptr->flags=0;
  199224. #endif
  199225. png_error(png_ptr,
  199226. "The info struct allocated by the application for writing is too small.");
  199227. }
  199228. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199229. }
  199230. #endif /* PNG_1_0_X || PNG_1_2_X */
  199231. void PNGAPI
  199232. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199233. png_size_t png_struct_size)
  199234. {
  199235. png_structp png_ptr=*ptr_ptr;
  199236. #ifdef PNG_SETJMP_SUPPORTED
  199237. jmp_buf tmp_jmp; /* to save current jump buffer */
  199238. #endif
  199239. int i = 0;
  199240. if (png_ptr == NULL)
  199241. return;
  199242. do
  199243. {
  199244. if (user_png_ver[i] != png_libpng_ver[i])
  199245. {
  199246. #ifdef PNG_LEGACY_SUPPORTED
  199247. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199248. #else
  199249. png_ptr->warning_fn=NULL;
  199250. png_warning(png_ptr,
  199251. "Application uses deprecated png_write_init() and should be recompiled.");
  199252. break;
  199253. #endif
  199254. }
  199255. } while (png_libpng_ver[i++]);
  199256. png_debug(1, "in png_write_init_3\n");
  199257. #ifdef PNG_SETJMP_SUPPORTED
  199258. /* save jump buffer and error functions */
  199259. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199260. #endif
  199261. if (png_sizeof(png_struct) > png_struct_size)
  199262. {
  199263. png_destroy_struct(png_ptr);
  199264. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199265. *ptr_ptr = png_ptr;
  199266. }
  199267. /* reset all variables to 0 */
  199268. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199269. /* added at libpng-1.2.6 */
  199270. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199271. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199272. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199273. #endif
  199274. #ifdef PNG_SETJMP_SUPPORTED
  199275. /* restore jump buffer */
  199276. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199277. #endif
  199278. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199279. png_flush_ptr_NULL);
  199280. /* initialize zbuf - compression buffer */
  199281. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199282. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199283. (png_uint_32)png_ptr->zbuf_size);
  199284. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199285. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199286. 1, png_doublep_NULL, png_doublep_NULL);
  199287. #endif
  199288. }
  199289. /* Write a few rows of image data. If the image is interlaced,
  199290. * either you will have to write the 7 sub images, or, if you
  199291. * have called png_set_interlace_handling(), you will have to
  199292. * "write" the image seven times.
  199293. */
  199294. void PNGAPI
  199295. png_write_rows(png_structp png_ptr, png_bytepp row,
  199296. png_uint_32 num_rows)
  199297. {
  199298. png_uint_32 i; /* row counter */
  199299. png_bytepp rp; /* row pointer */
  199300. png_debug(1, "in png_write_rows\n");
  199301. if (png_ptr == NULL)
  199302. return;
  199303. /* loop through the rows */
  199304. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199305. {
  199306. png_write_row(png_ptr, *rp);
  199307. }
  199308. }
  199309. /* Write the image. You only need to call this function once, even
  199310. * if you are writing an interlaced image.
  199311. */
  199312. void PNGAPI
  199313. png_write_image(png_structp png_ptr, png_bytepp image)
  199314. {
  199315. png_uint_32 i; /* row index */
  199316. int pass, num_pass; /* pass variables */
  199317. png_bytepp rp; /* points to current row */
  199318. if (png_ptr == NULL)
  199319. return;
  199320. png_debug(1, "in png_write_image\n");
  199321. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199322. /* intialize interlace handling. If image is not interlaced,
  199323. this will set pass to 1 */
  199324. num_pass = png_set_interlace_handling(png_ptr);
  199325. #else
  199326. num_pass = 1;
  199327. #endif
  199328. /* loop through passes */
  199329. for (pass = 0; pass < num_pass; pass++)
  199330. {
  199331. /* loop through image */
  199332. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199333. {
  199334. png_write_row(png_ptr, *rp);
  199335. }
  199336. }
  199337. }
  199338. /* called by user to write a row of image data */
  199339. void PNGAPI
  199340. png_write_row(png_structp png_ptr, png_bytep row)
  199341. {
  199342. if (png_ptr == NULL)
  199343. return;
  199344. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199345. png_ptr->row_number, png_ptr->pass);
  199346. /* initialize transformations and other stuff if first time */
  199347. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199348. {
  199349. /* make sure we wrote the header info */
  199350. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199351. png_error(png_ptr,
  199352. "png_write_info was never called before png_write_row.");
  199353. /* check for transforms that have been set but were defined out */
  199354. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199355. if (png_ptr->transformations & PNG_INVERT_MONO)
  199356. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199357. #endif
  199358. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199359. if (png_ptr->transformations & PNG_FILLER)
  199360. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199361. #endif
  199362. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199363. if (png_ptr->transformations & PNG_PACKSWAP)
  199364. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199365. #endif
  199366. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199367. if (png_ptr->transformations & PNG_PACK)
  199368. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199369. #endif
  199370. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199371. if (png_ptr->transformations & PNG_SHIFT)
  199372. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199373. #endif
  199374. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199375. if (png_ptr->transformations & PNG_BGR)
  199376. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199377. #endif
  199378. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199379. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199380. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199381. #endif
  199382. png_write_start_row(png_ptr);
  199383. }
  199384. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199385. /* if interlaced and not interested in row, return */
  199386. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199387. {
  199388. switch (png_ptr->pass)
  199389. {
  199390. case 0:
  199391. if (png_ptr->row_number & 0x07)
  199392. {
  199393. png_write_finish_row(png_ptr);
  199394. return;
  199395. }
  199396. break;
  199397. case 1:
  199398. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199399. {
  199400. png_write_finish_row(png_ptr);
  199401. return;
  199402. }
  199403. break;
  199404. case 2:
  199405. if ((png_ptr->row_number & 0x07) != 4)
  199406. {
  199407. png_write_finish_row(png_ptr);
  199408. return;
  199409. }
  199410. break;
  199411. case 3:
  199412. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199413. {
  199414. png_write_finish_row(png_ptr);
  199415. return;
  199416. }
  199417. break;
  199418. case 4:
  199419. if ((png_ptr->row_number & 0x03) != 2)
  199420. {
  199421. png_write_finish_row(png_ptr);
  199422. return;
  199423. }
  199424. break;
  199425. case 5:
  199426. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199427. {
  199428. png_write_finish_row(png_ptr);
  199429. return;
  199430. }
  199431. break;
  199432. case 6:
  199433. if (!(png_ptr->row_number & 0x01))
  199434. {
  199435. png_write_finish_row(png_ptr);
  199436. return;
  199437. }
  199438. break;
  199439. }
  199440. }
  199441. #endif
  199442. /* set up row info for transformations */
  199443. png_ptr->row_info.color_type = png_ptr->color_type;
  199444. png_ptr->row_info.width = png_ptr->usr_width;
  199445. png_ptr->row_info.channels = png_ptr->usr_channels;
  199446. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199447. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199448. png_ptr->row_info.channels);
  199449. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199450. png_ptr->row_info.width);
  199451. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199452. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199453. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199454. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199455. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199456. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199457. /* Copy user's row into buffer, leaving room for filter byte. */
  199458. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199459. png_ptr->row_info.rowbytes);
  199460. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199461. /* handle interlacing */
  199462. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199463. (png_ptr->transformations & PNG_INTERLACE))
  199464. {
  199465. png_do_write_interlace(&(png_ptr->row_info),
  199466. png_ptr->row_buf + 1, png_ptr->pass);
  199467. /* this should always get caught above, but still ... */
  199468. if (!(png_ptr->row_info.width))
  199469. {
  199470. png_write_finish_row(png_ptr);
  199471. return;
  199472. }
  199473. }
  199474. #endif
  199475. /* handle other transformations */
  199476. if (png_ptr->transformations)
  199477. png_do_write_transformations(png_ptr);
  199478. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199479. /* Write filter_method 64 (intrapixel differencing) only if
  199480. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199481. * 2. Libpng did not write a PNG signature (this filter_method is only
  199482. * used in PNG datastreams that are embedded in MNG datastreams) and
  199483. * 3. The application called png_permit_mng_features with a mask that
  199484. * included PNG_FLAG_MNG_FILTER_64 and
  199485. * 4. The filter_method is 64 and
  199486. * 5. The color_type is RGB or RGBA
  199487. */
  199488. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199489. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199490. {
  199491. /* Intrapixel differencing */
  199492. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199493. }
  199494. #endif
  199495. /* Find a filter if necessary, filter the row and write it out. */
  199496. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199497. if (png_ptr->write_row_fn != NULL)
  199498. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199499. }
  199500. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199501. /* Set the automatic flush interval or 0 to turn flushing off */
  199502. void PNGAPI
  199503. png_set_flush(png_structp png_ptr, int nrows)
  199504. {
  199505. png_debug(1, "in png_set_flush\n");
  199506. if (png_ptr == NULL)
  199507. return;
  199508. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199509. }
  199510. /* flush the current output buffers now */
  199511. void PNGAPI
  199512. png_write_flush(png_structp png_ptr)
  199513. {
  199514. int wrote_IDAT;
  199515. png_debug(1, "in png_write_flush\n");
  199516. if (png_ptr == NULL)
  199517. return;
  199518. /* We have already written out all of the data */
  199519. if (png_ptr->row_number >= png_ptr->num_rows)
  199520. return;
  199521. do
  199522. {
  199523. int ret;
  199524. /* compress the data */
  199525. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199526. wrote_IDAT = 0;
  199527. /* check for compression errors */
  199528. if (ret != Z_OK)
  199529. {
  199530. if (png_ptr->zstream.msg != NULL)
  199531. png_error(png_ptr, png_ptr->zstream.msg);
  199532. else
  199533. png_error(png_ptr, "zlib error");
  199534. }
  199535. if (!(png_ptr->zstream.avail_out))
  199536. {
  199537. /* write the IDAT and reset the zlib output buffer */
  199538. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199539. png_ptr->zbuf_size);
  199540. png_ptr->zstream.next_out = png_ptr->zbuf;
  199541. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199542. wrote_IDAT = 1;
  199543. }
  199544. } while(wrote_IDAT == 1);
  199545. /* If there is any data left to be output, write it into a new IDAT */
  199546. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199547. {
  199548. /* write the IDAT and reset the zlib output buffer */
  199549. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199550. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199551. png_ptr->zstream.next_out = png_ptr->zbuf;
  199552. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199553. }
  199554. png_ptr->flush_rows = 0;
  199555. png_flush(png_ptr);
  199556. }
  199557. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199558. /* free all memory used by the write */
  199559. void PNGAPI
  199560. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199561. {
  199562. png_structp png_ptr = NULL;
  199563. png_infop info_ptr = NULL;
  199564. #ifdef PNG_USER_MEM_SUPPORTED
  199565. png_free_ptr free_fn = NULL;
  199566. png_voidp mem_ptr = NULL;
  199567. #endif
  199568. png_debug(1, "in png_destroy_write_struct\n");
  199569. if (png_ptr_ptr != NULL)
  199570. {
  199571. png_ptr = *png_ptr_ptr;
  199572. #ifdef PNG_USER_MEM_SUPPORTED
  199573. free_fn = png_ptr->free_fn;
  199574. mem_ptr = png_ptr->mem_ptr;
  199575. #endif
  199576. }
  199577. if (info_ptr_ptr != NULL)
  199578. info_ptr = *info_ptr_ptr;
  199579. if (info_ptr != NULL)
  199580. {
  199581. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199582. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199583. if (png_ptr->num_chunk_list)
  199584. {
  199585. png_free(png_ptr, png_ptr->chunk_list);
  199586. png_ptr->chunk_list=NULL;
  199587. png_ptr->num_chunk_list=0;
  199588. }
  199589. #endif
  199590. #ifdef PNG_USER_MEM_SUPPORTED
  199591. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199592. (png_voidp)mem_ptr);
  199593. #else
  199594. png_destroy_struct((png_voidp)info_ptr);
  199595. #endif
  199596. *info_ptr_ptr = NULL;
  199597. }
  199598. if (png_ptr != NULL)
  199599. {
  199600. png_write_destroy(png_ptr);
  199601. #ifdef PNG_USER_MEM_SUPPORTED
  199602. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199603. (png_voidp)mem_ptr);
  199604. #else
  199605. png_destroy_struct((png_voidp)png_ptr);
  199606. #endif
  199607. *png_ptr_ptr = NULL;
  199608. }
  199609. }
  199610. /* Free any memory used in png_ptr struct (old method) */
  199611. void /* PRIVATE */
  199612. png_write_destroy(png_structp png_ptr)
  199613. {
  199614. #ifdef PNG_SETJMP_SUPPORTED
  199615. jmp_buf tmp_jmp; /* save jump buffer */
  199616. #endif
  199617. png_error_ptr error_fn;
  199618. png_error_ptr warning_fn;
  199619. png_voidp error_ptr;
  199620. #ifdef PNG_USER_MEM_SUPPORTED
  199621. png_free_ptr free_fn;
  199622. #endif
  199623. png_debug(1, "in png_write_destroy\n");
  199624. /* free any memory zlib uses */
  199625. deflateEnd(&png_ptr->zstream);
  199626. /* free our memory. png_free checks NULL for us. */
  199627. png_free(png_ptr, png_ptr->zbuf);
  199628. png_free(png_ptr, png_ptr->row_buf);
  199629. png_free(png_ptr, png_ptr->prev_row);
  199630. png_free(png_ptr, png_ptr->sub_row);
  199631. png_free(png_ptr, png_ptr->up_row);
  199632. png_free(png_ptr, png_ptr->avg_row);
  199633. png_free(png_ptr, png_ptr->paeth_row);
  199634. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199635. png_free(png_ptr, png_ptr->time_buffer);
  199636. #endif
  199637. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199638. png_free(png_ptr, png_ptr->prev_filters);
  199639. png_free(png_ptr, png_ptr->filter_weights);
  199640. png_free(png_ptr, png_ptr->inv_filter_weights);
  199641. png_free(png_ptr, png_ptr->filter_costs);
  199642. png_free(png_ptr, png_ptr->inv_filter_costs);
  199643. #endif
  199644. #ifdef PNG_SETJMP_SUPPORTED
  199645. /* reset structure */
  199646. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199647. #endif
  199648. error_fn = png_ptr->error_fn;
  199649. warning_fn = png_ptr->warning_fn;
  199650. error_ptr = png_ptr->error_ptr;
  199651. #ifdef PNG_USER_MEM_SUPPORTED
  199652. free_fn = png_ptr->free_fn;
  199653. #endif
  199654. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199655. png_ptr->error_fn = error_fn;
  199656. png_ptr->warning_fn = warning_fn;
  199657. png_ptr->error_ptr = error_ptr;
  199658. #ifdef PNG_USER_MEM_SUPPORTED
  199659. png_ptr->free_fn = free_fn;
  199660. #endif
  199661. #ifdef PNG_SETJMP_SUPPORTED
  199662. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199663. #endif
  199664. }
  199665. /* Allow the application to select one or more row filters to use. */
  199666. void PNGAPI
  199667. png_set_filter(png_structp png_ptr, int method, int filters)
  199668. {
  199669. png_debug(1, "in png_set_filter\n");
  199670. if (png_ptr == NULL)
  199671. return;
  199672. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199673. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199674. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199675. method = PNG_FILTER_TYPE_BASE;
  199676. #endif
  199677. if (method == PNG_FILTER_TYPE_BASE)
  199678. {
  199679. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199680. {
  199681. #ifndef PNG_NO_WRITE_FILTER
  199682. case 5:
  199683. case 6:
  199684. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199685. #endif /* PNG_NO_WRITE_FILTER */
  199686. case PNG_FILTER_VALUE_NONE:
  199687. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199688. #ifndef PNG_NO_WRITE_FILTER
  199689. case PNG_FILTER_VALUE_SUB:
  199690. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199691. case PNG_FILTER_VALUE_UP:
  199692. png_ptr->do_filter=PNG_FILTER_UP; break;
  199693. case PNG_FILTER_VALUE_AVG:
  199694. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199695. case PNG_FILTER_VALUE_PAETH:
  199696. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199697. default: png_ptr->do_filter = (png_byte)filters; break;
  199698. #else
  199699. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199700. #endif /* PNG_NO_WRITE_FILTER */
  199701. }
  199702. /* If we have allocated the row_buf, this means we have already started
  199703. * with the image and we should have allocated all of the filter buffers
  199704. * that have been selected. If prev_row isn't already allocated, then
  199705. * it is too late to start using the filters that need it, since we
  199706. * will be missing the data in the previous row. If an application
  199707. * wants to start and stop using particular filters during compression,
  199708. * it should start out with all of the filters, and then add and
  199709. * remove them after the start of compression.
  199710. */
  199711. if (png_ptr->row_buf != NULL)
  199712. {
  199713. #ifndef PNG_NO_WRITE_FILTER
  199714. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199715. {
  199716. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199717. (png_ptr->rowbytes + 1));
  199718. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199719. }
  199720. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199721. {
  199722. if (png_ptr->prev_row == NULL)
  199723. {
  199724. png_warning(png_ptr, "Can't add Up filter after starting");
  199725. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199726. }
  199727. else
  199728. {
  199729. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199730. (png_ptr->rowbytes + 1));
  199731. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199732. }
  199733. }
  199734. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199735. {
  199736. if (png_ptr->prev_row == NULL)
  199737. {
  199738. png_warning(png_ptr, "Can't add Average filter after starting");
  199739. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199740. }
  199741. else
  199742. {
  199743. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199744. (png_ptr->rowbytes + 1));
  199745. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199746. }
  199747. }
  199748. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199749. png_ptr->paeth_row == NULL)
  199750. {
  199751. if (png_ptr->prev_row == NULL)
  199752. {
  199753. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199754. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199755. }
  199756. else
  199757. {
  199758. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199759. (png_ptr->rowbytes + 1));
  199760. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199761. }
  199762. }
  199763. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199764. #endif /* PNG_NO_WRITE_FILTER */
  199765. png_ptr->do_filter = PNG_FILTER_NONE;
  199766. }
  199767. }
  199768. else
  199769. png_error(png_ptr, "Unknown custom filter method");
  199770. }
  199771. /* This allows us to influence the way in which libpng chooses the "best"
  199772. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199773. * differences metric is relatively fast and effective, there is some
  199774. * question as to whether it can be improved upon by trying to keep the
  199775. * filtered data going to zlib more consistent, hopefully resulting in
  199776. * better compression.
  199777. */
  199778. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199779. void PNGAPI
  199780. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199781. int num_weights, png_doublep filter_weights,
  199782. png_doublep filter_costs)
  199783. {
  199784. int i;
  199785. png_debug(1, "in png_set_filter_heuristics\n");
  199786. if (png_ptr == NULL)
  199787. return;
  199788. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199789. {
  199790. png_warning(png_ptr, "Unknown filter heuristic method");
  199791. return;
  199792. }
  199793. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199794. {
  199795. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199796. }
  199797. if (num_weights < 0 || filter_weights == NULL ||
  199798. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199799. {
  199800. num_weights = 0;
  199801. }
  199802. png_ptr->num_prev_filters = (png_byte)num_weights;
  199803. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199804. if (num_weights > 0)
  199805. {
  199806. if (png_ptr->prev_filters == NULL)
  199807. {
  199808. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199809. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199810. /* To make sure that the weighting starts out fairly */
  199811. for (i = 0; i < num_weights; i++)
  199812. {
  199813. png_ptr->prev_filters[i] = 255;
  199814. }
  199815. }
  199816. if (png_ptr->filter_weights == NULL)
  199817. {
  199818. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199819. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199820. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199821. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199822. for (i = 0; i < num_weights; i++)
  199823. {
  199824. png_ptr->inv_filter_weights[i] =
  199825. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199826. }
  199827. }
  199828. for (i = 0; i < num_weights; i++)
  199829. {
  199830. if (filter_weights[i] < 0.0)
  199831. {
  199832. png_ptr->inv_filter_weights[i] =
  199833. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199834. }
  199835. else
  199836. {
  199837. png_ptr->inv_filter_weights[i] =
  199838. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199839. png_ptr->filter_weights[i] =
  199840. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199841. }
  199842. }
  199843. }
  199844. /* If, in the future, there are other filter methods, this would
  199845. * need to be based on png_ptr->filter.
  199846. */
  199847. if (png_ptr->filter_costs == NULL)
  199848. {
  199849. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199850. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199851. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199852. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199853. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199854. {
  199855. png_ptr->inv_filter_costs[i] =
  199856. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199857. }
  199858. }
  199859. /* Here is where we set the relative costs of the different filters. We
  199860. * should take the desired compression level into account when setting
  199861. * the costs, so that Paeth, for instance, has a high relative cost at low
  199862. * compression levels, while it has a lower relative cost at higher
  199863. * compression settings. The filter types are in order of increasing
  199864. * relative cost, so it would be possible to do this with an algorithm.
  199865. */
  199866. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199867. {
  199868. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199869. {
  199870. png_ptr->inv_filter_costs[i] =
  199871. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199872. }
  199873. else if (filter_costs[i] >= 1.0)
  199874. {
  199875. png_ptr->inv_filter_costs[i] =
  199876. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199877. png_ptr->filter_costs[i] =
  199878. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199879. }
  199880. }
  199881. }
  199882. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199883. void PNGAPI
  199884. png_set_compression_level(png_structp png_ptr, int level)
  199885. {
  199886. png_debug(1, "in png_set_compression_level\n");
  199887. if (png_ptr == NULL)
  199888. return;
  199889. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199890. png_ptr->zlib_level = level;
  199891. }
  199892. void PNGAPI
  199893. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199894. {
  199895. png_debug(1, "in png_set_compression_mem_level\n");
  199896. if (png_ptr == NULL)
  199897. return;
  199898. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199899. png_ptr->zlib_mem_level = mem_level;
  199900. }
  199901. void PNGAPI
  199902. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199903. {
  199904. png_debug(1, "in png_set_compression_strategy\n");
  199905. if (png_ptr == NULL)
  199906. return;
  199907. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199908. png_ptr->zlib_strategy = strategy;
  199909. }
  199910. void PNGAPI
  199911. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199912. {
  199913. if (png_ptr == NULL)
  199914. return;
  199915. if (window_bits > 15)
  199916. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199917. else if (window_bits < 8)
  199918. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199919. #ifndef WBITS_8_OK
  199920. /* avoid libpng bug with 256-byte windows */
  199921. if (window_bits == 8)
  199922. {
  199923. png_warning(png_ptr, "Compression window is being reset to 512");
  199924. window_bits=9;
  199925. }
  199926. #endif
  199927. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199928. png_ptr->zlib_window_bits = window_bits;
  199929. }
  199930. void PNGAPI
  199931. png_set_compression_method(png_structp png_ptr, int method)
  199932. {
  199933. png_debug(1, "in png_set_compression_method\n");
  199934. if (png_ptr == NULL)
  199935. return;
  199936. if (method != 8)
  199937. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199938. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199939. png_ptr->zlib_method = method;
  199940. }
  199941. void PNGAPI
  199942. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199943. {
  199944. if (png_ptr == NULL)
  199945. return;
  199946. png_ptr->write_row_fn = write_row_fn;
  199947. }
  199948. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199949. void PNGAPI
  199950. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199951. write_user_transform_fn)
  199952. {
  199953. png_debug(1, "in png_set_write_user_transform_fn\n");
  199954. if (png_ptr == NULL)
  199955. return;
  199956. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199957. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199958. }
  199959. #endif
  199960. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199961. void PNGAPI
  199962. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199963. int transforms, voidp params)
  199964. {
  199965. if (png_ptr == NULL || info_ptr == NULL)
  199966. return;
  199967. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199968. /* invert the alpha channel from opacity to transparency */
  199969. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199970. png_set_invert_alpha(png_ptr);
  199971. #endif
  199972. /* Write the file header information. */
  199973. png_write_info(png_ptr, info_ptr);
  199974. /* ------ these transformations don't touch the info structure ------- */
  199975. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199976. /* invert monochrome pixels */
  199977. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199978. png_set_invert_mono(png_ptr);
  199979. #endif
  199980. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199981. /* Shift the pixels up to a legal bit depth and fill in
  199982. * as appropriate to correctly scale the image.
  199983. */
  199984. if ((transforms & PNG_TRANSFORM_SHIFT)
  199985. && (info_ptr->valid & PNG_INFO_sBIT))
  199986. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199987. #endif
  199988. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199989. /* pack pixels into bytes */
  199990. if (transforms & PNG_TRANSFORM_PACKING)
  199991. png_set_packing(png_ptr);
  199992. #endif
  199993. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199994. /* swap location of alpha bytes from ARGB to RGBA */
  199995. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199996. png_set_swap_alpha(png_ptr);
  199997. #endif
  199998. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199999. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200000. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200001. */
  200002. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200003. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200004. #endif
  200005. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200006. /* flip BGR pixels to RGB */
  200007. if (transforms & PNG_TRANSFORM_BGR)
  200008. png_set_bgr(png_ptr);
  200009. #endif
  200010. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200011. /* swap bytes of 16-bit files to most significant byte first */
  200012. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200013. png_set_swap(png_ptr);
  200014. #endif
  200015. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200016. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200017. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200018. png_set_packswap(png_ptr);
  200019. #endif
  200020. /* ----------------------- end of transformations ------------------- */
  200021. /* write the bits */
  200022. if (info_ptr->valid & PNG_INFO_IDAT)
  200023. png_write_image(png_ptr, info_ptr->row_pointers);
  200024. /* It is REQUIRED to call this to finish writing the rest of the file */
  200025. png_write_end(png_ptr, info_ptr);
  200026. transforms = transforms; /* quiet compiler warnings */
  200027. params = params;
  200028. }
  200029. #endif
  200030. #endif /* PNG_WRITE_SUPPORTED */
  200031. /*** End of inlined file: pngwrite.c ***/
  200032. /*** Start of inlined file: pngwtran.c ***/
  200033. /* pngwtran.c - transforms the data in a row for PNG writers
  200034. *
  200035. * Last changed in libpng 1.2.9 April 14, 2006
  200036. * For conditions of distribution and use, see copyright notice in png.h
  200037. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200038. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200039. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200040. */
  200041. #define PNG_INTERNAL
  200042. #ifdef PNG_WRITE_SUPPORTED
  200043. /* Transform the data according to the user's wishes. The order of
  200044. * transformations is significant.
  200045. */
  200046. void /* PRIVATE */
  200047. png_do_write_transformations(png_structp png_ptr)
  200048. {
  200049. png_debug(1, "in png_do_write_transformations\n");
  200050. if (png_ptr == NULL)
  200051. return;
  200052. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200053. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200054. if(png_ptr->write_user_transform_fn != NULL)
  200055. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200056. (png_ptr, /* png_ptr */
  200057. &(png_ptr->row_info), /* row_info: */
  200058. /* png_uint_32 width; width of row */
  200059. /* png_uint_32 rowbytes; number of bytes in row */
  200060. /* png_byte color_type; color type of pixels */
  200061. /* png_byte bit_depth; bit depth of samples */
  200062. /* png_byte channels; number of channels (1-4) */
  200063. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200064. png_ptr->row_buf + 1); /* start of pixel data for row */
  200065. #endif
  200066. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200067. if (png_ptr->transformations & PNG_FILLER)
  200068. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200069. png_ptr->flags);
  200070. #endif
  200071. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200072. if (png_ptr->transformations & PNG_PACKSWAP)
  200073. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200074. #endif
  200075. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200076. if (png_ptr->transformations & PNG_PACK)
  200077. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200078. (png_uint_32)png_ptr->bit_depth);
  200079. #endif
  200080. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200081. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200082. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200083. #endif
  200084. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200085. if (png_ptr->transformations & PNG_SHIFT)
  200086. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200087. &(png_ptr->shift));
  200088. #endif
  200089. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200090. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200091. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200092. #endif
  200093. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200094. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200095. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200096. #endif
  200097. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200098. if (png_ptr->transformations & PNG_BGR)
  200099. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200100. #endif
  200101. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200102. if (png_ptr->transformations & PNG_INVERT_MONO)
  200103. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200104. #endif
  200105. }
  200106. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200107. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200108. * row_info bit depth should be 8 (one pixel per byte). The channels
  200109. * should be 1 (this only happens on grayscale and paletted images).
  200110. */
  200111. void /* PRIVATE */
  200112. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200113. {
  200114. png_debug(1, "in png_do_pack\n");
  200115. if (row_info->bit_depth == 8 &&
  200116. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200117. row != NULL && row_info != NULL &&
  200118. #endif
  200119. row_info->channels == 1)
  200120. {
  200121. switch ((int)bit_depth)
  200122. {
  200123. case 1:
  200124. {
  200125. png_bytep sp, dp;
  200126. int mask, v;
  200127. png_uint_32 i;
  200128. png_uint_32 row_width = row_info->width;
  200129. sp = row;
  200130. dp = row;
  200131. mask = 0x80;
  200132. v = 0;
  200133. for (i = 0; i < row_width; i++)
  200134. {
  200135. if (*sp != 0)
  200136. v |= mask;
  200137. sp++;
  200138. if (mask > 1)
  200139. mask >>= 1;
  200140. else
  200141. {
  200142. mask = 0x80;
  200143. *dp = (png_byte)v;
  200144. dp++;
  200145. v = 0;
  200146. }
  200147. }
  200148. if (mask != 0x80)
  200149. *dp = (png_byte)v;
  200150. break;
  200151. }
  200152. case 2:
  200153. {
  200154. png_bytep sp, dp;
  200155. int shift, v;
  200156. png_uint_32 i;
  200157. png_uint_32 row_width = row_info->width;
  200158. sp = row;
  200159. dp = row;
  200160. shift = 6;
  200161. v = 0;
  200162. for (i = 0; i < row_width; i++)
  200163. {
  200164. png_byte value;
  200165. value = (png_byte)(*sp & 0x03);
  200166. v |= (value << shift);
  200167. if (shift == 0)
  200168. {
  200169. shift = 6;
  200170. *dp = (png_byte)v;
  200171. dp++;
  200172. v = 0;
  200173. }
  200174. else
  200175. shift -= 2;
  200176. sp++;
  200177. }
  200178. if (shift != 6)
  200179. *dp = (png_byte)v;
  200180. break;
  200181. }
  200182. case 4:
  200183. {
  200184. png_bytep sp, dp;
  200185. int shift, v;
  200186. png_uint_32 i;
  200187. png_uint_32 row_width = row_info->width;
  200188. sp = row;
  200189. dp = row;
  200190. shift = 4;
  200191. v = 0;
  200192. for (i = 0; i < row_width; i++)
  200193. {
  200194. png_byte value;
  200195. value = (png_byte)(*sp & 0x0f);
  200196. v |= (value << shift);
  200197. if (shift == 0)
  200198. {
  200199. shift = 4;
  200200. *dp = (png_byte)v;
  200201. dp++;
  200202. v = 0;
  200203. }
  200204. else
  200205. shift -= 4;
  200206. sp++;
  200207. }
  200208. if (shift != 4)
  200209. *dp = (png_byte)v;
  200210. break;
  200211. }
  200212. }
  200213. row_info->bit_depth = (png_byte)bit_depth;
  200214. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200215. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200216. row_info->width);
  200217. }
  200218. }
  200219. #endif
  200220. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200221. /* Shift pixel values to take advantage of whole range. Pass the
  200222. * true number of bits in bit_depth. The row should be packed
  200223. * according to row_info->bit_depth. Thus, if you had a row of
  200224. * bit depth 4, but the pixels only had values from 0 to 7, you
  200225. * would pass 3 as bit_depth, and this routine would translate the
  200226. * data to 0 to 15.
  200227. */
  200228. void /* PRIVATE */
  200229. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200230. {
  200231. png_debug(1, "in png_do_shift\n");
  200232. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200233. if (row != NULL && row_info != NULL &&
  200234. #else
  200235. if (
  200236. #endif
  200237. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200238. {
  200239. int shift_start[4], shift_dec[4];
  200240. int channels = 0;
  200241. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200242. {
  200243. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200244. shift_dec[channels] = bit_depth->red;
  200245. channels++;
  200246. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200247. shift_dec[channels] = bit_depth->green;
  200248. channels++;
  200249. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200250. shift_dec[channels] = bit_depth->blue;
  200251. channels++;
  200252. }
  200253. else
  200254. {
  200255. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200256. shift_dec[channels] = bit_depth->gray;
  200257. channels++;
  200258. }
  200259. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200260. {
  200261. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200262. shift_dec[channels] = bit_depth->alpha;
  200263. channels++;
  200264. }
  200265. /* with low row depths, could only be grayscale, so one channel */
  200266. if (row_info->bit_depth < 8)
  200267. {
  200268. png_bytep bp = row;
  200269. png_uint_32 i;
  200270. png_byte mask;
  200271. png_uint_32 row_bytes = row_info->rowbytes;
  200272. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200273. mask = 0x55;
  200274. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200275. mask = 0x11;
  200276. else
  200277. mask = 0xff;
  200278. for (i = 0; i < row_bytes; i++, bp++)
  200279. {
  200280. png_uint_16 v;
  200281. int j;
  200282. v = *bp;
  200283. *bp = 0;
  200284. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200285. {
  200286. if (j > 0)
  200287. *bp |= (png_byte)((v << j) & 0xff);
  200288. else
  200289. *bp |= (png_byte)((v >> (-j)) & mask);
  200290. }
  200291. }
  200292. }
  200293. else if (row_info->bit_depth == 8)
  200294. {
  200295. png_bytep bp = row;
  200296. png_uint_32 i;
  200297. png_uint_32 istop = channels * row_info->width;
  200298. for (i = 0; i < istop; i++, bp++)
  200299. {
  200300. png_uint_16 v;
  200301. int j;
  200302. int c = (int)(i%channels);
  200303. v = *bp;
  200304. *bp = 0;
  200305. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200306. {
  200307. if (j > 0)
  200308. *bp |= (png_byte)((v << j) & 0xff);
  200309. else
  200310. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200311. }
  200312. }
  200313. }
  200314. else
  200315. {
  200316. png_bytep bp;
  200317. png_uint_32 i;
  200318. png_uint_32 istop = channels * row_info->width;
  200319. for (bp = row, i = 0; i < istop; i++)
  200320. {
  200321. int c = (int)(i%channels);
  200322. png_uint_16 value, v;
  200323. int j;
  200324. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200325. value = 0;
  200326. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200327. {
  200328. if (j > 0)
  200329. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200330. else
  200331. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200332. }
  200333. *bp++ = (png_byte)(value >> 8);
  200334. *bp++ = (png_byte)(value & 0xff);
  200335. }
  200336. }
  200337. }
  200338. }
  200339. #endif
  200340. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200341. void /* PRIVATE */
  200342. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200343. {
  200344. png_debug(1, "in png_do_write_swap_alpha\n");
  200345. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200346. if (row != NULL && row_info != NULL)
  200347. #endif
  200348. {
  200349. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200350. {
  200351. /* This converts from ARGB to RGBA */
  200352. if (row_info->bit_depth == 8)
  200353. {
  200354. png_bytep sp, dp;
  200355. png_uint_32 i;
  200356. png_uint_32 row_width = row_info->width;
  200357. for (i = 0, sp = dp = row; i < row_width; i++)
  200358. {
  200359. png_byte save = *(sp++);
  200360. *(dp++) = *(sp++);
  200361. *(dp++) = *(sp++);
  200362. *(dp++) = *(sp++);
  200363. *(dp++) = save;
  200364. }
  200365. }
  200366. /* This converts from AARRGGBB to RRGGBBAA */
  200367. else
  200368. {
  200369. png_bytep sp, dp;
  200370. png_uint_32 i;
  200371. png_uint_32 row_width = row_info->width;
  200372. for (i = 0, sp = dp = row; i < row_width; i++)
  200373. {
  200374. png_byte save[2];
  200375. save[0] = *(sp++);
  200376. save[1] = *(sp++);
  200377. *(dp++) = *(sp++);
  200378. *(dp++) = *(sp++);
  200379. *(dp++) = *(sp++);
  200380. *(dp++) = *(sp++);
  200381. *(dp++) = *(sp++);
  200382. *(dp++) = *(sp++);
  200383. *(dp++) = save[0];
  200384. *(dp++) = save[1];
  200385. }
  200386. }
  200387. }
  200388. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200389. {
  200390. /* This converts from AG to GA */
  200391. if (row_info->bit_depth == 8)
  200392. {
  200393. png_bytep sp, dp;
  200394. png_uint_32 i;
  200395. png_uint_32 row_width = row_info->width;
  200396. for (i = 0, sp = dp = row; i < row_width; i++)
  200397. {
  200398. png_byte save = *(sp++);
  200399. *(dp++) = *(sp++);
  200400. *(dp++) = save;
  200401. }
  200402. }
  200403. /* This converts from AAGG to GGAA */
  200404. else
  200405. {
  200406. png_bytep sp, dp;
  200407. png_uint_32 i;
  200408. png_uint_32 row_width = row_info->width;
  200409. for (i = 0, sp = dp = row; i < row_width; i++)
  200410. {
  200411. png_byte save[2];
  200412. save[0] = *(sp++);
  200413. save[1] = *(sp++);
  200414. *(dp++) = *(sp++);
  200415. *(dp++) = *(sp++);
  200416. *(dp++) = save[0];
  200417. *(dp++) = save[1];
  200418. }
  200419. }
  200420. }
  200421. }
  200422. }
  200423. #endif
  200424. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200425. void /* PRIVATE */
  200426. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200427. {
  200428. png_debug(1, "in png_do_write_invert_alpha\n");
  200429. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200430. if (row != NULL && row_info != NULL)
  200431. #endif
  200432. {
  200433. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200434. {
  200435. /* This inverts the alpha channel in RGBA */
  200436. if (row_info->bit_depth == 8)
  200437. {
  200438. png_bytep sp, dp;
  200439. png_uint_32 i;
  200440. png_uint_32 row_width = row_info->width;
  200441. for (i = 0, sp = dp = row; i < row_width; i++)
  200442. {
  200443. /* does nothing
  200444. *(dp++) = *(sp++);
  200445. *(dp++) = *(sp++);
  200446. *(dp++) = *(sp++);
  200447. */
  200448. sp+=3; dp = sp;
  200449. *(dp++) = (png_byte)(255 - *(sp++));
  200450. }
  200451. }
  200452. /* This inverts the alpha channel in RRGGBBAA */
  200453. else
  200454. {
  200455. png_bytep sp, dp;
  200456. png_uint_32 i;
  200457. png_uint_32 row_width = row_info->width;
  200458. for (i = 0, sp = dp = row; i < row_width; i++)
  200459. {
  200460. /* does nothing
  200461. *(dp++) = *(sp++);
  200462. *(dp++) = *(sp++);
  200463. *(dp++) = *(sp++);
  200464. *(dp++) = *(sp++);
  200465. *(dp++) = *(sp++);
  200466. *(dp++) = *(sp++);
  200467. */
  200468. sp+=6; dp = sp;
  200469. *(dp++) = (png_byte)(255 - *(sp++));
  200470. *(dp++) = (png_byte)(255 - *(sp++));
  200471. }
  200472. }
  200473. }
  200474. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200475. {
  200476. /* This inverts the alpha channel in GA */
  200477. if (row_info->bit_depth == 8)
  200478. {
  200479. png_bytep sp, dp;
  200480. png_uint_32 i;
  200481. png_uint_32 row_width = row_info->width;
  200482. for (i = 0, sp = dp = row; i < row_width; i++)
  200483. {
  200484. *(dp++) = *(sp++);
  200485. *(dp++) = (png_byte)(255 - *(sp++));
  200486. }
  200487. }
  200488. /* This inverts the alpha channel in GGAA */
  200489. else
  200490. {
  200491. png_bytep sp, dp;
  200492. png_uint_32 i;
  200493. png_uint_32 row_width = row_info->width;
  200494. for (i = 0, sp = dp = row; i < row_width; i++)
  200495. {
  200496. /* does nothing
  200497. *(dp++) = *(sp++);
  200498. *(dp++) = *(sp++);
  200499. */
  200500. sp+=2; dp = sp;
  200501. *(dp++) = (png_byte)(255 - *(sp++));
  200502. *(dp++) = (png_byte)(255 - *(sp++));
  200503. }
  200504. }
  200505. }
  200506. }
  200507. }
  200508. #endif
  200509. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200510. /* undoes intrapixel differencing */
  200511. void /* PRIVATE */
  200512. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200513. {
  200514. png_debug(1, "in png_do_write_intrapixel\n");
  200515. if (
  200516. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200517. row != NULL && row_info != NULL &&
  200518. #endif
  200519. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200520. {
  200521. int bytes_per_pixel;
  200522. png_uint_32 row_width = row_info->width;
  200523. if (row_info->bit_depth == 8)
  200524. {
  200525. png_bytep rp;
  200526. png_uint_32 i;
  200527. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200528. bytes_per_pixel = 3;
  200529. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200530. bytes_per_pixel = 4;
  200531. else
  200532. return;
  200533. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200534. {
  200535. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200536. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200537. }
  200538. }
  200539. else if (row_info->bit_depth == 16)
  200540. {
  200541. png_bytep rp;
  200542. png_uint_32 i;
  200543. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200544. bytes_per_pixel = 6;
  200545. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200546. bytes_per_pixel = 8;
  200547. else
  200548. return;
  200549. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200550. {
  200551. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200552. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200553. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200554. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200555. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200556. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200557. *(rp+1) = (png_byte)(red & 0xff);
  200558. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200559. *(rp+5) = (png_byte)(blue & 0xff);
  200560. }
  200561. }
  200562. }
  200563. }
  200564. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200565. #endif /* PNG_WRITE_SUPPORTED */
  200566. /*** End of inlined file: pngwtran.c ***/
  200567. /*** Start of inlined file: pngwutil.c ***/
  200568. /* pngwutil.c - utilities to write a PNG file
  200569. *
  200570. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200571. * For conditions of distribution and use, see copyright notice in png.h
  200572. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200573. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200574. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200575. */
  200576. #define PNG_INTERNAL
  200577. #ifdef PNG_WRITE_SUPPORTED
  200578. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200579. * with unsigned numbers for convenience, although one supported
  200580. * ancillary chunk uses signed (two's complement) numbers.
  200581. */
  200582. void PNGAPI
  200583. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200584. {
  200585. buf[0] = (png_byte)((i >> 24) & 0xff);
  200586. buf[1] = (png_byte)((i >> 16) & 0xff);
  200587. buf[2] = (png_byte)((i >> 8) & 0xff);
  200588. buf[3] = (png_byte)(i & 0xff);
  200589. }
  200590. /* The png_save_int_32 function assumes integers are stored in two's
  200591. * complement format. If this isn't the case, then this routine needs to
  200592. * be modified to write data in two's complement format.
  200593. */
  200594. void PNGAPI
  200595. png_save_int_32(png_bytep buf, png_int_32 i)
  200596. {
  200597. buf[0] = (png_byte)((i >> 24) & 0xff);
  200598. buf[1] = (png_byte)((i >> 16) & 0xff);
  200599. buf[2] = (png_byte)((i >> 8) & 0xff);
  200600. buf[3] = (png_byte)(i & 0xff);
  200601. }
  200602. /* Place a 16-bit number into a buffer in PNG byte order.
  200603. * The parameter is declared unsigned int, not png_uint_16,
  200604. * just to avoid potential problems on pre-ANSI C compilers.
  200605. */
  200606. void PNGAPI
  200607. png_save_uint_16(png_bytep buf, unsigned int i)
  200608. {
  200609. buf[0] = (png_byte)((i >> 8) & 0xff);
  200610. buf[1] = (png_byte)(i & 0xff);
  200611. }
  200612. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200613. * representing the chunk name. The array must be at least 4 bytes in
  200614. * length, and does not need to be null terminated. To be safe, pass the
  200615. * pre-defined chunk names here, and if you need a new one, define it
  200616. * where the others are defined. The length is the length of the data.
  200617. * All the data must be present. If that is not possible, use the
  200618. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200619. * functions instead.
  200620. */
  200621. void PNGAPI
  200622. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200623. png_bytep data, png_size_t length)
  200624. {
  200625. if(png_ptr == NULL) return;
  200626. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200627. png_write_chunk_data(png_ptr, data, length);
  200628. png_write_chunk_end(png_ptr);
  200629. }
  200630. /* Write the start of a PNG chunk. The type is the chunk type.
  200631. * The total_length is the sum of the lengths of all the data you will be
  200632. * passing in png_write_chunk_data().
  200633. */
  200634. void PNGAPI
  200635. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200636. png_uint_32 length)
  200637. {
  200638. png_byte buf[4];
  200639. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200640. if(png_ptr == NULL) return;
  200641. /* write the length */
  200642. png_save_uint_32(buf, length);
  200643. png_write_data(png_ptr, buf, (png_size_t)4);
  200644. /* write the chunk name */
  200645. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200646. /* reset the crc and run it over the chunk name */
  200647. png_reset_crc(png_ptr);
  200648. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200649. }
  200650. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200651. * Note that multiple calls to this function are allowed, and that the
  200652. * sum of the lengths from these calls *must* add up to the total_length
  200653. * given to png_write_chunk_start().
  200654. */
  200655. void PNGAPI
  200656. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200657. {
  200658. /* write the data, and run the CRC over it */
  200659. if(png_ptr == NULL) return;
  200660. if (data != NULL && length > 0)
  200661. {
  200662. png_calculate_crc(png_ptr, data, length);
  200663. png_write_data(png_ptr, data, length);
  200664. }
  200665. }
  200666. /* Finish a chunk started with png_write_chunk_start(). */
  200667. void PNGAPI
  200668. png_write_chunk_end(png_structp png_ptr)
  200669. {
  200670. png_byte buf[4];
  200671. if(png_ptr == NULL) return;
  200672. /* write the crc */
  200673. png_save_uint_32(buf, png_ptr->crc);
  200674. png_write_data(png_ptr, buf, (png_size_t)4);
  200675. }
  200676. /* Simple function to write the signature. If we have already written
  200677. * the magic bytes of the signature, or more likely, the PNG stream is
  200678. * being embedded into another stream and doesn't need its own signature,
  200679. * we should call png_set_sig_bytes() to tell libpng how many of the
  200680. * bytes have already been written.
  200681. */
  200682. void /* PRIVATE */
  200683. png_write_sig(png_structp png_ptr)
  200684. {
  200685. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200686. /* write the rest of the 8 byte signature */
  200687. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200688. (png_size_t)8 - png_ptr->sig_bytes);
  200689. if(png_ptr->sig_bytes < 3)
  200690. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200691. }
  200692. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200693. /*
  200694. * This pair of functions encapsulates the operation of (a) compressing a
  200695. * text string, and (b) issuing it later as a series of chunk data writes.
  200696. * The compression_state structure is shared context for these functions
  200697. * set up by the caller in order to make the whole mess thread-safe.
  200698. */
  200699. typedef struct
  200700. {
  200701. char *input; /* the uncompressed input data */
  200702. int input_len; /* its length */
  200703. int num_output_ptr; /* number of output pointers used */
  200704. int max_output_ptr; /* size of output_ptr */
  200705. png_charpp output_ptr; /* array of pointers to output */
  200706. } compression_state;
  200707. /* compress given text into storage in the png_ptr structure */
  200708. static int /* PRIVATE */
  200709. png_text_compress(png_structp png_ptr,
  200710. png_charp text, png_size_t text_len, int compression,
  200711. compression_state *comp)
  200712. {
  200713. int ret;
  200714. comp->num_output_ptr = 0;
  200715. comp->max_output_ptr = 0;
  200716. comp->output_ptr = NULL;
  200717. comp->input = NULL;
  200718. comp->input_len = 0;
  200719. /* we may just want to pass the text right through */
  200720. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200721. {
  200722. comp->input = text;
  200723. comp->input_len = text_len;
  200724. return((int)text_len);
  200725. }
  200726. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200727. {
  200728. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200729. char msg[50];
  200730. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200731. png_warning(png_ptr, msg);
  200732. #else
  200733. png_warning(png_ptr, "Unknown compression type");
  200734. #endif
  200735. }
  200736. /* We can't write the chunk until we find out how much data we have,
  200737. * which means we need to run the compressor first and save the
  200738. * output. This shouldn't be a problem, as the vast majority of
  200739. * comments should be reasonable, but we will set up an array of
  200740. * malloc'd pointers to be sure.
  200741. *
  200742. * If we knew the application was well behaved, we could simplify this
  200743. * greatly by assuming we can always malloc an output buffer large
  200744. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200745. * and malloc this directly. The only time this would be a bad idea is
  200746. * if we can't malloc more than 64K and we have 64K of random input
  200747. * data, or if the input string is incredibly large (although this
  200748. * wouldn't cause a failure, just a slowdown due to swapping).
  200749. */
  200750. /* set up the compression buffers */
  200751. png_ptr->zstream.avail_in = (uInt)text_len;
  200752. png_ptr->zstream.next_in = (Bytef *)text;
  200753. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200754. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200755. /* this is the same compression loop as in png_write_row() */
  200756. do
  200757. {
  200758. /* compress the data */
  200759. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200760. if (ret != Z_OK)
  200761. {
  200762. /* error */
  200763. if (png_ptr->zstream.msg != NULL)
  200764. png_error(png_ptr, png_ptr->zstream.msg);
  200765. else
  200766. png_error(png_ptr, "zlib error");
  200767. }
  200768. /* check to see if we need more room */
  200769. if (!(png_ptr->zstream.avail_out))
  200770. {
  200771. /* make sure the output array has room */
  200772. if (comp->num_output_ptr >= comp->max_output_ptr)
  200773. {
  200774. int old_max;
  200775. old_max = comp->max_output_ptr;
  200776. comp->max_output_ptr = comp->num_output_ptr + 4;
  200777. if (comp->output_ptr != NULL)
  200778. {
  200779. png_charpp old_ptr;
  200780. old_ptr = comp->output_ptr;
  200781. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200782. (png_uint_32)(comp->max_output_ptr *
  200783. png_sizeof (png_charpp)));
  200784. png_memcpy(comp->output_ptr, old_ptr, old_max
  200785. * png_sizeof (png_charp));
  200786. png_free(png_ptr, old_ptr);
  200787. }
  200788. else
  200789. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200790. (png_uint_32)(comp->max_output_ptr *
  200791. png_sizeof (png_charp)));
  200792. }
  200793. /* save the data */
  200794. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200795. (png_uint_32)png_ptr->zbuf_size);
  200796. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200797. png_ptr->zbuf_size);
  200798. comp->num_output_ptr++;
  200799. /* and reset the buffer */
  200800. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200801. png_ptr->zstream.next_out = png_ptr->zbuf;
  200802. }
  200803. /* continue until we don't have any more to compress */
  200804. } while (png_ptr->zstream.avail_in);
  200805. /* finish the compression */
  200806. do
  200807. {
  200808. /* tell zlib we are finished */
  200809. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200810. if (ret == Z_OK)
  200811. {
  200812. /* check to see if we need more room */
  200813. if (!(png_ptr->zstream.avail_out))
  200814. {
  200815. /* check to make sure our output array has room */
  200816. if (comp->num_output_ptr >= comp->max_output_ptr)
  200817. {
  200818. int old_max;
  200819. old_max = comp->max_output_ptr;
  200820. comp->max_output_ptr = comp->num_output_ptr + 4;
  200821. if (comp->output_ptr != NULL)
  200822. {
  200823. png_charpp old_ptr;
  200824. old_ptr = comp->output_ptr;
  200825. /* This could be optimized to realloc() */
  200826. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200827. (png_uint_32)(comp->max_output_ptr *
  200828. png_sizeof (png_charpp)));
  200829. png_memcpy(comp->output_ptr, old_ptr,
  200830. old_max * png_sizeof (png_charp));
  200831. png_free(png_ptr, old_ptr);
  200832. }
  200833. else
  200834. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200835. (png_uint_32)(comp->max_output_ptr *
  200836. png_sizeof (png_charp)));
  200837. }
  200838. /* save off the data */
  200839. comp->output_ptr[comp->num_output_ptr] =
  200840. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200841. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200842. png_ptr->zbuf_size);
  200843. comp->num_output_ptr++;
  200844. /* and reset the buffer pointers */
  200845. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200846. png_ptr->zstream.next_out = png_ptr->zbuf;
  200847. }
  200848. }
  200849. else if (ret != Z_STREAM_END)
  200850. {
  200851. /* we got an error */
  200852. if (png_ptr->zstream.msg != NULL)
  200853. png_error(png_ptr, png_ptr->zstream.msg);
  200854. else
  200855. png_error(png_ptr, "zlib error");
  200856. }
  200857. } while (ret != Z_STREAM_END);
  200858. /* text length is number of buffers plus last buffer */
  200859. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200860. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200861. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200862. return((int)text_len);
  200863. }
  200864. /* ship the compressed text out via chunk writes */
  200865. static void /* PRIVATE */
  200866. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200867. {
  200868. int i;
  200869. /* handle the no-compression case */
  200870. if (comp->input)
  200871. {
  200872. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200873. (png_size_t)comp->input_len);
  200874. return;
  200875. }
  200876. /* write saved output buffers, if any */
  200877. for (i = 0; i < comp->num_output_ptr; i++)
  200878. {
  200879. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200880. png_ptr->zbuf_size);
  200881. png_free(png_ptr, comp->output_ptr[i]);
  200882. comp->output_ptr[i]=NULL;
  200883. }
  200884. if (comp->max_output_ptr != 0)
  200885. png_free(png_ptr, comp->output_ptr);
  200886. comp->output_ptr=NULL;
  200887. /* write anything left in zbuf */
  200888. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200889. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200890. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200891. /* reset zlib for another zTXt/iTXt or image data */
  200892. deflateReset(&png_ptr->zstream);
  200893. png_ptr->zstream.data_type = Z_BINARY;
  200894. }
  200895. #endif
  200896. /* Write the IHDR chunk, and update the png_struct with the necessary
  200897. * information. Note that the rest of this code depends upon this
  200898. * information being correct.
  200899. */
  200900. void /* PRIVATE */
  200901. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200902. int bit_depth, int color_type, int compression_type, int filter_type,
  200903. int interlace_type)
  200904. {
  200905. #ifdef PNG_USE_LOCAL_ARRAYS
  200906. PNG_IHDR;
  200907. #endif
  200908. png_byte buf[13]; /* buffer to store the IHDR info */
  200909. png_debug(1, "in png_write_IHDR\n");
  200910. /* Check that we have valid input data from the application info */
  200911. switch (color_type)
  200912. {
  200913. case PNG_COLOR_TYPE_GRAY:
  200914. switch (bit_depth)
  200915. {
  200916. case 1:
  200917. case 2:
  200918. case 4:
  200919. case 8:
  200920. case 16: png_ptr->channels = 1; break;
  200921. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200922. }
  200923. break;
  200924. case PNG_COLOR_TYPE_RGB:
  200925. if (bit_depth != 8 && bit_depth != 16)
  200926. png_error(png_ptr, "Invalid bit depth for RGB image");
  200927. png_ptr->channels = 3;
  200928. break;
  200929. case PNG_COLOR_TYPE_PALETTE:
  200930. switch (bit_depth)
  200931. {
  200932. case 1:
  200933. case 2:
  200934. case 4:
  200935. case 8: png_ptr->channels = 1; break;
  200936. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200937. }
  200938. break;
  200939. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200940. if (bit_depth != 8 && bit_depth != 16)
  200941. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200942. png_ptr->channels = 2;
  200943. break;
  200944. case PNG_COLOR_TYPE_RGB_ALPHA:
  200945. if (bit_depth != 8 && bit_depth != 16)
  200946. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200947. png_ptr->channels = 4;
  200948. break;
  200949. default:
  200950. png_error(png_ptr, "Invalid image color type specified");
  200951. }
  200952. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200953. {
  200954. png_warning(png_ptr, "Invalid compression type specified");
  200955. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200956. }
  200957. /* Write filter_method 64 (intrapixel differencing) only if
  200958. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200959. * 2. Libpng did not write a PNG signature (this filter_method is only
  200960. * used in PNG datastreams that are embedded in MNG datastreams) and
  200961. * 3. The application called png_permit_mng_features with a mask that
  200962. * included PNG_FLAG_MNG_FILTER_64 and
  200963. * 4. The filter_method is 64 and
  200964. * 5. The color_type is RGB or RGBA
  200965. */
  200966. if (
  200967. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200968. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200969. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200970. (color_type == PNG_COLOR_TYPE_RGB ||
  200971. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200972. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200973. #endif
  200974. filter_type != PNG_FILTER_TYPE_BASE)
  200975. {
  200976. png_warning(png_ptr, "Invalid filter type specified");
  200977. filter_type = PNG_FILTER_TYPE_BASE;
  200978. }
  200979. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200980. if (interlace_type != PNG_INTERLACE_NONE &&
  200981. interlace_type != PNG_INTERLACE_ADAM7)
  200982. {
  200983. png_warning(png_ptr, "Invalid interlace type specified");
  200984. interlace_type = PNG_INTERLACE_ADAM7;
  200985. }
  200986. #else
  200987. interlace_type=PNG_INTERLACE_NONE;
  200988. #endif
  200989. /* save off the relevent information */
  200990. png_ptr->bit_depth = (png_byte)bit_depth;
  200991. png_ptr->color_type = (png_byte)color_type;
  200992. png_ptr->interlaced = (png_byte)interlace_type;
  200993. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200994. png_ptr->filter_type = (png_byte)filter_type;
  200995. #endif
  200996. png_ptr->compression_type = (png_byte)compression_type;
  200997. png_ptr->width = width;
  200998. png_ptr->height = height;
  200999. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201000. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201001. /* set the usr info, so any transformations can modify it */
  201002. png_ptr->usr_width = png_ptr->width;
  201003. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201004. png_ptr->usr_channels = png_ptr->channels;
  201005. /* pack the header information into the buffer */
  201006. png_save_uint_32(buf, width);
  201007. png_save_uint_32(buf + 4, height);
  201008. buf[8] = (png_byte)bit_depth;
  201009. buf[9] = (png_byte)color_type;
  201010. buf[10] = (png_byte)compression_type;
  201011. buf[11] = (png_byte)filter_type;
  201012. buf[12] = (png_byte)interlace_type;
  201013. /* write the chunk */
  201014. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201015. /* initialize zlib with PNG info */
  201016. png_ptr->zstream.zalloc = png_zalloc;
  201017. png_ptr->zstream.zfree = png_zfree;
  201018. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201019. if (!(png_ptr->do_filter))
  201020. {
  201021. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201022. png_ptr->bit_depth < 8)
  201023. png_ptr->do_filter = PNG_FILTER_NONE;
  201024. else
  201025. png_ptr->do_filter = PNG_ALL_FILTERS;
  201026. }
  201027. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201028. {
  201029. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201030. png_ptr->zlib_strategy = Z_FILTERED;
  201031. else
  201032. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201033. }
  201034. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201035. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201036. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201037. png_ptr->zlib_mem_level = 8;
  201038. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201039. png_ptr->zlib_window_bits = 15;
  201040. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201041. png_ptr->zlib_method = 8;
  201042. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201043. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201044. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201045. png_error(png_ptr, "zlib failed to initialize compressor");
  201046. png_ptr->zstream.next_out = png_ptr->zbuf;
  201047. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201048. /* libpng is not interested in zstream.data_type */
  201049. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201050. png_ptr->zstream.data_type = Z_BINARY;
  201051. png_ptr->mode = PNG_HAVE_IHDR;
  201052. }
  201053. /* write the palette. We are careful not to trust png_color to be in the
  201054. * correct order for PNG, so people can redefine it to any convenient
  201055. * structure.
  201056. */
  201057. void /* PRIVATE */
  201058. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201059. {
  201060. #ifdef PNG_USE_LOCAL_ARRAYS
  201061. PNG_PLTE;
  201062. #endif
  201063. png_uint_32 i;
  201064. png_colorp pal_ptr;
  201065. png_byte buf[3];
  201066. png_debug(1, "in png_write_PLTE\n");
  201067. if ((
  201068. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201069. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201070. #endif
  201071. num_pal == 0) || num_pal > 256)
  201072. {
  201073. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201074. {
  201075. png_error(png_ptr, "Invalid number of colors in palette");
  201076. }
  201077. else
  201078. {
  201079. png_warning(png_ptr, "Invalid number of colors in palette");
  201080. return;
  201081. }
  201082. }
  201083. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201084. {
  201085. png_warning(png_ptr,
  201086. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201087. return;
  201088. }
  201089. png_ptr->num_palette = (png_uint_16)num_pal;
  201090. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201091. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201092. #ifndef PNG_NO_POINTER_INDEXING
  201093. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201094. {
  201095. buf[0] = pal_ptr->red;
  201096. buf[1] = pal_ptr->green;
  201097. buf[2] = pal_ptr->blue;
  201098. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201099. }
  201100. #else
  201101. /* This is a little slower but some buggy compilers need to do this instead */
  201102. pal_ptr=palette;
  201103. for (i = 0; i < num_pal; i++)
  201104. {
  201105. buf[0] = pal_ptr[i].red;
  201106. buf[1] = pal_ptr[i].green;
  201107. buf[2] = pal_ptr[i].blue;
  201108. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201109. }
  201110. #endif
  201111. png_write_chunk_end(png_ptr);
  201112. png_ptr->mode |= PNG_HAVE_PLTE;
  201113. }
  201114. /* write an IDAT chunk */
  201115. void /* PRIVATE */
  201116. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201117. {
  201118. #ifdef PNG_USE_LOCAL_ARRAYS
  201119. PNG_IDAT;
  201120. #endif
  201121. png_debug(1, "in png_write_IDAT\n");
  201122. /* Optimize the CMF field in the zlib stream. */
  201123. /* This hack of the zlib stream is compliant to the stream specification. */
  201124. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201125. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201126. {
  201127. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201128. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201129. {
  201130. /* Avoid memory underflows and multiplication overflows. */
  201131. /* The conditions below are practically always satisfied;
  201132. however, they still must be checked. */
  201133. if (length >= 2 &&
  201134. png_ptr->height < 16384 && png_ptr->width < 16384)
  201135. {
  201136. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201137. ((png_ptr->width *
  201138. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201139. unsigned int z_cinfo = z_cmf >> 4;
  201140. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201141. while (uncompressed_idat_size <= half_z_window_size &&
  201142. half_z_window_size >= 256)
  201143. {
  201144. z_cinfo--;
  201145. half_z_window_size >>= 1;
  201146. }
  201147. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201148. if (data[0] != (png_byte)z_cmf)
  201149. {
  201150. data[0] = (png_byte)z_cmf;
  201151. data[1] &= 0xe0;
  201152. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201153. }
  201154. }
  201155. }
  201156. else
  201157. png_error(png_ptr,
  201158. "Invalid zlib compression method or flags in IDAT");
  201159. }
  201160. png_write_chunk(png_ptr, png_IDAT, data, length);
  201161. png_ptr->mode |= PNG_HAVE_IDAT;
  201162. }
  201163. /* write an IEND chunk */
  201164. void /* PRIVATE */
  201165. png_write_IEND(png_structp png_ptr)
  201166. {
  201167. #ifdef PNG_USE_LOCAL_ARRAYS
  201168. PNG_IEND;
  201169. #endif
  201170. png_debug(1, "in png_write_IEND\n");
  201171. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201172. (png_size_t)0);
  201173. png_ptr->mode |= PNG_HAVE_IEND;
  201174. }
  201175. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201176. /* write a gAMA chunk */
  201177. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201178. void /* PRIVATE */
  201179. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201180. {
  201181. #ifdef PNG_USE_LOCAL_ARRAYS
  201182. PNG_gAMA;
  201183. #endif
  201184. png_uint_32 igamma;
  201185. png_byte buf[4];
  201186. png_debug(1, "in png_write_gAMA\n");
  201187. /* file_gamma is saved in 1/100,000ths */
  201188. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201189. png_save_uint_32(buf, igamma);
  201190. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201191. }
  201192. #endif
  201193. #ifdef PNG_FIXED_POINT_SUPPORTED
  201194. void /* PRIVATE */
  201195. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201196. {
  201197. #ifdef PNG_USE_LOCAL_ARRAYS
  201198. PNG_gAMA;
  201199. #endif
  201200. png_byte buf[4];
  201201. png_debug(1, "in png_write_gAMA\n");
  201202. /* file_gamma is saved in 1/100,000ths */
  201203. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201204. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201205. }
  201206. #endif
  201207. #endif
  201208. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201209. /* write a sRGB chunk */
  201210. void /* PRIVATE */
  201211. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201212. {
  201213. #ifdef PNG_USE_LOCAL_ARRAYS
  201214. PNG_sRGB;
  201215. #endif
  201216. png_byte buf[1];
  201217. png_debug(1, "in png_write_sRGB\n");
  201218. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201219. png_warning(png_ptr,
  201220. "Invalid sRGB rendering intent specified");
  201221. buf[0]=(png_byte)srgb_intent;
  201222. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201223. }
  201224. #endif
  201225. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201226. /* write an iCCP chunk */
  201227. void /* PRIVATE */
  201228. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201229. png_charp profile, int profile_len)
  201230. {
  201231. #ifdef PNG_USE_LOCAL_ARRAYS
  201232. PNG_iCCP;
  201233. #endif
  201234. png_size_t name_len;
  201235. png_charp new_name;
  201236. compression_state comp;
  201237. int embedded_profile_len = 0;
  201238. png_debug(1, "in png_write_iCCP\n");
  201239. comp.num_output_ptr = 0;
  201240. comp.max_output_ptr = 0;
  201241. comp.output_ptr = NULL;
  201242. comp.input = NULL;
  201243. comp.input_len = 0;
  201244. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201245. &new_name)) == 0)
  201246. {
  201247. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201248. return;
  201249. }
  201250. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201251. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201252. if (profile == NULL)
  201253. profile_len = 0;
  201254. if (profile_len > 3)
  201255. embedded_profile_len =
  201256. ((*( (png_bytep)profile ))<<24) |
  201257. ((*( (png_bytep)profile+1))<<16) |
  201258. ((*( (png_bytep)profile+2))<< 8) |
  201259. ((*( (png_bytep)profile+3)) );
  201260. if (profile_len < embedded_profile_len)
  201261. {
  201262. png_warning(png_ptr,
  201263. "Embedded profile length too large in iCCP chunk");
  201264. return;
  201265. }
  201266. if (profile_len > embedded_profile_len)
  201267. {
  201268. png_warning(png_ptr,
  201269. "Truncating profile to actual length in iCCP chunk");
  201270. profile_len = embedded_profile_len;
  201271. }
  201272. if (profile_len)
  201273. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201274. PNG_COMPRESSION_TYPE_BASE, &comp);
  201275. /* make sure we include the NULL after the name and the compression type */
  201276. png_write_chunk_start(png_ptr, png_iCCP,
  201277. (png_uint_32)name_len+profile_len+2);
  201278. new_name[name_len+1]=0x00;
  201279. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201280. if (profile_len)
  201281. png_write_compressed_data_out(png_ptr, &comp);
  201282. png_write_chunk_end(png_ptr);
  201283. png_free(png_ptr, new_name);
  201284. }
  201285. #endif
  201286. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201287. /* write a sPLT chunk */
  201288. void /* PRIVATE */
  201289. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201290. {
  201291. #ifdef PNG_USE_LOCAL_ARRAYS
  201292. PNG_sPLT;
  201293. #endif
  201294. png_size_t name_len;
  201295. png_charp new_name;
  201296. png_byte entrybuf[10];
  201297. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201298. int palette_size = entry_size * spalette->nentries;
  201299. png_sPLT_entryp ep;
  201300. #ifdef PNG_NO_POINTER_INDEXING
  201301. int i;
  201302. #endif
  201303. png_debug(1, "in png_write_sPLT\n");
  201304. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201305. spalette->name, &new_name))==0)
  201306. {
  201307. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201308. return;
  201309. }
  201310. /* make sure we include the NULL after the name */
  201311. png_write_chunk_start(png_ptr, png_sPLT,
  201312. (png_uint_32)(name_len + 2 + palette_size));
  201313. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201314. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201315. /* loop through each palette entry, writing appropriately */
  201316. #ifndef PNG_NO_POINTER_INDEXING
  201317. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201318. {
  201319. if (spalette->depth == 8)
  201320. {
  201321. entrybuf[0] = (png_byte)ep->red;
  201322. entrybuf[1] = (png_byte)ep->green;
  201323. entrybuf[2] = (png_byte)ep->blue;
  201324. entrybuf[3] = (png_byte)ep->alpha;
  201325. png_save_uint_16(entrybuf + 4, ep->frequency);
  201326. }
  201327. else
  201328. {
  201329. png_save_uint_16(entrybuf + 0, ep->red);
  201330. png_save_uint_16(entrybuf + 2, ep->green);
  201331. png_save_uint_16(entrybuf + 4, ep->blue);
  201332. png_save_uint_16(entrybuf + 6, ep->alpha);
  201333. png_save_uint_16(entrybuf + 8, ep->frequency);
  201334. }
  201335. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201336. }
  201337. #else
  201338. ep=spalette->entries;
  201339. for (i=0; i>spalette->nentries; i++)
  201340. {
  201341. if (spalette->depth == 8)
  201342. {
  201343. entrybuf[0] = (png_byte)ep[i].red;
  201344. entrybuf[1] = (png_byte)ep[i].green;
  201345. entrybuf[2] = (png_byte)ep[i].blue;
  201346. entrybuf[3] = (png_byte)ep[i].alpha;
  201347. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201348. }
  201349. else
  201350. {
  201351. png_save_uint_16(entrybuf + 0, ep[i].red);
  201352. png_save_uint_16(entrybuf + 2, ep[i].green);
  201353. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201354. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201355. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201356. }
  201357. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201358. }
  201359. #endif
  201360. png_write_chunk_end(png_ptr);
  201361. png_free(png_ptr, new_name);
  201362. }
  201363. #endif
  201364. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201365. /* write the sBIT chunk */
  201366. void /* PRIVATE */
  201367. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201368. {
  201369. #ifdef PNG_USE_LOCAL_ARRAYS
  201370. PNG_sBIT;
  201371. #endif
  201372. png_byte buf[4];
  201373. png_size_t size;
  201374. png_debug(1, "in png_write_sBIT\n");
  201375. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201376. if (color_type & PNG_COLOR_MASK_COLOR)
  201377. {
  201378. png_byte maxbits;
  201379. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201380. png_ptr->usr_bit_depth);
  201381. if (sbit->red == 0 || sbit->red > maxbits ||
  201382. sbit->green == 0 || sbit->green > maxbits ||
  201383. sbit->blue == 0 || sbit->blue > maxbits)
  201384. {
  201385. png_warning(png_ptr, "Invalid sBIT depth specified");
  201386. return;
  201387. }
  201388. buf[0] = sbit->red;
  201389. buf[1] = sbit->green;
  201390. buf[2] = sbit->blue;
  201391. size = 3;
  201392. }
  201393. else
  201394. {
  201395. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201396. {
  201397. png_warning(png_ptr, "Invalid sBIT depth specified");
  201398. return;
  201399. }
  201400. buf[0] = sbit->gray;
  201401. size = 1;
  201402. }
  201403. if (color_type & PNG_COLOR_MASK_ALPHA)
  201404. {
  201405. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201406. {
  201407. png_warning(png_ptr, "Invalid sBIT depth specified");
  201408. return;
  201409. }
  201410. buf[size++] = sbit->alpha;
  201411. }
  201412. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201413. }
  201414. #endif
  201415. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201416. /* write the cHRM chunk */
  201417. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201418. void /* PRIVATE */
  201419. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201420. double red_x, double red_y, double green_x, double green_y,
  201421. double blue_x, double blue_y)
  201422. {
  201423. #ifdef PNG_USE_LOCAL_ARRAYS
  201424. PNG_cHRM;
  201425. #endif
  201426. png_byte buf[32];
  201427. png_uint_32 itemp;
  201428. png_debug(1, "in png_write_cHRM\n");
  201429. /* each value is saved in 1/100,000ths */
  201430. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201431. white_x + white_y > 1.0)
  201432. {
  201433. png_warning(png_ptr, "Invalid cHRM white point specified");
  201434. #if !defined(PNG_NO_CONSOLE_IO)
  201435. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201436. #endif
  201437. return;
  201438. }
  201439. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201440. png_save_uint_32(buf, itemp);
  201441. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201442. png_save_uint_32(buf + 4, itemp);
  201443. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201444. {
  201445. png_warning(png_ptr, "Invalid cHRM red point specified");
  201446. return;
  201447. }
  201448. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201449. png_save_uint_32(buf + 8, itemp);
  201450. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201451. png_save_uint_32(buf + 12, itemp);
  201452. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201453. {
  201454. png_warning(png_ptr, "Invalid cHRM green point specified");
  201455. return;
  201456. }
  201457. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201458. png_save_uint_32(buf + 16, itemp);
  201459. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201460. png_save_uint_32(buf + 20, itemp);
  201461. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201462. {
  201463. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201464. return;
  201465. }
  201466. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201467. png_save_uint_32(buf + 24, itemp);
  201468. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201469. png_save_uint_32(buf + 28, itemp);
  201470. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201471. }
  201472. #endif
  201473. #ifdef PNG_FIXED_POINT_SUPPORTED
  201474. void /* PRIVATE */
  201475. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201476. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201477. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201478. png_fixed_point blue_y)
  201479. {
  201480. #ifdef PNG_USE_LOCAL_ARRAYS
  201481. PNG_cHRM;
  201482. #endif
  201483. png_byte buf[32];
  201484. png_debug(1, "in png_write_cHRM\n");
  201485. /* each value is saved in 1/100,000ths */
  201486. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201487. {
  201488. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201489. #if !defined(PNG_NO_CONSOLE_IO)
  201490. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201491. #endif
  201492. return;
  201493. }
  201494. png_save_uint_32(buf, (png_uint_32)white_x);
  201495. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201496. if (red_x + red_y > 100000L)
  201497. {
  201498. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201499. return;
  201500. }
  201501. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201502. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201503. if (green_x + green_y > 100000L)
  201504. {
  201505. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201506. return;
  201507. }
  201508. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201509. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201510. if (blue_x + blue_y > 100000L)
  201511. {
  201512. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201513. return;
  201514. }
  201515. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201516. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201517. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201518. }
  201519. #endif
  201520. #endif
  201521. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201522. /* write the tRNS chunk */
  201523. void /* PRIVATE */
  201524. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201525. int num_trans, int color_type)
  201526. {
  201527. #ifdef PNG_USE_LOCAL_ARRAYS
  201528. PNG_tRNS;
  201529. #endif
  201530. png_byte buf[6];
  201531. png_debug(1, "in png_write_tRNS\n");
  201532. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201533. {
  201534. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201535. {
  201536. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201537. return;
  201538. }
  201539. /* write the chunk out as it is */
  201540. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201541. }
  201542. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201543. {
  201544. /* one 16 bit value */
  201545. if(tran->gray >= (1 << png_ptr->bit_depth))
  201546. {
  201547. png_warning(png_ptr,
  201548. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201549. return;
  201550. }
  201551. png_save_uint_16(buf, tran->gray);
  201552. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201553. }
  201554. else if (color_type == PNG_COLOR_TYPE_RGB)
  201555. {
  201556. /* three 16 bit values */
  201557. png_save_uint_16(buf, tran->red);
  201558. png_save_uint_16(buf + 2, tran->green);
  201559. png_save_uint_16(buf + 4, tran->blue);
  201560. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201561. {
  201562. png_warning(png_ptr,
  201563. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201564. return;
  201565. }
  201566. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201567. }
  201568. else
  201569. {
  201570. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201571. }
  201572. }
  201573. #endif
  201574. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201575. /* write the background chunk */
  201576. void /* PRIVATE */
  201577. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201578. {
  201579. #ifdef PNG_USE_LOCAL_ARRAYS
  201580. PNG_bKGD;
  201581. #endif
  201582. png_byte buf[6];
  201583. png_debug(1, "in png_write_bKGD\n");
  201584. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201585. {
  201586. if (
  201587. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201588. (png_ptr->num_palette ||
  201589. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201590. #endif
  201591. back->index > png_ptr->num_palette)
  201592. {
  201593. png_warning(png_ptr, "Invalid background palette index");
  201594. return;
  201595. }
  201596. buf[0] = back->index;
  201597. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201598. }
  201599. else if (color_type & PNG_COLOR_MASK_COLOR)
  201600. {
  201601. png_save_uint_16(buf, back->red);
  201602. png_save_uint_16(buf + 2, back->green);
  201603. png_save_uint_16(buf + 4, back->blue);
  201604. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201605. {
  201606. png_warning(png_ptr,
  201607. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201608. return;
  201609. }
  201610. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201611. }
  201612. else
  201613. {
  201614. if(back->gray >= (1 << png_ptr->bit_depth))
  201615. {
  201616. png_warning(png_ptr,
  201617. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201618. return;
  201619. }
  201620. png_save_uint_16(buf, back->gray);
  201621. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201622. }
  201623. }
  201624. #endif
  201625. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201626. /* write the histogram */
  201627. void /* PRIVATE */
  201628. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201629. {
  201630. #ifdef PNG_USE_LOCAL_ARRAYS
  201631. PNG_hIST;
  201632. #endif
  201633. int i;
  201634. png_byte buf[3];
  201635. png_debug(1, "in png_write_hIST\n");
  201636. if (num_hist > (int)png_ptr->num_palette)
  201637. {
  201638. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201639. png_ptr->num_palette);
  201640. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201641. return;
  201642. }
  201643. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201644. for (i = 0; i < num_hist; i++)
  201645. {
  201646. png_save_uint_16(buf, hist[i]);
  201647. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201648. }
  201649. png_write_chunk_end(png_ptr);
  201650. }
  201651. #endif
  201652. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201653. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201654. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201655. * and if invalid, correct the keyword rather than discarding the entire
  201656. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201657. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201658. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201659. *
  201660. * The new_key is allocated to hold the corrected keyword and must be freed
  201661. * by the calling routine. This avoids problems with trying to write to
  201662. * static keywords without having to have duplicate copies of the strings.
  201663. */
  201664. png_size_t /* PRIVATE */
  201665. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201666. {
  201667. png_size_t key_len;
  201668. png_charp kp, dp;
  201669. int kflag;
  201670. int kwarn=0;
  201671. png_debug(1, "in png_check_keyword\n");
  201672. *new_key = NULL;
  201673. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201674. {
  201675. png_warning(png_ptr, "zero length keyword");
  201676. return ((png_size_t)0);
  201677. }
  201678. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201679. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201680. if (*new_key == NULL)
  201681. {
  201682. png_warning(png_ptr, "Out of memory while procesing keyword");
  201683. return ((png_size_t)0);
  201684. }
  201685. /* Replace non-printing characters with a blank and print a warning */
  201686. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201687. {
  201688. if ((png_byte)*kp < 0x20 ||
  201689. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201690. {
  201691. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201692. char msg[40];
  201693. png_snprintf(msg, 40,
  201694. "invalid keyword character 0x%02X", (png_byte)*kp);
  201695. png_warning(png_ptr, msg);
  201696. #else
  201697. png_warning(png_ptr, "invalid character in keyword");
  201698. #endif
  201699. *dp = ' ';
  201700. }
  201701. else
  201702. {
  201703. *dp = *kp;
  201704. }
  201705. }
  201706. *dp = '\0';
  201707. /* Remove any trailing white space. */
  201708. kp = *new_key + key_len - 1;
  201709. if (*kp == ' ')
  201710. {
  201711. png_warning(png_ptr, "trailing spaces removed from keyword");
  201712. while (*kp == ' ')
  201713. {
  201714. *(kp--) = '\0';
  201715. key_len--;
  201716. }
  201717. }
  201718. /* Remove any leading white space. */
  201719. kp = *new_key;
  201720. if (*kp == ' ')
  201721. {
  201722. png_warning(png_ptr, "leading spaces removed from keyword");
  201723. while (*kp == ' ')
  201724. {
  201725. kp++;
  201726. key_len--;
  201727. }
  201728. }
  201729. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201730. /* Remove multiple internal spaces. */
  201731. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201732. {
  201733. if (*kp == ' ' && kflag == 0)
  201734. {
  201735. *(dp++) = *kp;
  201736. kflag = 1;
  201737. }
  201738. else if (*kp == ' ')
  201739. {
  201740. key_len--;
  201741. kwarn=1;
  201742. }
  201743. else
  201744. {
  201745. *(dp++) = *kp;
  201746. kflag = 0;
  201747. }
  201748. }
  201749. *dp = '\0';
  201750. if(kwarn)
  201751. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201752. if (key_len == 0)
  201753. {
  201754. png_free(png_ptr, *new_key);
  201755. *new_key=NULL;
  201756. png_warning(png_ptr, "Zero length keyword");
  201757. }
  201758. if (key_len > 79)
  201759. {
  201760. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201761. new_key[79] = '\0';
  201762. key_len = 79;
  201763. }
  201764. return (key_len);
  201765. }
  201766. #endif
  201767. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201768. /* write a tEXt chunk */
  201769. void /* PRIVATE */
  201770. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201771. png_size_t text_len)
  201772. {
  201773. #ifdef PNG_USE_LOCAL_ARRAYS
  201774. PNG_tEXt;
  201775. #endif
  201776. png_size_t key_len;
  201777. png_charp new_key;
  201778. png_debug(1, "in png_write_tEXt\n");
  201779. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201780. {
  201781. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201782. return;
  201783. }
  201784. if (text == NULL || *text == '\0')
  201785. text_len = 0;
  201786. else
  201787. text_len = png_strlen(text);
  201788. /* make sure we include the 0 after the key */
  201789. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201790. /*
  201791. * We leave it to the application to meet PNG-1.0 requirements on the
  201792. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201793. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201794. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201795. */
  201796. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201797. if (text_len)
  201798. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201799. png_write_chunk_end(png_ptr);
  201800. png_free(png_ptr, new_key);
  201801. }
  201802. #endif
  201803. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201804. /* write a compressed text chunk */
  201805. void /* PRIVATE */
  201806. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201807. png_size_t text_len, int compression)
  201808. {
  201809. #ifdef PNG_USE_LOCAL_ARRAYS
  201810. PNG_zTXt;
  201811. #endif
  201812. png_size_t key_len;
  201813. char buf[1];
  201814. png_charp new_key;
  201815. compression_state comp;
  201816. png_debug(1, "in png_write_zTXt\n");
  201817. comp.num_output_ptr = 0;
  201818. comp.max_output_ptr = 0;
  201819. comp.output_ptr = NULL;
  201820. comp.input = NULL;
  201821. comp.input_len = 0;
  201822. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201823. {
  201824. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201825. return;
  201826. }
  201827. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201828. {
  201829. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201830. png_free(png_ptr, new_key);
  201831. return;
  201832. }
  201833. text_len = png_strlen(text);
  201834. /* compute the compressed data; do it now for the length */
  201835. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201836. &comp);
  201837. /* write start of chunk */
  201838. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201839. (key_len+text_len+2));
  201840. /* write key */
  201841. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201842. png_free(png_ptr, new_key);
  201843. buf[0] = (png_byte)compression;
  201844. /* write compression */
  201845. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201846. /* write the compressed data */
  201847. png_write_compressed_data_out(png_ptr, &comp);
  201848. /* close the chunk */
  201849. png_write_chunk_end(png_ptr);
  201850. }
  201851. #endif
  201852. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201853. /* write an iTXt chunk */
  201854. void /* PRIVATE */
  201855. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201856. png_charp lang, png_charp lang_key, png_charp text)
  201857. {
  201858. #ifdef PNG_USE_LOCAL_ARRAYS
  201859. PNG_iTXt;
  201860. #endif
  201861. png_size_t lang_len, key_len, lang_key_len, text_len;
  201862. png_charp new_lang, new_key;
  201863. png_byte cbuf[2];
  201864. compression_state comp;
  201865. png_debug(1, "in png_write_iTXt\n");
  201866. comp.num_output_ptr = 0;
  201867. comp.max_output_ptr = 0;
  201868. comp.output_ptr = NULL;
  201869. comp.input = NULL;
  201870. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201871. {
  201872. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201873. return;
  201874. }
  201875. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201876. {
  201877. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201878. new_lang = NULL;
  201879. lang_len = 0;
  201880. }
  201881. if (lang_key == NULL)
  201882. lang_key_len = 0;
  201883. else
  201884. lang_key_len = png_strlen(lang_key);
  201885. if (text == NULL)
  201886. text_len = 0;
  201887. else
  201888. text_len = png_strlen(text);
  201889. /* compute the compressed data; do it now for the length */
  201890. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201891. &comp);
  201892. /* make sure we include the compression flag, the compression byte,
  201893. * and the NULs after the key, lang, and lang_key parts */
  201894. png_write_chunk_start(png_ptr, png_iTXt,
  201895. (png_uint_32)(
  201896. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201897. + key_len
  201898. + lang_len
  201899. + lang_key_len
  201900. + text_len));
  201901. /*
  201902. * We leave it to the application to meet PNG-1.0 requirements on the
  201903. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201904. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201905. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201906. */
  201907. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201908. /* set the compression flag */
  201909. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201910. compression == PNG_TEXT_COMPRESSION_NONE)
  201911. cbuf[0] = 0;
  201912. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201913. cbuf[0] = 1;
  201914. /* set the compression method */
  201915. cbuf[1] = 0;
  201916. png_write_chunk_data(png_ptr, cbuf, 2);
  201917. cbuf[0] = 0;
  201918. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201919. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201920. png_write_compressed_data_out(png_ptr, &comp);
  201921. png_write_chunk_end(png_ptr);
  201922. png_free(png_ptr, new_key);
  201923. if (new_lang)
  201924. png_free(png_ptr, new_lang);
  201925. }
  201926. #endif
  201927. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201928. /* write the oFFs chunk */
  201929. void /* PRIVATE */
  201930. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201931. int unit_type)
  201932. {
  201933. #ifdef PNG_USE_LOCAL_ARRAYS
  201934. PNG_oFFs;
  201935. #endif
  201936. png_byte buf[9];
  201937. png_debug(1, "in png_write_oFFs\n");
  201938. if (unit_type >= PNG_OFFSET_LAST)
  201939. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201940. png_save_int_32(buf, x_offset);
  201941. png_save_int_32(buf + 4, y_offset);
  201942. buf[8] = (png_byte)unit_type;
  201943. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201944. }
  201945. #endif
  201946. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201947. /* write the pCAL chunk (described in the PNG extensions document) */
  201948. void /* PRIVATE */
  201949. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201950. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201951. {
  201952. #ifdef PNG_USE_LOCAL_ARRAYS
  201953. PNG_pCAL;
  201954. #endif
  201955. png_size_t purpose_len, units_len, total_len;
  201956. png_uint_32p params_len;
  201957. png_byte buf[10];
  201958. png_charp new_purpose;
  201959. int i;
  201960. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201961. if (type >= PNG_EQUATION_LAST)
  201962. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201963. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201964. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201965. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201966. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201967. total_len = purpose_len + units_len + 10;
  201968. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201969. *png_sizeof(png_uint_32)));
  201970. /* Find the length of each parameter, making sure we don't count the
  201971. null terminator for the last parameter. */
  201972. for (i = 0; i < nparams; i++)
  201973. {
  201974. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201975. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201976. total_len += (png_size_t)params_len[i];
  201977. }
  201978. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201979. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201980. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201981. png_save_int_32(buf, X0);
  201982. png_save_int_32(buf + 4, X1);
  201983. buf[8] = (png_byte)type;
  201984. buf[9] = (png_byte)nparams;
  201985. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201986. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201987. png_free(png_ptr, new_purpose);
  201988. for (i = 0; i < nparams; i++)
  201989. {
  201990. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201991. (png_size_t)params_len[i]);
  201992. }
  201993. png_free(png_ptr, params_len);
  201994. png_write_chunk_end(png_ptr);
  201995. }
  201996. #endif
  201997. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201998. /* write the sCAL chunk */
  201999. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202000. void /* PRIVATE */
  202001. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202002. {
  202003. #ifdef PNG_USE_LOCAL_ARRAYS
  202004. PNG_sCAL;
  202005. #endif
  202006. char buf[64];
  202007. png_size_t total_len;
  202008. png_debug(1, "in png_write_sCAL\n");
  202009. buf[0] = (char)unit;
  202010. #if defined(_WIN32_WCE)
  202011. /* sprintf() function is not supported on WindowsCE */
  202012. {
  202013. wchar_t wc_buf[32];
  202014. size_t wc_len;
  202015. swprintf(wc_buf, TEXT("%12.12e"), width);
  202016. wc_len = wcslen(wc_buf);
  202017. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202018. total_len = wc_len + 2;
  202019. swprintf(wc_buf, TEXT("%12.12e"), height);
  202020. wc_len = wcslen(wc_buf);
  202021. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202022. NULL, NULL);
  202023. total_len += wc_len;
  202024. }
  202025. #else
  202026. png_snprintf(buf + 1, 63, "%12.12e", width);
  202027. total_len = 1 + png_strlen(buf + 1) + 1;
  202028. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202029. total_len += png_strlen(buf + total_len);
  202030. #endif
  202031. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202032. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202033. }
  202034. #else
  202035. #ifdef PNG_FIXED_POINT_SUPPORTED
  202036. void /* PRIVATE */
  202037. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202038. png_charp height)
  202039. {
  202040. #ifdef PNG_USE_LOCAL_ARRAYS
  202041. PNG_sCAL;
  202042. #endif
  202043. png_byte buf[64];
  202044. png_size_t wlen, hlen, total_len;
  202045. png_debug(1, "in png_write_sCAL_s\n");
  202046. wlen = png_strlen(width);
  202047. hlen = png_strlen(height);
  202048. total_len = wlen + hlen + 2;
  202049. if (total_len > 64)
  202050. {
  202051. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202052. return;
  202053. }
  202054. buf[0] = (png_byte)unit;
  202055. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202056. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202057. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202058. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202059. }
  202060. #endif
  202061. #endif
  202062. #endif
  202063. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202064. /* write the pHYs chunk */
  202065. void /* PRIVATE */
  202066. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202067. png_uint_32 y_pixels_per_unit,
  202068. int unit_type)
  202069. {
  202070. #ifdef PNG_USE_LOCAL_ARRAYS
  202071. PNG_pHYs;
  202072. #endif
  202073. png_byte buf[9];
  202074. png_debug(1, "in png_write_pHYs\n");
  202075. if (unit_type >= PNG_RESOLUTION_LAST)
  202076. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202077. png_save_uint_32(buf, x_pixels_per_unit);
  202078. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202079. buf[8] = (png_byte)unit_type;
  202080. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202081. }
  202082. #endif
  202083. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202084. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202085. * or png_convert_from_time_t(), or fill in the structure yourself.
  202086. */
  202087. void /* PRIVATE */
  202088. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202089. {
  202090. #ifdef PNG_USE_LOCAL_ARRAYS
  202091. PNG_tIME;
  202092. #endif
  202093. png_byte buf[7];
  202094. png_debug(1, "in png_write_tIME\n");
  202095. if (mod_time->month > 12 || mod_time->month < 1 ||
  202096. mod_time->day > 31 || mod_time->day < 1 ||
  202097. mod_time->hour > 23 || mod_time->second > 60)
  202098. {
  202099. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202100. return;
  202101. }
  202102. png_save_uint_16(buf, mod_time->year);
  202103. buf[2] = mod_time->month;
  202104. buf[3] = mod_time->day;
  202105. buf[4] = mod_time->hour;
  202106. buf[5] = mod_time->minute;
  202107. buf[6] = mod_time->second;
  202108. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202109. }
  202110. #endif
  202111. /* initializes the row writing capability of libpng */
  202112. void /* PRIVATE */
  202113. png_write_start_row(png_structp png_ptr)
  202114. {
  202115. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202116. #ifdef PNG_USE_LOCAL_ARRAYS
  202117. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202118. /* start of interlace block */
  202119. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202120. /* offset to next interlace block */
  202121. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202122. /* start of interlace block in the y direction */
  202123. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202124. /* offset to next interlace block in the y direction */
  202125. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202126. #endif
  202127. #endif
  202128. png_size_t buf_size;
  202129. png_debug(1, "in png_write_start_row\n");
  202130. buf_size = (png_size_t)(PNG_ROWBYTES(
  202131. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202132. /* set up row buffer */
  202133. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202134. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202135. #ifndef PNG_NO_WRITE_FILTERING
  202136. /* set up filtering buffer, if using this filter */
  202137. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202138. {
  202139. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202140. (png_ptr->rowbytes + 1));
  202141. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202142. }
  202143. /* We only need to keep the previous row if we are using one of these. */
  202144. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202145. {
  202146. /* set up previous row buffer */
  202147. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202148. png_memset(png_ptr->prev_row, 0, buf_size);
  202149. if (png_ptr->do_filter & PNG_FILTER_UP)
  202150. {
  202151. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202152. (png_ptr->rowbytes + 1));
  202153. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202154. }
  202155. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202156. {
  202157. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202158. (png_ptr->rowbytes + 1));
  202159. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202160. }
  202161. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202162. {
  202163. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202164. (png_ptr->rowbytes + 1));
  202165. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202166. }
  202167. #endif /* PNG_NO_WRITE_FILTERING */
  202168. }
  202169. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202170. /* if interlaced, we need to set up width and height of pass */
  202171. if (png_ptr->interlaced)
  202172. {
  202173. if (!(png_ptr->transformations & PNG_INTERLACE))
  202174. {
  202175. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202176. png_pass_ystart[0]) / png_pass_yinc[0];
  202177. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202178. png_pass_start[0]) / png_pass_inc[0];
  202179. }
  202180. else
  202181. {
  202182. png_ptr->num_rows = png_ptr->height;
  202183. png_ptr->usr_width = png_ptr->width;
  202184. }
  202185. }
  202186. else
  202187. #endif
  202188. {
  202189. png_ptr->num_rows = png_ptr->height;
  202190. png_ptr->usr_width = png_ptr->width;
  202191. }
  202192. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202193. png_ptr->zstream.next_out = png_ptr->zbuf;
  202194. }
  202195. /* Internal use only. Called when finished processing a row of data. */
  202196. void /* PRIVATE */
  202197. png_write_finish_row(png_structp png_ptr)
  202198. {
  202199. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202200. #ifdef PNG_USE_LOCAL_ARRAYS
  202201. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202202. /* start of interlace block */
  202203. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202204. /* offset to next interlace block */
  202205. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202206. /* start of interlace block in the y direction */
  202207. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202208. /* offset to next interlace block in the y direction */
  202209. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202210. #endif
  202211. #endif
  202212. int ret;
  202213. png_debug(1, "in png_write_finish_row\n");
  202214. /* next row */
  202215. png_ptr->row_number++;
  202216. /* see if we are done */
  202217. if (png_ptr->row_number < png_ptr->num_rows)
  202218. return;
  202219. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202220. /* if interlaced, go to next pass */
  202221. if (png_ptr->interlaced)
  202222. {
  202223. png_ptr->row_number = 0;
  202224. if (png_ptr->transformations & PNG_INTERLACE)
  202225. {
  202226. png_ptr->pass++;
  202227. }
  202228. else
  202229. {
  202230. /* loop until we find a non-zero width or height pass */
  202231. do
  202232. {
  202233. png_ptr->pass++;
  202234. if (png_ptr->pass >= 7)
  202235. break;
  202236. png_ptr->usr_width = (png_ptr->width +
  202237. png_pass_inc[png_ptr->pass] - 1 -
  202238. png_pass_start[png_ptr->pass]) /
  202239. png_pass_inc[png_ptr->pass];
  202240. png_ptr->num_rows = (png_ptr->height +
  202241. png_pass_yinc[png_ptr->pass] - 1 -
  202242. png_pass_ystart[png_ptr->pass]) /
  202243. png_pass_yinc[png_ptr->pass];
  202244. if (png_ptr->transformations & PNG_INTERLACE)
  202245. break;
  202246. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202247. }
  202248. /* reset the row above the image for the next pass */
  202249. if (png_ptr->pass < 7)
  202250. {
  202251. if (png_ptr->prev_row != NULL)
  202252. png_memset(png_ptr->prev_row, 0,
  202253. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202254. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202255. return;
  202256. }
  202257. }
  202258. #endif
  202259. /* if we get here, we've just written the last row, so we need
  202260. to flush the compressor */
  202261. do
  202262. {
  202263. /* tell the compressor we are done */
  202264. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202265. /* check for an error */
  202266. if (ret == Z_OK)
  202267. {
  202268. /* check to see if we need more room */
  202269. if (!(png_ptr->zstream.avail_out))
  202270. {
  202271. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202272. png_ptr->zstream.next_out = png_ptr->zbuf;
  202273. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202274. }
  202275. }
  202276. else if (ret != Z_STREAM_END)
  202277. {
  202278. if (png_ptr->zstream.msg != NULL)
  202279. png_error(png_ptr, png_ptr->zstream.msg);
  202280. else
  202281. png_error(png_ptr, "zlib error");
  202282. }
  202283. } while (ret != Z_STREAM_END);
  202284. /* write any extra space */
  202285. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202286. {
  202287. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202288. png_ptr->zstream.avail_out);
  202289. }
  202290. deflateReset(&png_ptr->zstream);
  202291. png_ptr->zstream.data_type = Z_BINARY;
  202292. }
  202293. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202294. /* Pick out the correct pixels for the interlace pass.
  202295. * The basic idea here is to go through the row with a source
  202296. * pointer and a destination pointer (sp and dp), and copy the
  202297. * correct pixels for the pass. As the row gets compacted,
  202298. * sp will always be >= dp, so we should never overwrite anything.
  202299. * See the default: case for the easiest code to understand.
  202300. */
  202301. void /* PRIVATE */
  202302. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202303. {
  202304. #ifdef PNG_USE_LOCAL_ARRAYS
  202305. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202306. /* start of interlace block */
  202307. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202308. /* offset to next interlace block */
  202309. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202310. #endif
  202311. png_debug(1, "in png_do_write_interlace\n");
  202312. /* we don't have to do anything on the last pass (6) */
  202313. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202314. if (row != NULL && row_info != NULL && pass < 6)
  202315. #else
  202316. if (pass < 6)
  202317. #endif
  202318. {
  202319. /* each pixel depth is handled separately */
  202320. switch (row_info->pixel_depth)
  202321. {
  202322. case 1:
  202323. {
  202324. png_bytep sp;
  202325. png_bytep dp;
  202326. int shift;
  202327. int d;
  202328. int value;
  202329. png_uint_32 i;
  202330. png_uint_32 row_width = row_info->width;
  202331. dp = row;
  202332. d = 0;
  202333. shift = 7;
  202334. for (i = png_pass_start[pass]; i < row_width;
  202335. i += png_pass_inc[pass])
  202336. {
  202337. sp = row + (png_size_t)(i >> 3);
  202338. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202339. d |= (value << shift);
  202340. if (shift == 0)
  202341. {
  202342. shift = 7;
  202343. *dp++ = (png_byte)d;
  202344. d = 0;
  202345. }
  202346. else
  202347. shift--;
  202348. }
  202349. if (shift != 7)
  202350. *dp = (png_byte)d;
  202351. break;
  202352. }
  202353. case 2:
  202354. {
  202355. png_bytep sp;
  202356. png_bytep dp;
  202357. int shift;
  202358. int d;
  202359. int value;
  202360. png_uint_32 i;
  202361. png_uint_32 row_width = row_info->width;
  202362. dp = row;
  202363. shift = 6;
  202364. d = 0;
  202365. for (i = png_pass_start[pass]; i < row_width;
  202366. i += png_pass_inc[pass])
  202367. {
  202368. sp = row + (png_size_t)(i >> 2);
  202369. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202370. d |= (value << shift);
  202371. if (shift == 0)
  202372. {
  202373. shift = 6;
  202374. *dp++ = (png_byte)d;
  202375. d = 0;
  202376. }
  202377. else
  202378. shift -= 2;
  202379. }
  202380. if (shift != 6)
  202381. *dp = (png_byte)d;
  202382. break;
  202383. }
  202384. case 4:
  202385. {
  202386. png_bytep sp;
  202387. png_bytep dp;
  202388. int shift;
  202389. int d;
  202390. int value;
  202391. png_uint_32 i;
  202392. png_uint_32 row_width = row_info->width;
  202393. dp = row;
  202394. shift = 4;
  202395. d = 0;
  202396. for (i = png_pass_start[pass]; i < row_width;
  202397. i += png_pass_inc[pass])
  202398. {
  202399. sp = row + (png_size_t)(i >> 1);
  202400. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202401. d |= (value << shift);
  202402. if (shift == 0)
  202403. {
  202404. shift = 4;
  202405. *dp++ = (png_byte)d;
  202406. d = 0;
  202407. }
  202408. else
  202409. shift -= 4;
  202410. }
  202411. if (shift != 4)
  202412. *dp = (png_byte)d;
  202413. break;
  202414. }
  202415. default:
  202416. {
  202417. png_bytep sp;
  202418. png_bytep dp;
  202419. png_uint_32 i;
  202420. png_uint_32 row_width = row_info->width;
  202421. png_size_t pixel_bytes;
  202422. /* start at the beginning */
  202423. dp = row;
  202424. /* find out how many bytes each pixel takes up */
  202425. pixel_bytes = (row_info->pixel_depth >> 3);
  202426. /* loop through the row, only looking at the pixels that
  202427. matter */
  202428. for (i = png_pass_start[pass]; i < row_width;
  202429. i += png_pass_inc[pass])
  202430. {
  202431. /* find out where the original pixel is */
  202432. sp = row + (png_size_t)i * pixel_bytes;
  202433. /* move the pixel */
  202434. if (dp != sp)
  202435. png_memcpy(dp, sp, pixel_bytes);
  202436. /* next pixel */
  202437. dp += pixel_bytes;
  202438. }
  202439. break;
  202440. }
  202441. }
  202442. /* set new row width */
  202443. row_info->width = (row_info->width +
  202444. png_pass_inc[pass] - 1 -
  202445. png_pass_start[pass]) /
  202446. png_pass_inc[pass];
  202447. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202448. row_info->width);
  202449. }
  202450. }
  202451. #endif
  202452. /* This filters the row, chooses which filter to use, if it has not already
  202453. * been specified by the application, and then writes the row out with the
  202454. * chosen filter.
  202455. */
  202456. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202457. #define PNG_HISHIFT 10
  202458. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202459. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202460. void /* PRIVATE */
  202461. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202462. {
  202463. png_bytep best_row;
  202464. #ifndef PNG_NO_WRITE_FILTER
  202465. png_bytep prev_row, row_buf;
  202466. png_uint_32 mins, bpp;
  202467. png_byte filter_to_do = png_ptr->do_filter;
  202468. png_uint_32 row_bytes = row_info->rowbytes;
  202469. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202470. int num_p_filters = (int)png_ptr->num_prev_filters;
  202471. #endif
  202472. png_debug(1, "in png_write_find_filter\n");
  202473. /* find out how many bytes offset each pixel is */
  202474. bpp = (row_info->pixel_depth + 7) >> 3;
  202475. prev_row = png_ptr->prev_row;
  202476. #endif
  202477. best_row = png_ptr->row_buf;
  202478. #ifndef PNG_NO_WRITE_FILTER
  202479. row_buf = best_row;
  202480. mins = PNG_MAXSUM;
  202481. /* The prediction method we use is to find which method provides the
  202482. * smallest value when summing the absolute values of the distances
  202483. * from zero, using anything >= 128 as negative numbers. This is known
  202484. * as the "minimum sum of absolute differences" heuristic. Other
  202485. * heuristics are the "weighted minimum sum of absolute differences"
  202486. * (experimental and can in theory improve compression), and the "zlib
  202487. * predictive" method (not implemented yet), which does test compressions
  202488. * of lines using different filter methods, and then chooses the
  202489. * (series of) filter(s) that give minimum compressed data size (VERY
  202490. * computationally expensive).
  202491. *
  202492. * GRR 980525: consider also
  202493. * (1) minimum sum of absolute differences from running average (i.e.,
  202494. * keep running sum of non-absolute differences & count of bytes)
  202495. * [track dispersion, too? restart average if dispersion too large?]
  202496. * (1b) minimum sum of absolute differences from sliding average, probably
  202497. * with window size <= deflate window (usually 32K)
  202498. * (2) minimum sum of squared differences from zero or running average
  202499. * (i.e., ~ root-mean-square approach)
  202500. */
  202501. /* We don't need to test the 'no filter' case if this is the only filter
  202502. * that has been chosen, as it doesn't actually do anything to the data.
  202503. */
  202504. if ((filter_to_do & PNG_FILTER_NONE) &&
  202505. filter_to_do != PNG_FILTER_NONE)
  202506. {
  202507. png_bytep rp;
  202508. png_uint_32 sum = 0;
  202509. png_uint_32 i;
  202510. int v;
  202511. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202512. {
  202513. v = *rp;
  202514. sum += (v < 128) ? v : 256 - v;
  202515. }
  202516. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202517. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202518. {
  202519. png_uint_32 sumhi, sumlo;
  202520. int j;
  202521. sumlo = sum & PNG_LOMASK;
  202522. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202523. /* Reduce the sum if we match any of the previous rows */
  202524. for (j = 0; j < num_p_filters; j++)
  202525. {
  202526. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202527. {
  202528. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202529. PNG_WEIGHT_SHIFT;
  202530. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202531. PNG_WEIGHT_SHIFT;
  202532. }
  202533. }
  202534. /* Factor in the cost of this filter (this is here for completeness,
  202535. * but it makes no sense to have a "cost" for the NONE filter, as
  202536. * it has the minimum possible computational cost - none).
  202537. */
  202538. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202539. PNG_COST_SHIFT;
  202540. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202541. PNG_COST_SHIFT;
  202542. if (sumhi > PNG_HIMASK)
  202543. sum = PNG_MAXSUM;
  202544. else
  202545. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202546. }
  202547. #endif
  202548. mins = sum;
  202549. }
  202550. /* sub filter */
  202551. if (filter_to_do == PNG_FILTER_SUB)
  202552. /* it's the only filter so no testing is needed */
  202553. {
  202554. png_bytep rp, lp, dp;
  202555. png_uint_32 i;
  202556. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202557. i++, rp++, dp++)
  202558. {
  202559. *dp = *rp;
  202560. }
  202561. for (lp = row_buf + 1; i < row_bytes;
  202562. i++, rp++, lp++, dp++)
  202563. {
  202564. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202565. }
  202566. best_row = png_ptr->sub_row;
  202567. }
  202568. else if (filter_to_do & PNG_FILTER_SUB)
  202569. {
  202570. png_bytep rp, dp, lp;
  202571. png_uint_32 sum = 0, lmins = mins;
  202572. png_uint_32 i;
  202573. int v;
  202574. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202575. /* We temporarily increase the "minimum sum" by the factor we
  202576. * would reduce the sum of this filter, so that we can do the
  202577. * early exit comparison without scaling the sum each time.
  202578. */
  202579. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202580. {
  202581. int j;
  202582. png_uint_32 lmhi, lmlo;
  202583. lmlo = lmins & PNG_LOMASK;
  202584. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202585. for (j = 0; j < num_p_filters; j++)
  202586. {
  202587. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202588. {
  202589. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202590. PNG_WEIGHT_SHIFT;
  202591. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202592. PNG_WEIGHT_SHIFT;
  202593. }
  202594. }
  202595. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202596. PNG_COST_SHIFT;
  202597. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202598. PNG_COST_SHIFT;
  202599. if (lmhi > PNG_HIMASK)
  202600. lmins = PNG_MAXSUM;
  202601. else
  202602. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202603. }
  202604. #endif
  202605. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202606. i++, rp++, dp++)
  202607. {
  202608. v = *dp = *rp;
  202609. sum += (v < 128) ? v : 256 - v;
  202610. }
  202611. for (lp = row_buf + 1; i < row_bytes;
  202612. i++, rp++, lp++, dp++)
  202613. {
  202614. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202615. sum += (v < 128) ? v : 256 - v;
  202616. if (sum > lmins) /* We are already worse, don't continue. */
  202617. break;
  202618. }
  202619. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202620. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202621. {
  202622. int j;
  202623. png_uint_32 sumhi, sumlo;
  202624. sumlo = sum & PNG_LOMASK;
  202625. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202626. for (j = 0; j < num_p_filters; j++)
  202627. {
  202628. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202629. {
  202630. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202631. PNG_WEIGHT_SHIFT;
  202632. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202633. PNG_WEIGHT_SHIFT;
  202634. }
  202635. }
  202636. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202637. PNG_COST_SHIFT;
  202638. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202639. PNG_COST_SHIFT;
  202640. if (sumhi > PNG_HIMASK)
  202641. sum = PNG_MAXSUM;
  202642. else
  202643. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202644. }
  202645. #endif
  202646. if (sum < mins)
  202647. {
  202648. mins = sum;
  202649. best_row = png_ptr->sub_row;
  202650. }
  202651. }
  202652. /* up filter */
  202653. if (filter_to_do == PNG_FILTER_UP)
  202654. {
  202655. png_bytep rp, dp, pp;
  202656. png_uint_32 i;
  202657. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202658. pp = prev_row + 1; i < row_bytes;
  202659. i++, rp++, pp++, dp++)
  202660. {
  202661. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202662. }
  202663. best_row = png_ptr->up_row;
  202664. }
  202665. else if (filter_to_do & PNG_FILTER_UP)
  202666. {
  202667. png_bytep rp, dp, pp;
  202668. png_uint_32 sum = 0, lmins = mins;
  202669. png_uint_32 i;
  202670. int v;
  202671. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202672. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202673. {
  202674. int j;
  202675. png_uint_32 lmhi, lmlo;
  202676. lmlo = lmins & PNG_LOMASK;
  202677. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202678. for (j = 0; j < num_p_filters; j++)
  202679. {
  202680. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202681. {
  202682. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202683. PNG_WEIGHT_SHIFT;
  202684. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202685. PNG_WEIGHT_SHIFT;
  202686. }
  202687. }
  202688. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202689. PNG_COST_SHIFT;
  202690. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202691. PNG_COST_SHIFT;
  202692. if (lmhi > PNG_HIMASK)
  202693. lmins = PNG_MAXSUM;
  202694. else
  202695. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202696. }
  202697. #endif
  202698. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202699. pp = prev_row + 1; i < row_bytes; i++)
  202700. {
  202701. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202702. sum += (v < 128) ? v : 256 - v;
  202703. if (sum > lmins) /* We are already worse, don't continue. */
  202704. break;
  202705. }
  202706. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202707. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202708. {
  202709. int j;
  202710. png_uint_32 sumhi, sumlo;
  202711. sumlo = sum & PNG_LOMASK;
  202712. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202713. for (j = 0; j < num_p_filters; j++)
  202714. {
  202715. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202716. {
  202717. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202718. PNG_WEIGHT_SHIFT;
  202719. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202720. PNG_WEIGHT_SHIFT;
  202721. }
  202722. }
  202723. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202724. PNG_COST_SHIFT;
  202725. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202726. PNG_COST_SHIFT;
  202727. if (sumhi > PNG_HIMASK)
  202728. sum = PNG_MAXSUM;
  202729. else
  202730. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202731. }
  202732. #endif
  202733. if (sum < mins)
  202734. {
  202735. mins = sum;
  202736. best_row = png_ptr->up_row;
  202737. }
  202738. }
  202739. /* avg filter */
  202740. if (filter_to_do == PNG_FILTER_AVG)
  202741. {
  202742. png_bytep rp, dp, pp, lp;
  202743. png_uint_32 i;
  202744. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202745. pp = prev_row + 1; i < bpp; i++)
  202746. {
  202747. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202748. }
  202749. for (lp = row_buf + 1; i < row_bytes; i++)
  202750. {
  202751. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202752. & 0xff);
  202753. }
  202754. best_row = png_ptr->avg_row;
  202755. }
  202756. else if (filter_to_do & PNG_FILTER_AVG)
  202757. {
  202758. png_bytep rp, dp, pp, lp;
  202759. png_uint_32 sum = 0, lmins = mins;
  202760. png_uint_32 i;
  202761. int v;
  202762. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202763. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202764. {
  202765. int j;
  202766. png_uint_32 lmhi, lmlo;
  202767. lmlo = lmins & PNG_LOMASK;
  202768. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202769. for (j = 0; j < num_p_filters; j++)
  202770. {
  202771. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202772. {
  202773. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202774. PNG_WEIGHT_SHIFT;
  202775. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202776. PNG_WEIGHT_SHIFT;
  202777. }
  202778. }
  202779. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202780. PNG_COST_SHIFT;
  202781. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202782. PNG_COST_SHIFT;
  202783. if (lmhi > PNG_HIMASK)
  202784. lmins = PNG_MAXSUM;
  202785. else
  202786. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202787. }
  202788. #endif
  202789. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202790. pp = prev_row + 1; i < bpp; i++)
  202791. {
  202792. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202793. sum += (v < 128) ? v : 256 - v;
  202794. }
  202795. for (lp = row_buf + 1; i < row_bytes; i++)
  202796. {
  202797. v = *dp++ =
  202798. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202799. sum += (v < 128) ? v : 256 - v;
  202800. if (sum > lmins) /* We are already worse, don't continue. */
  202801. break;
  202802. }
  202803. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202804. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202805. {
  202806. int j;
  202807. png_uint_32 sumhi, sumlo;
  202808. sumlo = sum & PNG_LOMASK;
  202809. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202810. for (j = 0; j < num_p_filters; j++)
  202811. {
  202812. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202813. {
  202814. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202815. PNG_WEIGHT_SHIFT;
  202816. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202817. PNG_WEIGHT_SHIFT;
  202818. }
  202819. }
  202820. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202821. PNG_COST_SHIFT;
  202822. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202823. PNG_COST_SHIFT;
  202824. if (sumhi > PNG_HIMASK)
  202825. sum = PNG_MAXSUM;
  202826. else
  202827. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202828. }
  202829. #endif
  202830. if (sum < mins)
  202831. {
  202832. mins = sum;
  202833. best_row = png_ptr->avg_row;
  202834. }
  202835. }
  202836. /* Paeth filter */
  202837. if (filter_to_do == PNG_FILTER_PAETH)
  202838. {
  202839. png_bytep rp, dp, pp, cp, lp;
  202840. png_uint_32 i;
  202841. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202842. pp = prev_row + 1; i < bpp; i++)
  202843. {
  202844. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202845. }
  202846. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202847. {
  202848. int a, b, c, pa, pb, pc, p;
  202849. b = *pp++;
  202850. c = *cp++;
  202851. a = *lp++;
  202852. p = b - c;
  202853. pc = a - c;
  202854. #ifdef PNG_USE_ABS
  202855. pa = abs(p);
  202856. pb = abs(pc);
  202857. pc = abs(p + pc);
  202858. #else
  202859. pa = p < 0 ? -p : p;
  202860. pb = pc < 0 ? -pc : pc;
  202861. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202862. #endif
  202863. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202864. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202865. }
  202866. best_row = png_ptr->paeth_row;
  202867. }
  202868. else if (filter_to_do & PNG_FILTER_PAETH)
  202869. {
  202870. png_bytep rp, dp, pp, cp, lp;
  202871. png_uint_32 sum = 0, lmins = mins;
  202872. png_uint_32 i;
  202873. int v;
  202874. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202875. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202876. {
  202877. int j;
  202878. png_uint_32 lmhi, lmlo;
  202879. lmlo = lmins & PNG_LOMASK;
  202880. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202881. for (j = 0; j < num_p_filters; j++)
  202882. {
  202883. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202884. {
  202885. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202886. PNG_WEIGHT_SHIFT;
  202887. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202888. PNG_WEIGHT_SHIFT;
  202889. }
  202890. }
  202891. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202892. PNG_COST_SHIFT;
  202893. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202894. PNG_COST_SHIFT;
  202895. if (lmhi > PNG_HIMASK)
  202896. lmins = PNG_MAXSUM;
  202897. else
  202898. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202899. }
  202900. #endif
  202901. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202902. pp = prev_row + 1; i < bpp; i++)
  202903. {
  202904. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202905. sum += (v < 128) ? v : 256 - v;
  202906. }
  202907. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202908. {
  202909. int a, b, c, pa, pb, pc, p;
  202910. b = *pp++;
  202911. c = *cp++;
  202912. a = *lp++;
  202913. #ifndef PNG_SLOW_PAETH
  202914. p = b - c;
  202915. pc = a - c;
  202916. #ifdef PNG_USE_ABS
  202917. pa = abs(p);
  202918. pb = abs(pc);
  202919. pc = abs(p + pc);
  202920. #else
  202921. pa = p < 0 ? -p : p;
  202922. pb = pc < 0 ? -pc : pc;
  202923. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202924. #endif
  202925. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202926. #else /* PNG_SLOW_PAETH */
  202927. p = a + b - c;
  202928. pa = abs(p - a);
  202929. pb = abs(p - b);
  202930. pc = abs(p - c);
  202931. if (pa <= pb && pa <= pc)
  202932. p = a;
  202933. else if (pb <= pc)
  202934. p = b;
  202935. else
  202936. p = c;
  202937. #endif /* PNG_SLOW_PAETH */
  202938. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202939. sum += (v < 128) ? v : 256 - v;
  202940. if (sum > lmins) /* We are already worse, don't continue. */
  202941. break;
  202942. }
  202943. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202944. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202945. {
  202946. int j;
  202947. png_uint_32 sumhi, sumlo;
  202948. sumlo = sum & PNG_LOMASK;
  202949. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202950. for (j = 0; j < num_p_filters; j++)
  202951. {
  202952. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202953. {
  202954. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202955. PNG_WEIGHT_SHIFT;
  202956. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202957. PNG_WEIGHT_SHIFT;
  202958. }
  202959. }
  202960. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202961. PNG_COST_SHIFT;
  202962. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202963. PNG_COST_SHIFT;
  202964. if (sumhi > PNG_HIMASK)
  202965. sum = PNG_MAXSUM;
  202966. else
  202967. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202968. }
  202969. #endif
  202970. if (sum < mins)
  202971. {
  202972. best_row = png_ptr->paeth_row;
  202973. }
  202974. }
  202975. #endif /* PNG_NO_WRITE_FILTER */
  202976. /* Do the actual writing of the filtered row data from the chosen filter. */
  202977. png_write_filtered_row(png_ptr, best_row);
  202978. #ifndef PNG_NO_WRITE_FILTER
  202979. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202980. /* Save the type of filter we picked this time for future calculations */
  202981. if (png_ptr->num_prev_filters > 0)
  202982. {
  202983. int j;
  202984. for (j = 1; j < num_p_filters; j++)
  202985. {
  202986. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202987. }
  202988. png_ptr->prev_filters[j] = best_row[0];
  202989. }
  202990. #endif
  202991. #endif /* PNG_NO_WRITE_FILTER */
  202992. }
  202993. /* Do the actual writing of a previously filtered row. */
  202994. void /* PRIVATE */
  202995. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202996. {
  202997. png_debug(1, "in png_write_filtered_row\n");
  202998. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202999. /* set up the zlib input buffer */
  203000. png_ptr->zstream.next_in = filtered_row;
  203001. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203002. /* repeat until we have compressed all the data */
  203003. do
  203004. {
  203005. int ret; /* return of zlib */
  203006. /* compress the data */
  203007. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203008. /* check for compression errors */
  203009. if (ret != Z_OK)
  203010. {
  203011. if (png_ptr->zstream.msg != NULL)
  203012. png_error(png_ptr, png_ptr->zstream.msg);
  203013. else
  203014. png_error(png_ptr, "zlib error");
  203015. }
  203016. /* see if it is time to write another IDAT */
  203017. if (!(png_ptr->zstream.avail_out))
  203018. {
  203019. /* write the IDAT and reset the zlib output buffer */
  203020. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203021. png_ptr->zstream.next_out = png_ptr->zbuf;
  203022. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203023. }
  203024. /* repeat until all data has been compressed */
  203025. } while (png_ptr->zstream.avail_in);
  203026. /* swap the current and previous rows */
  203027. if (png_ptr->prev_row != NULL)
  203028. {
  203029. png_bytep tptr;
  203030. tptr = png_ptr->prev_row;
  203031. png_ptr->prev_row = png_ptr->row_buf;
  203032. png_ptr->row_buf = tptr;
  203033. }
  203034. /* finish row - updates counters and flushes zlib if last row */
  203035. png_write_finish_row(png_ptr);
  203036. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203037. png_ptr->flush_rows++;
  203038. if (png_ptr->flush_dist > 0 &&
  203039. png_ptr->flush_rows >= png_ptr->flush_dist)
  203040. {
  203041. png_write_flush(png_ptr);
  203042. }
  203043. #endif
  203044. }
  203045. #endif /* PNG_WRITE_SUPPORTED */
  203046. /*** End of inlined file: pngwutil.c ***/
  203047. #else
  203048. extern "C"
  203049. {
  203050. #include <png.h>
  203051. #include <pngconf.h>
  203052. }
  203053. #endif
  203054. }
  203055. #undef max
  203056. #undef min
  203057. #if JUCE_MSVC
  203058. #pragma warning (pop)
  203059. #endif
  203060. BEGIN_JUCE_NAMESPACE
  203061. using ::calloc;
  203062. using ::malloc;
  203063. using ::free;
  203064. namespace PNGHelpers
  203065. {
  203066. using namespace pnglibNamespace;
  203067. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  203068. {
  203069. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203070. }
  203071. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203072. {
  203073. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203074. }
  203075. struct PNGErrorStruct {};
  203076. static void errorCallback (png_structp, png_const_charp)
  203077. {
  203078. throw PNGErrorStruct();
  203079. }
  203080. }
  203081. PNGImageFormat::PNGImageFormat() {}
  203082. PNGImageFormat::~PNGImageFormat() {}
  203083. const String PNGImageFormat::getFormatName()
  203084. {
  203085. return "PNG";
  203086. }
  203087. bool PNGImageFormat::canUnderstand (InputStream& in)
  203088. {
  203089. const int bytesNeeded = 4;
  203090. char header [bytesNeeded];
  203091. return in.read (header, bytesNeeded) == bytesNeeded
  203092. && header[1] == 'P'
  203093. && header[2] == 'N'
  203094. && header[3] == 'G';
  203095. }
  203096. const Image PNGImageFormat::decodeImage (InputStream& in)
  203097. {
  203098. using namespace pnglibNamespace;
  203099. Image image;
  203100. png_structp pngReadStruct;
  203101. png_infop pngInfoStruct;
  203102. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203103. if (pngReadStruct != 0)
  203104. {
  203105. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203106. if (pngInfoStruct == 0)
  203107. {
  203108. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203109. return Image::null;
  203110. }
  203111. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203112. // read the header..
  203113. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203114. png_uint_32 width, height;
  203115. int bitDepth, colorType, interlaceType;
  203116. png_read_info (pngReadStruct, pngInfoStruct);
  203117. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203118. &width, &height,
  203119. &bitDepth, &colorType,
  203120. &interlaceType, 0, 0);
  203121. if (bitDepth == 16)
  203122. png_set_strip_16 (pngReadStruct);
  203123. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203124. png_set_expand (pngReadStruct);
  203125. if (bitDepth < 8)
  203126. png_set_expand (pngReadStruct);
  203127. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203128. png_set_expand (pngReadStruct);
  203129. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203130. png_set_gray_to_rgb (pngReadStruct);
  203131. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203132. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203133. || pngInfoStruct->num_trans > 0;
  203134. // Load the image into a temp buffer in the pnglib format..
  203135. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203136. {
  203137. HeapBlock <png_bytep> rows (height);
  203138. for (int y = (int) height; --y >= 0;)
  203139. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203140. png_read_image (pngReadStruct, rows);
  203141. png_read_end (pngReadStruct, pngInfoStruct);
  203142. }
  203143. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203144. // now convert the data to a juce image format..
  203145. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203146. (int) width, (int) height, hasAlphaChan);
  203147. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203148. const Image::BitmapData destData (image, true);
  203149. uint8* srcRow = tempBuffer;
  203150. uint8* destRow = destData.data;
  203151. for (int y = 0; y < (int) height; ++y)
  203152. {
  203153. const uint8* src = srcRow;
  203154. srcRow += (width << 2);
  203155. uint8* dest = destRow;
  203156. destRow += destData.lineStride;
  203157. if (hasAlphaChan)
  203158. {
  203159. for (int i = (int) width; --i >= 0;)
  203160. {
  203161. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203162. ((PixelARGB*) dest)->premultiply();
  203163. dest += destData.pixelStride;
  203164. src += 4;
  203165. }
  203166. }
  203167. else
  203168. {
  203169. for (int i = (int) width; --i >= 0;)
  203170. {
  203171. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203172. dest += destData.pixelStride;
  203173. src += 4;
  203174. }
  203175. }
  203176. }
  203177. }
  203178. return image;
  203179. }
  203180. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203181. {
  203182. using namespace pnglibNamespace;
  203183. const int width = image.getWidth();
  203184. const int height = image.getHeight();
  203185. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203186. if (pngWriteStruct == 0)
  203187. return false;
  203188. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203189. if (pngInfoStruct == 0)
  203190. {
  203191. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203192. return false;
  203193. }
  203194. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203195. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203196. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203197. : PNG_COLOR_TYPE_RGB,
  203198. PNG_INTERLACE_NONE,
  203199. PNG_COMPRESSION_TYPE_BASE,
  203200. PNG_FILTER_TYPE_BASE);
  203201. HeapBlock <uint8> rowData (width * 4);
  203202. png_color_8 sig_bit;
  203203. sig_bit.red = 8;
  203204. sig_bit.green = 8;
  203205. sig_bit.blue = 8;
  203206. sig_bit.alpha = 8;
  203207. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203208. png_write_info (pngWriteStruct, pngInfoStruct);
  203209. png_set_shift (pngWriteStruct, &sig_bit);
  203210. png_set_packing (pngWriteStruct);
  203211. const Image::BitmapData srcData (image, false);
  203212. for (int y = 0; y < height; ++y)
  203213. {
  203214. uint8* dst = rowData;
  203215. const uint8* src = srcData.getLinePointer (y);
  203216. if (image.hasAlphaChannel())
  203217. {
  203218. for (int i = width; --i >= 0;)
  203219. {
  203220. PixelARGB p (*(const PixelARGB*) src);
  203221. p.unpremultiply();
  203222. *dst++ = p.getRed();
  203223. *dst++ = p.getGreen();
  203224. *dst++ = p.getBlue();
  203225. *dst++ = p.getAlpha();
  203226. src += srcData.pixelStride;
  203227. }
  203228. }
  203229. else
  203230. {
  203231. for (int i = width; --i >= 0;)
  203232. {
  203233. *dst++ = ((const PixelRGB*) src)->getRed();
  203234. *dst++ = ((const PixelRGB*) src)->getGreen();
  203235. *dst++ = ((const PixelRGB*) src)->getBlue();
  203236. src += srcData.pixelStride;
  203237. }
  203238. }
  203239. png_write_rows (pngWriteStruct, &rowData, 1);
  203240. }
  203241. png_write_end (pngWriteStruct, pngInfoStruct);
  203242. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203243. out.flush();
  203244. return true;
  203245. }
  203246. END_JUCE_NAMESPACE
  203247. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203248. #endif
  203249. //==============================================================================
  203250. #if JUCE_BUILD_NATIVE
  203251. #if JUCE_WINDOWS
  203252. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203253. /*
  203254. This file wraps together all the win32-specific code, so that
  203255. we can include all the native headers just once, and compile all our
  203256. platform-specific stuff in one big lump, keeping it out of the way of
  203257. the rest of the codebase.
  203258. */
  203259. #if JUCE_WINDOWS
  203260. BEGIN_JUCE_NAMESPACE
  203261. #define JUCE_INCLUDED_FILE 1
  203262. // Now include the actual code files..
  203263. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203264. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203265. // compiled on its own).
  203266. #if JUCE_INCLUDED_FILE
  203267. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203268. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203269. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203270. #ifndef DOXYGEN
  203271. // use with DynamicLibraryLoader to simplify importing functions
  203272. //
  203273. // functionName: function to import
  203274. // localFunctionName: name you want to use to actually call it (must be different)
  203275. // returnType: the return type
  203276. // object: the DynamicLibraryLoader to use
  203277. // params: list of params (bracketed)
  203278. //
  203279. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203280. typedef returnType (WINAPI *type##localFunctionName) params; \
  203281. type##localFunctionName localFunctionName \
  203282. = (type##localFunctionName)object.findProcAddress (#functionName);
  203283. // loads and unloads a DLL automatically
  203284. class JUCE_API DynamicLibraryLoader
  203285. {
  203286. public:
  203287. DynamicLibraryLoader (const String& name);
  203288. ~DynamicLibraryLoader();
  203289. void* findProcAddress (const String& functionName);
  203290. private:
  203291. void* libHandle;
  203292. };
  203293. #endif
  203294. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203295. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203296. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203297. {
  203298. libHandle = LoadLibrary (name);
  203299. }
  203300. DynamicLibraryLoader::~DynamicLibraryLoader()
  203301. {
  203302. FreeLibrary ((HMODULE) libHandle);
  203303. }
  203304. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203305. {
  203306. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  203307. }
  203308. #endif
  203309. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203310. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203311. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203312. // compiled on its own).
  203313. #if JUCE_INCLUDED_FILE
  203314. extern void juce_initialiseThreadEvents();
  203315. void Logger::outputDebugString (const String& text)
  203316. {
  203317. OutputDebugString (text + "\n");
  203318. }
  203319. static int64 hiResTicksPerSecond;
  203320. static double hiResTicksScaleFactor;
  203321. #if JUCE_USE_INTRINSICS
  203322. // CPU info functions using intrinsics...
  203323. #pragma intrinsic (__cpuid)
  203324. #pragma intrinsic (__rdtsc)
  203325. const String SystemStats::getCpuVendor()
  203326. {
  203327. int info [4];
  203328. __cpuid (info, 0);
  203329. char v [12];
  203330. memcpy (v, info + 1, 4);
  203331. memcpy (v + 4, info + 3, 4);
  203332. memcpy (v + 8, info + 2, 4);
  203333. return String (v, 12);
  203334. }
  203335. #else
  203336. // CPU info functions using old fashioned inline asm...
  203337. static void juce_getCpuVendor (char* const v)
  203338. {
  203339. int vendor[4];
  203340. zeromem (vendor, 16);
  203341. #ifdef JUCE_64BIT
  203342. #else
  203343. #ifndef __MINGW32__
  203344. __try
  203345. #endif
  203346. {
  203347. #if JUCE_GCC
  203348. unsigned int dummy = 0;
  203349. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203350. #else
  203351. __asm
  203352. {
  203353. mov eax, 0
  203354. cpuid
  203355. mov [vendor], ebx
  203356. mov [vendor + 4], edx
  203357. mov [vendor + 8], ecx
  203358. }
  203359. #endif
  203360. }
  203361. #ifndef __MINGW32__
  203362. __except (EXCEPTION_EXECUTE_HANDLER)
  203363. {
  203364. *v = 0;
  203365. }
  203366. #endif
  203367. #endif
  203368. memcpy (v, vendor, 16);
  203369. }
  203370. const String SystemStats::getCpuVendor()
  203371. {
  203372. char v [16];
  203373. juce_getCpuVendor (v);
  203374. return String (v, 16);
  203375. }
  203376. #endif
  203377. void SystemStats::initialiseStats()
  203378. {
  203379. juce_initialiseThreadEvents();
  203380. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203381. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203382. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203383. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203384. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203385. #else
  203386. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203387. #endif
  203388. {
  203389. SYSTEM_INFO systemInfo;
  203390. GetSystemInfo (&systemInfo);
  203391. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203392. }
  203393. LARGE_INTEGER f;
  203394. QueryPerformanceFrequency (&f);
  203395. hiResTicksPerSecond = f.QuadPart;
  203396. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203397. String s (SystemStats::getJUCEVersion());
  203398. const MMRESULT res = timeBeginPeriod (1);
  203399. (void) res;
  203400. jassert (res == TIMERR_NOERROR);
  203401. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203402. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203403. #endif
  203404. }
  203405. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203406. {
  203407. OSVERSIONINFO info;
  203408. info.dwOSVersionInfoSize = sizeof (info);
  203409. GetVersionEx (&info);
  203410. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203411. {
  203412. switch (info.dwMajorVersion)
  203413. {
  203414. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203415. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203416. default: jassertfalse; break; // !! not a supported OS!
  203417. }
  203418. }
  203419. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203420. {
  203421. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203422. return Win98;
  203423. }
  203424. return UnknownOS;
  203425. }
  203426. const String SystemStats::getOperatingSystemName()
  203427. {
  203428. const char* name = "Unknown OS";
  203429. switch (getOperatingSystemType())
  203430. {
  203431. case Windows7: name = "Windows 7"; break;
  203432. case WinVista: name = "Windows Vista"; break;
  203433. case WinXP: name = "Windows XP"; break;
  203434. case Win2000: name = "Windows 2000"; break;
  203435. case Win98: name = "Windows 98"; break;
  203436. default: jassertfalse; break; // !! new type of OS?
  203437. }
  203438. return name;
  203439. }
  203440. bool SystemStats::isOperatingSystem64Bit()
  203441. {
  203442. #ifdef _WIN64
  203443. return true;
  203444. #else
  203445. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203446. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203447. BOOL isWow64 = FALSE;
  203448. return (fnIsWow64Process != 0)
  203449. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203450. && (isWow64 != FALSE);
  203451. #endif
  203452. }
  203453. int SystemStats::getMemorySizeInMegabytes()
  203454. {
  203455. MEMORYSTATUSEX mem;
  203456. mem.dwLength = sizeof (mem);
  203457. GlobalMemoryStatusEx (&mem);
  203458. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203459. }
  203460. uint32 juce_millisecondsSinceStartup() throw()
  203461. {
  203462. return (uint32) GetTickCount();
  203463. }
  203464. int64 Time::getHighResolutionTicks() throw()
  203465. {
  203466. LARGE_INTEGER ticks;
  203467. QueryPerformanceCounter (&ticks);
  203468. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203469. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203470. // fix for a very obscure PCI hardware bug that can make the counter
  203471. // sometimes jump forwards by a few seconds..
  203472. static int64 hiResTicksOffset = 0;
  203473. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203474. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203475. hiResTicksOffset = newOffset;
  203476. return ticks.QuadPart + hiResTicksOffset;
  203477. }
  203478. double Time::getMillisecondCounterHiRes() throw()
  203479. {
  203480. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203481. }
  203482. int64 Time::getHighResolutionTicksPerSecond() throw()
  203483. {
  203484. return hiResTicksPerSecond;
  203485. }
  203486. static int64 juce_getClockCycleCounter() throw()
  203487. {
  203488. #if JUCE_USE_INTRINSICS
  203489. // MS intrinsics version...
  203490. return __rdtsc();
  203491. #elif JUCE_GCC
  203492. // GNU inline asm version...
  203493. unsigned int hi = 0, lo = 0;
  203494. __asm__ __volatile__ (
  203495. "xor %%eax, %%eax \n\
  203496. xor %%edx, %%edx \n\
  203497. rdtsc \n\
  203498. movl %%eax, %[lo] \n\
  203499. movl %%edx, %[hi]"
  203500. :
  203501. : [hi] "m" (hi),
  203502. [lo] "m" (lo)
  203503. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203504. return (int64) ((((uint64) hi) << 32) | lo);
  203505. #else
  203506. // MSVC inline asm version...
  203507. unsigned int hi = 0, lo = 0;
  203508. __asm
  203509. {
  203510. xor eax, eax
  203511. xor edx, edx
  203512. rdtsc
  203513. mov lo, eax
  203514. mov hi, edx
  203515. }
  203516. return (int64) ((((uint64) hi) << 32) | lo);
  203517. #endif
  203518. }
  203519. int SystemStats::getCpuSpeedInMegaherz()
  203520. {
  203521. const int64 cycles = juce_getClockCycleCounter();
  203522. const uint32 millis = Time::getMillisecondCounter();
  203523. int lastResult = 0;
  203524. for (;;)
  203525. {
  203526. int n = 1000000;
  203527. while (--n > 0) {}
  203528. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203529. const int64 cyclesNow = juce_getClockCycleCounter();
  203530. if (millisElapsed > 80)
  203531. {
  203532. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203533. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203534. return newResult;
  203535. lastResult = newResult;
  203536. }
  203537. }
  203538. }
  203539. bool Time::setSystemTimeToThisTime() const
  203540. {
  203541. SYSTEMTIME st;
  203542. st.wDayOfWeek = 0;
  203543. st.wYear = (WORD) getYear();
  203544. st.wMonth = (WORD) (getMonth() + 1);
  203545. st.wDay = (WORD) getDayOfMonth();
  203546. st.wHour = (WORD) getHours();
  203547. st.wMinute = (WORD) getMinutes();
  203548. st.wSecond = (WORD) getSeconds();
  203549. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203550. // do this twice because of daylight saving conversion problems - the
  203551. // first one sets it up, the second one kicks it in.
  203552. return SetLocalTime (&st) != 0
  203553. && SetLocalTime (&st) != 0;
  203554. }
  203555. int SystemStats::getPageSize()
  203556. {
  203557. SYSTEM_INFO systemInfo;
  203558. GetSystemInfo (&systemInfo);
  203559. return systemInfo.dwPageSize;
  203560. }
  203561. const String SystemStats::getLogonName()
  203562. {
  203563. TCHAR text [256];
  203564. DWORD len = numElementsInArray (text) - 2;
  203565. zerostruct (text);
  203566. GetUserName (text, &len);
  203567. return String (text, len);
  203568. }
  203569. const String SystemStats::getFullUserName()
  203570. {
  203571. return getLogonName();
  203572. }
  203573. #endif
  203574. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203575. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203576. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203577. // compiled on its own).
  203578. #if JUCE_INCLUDED_FILE
  203579. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203580. extern HWND juce_messageWindowHandle;
  203581. #endif
  203582. #if ! JUCE_USE_INTRINSICS
  203583. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203584. // older ones we have to actually call the ops as win32 functions..
  203585. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203586. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203587. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203588. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203589. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203590. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203591. {
  203592. jassertfalse; // This operation isn't available in old MS compiler versions!
  203593. __int64 oldValue = *value;
  203594. if (oldValue == valueToCompare)
  203595. *value = newValue;
  203596. return oldValue;
  203597. }
  203598. #endif
  203599. CriticalSection::CriticalSection() throw()
  203600. {
  203601. // (just to check the MS haven't changed this structure and broken things...)
  203602. #if _MSC_VER >= 1400
  203603. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203604. #else
  203605. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203606. #endif
  203607. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203608. }
  203609. CriticalSection::~CriticalSection() throw()
  203610. {
  203611. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203612. }
  203613. void CriticalSection::enter() const throw()
  203614. {
  203615. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203616. }
  203617. bool CriticalSection::tryEnter() const throw()
  203618. {
  203619. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203620. }
  203621. void CriticalSection::exit() const throw()
  203622. {
  203623. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203624. }
  203625. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203626. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203627. {
  203628. }
  203629. WaitableEvent::~WaitableEvent() throw()
  203630. {
  203631. CloseHandle (internal);
  203632. }
  203633. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203634. {
  203635. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203636. }
  203637. void WaitableEvent::signal() const throw()
  203638. {
  203639. SetEvent (internal);
  203640. }
  203641. void WaitableEvent::reset() const throw()
  203642. {
  203643. ResetEvent (internal);
  203644. }
  203645. void JUCE_API juce_threadEntryPoint (void*);
  203646. static unsigned int __stdcall threadEntryProc (void* userData)
  203647. {
  203648. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203649. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203650. GetCurrentThreadId(), TRUE);
  203651. #endif
  203652. juce_threadEntryPoint (userData);
  203653. _endthreadex (0);
  203654. return 0;
  203655. }
  203656. void juce_CloseThreadHandle (void* handle)
  203657. {
  203658. CloseHandle ((HANDLE) handle);
  203659. }
  203660. void* juce_createThread (void* userData)
  203661. {
  203662. unsigned int threadId;
  203663. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203664. }
  203665. void juce_killThread (void* handle)
  203666. {
  203667. if (handle != 0)
  203668. {
  203669. #if JUCE_DEBUG
  203670. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203671. #endif
  203672. TerminateThread (handle, 0);
  203673. }
  203674. }
  203675. void juce_setCurrentThreadName (const String& name)
  203676. {
  203677. #if JUCE_DEBUG && JUCE_MSVC
  203678. struct
  203679. {
  203680. DWORD dwType;
  203681. LPCSTR szName;
  203682. DWORD dwThreadID;
  203683. DWORD dwFlags;
  203684. } info;
  203685. info.dwType = 0x1000;
  203686. info.szName = name.toCString();
  203687. info.dwThreadID = GetCurrentThreadId();
  203688. info.dwFlags = 0;
  203689. __try
  203690. {
  203691. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203692. }
  203693. __except (EXCEPTION_CONTINUE_EXECUTION)
  203694. {}
  203695. #else
  203696. (void) name;
  203697. #endif
  203698. }
  203699. Thread::ThreadID Thread::getCurrentThreadId()
  203700. {
  203701. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203702. }
  203703. // priority 1 to 10 where 5=normal, 1=low
  203704. bool juce_setThreadPriority (void* threadHandle, int priority)
  203705. {
  203706. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203707. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203708. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203709. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203710. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203711. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203712. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203713. if (threadHandle == 0)
  203714. threadHandle = GetCurrentThread();
  203715. return SetThreadPriority (threadHandle, pri) != FALSE;
  203716. }
  203717. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203718. {
  203719. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203720. }
  203721. static HANDLE sleepEvent = 0;
  203722. void juce_initialiseThreadEvents()
  203723. {
  203724. if (sleepEvent == 0)
  203725. #if JUCE_DEBUG
  203726. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203727. #else
  203728. sleepEvent = CreateEvent (0, 0, 0, 0);
  203729. #endif
  203730. }
  203731. void Thread::yield()
  203732. {
  203733. Sleep (0);
  203734. }
  203735. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203736. {
  203737. if (millisecs >= 10)
  203738. {
  203739. Sleep (millisecs);
  203740. }
  203741. else
  203742. {
  203743. jassert (sleepEvent != 0);
  203744. // unlike Sleep() this is guaranteed to return to the current thread after
  203745. // the time expires, so we'll use this for short waits, which are more likely
  203746. // to need to be accurate
  203747. WaitForSingleObject (sleepEvent, millisecs);
  203748. }
  203749. }
  203750. static int lastProcessPriority = -1;
  203751. // called by WindowDriver because Windows does wierd things to process priority
  203752. // when you swap apps, and this forces an update when the app is brought to the front.
  203753. void juce_repeatLastProcessPriority()
  203754. {
  203755. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203756. {
  203757. DWORD p;
  203758. switch (lastProcessPriority)
  203759. {
  203760. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203761. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203762. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203763. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203764. default: jassertfalse; return; // bad priority value
  203765. }
  203766. SetPriorityClass (GetCurrentProcess(), p);
  203767. }
  203768. }
  203769. void Process::setPriority (ProcessPriority prior)
  203770. {
  203771. if (lastProcessPriority != (int) prior)
  203772. {
  203773. lastProcessPriority = (int) prior;
  203774. juce_repeatLastProcessPriority();
  203775. }
  203776. }
  203777. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  203778. {
  203779. return IsDebuggerPresent() != FALSE;
  203780. }
  203781. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203782. {
  203783. return juce_isRunningUnderDebugger();
  203784. }
  203785. void Process::raisePrivilege()
  203786. {
  203787. jassertfalse; // xxx not implemented
  203788. }
  203789. void Process::lowerPrivilege()
  203790. {
  203791. jassertfalse; // xxx not implemented
  203792. }
  203793. void Process::terminate()
  203794. {
  203795. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203796. _CrtDumpMemoryLeaks();
  203797. #endif
  203798. // bullet in the head in case there's a problem shutting down..
  203799. ExitProcess (0);
  203800. }
  203801. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203802. {
  203803. void* result = 0;
  203804. JUCE_TRY
  203805. {
  203806. result = LoadLibrary (name);
  203807. }
  203808. JUCE_CATCH_ALL
  203809. return result;
  203810. }
  203811. void PlatformUtilities::freeDynamicLibrary (void* h)
  203812. {
  203813. JUCE_TRY
  203814. {
  203815. if (h != 0)
  203816. FreeLibrary ((HMODULE) h);
  203817. }
  203818. JUCE_CATCH_ALL
  203819. }
  203820. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203821. {
  203822. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  203823. }
  203824. class InterProcessLock::Pimpl
  203825. {
  203826. public:
  203827. Pimpl (const String& name, const int timeOutMillisecs)
  203828. : handle (0), refCount (1)
  203829. {
  203830. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203831. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203832. {
  203833. if (timeOutMillisecs == 0)
  203834. {
  203835. close();
  203836. return;
  203837. }
  203838. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203839. {
  203840. case WAIT_OBJECT_0:
  203841. case WAIT_ABANDONED:
  203842. break;
  203843. case WAIT_TIMEOUT:
  203844. default:
  203845. close();
  203846. break;
  203847. }
  203848. }
  203849. }
  203850. ~Pimpl()
  203851. {
  203852. close();
  203853. }
  203854. void close()
  203855. {
  203856. if (handle != 0)
  203857. {
  203858. ReleaseMutex (handle);
  203859. CloseHandle (handle);
  203860. handle = 0;
  203861. }
  203862. }
  203863. HANDLE handle;
  203864. int refCount;
  203865. };
  203866. InterProcessLock::InterProcessLock (const String& name_)
  203867. : name (name_)
  203868. {
  203869. }
  203870. InterProcessLock::~InterProcessLock()
  203871. {
  203872. }
  203873. bool InterProcessLock::enter (const int timeOutMillisecs)
  203874. {
  203875. const ScopedLock sl (lock);
  203876. if (pimpl == 0)
  203877. {
  203878. pimpl = new Pimpl (name, timeOutMillisecs);
  203879. if (pimpl->handle == 0)
  203880. pimpl = 0;
  203881. }
  203882. else
  203883. {
  203884. pimpl->refCount++;
  203885. }
  203886. return pimpl != 0;
  203887. }
  203888. void InterProcessLock::exit()
  203889. {
  203890. const ScopedLock sl (lock);
  203891. // Trying to release the lock too many times!
  203892. jassert (pimpl != 0);
  203893. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203894. pimpl = 0;
  203895. }
  203896. #endif
  203897. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203898. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203899. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203900. // compiled on its own).
  203901. #if JUCE_INCLUDED_FILE
  203902. #ifndef CSIDL_MYMUSIC
  203903. #define CSIDL_MYMUSIC 0x000d
  203904. #endif
  203905. #ifndef CSIDL_MYVIDEO
  203906. #define CSIDL_MYVIDEO 0x000e
  203907. #endif
  203908. #ifndef INVALID_FILE_ATTRIBUTES
  203909. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203910. #endif
  203911. const juce_wchar File::separator = '\\';
  203912. const String File::separatorString ("\\");
  203913. bool File::exists() const
  203914. {
  203915. return fullPath.isNotEmpty()
  203916. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  203917. }
  203918. bool File::existsAsFile() const
  203919. {
  203920. return fullPath.isNotEmpty()
  203921. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203922. }
  203923. bool File::isDirectory() const
  203924. {
  203925. const DWORD attr = GetFileAttributes (fullPath);
  203926. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203927. }
  203928. bool File::hasWriteAccess() const
  203929. {
  203930. if (exists())
  203931. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  203932. // on windows, it seems that even read-only directories can still be written into,
  203933. // so checking the parent directory's permissions would return the wrong result..
  203934. return true;
  203935. }
  203936. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203937. {
  203938. DWORD attr = GetFileAttributes (fullPath);
  203939. if (attr == INVALID_FILE_ATTRIBUTES)
  203940. return false;
  203941. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203942. return true;
  203943. if (shouldBeReadOnly)
  203944. attr |= FILE_ATTRIBUTE_READONLY;
  203945. else
  203946. attr &= ~FILE_ATTRIBUTE_READONLY;
  203947. return SetFileAttributes (fullPath, attr) != FALSE;
  203948. }
  203949. bool File::isHidden() const
  203950. {
  203951. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203952. }
  203953. bool File::deleteFile() const
  203954. {
  203955. if (! exists())
  203956. return true;
  203957. else if (isDirectory())
  203958. return RemoveDirectory (fullPath) != 0;
  203959. else
  203960. return DeleteFile (fullPath) != 0;
  203961. }
  203962. bool File::moveToTrash() const
  203963. {
  203964. if (! exists())
  203965. return true;
  203966. SHFILEOPSTRUCT fos;
  203967. zerostruct (fos);
  203968. // The string we pass in must be double null terminated..
  203969. String doubleNullTermPath (getFullPathName() + " ");
  203970. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  203971. p [getFullPathName().length()] = 0;
  203972. fos.wFunc = FO_DELETE;
  203973. fos.pFrom = p;
  203974. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203975. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203976. return SHFileOperation (&fos) == 0;
  203977. }
  203978. bool File::copyInternal (const File& dest) const
  203979. {
  203980. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  203981. }
  203982. bool File::moveInternal (const File& dest) const
  203983. {
  203984. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  203985. }
  203986. void File::createDirectoryInternal (const String& fileName) const
  203987. {
  203988. CreateDirectory (fileName, 0);
  203989. }
  203990. int64 juce_fileSetPosition (void* handle, int64 pos)
  203991. {
  203992. LARGE_INTEGER li;
  203993. li.QuadPart = pos;
  203994. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203995. return li.QuadPart;
  203996. }
  203997. void FileInputStream::openHandle()
  203998. {
  203999. totalSize = file.getSize();
  204000. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204001. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204002. if (h != INVALID_HANDLE_VALUE)
  204003. fileHandle = (void*) h;
  204004. }
  204005. void FileInputStream::closeHandle()
  204006. {
  204007. CloseHandle ((HANDLE) fileHandle);
  204008. }
  204009. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204010. {
  204011. if (fileHandle != 0)
  204012. {
  204013. DWORD actualNum = 0;
  204014. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204015. return (size_t) actualNum;
  204016. }
  204017. return 0;
  204018. }
  204019. void FileOutputStream::openHandle()
  204020. {
  204021. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204022. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204023. if (h != INVALID_HANDLE_VALUE)
  204024. {
  204025. LARGE_INTEGER li;
  204026. li.QuadPart = 0;
  204027. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204028. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204029. {
  204030. fileHandle = (void*) h;
  204031. currentPosition = li.QuadPart;
  204032. }
  204033. }
  204034. }
  204035. void FileOutputStream::closeHandle()
  204036. {
  204037. CloseHandle ((HANDLE) fileHandle);
  204038. }
  204039. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204040. {
  204041. if (fileHandle != 0)
  204042. {
  204043. DWORD actualNum = 0;
  204044. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204045. return (int) actualNum;
  204046. }
  204047. return 0;
  204048. }
  204049. void FileOutputStream::flushInternal()
  204050. {
  204051. if (fileHandle != 0)
  204052. FlushFileBuffers ((HANDLE) fileHandle);
  204053. }
  204054. int64 File::getSize() const
  204055. {
  204056. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204057. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204058. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204059. return 0;
  204060. }
  204061. static int64 fileTimeToTime (const FILETIME* const ft)
  204062. {
  204063. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204064. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204065. }
  204066. static void timeToFileTime (const int64 time, FILETIME* const ft)
  204067. {
  204068. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204069. }
  204070. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204071. {
  204072. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204073. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204074. {
  204075. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204076. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204077. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204078. }
  204079. else
  204080. {
  204081. creationTime = accessTime = modificationTime = 0;
  204082. }
  204083. }
  204084. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204085. {
  204086. bool ok = false;
  204087. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204088. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204089. if (h != INVALID_HANDLE_VALUE)
  204090. {
  204091. FILETIME m, a, c;
  204092. timeToFileTime (modificationTime, &m);
  204093. timeToFileTime (accessTime, &a);
  204094. timeToFileTime (creationTime, &c);
  204095. ok = SetFileTime (h,
  204096. creationTime > 0 ? &c : 0,
  204097. accessTime > 0 ? &a : 0,
  204098. modificationTime > 0 ? &m : 0) != 0;
  204099. CloseHandle (h);
  204100. }
  204101. return ok;
  204102. }
  204103. void File::findFileSystemRoots (Array<File>& destArray)
  204104. {
  204105. TCHAR buffer [2048];
  204106. buffer[0] = 0;
  204107. buffer[1] = 0;
  204108. GetLogicalDriveStrings (2048, buffer);
  204109. const TCHAR* n = buffer;
  204110. StringArray roots;
  204111. while (*n != 0)
  204112. {
  204113. roots.add (String (n));
  204114. while (*n++ != 0)
  204115. {}
  204116. }
  204117. roots.sort (true);
  204118. for (int i = 0; i < roots.size(); ++i)
  204119. destArray.add (roots [i]);
  204120. }
  204121. static const String getDriveFromPath (const String& path)
  204122. {
  204123. if (path.isNotEmpty() && path[1] == ':')
  204124. return path.substring (0, 2) + '\\';
  204125. return path;
  204126. }
  204127. const String File::getVolumeLabel() const
  204128. {
  204129. TCHAR dest[64];
  204130. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204131. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204132. dest[0] = 0;
  204133. return dest;
  204134. }
  204135. int File::getVolumeSerialNumber() const
  204136. {
  204137. TCHAR dest[64];
  204138. DWORD serialNum;
  204139. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204140. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204141. return 0;
  204142. return (int) serialNum;
  204143. }
  204144. static int64 getDiskSpaceInfo (const String& path, const bool total)
  204145. {
  204146. ULARGE_INTEGER spc, tot, totFree;
  204147. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204148. return total ? (int64) tot.QuadPart
  204149. : (int64) spc.QuadPart;
  204150. return 0;
  204151. }
  204152. int64 File::getBytesFreeOnVolume() const
  204153. {
  204154. return getDiskSpaceInfo (getFullPathName(), false);
  204155. }
  204156. int64 File::getVolumeTotalSize() const
  204157. {
  204158. return getDiskSpaceInfo (getFullPathName(), true);
  204159. }
  204160. static unsigned int getWindowsDriveType (const String& path)
  204161. {
  204162. return GetDriveType (getDriveFromPath (path));
  204163. }
  204164. bool File::isOnCDRomDrive() const
  204165. {
  204166. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204167. }
  204168. bool File::isOnHardDisk() const
  204169. {
  204170. if (fullPath.isEmpty())
  204171. return false;
  204172. const unsigned int n = getWindowsDriveType (getFullPathName());
  204173. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204174. return n != DRIVE_REMOVABLE;
  204175. else
  204176. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204177. }
  204178. bool File::isOnRemovableDrive() const
  204179. {
  204180. if (fullPath.isEmpty())
  204181. return false;
  204182. const unsigned int n = getWindowsDriveType (getFullPathName());
  204183. return n == DRIVE_CDROM
  204184. || n == DRIVE_REMOTE
  204185. || n == DRIVE_REMOVABLE
  204186. || n == DRIVE_RAMDISK;
  204187. }
  204188. static const File juce_getSpecialFolderPath (int type)
  204189. {
  204190. WCHAR path [MAX_PATH + 256];
  204191. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204192. return File (String (path));
  204193. return File::nonexistent;
  204194. }
  204195. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204196. {
  204197. int csidlType = 0;
  204198. switch (type)
  204199. {
  204200. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204201. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204202. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204203. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204204. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204205. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204206. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204207. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204208. case tempDirectory:
  204209. {
  204210. WCHAR dest [2048];
  204211. dest[0] = 0;
  204212. GetTempPath (numElementsInArray (dest), dest);
  204213. return File (String (dest));
  204214. }
  204215. case invokedExecutableFile:
  204216. case currentExecutableFile:
  204217. case currentApplicationFile:
  204218. {
  204219. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204220. WCHAR dest [MAX_PATH + 256];
  204221. dest[0] = 0;
  204222. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204223. return File (String (dest));
  204224. }
  204225. case hostApplicationPath:
  204226. {
  204227. WCHAR dest [MAX_PATH + 256];
  204228. dest[0] = 0;
  204229. GetModuleFileName (0, dest, numElementsInArray (dest));
  204230. return File (String (dest));
  204231. }
  204232. default:
  204233. jassertfalse; // unknown type?
  204234. return File::nonexistent;
  204235. }
  204236. return juce_getSpecialFolderPath (csidlType);
  204237. }
  204238. const File File::getCurrentWorkingDirectory()
  204239. {
  204240. WCHAR dest [MAX_PATH + 256];
  204241. dest[0] = 0;
  204242. GetCurrentDirectory (numElementsInArray (dest), dest);
  204243. return File (String (dest));
  204244. }
  204245. bool File::setAsCurrentWorkingDirectory() const
  204246. {
  204247. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204248. }
  204249. const String File::getVersion() const
  204250. {
  204251. String result;
  204252. DWORD handle = 0;
  204253. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204254. HeapBlock<char> buffer;
  204255. buffer.calloc (bufferSize);
  204256. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204257. {
  204258. VS_FIXEDFILEINFO* vffi;
  204259. UINT len = 0;
  204260. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204261. {
  204262. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204263. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204264. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204265. << (int) LOWORD (vffi->dwFileVersionLS);
  204266. }
  204267. }
  204268. return result;
  204269. }
  204270. const File File::getLinkedTarget() const
  204271. {
  204272. File result (*this);
  204273. String p (getFullPathName());
  204274. if (! exists())
  204275. p += ".lnk";
  204276. else if (getFileExtension() != ".lnk")
  204277. return result;
  204278. ComSmartPtr <IShellLink> shellLink;
  204279. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204280. {
  204281. ComSmartPtr <IPersistFile> persistFile;
  204282. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  204283. {
  204284. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204285. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204286. {
  204287. WIN32_FIND_DATA winFindData;
  204288. WCHAR resolvedPath [MAX_PATH];
  204289. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204290. result = File (resolvedPath);
  204291. }
  204292. }
  204293. }
  204294. return result;
  204295. }
  204296. class DirectoryIterator::NativeIterator::Pimpl
  204297. {
  204298. public:
  204299. Pimpl (const File& directory, const String& wildCard)
  204300. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204301. handle (INVALID_HANDLE_VALUE)
  204302. {
  204303. }
  204304. ~Pimpl()
  204305. {
  204306. if (handle != INVALID_HANDLE_VALUE)
  204307. FindClose (handle);
  204308. }
  204309. bool next (String& filenameFound,
  204310. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204311. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204312. {
  204313. WIN32_FIND_DATA findData;
  204314. if (handle == INVALID_HANDLE_VALUE)
  204315. {
  204316. handle = FindFirstFile (directoryWithWildCard, &findData);
  204317. if (handle == INVALID_HANDLE_VALUE)
  204318. return false;
  204319. }
  204320. else
  204321. {
  204322. if (FindNextFile (handle, &findData) == 0)
  204323. return false;
  204324. }
  204325. filenameFound = findData.cFileName;
  204326. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204327. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204328. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204329. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204330. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204331. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204332. return true;
  204333. }
  204334. juce_UseDebuggingNewOperator
  204335. private:
  204336. const String directoryWithWildCard;
  204337. HANDLE handle;
  204338. Pimpl (const Pimpl&);
  204339. Pimpl& operator= (const Pimpl&);
  204340. };
  204341. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204342. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204343. {
  204344. }
  204345. DirectoryIterator::NativeIterator::~NativeIterator()
  204346. {
  204347. }
  204348. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204349. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204350. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204351. {
  204352. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204353. }
  204354. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204355. {
  204356. HINSTANCE hInstance = 0;
  204357. JUCE_TRY
  204358. {
  204359. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204360. }
  204361. JUCE_CATCH_ALL
  204362. return hInstance > (HINSTANCE) 32;
  204363. }
  204364. void File::revealToUser() const
  204365. {
  204366. if (isDirectory())
  204367. startAsProcess();
  204368. else if (getParentDirectory().exists())
  204369. getParentDirectory().startAsProcess();
  204370. }
  204371. class NamedPipeInternal
  204372. {
  204373. public:
  204374. NamedPipeInternal (const String& file, const bool isPipe_)
  204375. : pipeH (0),
  204376. cancelEvent (0),
  204377. connected (false),
  204378. isPipe (isPipe_)
  204379. {
  204380. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204381. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204382. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204383. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204384. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204385. }
  204386. ~NamedPipeInternal()
  204387. {
  204388. disconnectPipe();
  204389. if (pipeH != 0)
  204390. CloseHandle (pipeH);
  204391. CloseHandle (cancelEvent);
  204392. }
  204393. bool connect (const int timeOutMs)
  204394. {
  204395. if (! isPipe)
  204396. return true;
  204397. if (! connected)
  204398. {
  204399. OVERLAPPED over;
  204400. zerostruct (over);
  204401. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204402. if (ConnectNamedPipe (pipeH, &over))
  204403. {
  204404. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204405. }
  204406. else
  204407. {
  204408. const int err = GetLastError();
  204409. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204410. {
  204411. HANDLE handles[] = { over.hEvent, cancelEvent };
  204412. if (WaitForMultipleObjects (2, handles, FALSE,
  204413. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204414. connected = true;
  204415. }
  204416. else if (err == ERROR_PIPE_CONNECTED)
  204417. {
  204418. connected = true;
  204419. }
  204420. }
  204421. CloseHandle (over.hEvent);
  204422. }
  204423. return connected;
  204424. }
  204425. void disconnectPipe()
  204426. {
  204427. if (connected)
  204428. {
  204429. DisconnectNamedPipe (pipeH);
  204430. connected = false;
  204431. }
  204432. }
  204433. HANDLE pipeH;
  204434. HANDLE cancelEvent;
  204435. bool connected, isPipe;
  204436. };
  204437. void NamedPipe::close()
  204438. {
  204439. cancelPendingReads();
  204440. const ScopedLock sl (lock);
  204441. delete static_cast<NamedPipeInternal*> (internal);
  204442. internal = 0;
  204443. }
  204444. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204445. {
  204446. close();
  204447. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204448. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204449. {
  204450. internal = intern.release();
  204451. return true;
  204452. }
  204453. return false;
  204454. }
  204455. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204456. {
  204457. const ScopedLock sl (lock);
  204458. int bytesRead = -1;
  204459. bool waitAgain = true;
  204460. while (waitAgain && internal != 0)
  204461. {
  204462. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204463. waitAgain = false;
  204464. if (! intern->connect (timeOutMilliseconds))
  204465. break;
  204466. if (maxBytesToRead <= 0)
  204467. return 0;
  204468. OVERLAPPED over;
  204469. zerostruct (over);
  204470. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204471. unsigned long numRead;
  204472. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204473. {
  204474. bytesRead = (int) numRead;
  204475. }
  204476. else if (GetLastError() == ERROR_IO_PENDING)
  204477. {
  204478. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204479. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204480. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204481. : INFINITE);
  204482. if (waitResult != WAIT_OBJECT_0)
  204483. {
  204484. // if the operation timed out, let's cancel it...
  204485. CancelIo (intern->pipeH);
  204486. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204487. }
  204488. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204489. {
  204490. bytesRead = (int) numRead;
  204491. }
  204492. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204493. {
  204494. intern->disconnectPipe();
  204495. waitAgain = true;
  204496. }
  204497. }
  204498. else
  204499. {
  204500. waitAgain = internal != 0;
  204501. Sleep (5);
  204502. }
  204503. CloseHandle (over.hEvent);
  204504. }
  204505. return bytesRead;
  204506. }
  204507. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204508. {
  204509. int bytesWritten = -1;
  204510. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204511. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204512. {
  204513. if (numBytesToWrite <= 0)
  204514. return 0;
  204515. OVERLAPPED over;
  204516. zerostruct (over);
  204517. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204518. unsigned long numWritten;
  204519. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204520. {
  204521. bytesWritten = (int) numWritten;
  204522. }
  204523. else if (GetLastError() == ERROR_IO_PENDING)
  204524. {
  204525. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204526. DWORD waitResult;
  204527. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204528. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204529. : INFINITE);
  204530. if (waitResult != WAIT_OBJECT_0)
  204531. {
  204532. CancelIo (intern->pipeH);
  204533. WaitForSingleObject (over.hEvent, INFINITE);
  204534. }
  204535. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204536. {
  204537. bytesWritten = (int) numWritten;
  204538. }
  204539. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204540. {
  204541. intern->disconnectPipe();
  204542. }
  204543. }
  204544. CloseHandle (over.hEvent);
  204545. }
  204546. return bytesWritten;
  204547. }
  204548. void NamedPipe::cancelPendingReads()
  204549. {
  204550. if (internal != 0)
  204551. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204552. }
  204553. #endif
  204554. /*** End of inlined file: juce_win32_Files.cpp ***/
  204555. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204556. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204557. // compiled on its own).
  204558. #if JUCE_INCLUDED_FILE
  204559. #ifndef INTERNET_FLAG_NEED_FILE
  204560. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204561. #endif
  204562. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204563. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204564. #endif
  204565. struct ConnectionAndRequestStruct
  204566. {
  204567. HINTERNET connection, request;
  204568. };
  204569. static HINTERNET sessionHandle = 0;
  204570. #ifndef WORKAROUND_TIMEOUT_BUG
  204571. //#define WORKAROUND_TIMEOUT_BUG 1
  204572. #endif
  204573. #if WORKAROUND_TIMEOUT_BUG
  204574. // Required because of a Microsoft bug in setting a timeout
  204575. class InternetConnectThread : public Thread
  204576. {
  204577. public:
  204578. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204579. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204580. {
  204581. startThread();
  204582. }
  204583. ~InternetConnectThread()
  204584. {
  204585. stopThread (60000);
  204586. }
  204587. void run()
  204588. {
  204589. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204590. uc.nPort, _T(""), _T(""),
  204591. isFtp ? INTERNET_SERVICE_FTP
  204592. : INTERNET_SERVICE_HTTP,
  204593. 0, 0);
  204594. notify();
  204595. }
  204596. juce_UseDebuggingNewOperator
  204597. private:
  204598. URL_COMPONENTS& uc;
  204599. HINTERNET& connection;
  204600. const bool isFtp;
  204601. InternetConnectThread (const InternetConnectThread&);
  204602. InternetConnectThread& operator= (const InternetConnectThread&);
  204603. };
  204604. #endif
  204605. void* juce_openInternetFile (const String& url,
  204606. const String& headers,
  204607. const MemoryBlock& postData,
  204608. const bool isPost,
  204609. URL::OpenStreamProgressCallback* callback,
  204610. void* callbackContext,
  204611. int timeOutMs)
  204612. {
  204613. if (sessionHandle == 0)
  204614. sessionHandle = InternetOpen (_T("juce"),
  204615. INTERNET_OPEN_TYPE_PRECONFIG,
  204616. 0, 0, 0);
  204617. if (sessionHandle != 0)
  204618. {
  204619. // break up the url..
  204620. TCHAR file[1024], server[1024];
  204621. URL_COMPONENTS uc;
  204622. zerostruct (uc);
  204623. uc.dwStructSize = sizeof (uc);
  204624. uc.dwUrlPathLength = sizeof (file);
  204625. uc.dwHostNameLength = sizeof (server);
  204626. uc.lpszUrlPath = file;
  204627. uc.lpszHostName = server;
  204628. if (InternetCrackUrl (url, 0, 0, &uc))
  204629. {
  204630. int disable = 1;
  204631. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204632. if (timeOutMs == 0)
  204633. timeOutMs = 30000;
  204634. else if (timeOutMs < 0)
  204635. timeOutMs = -1;
  204636. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204637. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204638. #if WORKAROUND_TIMEOUT_BUG
  204639. HINTERNET connection = 0;
  204640. {
  204641. InternetConnectThread connectThread (uc, connection, isFtp);
  204642. connectThread.wait (timeOutMs);
  204643. if (connection == 0)
  204644. {
  204645. InternetCloseHandle (sessionHandle);
  204646. sessionHandle = 0;
  204647. }
  204648. }
  204649. #else
  204650. HINTERNET connection = InternetConnect (sessionHandle,
  204651. uc.lpszHostName,
  204652. uc.nPort,
  204653. _T(""), _T(""),
  204654. isFtp ? INTERNET_SERVICE_FTP
  204655. : INTERNET_SERVICE_HTTP,
  204656. 0, 0);
  204657. #endif
  204658. if (connection != 0)
  204659. {
  204660. if (isFtp)
  204661. {
  204662. HINTERNET request = FtpOpenFile (connection,
  204663. uc.lpszUrlPath,
  204664. GENERIC_READ,
  204665. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204666. 0);
  204667. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204668. result->connection = connection;
  204669. result->request = request;
  204670. return result;
  204671. }
  204672. else
  204673. {
  204674. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204675. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204676. if (url.startsWithIgnoreCase ("https:"))
  204677. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204678. // IE7 seems to automatically work out when it's https)
  204679. HINTERNET request = HttpOpenRequest (connection,
  204680. isPost ? _T("POST")
  204681. : _T("GET"),
  204682. uc.lpszUrlPath,
  204683. 0, 0, mimeTypes, flags, 0);
  204684. if (request != 0)
  204685. {
  204686. INTERNET_BUFFERS buffers;
  204687. zerostruct (buffers);
  204688. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204689. buffers.lpcszHeader = (LPCTSTR) headers;
  204690. buffers.dwHeadersLength = headers.length();
  204691. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204692. ConnectionAndRequestStruct* result = 0;
  204693. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204694. {
  204695. int bytesSent = 0;
  204696. for (;;)
  204697. {
  204698. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204699. DWORD bytesDone = 0;
  204700. if (bytesToDo > 0
  204701. && ! InternetWriteFile (request,
  204702. static_cast <const char*> (postData.getData()) + bytesSent,
  204703. bytesToDo, &bytesDone))
  204704. {
  204705. break;
  204706. }
  204707. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204708. {
  204709. result = new ConnectionAndRequestStruct();
  204710. result->connection = connection;
  204711. result->request = request;
  204712. if (! HttpEndRequest (request, 0, 0, 0))
  204713. break;
  204714. return result;
  204715. }
  204716. bytesSent += bytesDone;
  204717. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204718. break;
  204719. }
  204720. }
  204721. InternetCloseHandle (request);
  204722. }
  204723. InternetCloseHandle (connection);
  204724. }
  204725. }
  204726. }
  204727. }
  204728. return 0;
  204729. }
  204730. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204731. {
  204732. DWORD bytesRead = 0;
  204733. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204734. if (crs != 0)
  204735. InternetReadFile (crs->request,
  204736. buffer, bytesToRead,
  204737. &bytesRead);
  204738. return bytesRead;
  204739. }
  204740. int juce_seekInInternetFile (void* handle, int newPosition)
  204741. {
  204742. if (handle != 0)
  204743. {
  204744. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204745. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204746. }
  204747. return -1;
  204748. }
  204749. int64 juce_getInternetFileContentLength (void* handle)
  204750. {
  204751. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204752. if (crs != 0)
  204753. {
  204754. DWORD index = 0, result = 0, size = sizeof (result);
  204755. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204756. return (int64) result;
  204757. }
  204758. return -1;
  204759. }
  204760. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204761. {
  204762. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204763. if (crs != 0)
  204764. {
  204765. DWORD bufferSizeBytes = 4096;
  204766. for (;;)
  204767. {
  204768. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204769. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204770. {
  204771. StringArray headersArray;
  204772. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204773. for (int i = 0; i < headersArray.size(); ++i)
  204774. {
  204775. const String& header = headersArray[i];
  204776. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204777. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204778. const String previousValue (headers [key]);
  204779. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204780. }
  204781. break;
  204782. }
  204783. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204784. break;
  204785. }
  204786. }
  204787. }
  204788. void juce_closeInternetFile (void* handle)
  204789. {
  204790. if (handle != 0)
  204791. {
  204792. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204793. InternetCloseHandle (crs->request);
  204794. InternetCloseHandle (crs->connection);
  204795. }
  204796. }
  204797. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  204798. {
  204799. int numFound = 0;
  204800. DynamicLibraryLoader dll ("iphlpapi.dll");
  204801. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204802. if (getAdaptersInfo != 0)
  204803. {
  204804. ULONG len = sizeof (IP_ADAPTER_INFO);
  204805. MemoryBlock mb;
  204806. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204807. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204808. {
  204809. mb.setSize (len);
  204810. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204811. }
  204812. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204813. {
  204814. PIP_ADAPTER_INFO adapter = adapterInfo;
  204815. while (adapter != 0)
  204816. {
  204817. int64 mac = 0;
  204818. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204819. mac = (mac << 8) | adapter->Address[i];
  204820. if (littleEndian)
  204821. mac = (int64) ByteOrder::swap ((uint64) mac);
  204822. if (numFound < maxNum && mac != 0)
  204823. addresses [numFound++] = mac;
  204824. adapter = adapter->Next;
  204825. }
  204826. }
  204827. }
  204828. return numFound;
  204829. }
  204830. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  204831. {
  204832. int numFound = 0;
  204833. DynamicLibraryLoader dll ("netapi32.dll");
  204834. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204835. if (NetbiosCall != 0)
  204836. {
  204837. NCB ncb;
  204838. zerostruct (ncb);
  204839. struct ASTAT
  204840. {
  204841. ADAPTER_STATUS adapt;
  204842. NAME_BUFFER NameBuff [30];
  204843. };
  204844. ASTAT astat;
  204845. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204846. LANA_ENUM enums;
  204847. zerostruct (enums);
  204848. ncb.ncb_command = NCBENUM;
  204849. ncb.ncb_buffer = (unsigned char*) &enums;
  204850. ncb.ncb_length = sizeof (LANA_ENUM);
  204851. NetbiosCall (&ncb);
  204852. for (int i = 0; i < enums.length; ++i)
  204853. {
  204854. zerostruct (ncb);
  204855. ncb.ncb_command = NCBRESET;
  204856. ncb.ncb_lana_num = enums.lana[i];
  204857. if (NetbiosCall (&ncb) == 0)
  204858. {
  204859. zerostruct (ncb);
  204860. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204861. ncb.ncb_command = NCBASTAT;
  204862. ncb.ncb_lana_num = enums.lana[i];
  204863. ncb.ncb_buffer = (unsigned char*) &astat;
  204864. ncb.ncb_length = sizeof (ASTAT);
  204865. if (NetbiosCall (&ncb) == 0)
  204866. {
  204867. if (astat.adapt.adapter_type == 0xfe)
  204868. {
  204869. uint64 mac = 0;
  204870. for (int i = 6; --i >= 0;)
  204871. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  204872. if (numFound < maxNum && mac != 0)
  204873. addresses [numFound++] = mac;
  204874. }
  204875. }
  204876. }
  204877. }
  204878. }
  204879. return numFound;
  204880. }
  204881. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  204882. {
  204883. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  204884. if (numFound == 0)
  204885. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  204886. return numFound;
  204887. }
  204888. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204889. const String& emailSubject,
  204890. const String& bodyText,
  204891. const StringArray& filesToAttach)
  204892. {
  204893. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204894. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204895. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204896. bool ok = false;
  204897. if (mapiSendMail != 0)
  204898. {
  204899. MapiMessage message;
  204900. zerostruct (message);
  204901. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204902. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204903. MapiRecipDesc recip;
  204904. zerostruct (recip);
  204905. recip.ulRecipClass = MAPI_TO;
  204906. String targetEmailAddress_ (targetEmailAddress);
  204907. if (targetEmailAddress_.isEmpty())
  204908. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204909. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204910. message.nRecipCount = 1;
  204911. message.lpRecips = &recip;
  204912. HeapBlock <MapiFileDesc> files;
  204913. files.calloc (filesToAttach.size());
  204914. message.nFileCount = filesToAttach.size();
  204915. message.lpFiles = files;
  204916. for (int i = 0; i < filesToAttach.size(); ++i)
  204917. {
  204918. files[i].nPosition = (ULONG) -1;
  204919. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204920. }
  204921. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204922. }
  204923. FreeLibrary (h);
  204924. return ok;
  204925. }
  204926. #endif
  204927. /*** End of inlined file: juce_win32_Network.cpp ***/
  204928. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204929. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204930. // compiled on its own).
  204931. #if JUCE_INCLUDED_FILE
  204932. static HKEY findKeyForPath (String name,
  204933. const bool createForWriting,
  204934. String& valueName)
  204935. {
  204936. HKEY rootKey = 0;
  204937. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204938. rootKey = HKEY_CURRENT_USER;
  204939. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204940. rootKey = HKEY_LOCAL_MACHINE;
  204941. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204942. rootKey = HKEY_CLASSES_ROOT;
  204943. if (rootKey != 0)
  204944. {
  204945. name = name.substring (name.indexOfChar ('\\') + 1);
  204946. const int lastSlash = name.lastIndexOfChar ('\\');
  204947. valueName = name.substring (lastSlash + 1);
  204948. name = name.substring (0, lastSlash);
  204949. HKEY key;
  204950. DWORD result;
  204951. if (createForWriting)
  204952. {
  204953. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204954. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204955. return key;
  204956. }
  204957. else
  204958. {
  204959. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204960. return key;
  204961. }
  204962. }
  204963. return 0;
  204964. }
  204965. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204966. const String& defaultValue)
  204967. {
  204968. String valueName, result (defaultValue);
  204969. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204970. if (k != 0)
  204971. {
  204972. WCHAR buffer [2048];
  204973. unsigned long bufferSize = sizeof (buffer);
  204974. DWORD type = REG_SZ;
  204975. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204976. {
  204977. if (type == REG_SZ)
  204978. result = buffer;
  204979. else if (type == REG_DWORD)
  204980. result = String ((int) *(DWORD*) buffer);
  204981. }
  204982. RegCloseKey (k);
  204983. }
  204984. return result;
  204985. }
  204986. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204987. const String& value)
  204988. {
  204989. String valueName;
  204990. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204991. if (k != 0)
  204992. {
  204993. RegSetValueEx (k, valueName, 0, REG_SZ,
  204994. (const BYTE*) (const WCHAR*) value,
  204995. sizeof (WCHAR) * (value.length() + 1));
  204996. RegCloseKey (k);
  204997. }
  204998. }
  204999. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205000. {
  205001. bool exists = false;
  205002. String valueName;
  205003. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205004. if (k != 0)
  205005. {
  205006. unsigned char buffer [2048];
  205007. unsigned long bufferSize = sizeof (buffer);
  205008. DWORD type = 0;
  205009. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205010. exists = true;
  205011. RegCloseKey (k);
  205012. }
  205013. return exists;
  205014. }
  205015. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205016. {
  205017. String valueName;
  205018. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205019. if (k != 0)
  205020. {
  205021. RegDeleteValue (k, valueName);
  205022. RegCloseKey (k);
  205023. }
  205024. }
  205025. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205026. {
  205027. String valueName;
  205028. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205029. if (k != 0)
  205030. {
  205031. RegDeleteKey (k, valueName);
  205032. RegCloseKey (k);
  205033. }
  205034. }
  205035. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205036. const String& symbolicDescription,
  205037. const String& fullDescription,
  205038. const File& targetExecutable,
  205039. int iconResourceNumber)
  205040. {
  205041. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205042. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205043. if (iconResourceNumber != 0)
  205044. setRegistryValue (key + "\\DefaultIcon\\",
  205045. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205046. setRegistryValue (key + "\\", fullDescription);
  205047. setRegistryValue (key + "\\shell\\open\\command\\",
  205048. targetExecutable.getFullPathName() + " %1");
  205049. }
  205050. bool juce_IsRunningInWine()
  205051. {
  205052. HKEY key;
  205053. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205054. {
  205055. RegCloseKey (key);
  205056. return true;
  205057. }
  205058. return false;
  205059. }
  205060. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205061. {
  205062. String s (::GetCommandLineW());
  205063. StringArray tokens;
  205064. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205065. return tokens.joinIntoString (" ", 1);
  205066. }
  205067. static void* currentModuleHandle = 0;
  205068. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205069. {
  205070. if (currentModuleHandle == 0)
  205071. currentModuleHandle = GetModuleHandle (0);
  205072. return currentModuleHandle;
  205073. }
  205074. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205075. {
  205076. currentModuleHandle = newHandle;
  205077. }
  205078. void PlatformUtilities::fpuReset()
  205079. {
  205080. #if JUCE_MSVC
  205081. _clearfp();
  205082. #endif
  205083. }
  205084. void PlatformUtilities::beep()
  205085. {
  205086. MessageBeep (MB_OK);
  205087. }
  205088. #endif
  205089. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205090. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205091. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205092. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205093. // compiled on its own).
  205094. #if JUCE_INCLUDED_FILE
  205095. static const unsigned int specialId = WM_APP + 0x4400;
  205096. static const unsigned int broadcastId = WM_APP + 0x4403;
  205097. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205098. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205099. HWND juce_messageWindowHandle = 0;
  205100. extern long improbableWindowNumber; // defined in windowing.cpp
  205101. #ifndef WM_APPCOMMAND
  205102. #define WM_APPCOMMAND 0x0319
  205103. #endif
  205104. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205105. const UINT message,
  205106. const WPARAM wParam,
  205107. const LPARAM lParam) throw()
  205108. {
  205109. JUCE_TRY
  205110. {
  205111. if (h == juce_messageWindowHandle)
  205112. {
  205113. if (message == specialCallbackId)
  205114. {
  205115. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205116. return (LRESULT) (*func) ((void*) lParam);
  205117. }
  205118. else if (message == specialId)
  205119. {
  205120. // these are trapped early in the dispatch call, but must also be checked
  205121. // here in case there are windows modal dialog boxes doing their own
  205122. // dispatch loop and not calling our version
  205123. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205124. return 0;
  205125. }
  205126. else if (message == broadcastId)
  205127. {
  205128. const ScopedPointer <String> messageString ((String*) lParam);
  205129. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205130. return 0;
  205131. }
  205132. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205133. {
  205134. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205135. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205136. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205137. return 0;
  205138. }
  205139. }
  205140. }
  205141. JUCE_CATCH_EXCEPTION
  205142. return DefWindowProc (h, message, wParam, lParam);
  205143. }
  205144. static bool isEventBlockedByModalComps (MSG& m)
  205145. {
  205146. if (Component::getNumCurrentlyModalComponents() == 0
  205147. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205148. return false;
  205149. switch (m.message)
  205150. {
  205151. case WM_MOUSEMOVE:
  205152. case WM_NCMOUSEMOVE:
  205153. case 0x020A: /* WM_MOUSEWHEEL */
  205154. case 0x020E: /* WM_MOUSEHWHEEL */
  205155. case WM_KEYUP:
  205156. case WM_SYSKEYUP:
  205157. case WM_CHAR:
  205158. case WM_APPCOMMAND:
  205159. case WM_LBUTTONUP:
  205160. case WM_MBUTTONUP:
  205161. case WM_RBUTTONUP:
  205162. case WM_MOUSEACTIVATE:
  205163. case WM_NCMOUSEHOVER:
  205164. case WM_MOUSEHOVER:
  205165. return true;
  205166. case WM_NCLBUTTONDOWN:
  205167. case WM_NCLBUTTONDBLCLK:
  205168. case WM_NCRBUTTONDOWN:
  205169. case WM_NCRBUTTONDBLCLK:
  205170. case WM_NCMBUTTONDOWN:
  205171. case WM_NCMBUTTONDBLCLK:
  205172. case WM_LBUTTONDOWN:
  205173. case WM_LBUTTONDBLCLK:
  205174. case WM_MBUTTONDOWN:
  205175. case WM_MBUTTONDBLCLK:
  205176. case WM_RBUTTONDOWN:
  205177. case WM_RBUTTONDBLCLK:
  205178. case WM_KEYDOWN:
  205179. case WM_SYSKEYDOWN:
  205180. {
  205181. Component* const modal = Component::getCurrentlyModalComponent (0);
  205182. if (modal != 0)
  205183. modal->inputAttemptWhenModal();
  205184. return true;
  205185. }
  205186. default:
  205187. break;
  205188. }
  205189. return false;
  205190. }
  205191. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205192. {
  205193. MSG m;
  205194. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205195. return false;
  205196. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205197. {
  205198. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205199. {
  205200. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205201. }
  205202. else if (m.message == WM_QUIT)
  205203. {
  205204. if (JUCEApplication::getInstance() != 0)
  205205. JUCEApplication::getInstance()->systemRequestedQuit();
  205206. }
  205207. else if (! isEventBlockedByModalComps (m))
  205208. {
  205209. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205210. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205211. {
  205212. // if it's someone else's window being clicked on, and the focus is
  205213. // currently on a juce window, pass the kb focus over..
  205214. HWND currentFocus = GetFocus();
  205215. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205216. SetFocus (m.hwnd);
  205217. }
  205218. TranslateMessage (&m);
  205219. DispatchMessage (&m);
  205220. }
  205221. }
  205222. return true;
  205223. }
  205224. bool juce_postMessageToSystemQueue (Message* message)
  205225. {
  205226. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205227. }
  205228. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205229. void* userData)
  205230. {
  205231. if (MessageManager::getInstance()->isThisTheMessageThread())
  205232. {
  205233. return (*callback) (userData);
  205234. }
  205235. else
  205236. {
  205237. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205238. // deadlock because the message manager is blocked from running, and can't
  205239. // call your function..
  205240. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205241. return (void*) SendMessage (juce_messageWindowHandle,
  205242. specialCallbackId,
  205243. (WPARAM) callback,
  205244. (LPARAM) userData);
  205245. }
  205246. }
  205247. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205248. {
  205249. if (hwnd != juce_messageWindowHandle)
  205250. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205251. return TRUE;
  205252. }
  205253. void MessageManager::broadcastMessage (const String& value) throw()
  205254. {
  205255. Array<void*> windows;
  205256. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205257. const String localCopy (value);
  205258. COPYDATASTRUCT data;
  205259. data.dwData = broadcastId;
  205260. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205261. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205262. for (int i = windows.size(); --i >= 0;)
  205263. {
  205264. HWND hwnd = (HWND) windows.getUnchecked(i);
  205265. TCHAR windowName [64]; // no need to read longer strings than this
  205266. GetWindowText (hwnd, windowName, 64);
  205267. windowName [63] = 0;
  205268. if (String (windowName) == messageWindowName)
  205269. {
  205270. DWORD_PTR result;
  205271. SendMessageTimeout (hwnd, WM_COPYDATA,
  205272. (WPARAM) juce_messageWindowHandle,
  205273. (LPARAM) &data,
  205274. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205275. 8000,
  205276. &result);
  205277. }
  205278. }
  205279. }
  205280. static const String getMessageWindowClassName()
  205281. {
  205282. // this name has to be different for each app/dll instance because otherwise
  205283. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205284. // window class).
  205285. static int number = 0;
  205286. if (number == 0)
  205287. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205288. return "JUCEcs_" + String (number);
  205289. }
  205290. void MessageManager::doPlatformSpecificInitialisation()
  205291. {
  205292. OleInitialize (0);
  205293. const String className (getMessageWindowClassName());
  205294. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205295. WNDCLASSEX wc;
  205296. zerostruct (wc);
  205297. wc.cbSize = sizeof (wc);
  205298. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205299. wc.cbWndExtra = 4;
  205300. wc.hInstance = hmod;
  205301. wc.lpszClassName = className;
  205302. RegisterClassEx (&wc);
  205303. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205304. messageWindowName,
  205305. 0, 0, 0, 0, 0, 0, 0,
  205306. hmod, 0);
  205307. }
  205308. void MessageManager::doPlatformSpecificShutdown()
  205309. {
  205310. DestroyWindow (juce_messageWindowHandle);
  205311. UnregisterClass (getMessageWindowClassName(), 0);
  205312. OleUninitialize();
  205313. }
  205314. #endif
  205315. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205316. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205317. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205318. // compiled on its own).
  205319. #if JUCE_INCLUDED_FILE
  205320. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205321. NEWTEXTMETRICEXW*,
  205322. int type,
  205323. LPARAM lParam)
  205324. {
  205325. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205326. {
  205327. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205328. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205329. }
  205330. return 1;
  205331. }
  205332. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205333. NEWTEXTMETRICEXW*,
  205334. int type,
  205335. LPARAM lParam)
  205336. {
  205337. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205338. {
  205339. LOGFONTW lf;
  205340. zerostruct (lf);
  205341. lf.lfWeight = FW_DONTCARE;
  205342. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205343. lf.lfQuality = DEFAULT_QUALITY;
  205344. lf.lfCharSet = DEFAULT_CHARSET;
  205345. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205346. lf.lfPitchAndFamily = FF_DONTCARE;
  205347. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205348. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205349. HDC dc = CreateCompatibleDC (0);
  205350. EnumFontFamiliesEx (dc, &lf,
  205351. (FONTENUMPROCW) &wfontEnum2,
  205352. lParam, 0);
  205353. DeleteDC (dc);
  205354. }
  205355. return 1;
  205356. }
  205357. const StringArray Font::findAllTypefaceNames()
  205358. {
  205359. StringArray results;
  205360. HDC dc = CreateCompatibleDC (0);
  205361. {
  205362. LOGFONTW lf;
  205363. zerostruct (lf);
  205364. lf.lfWeight = FW_DONTCARE;
  205365. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205366. lf.lfQuality = DEFAULT_QUALITY;
  205367. lf.lfCharSet = DEFAULT_CHARSET;
  205368. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205369. lf.lfPitchAndFamily = FF_DONTCARE;
  205370. lf.lfFaceName[0] = 0;
  205371. EnumFontFamiliesEx (dc, &lf,
  205372. (FONTENUMPROCW) &wfontEnum1,
  205373. (LPARAM) &results, 0);
  205374. }
  205375. DeleteDC (dc);
  205376. results.sort (true);
  205377. return results;
  205378. }
  205379. extern bool juce_IsRunningInWine();
  205380. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205381. {
  205382. if (juce_IsRunningInWine())
  205383. {
  205384. // If we're running in Wine, then use fonts that might be available on Linux..
  205385. defaultSans = "Bitstream Vera Sans";
  205386. defaultSerif = "Bitstream Vera Serif";
  205387. defaultFixed = "Bitstream Vera Sans Mono";
  205388. }
  205389. else
  205390. {
  205391. defaultSans = "Verdana";
  205392. defaultSerif = "Times";
  205393. defaultFixed = "Lucida Console";
  205394. }
  205395. }
  205396. class FontDCHolder : private DeletedAtShutdown
  205397. {
  205398. public:
  205399. FontDCHolder()
  205400. : dc (0), numKPs (0), size (0),
  205401. bold (false), italic (false)
  205402. {
  205403. }
  205404. ~FontDCHolder()
  205405. {
  205406. if (dc != 0)
  205407. {
  205408. DeleteDC (dc);
  205409. DeleteObject (fontH);
  205410. }
  205411. clearSingletonInstance();
  205412. }
  205413. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205414. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205415. {
  205416. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205417. {
  205418. fontName = fontName_;
  205419. bold = bold_;
  205420. italic = italic_;
  205421. size = size_;
  205422. if (dc != 0)
  205423. {
  205424. DeleteDC (dc);
  205425. DeleteObject (fontH);
  205426. kps.free();
  205427. }
  205428. fontH = 0;
  205429. dc = CreateCompatibleDC (0);
  205430. SetMapperFlags (dc, 0);
  205431. SetMapMode (dc, MM_TEXT);
  205432. LOGFONTW lfw;
  205433. zerostruct (lfw);
  205434. lfw.lfCharSet = DEFAULT_CHARSET;
  205435. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205436. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205437. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205438. lfw.lfQuality = PROOF_QUALITY;
  205439. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205440. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205441. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205442. lfw.lfHeight = size > 0 ? size : -256;
  205443. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205444. if (standardSizedFont != 0)
  205445. {
  205446. if (SelectObject (dc, standardSizedFont) != 0)
  205447. {
  205448. fontH = standardSizedFont;
  205449. if (size == 0)
  205450. {
  205451. OUTLINETEXTMETRIC otm;
  205452. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205453. {
  205454. lfw.lfHeight = -(int) otm.otmEMSquare;
  205455. fontH = CreateFontIndirect (&lfw);
  205456. SelectObject (dc, fontH);
  205457. DeleteObject (standardSizedFont);
  205458. }
  205459. }
  205460. }
  205461. else
  205462. {
  205463. jassertfalse;
  205464. }
  205465. }
  205466. else
  205467. {
  205468. jassertfalse;
  205469. }
  205470. }
  205471. return dc;
  205472. }
  205473. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205474. {
  205475. if (kps == 0)
  205476. {
  205477. numKPs = GetKerningPairs (dc, 0, 0);
  205478. kps.calloc (numKPs);
  205479. GetKerningPairs (dc, numKPs, kps);
  205480. }
  205481. numKPs_ = numKPs;
  205482. return kps;
  205483. }
  205484. private:
  205485. HFONT fontH;
  205486. HDC dc;
  205487. String fontName;
  205488. HeapBlock <KERNINGPAIR> kps;
  205489. int numKPs, size;
  205490. bool bold, italic;
  205491. FontDCHolder (const FontDCHolder&);
  205492. FontDCHolder& operator= (const FontDCHolder&);
  205493. };
  205494. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205495. class WindowsTypeface : public CustomTypeface
  205496. {
  205497. public:
  205498. WindowsTypeface (const Font& font)
  205499. {
  205500. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205501. font.isBold(), font.isItalic(), 0);
  205502. TEXTMETRIC tm;
  205503. tm.tmAscent = tm.tmHeight = 1;
  205504. tm.tmDefaultChar = 0;
  205505. GetTextMetrics (dc, &tm);
  205506. setCharacteristics (font.getTypefaceName(),
  205507. tm.tmAscent / (float) tm.tmHeight,
  205508. font.isBold(), font.isItalic(),
  205509. tm.tmDefaultChar);
  205510. }
  205511. bool loadGlyphIfPossible (juce_wchar character)
  205512. {
  205513. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205514. GLYPHMETRICS gm;
  205515. {
  205516. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205517. WORD index = 0;
  205518. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205519. && index == 0xffff)
  205520. {
  205521. return false;
  205522. }
  205523. }
  205524. Path glyphPath;
  205525. TEXTMETRIC tm;
  205526. if (! GetTextMetrics (dc, &tm))
  205527. {
  205528. addGlyph (character, glyphPath, 0);
  205529. return true;
  205530. }
  205531. const float height = (float) tm.tmHeight;
  205532. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205533. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205534. &gm, 0, 0, &identityMatrix);
  205535. if (bufSize > 0)
  205536. {
  205537. HeapBlock<char> data (bufSize);
  205538. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205539. bufSize, data, &identityMatrix);
  205540. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205541. const float scaleX = 1.0f / height;
  205542. const float scaleY = -1.0f / height;
  205543. while ((char*) pheader < data + bufSize)
  205544. {
  205545. float x = scaleX * pheader->pfxStart.x.value;
  205546. float y = scaleY * pheader->pfxStart.y.value;
  205547. glyphPath.startNewSubPath (x, y);
  205548. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205549. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205550. while ((const char*) curve < curveEnd)
  205551. {
  205552. if (curve->wType == TT_PRIM_LINE)
  205553. {
  205554. for (int i = 0; i < curve->cpfx; ++i)
  205555. {
  205556. x = scaleX * curve->apfx[i].x.value;
  205557. y = scaleY * curve->apfx[i].y.value;
  205558. glyphPath.lineTo (x, y);
  205559. }
  205560. }
  205561. else if (curve->wType == TT_PRIM_QSPLINE)
  205562. {
  205563. for (int i = 0; i < curve->cpfx - 1; ++i)
  205564. {
  205565. const float x2 = scaleX * curve->apfx[i].x.value;
  205566. const float y2 = scaleY * curve->apfx[i].y.value;
  205567. float x3, y3;
  205568. if (i < curve->cpfx - 2)
  205569. {
  205570. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205571. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205572. }
  205573. else
  205574. {
  205575. x3 = scaleX * curve->apfx[i + 1].x.value;
  205576. y3 = scaleY * curve->apfx[i + 1].y.value;
  205577. }
  205578. glyphPath.quadraticTo (x2, y2, x3, y3);
  205579. x = x3;
  205580. y = y3;
  205581. }
  205582. }
  205583. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205584. }
  205585. pheader = (const TTPOLYGONHEADER*) curve;
  205586. glyphPath.closeSubPath();
  205587. }
  205588. }
  205589. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205590. int numKPs;
  205591. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205592. for (int i = 0; i < numKPs; ++i)
  205593. {
  205594. if (kps[i].wFirst == character)
  205595. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205596. kps[i].iKernAmount / height);
  205597. }
  205598. return true;
  205599. }
  205600. juce_UseDebuggingNewOperator
  205601. };
  205602. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205603. {
  205604. return new WindowsTypeface (font);
  205605. }
  205606. #endif
  205607. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205608. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205609. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205610. // compiled on its own).
  205611. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205612. class SharedD2DFactory : public DeletedAtShutdown
  205613. {
  205614. public:
  205615. SharedD2DFactory()
  205616. {
  205617. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205618. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205619. if (directWriteFactory != 0)
  205620. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205621. }
  205622. ~SharedD2DFactory()
  205623. {
  205624. clearSingletonInstance();
  205625. }
  205626. juce_DeclareSingleton (SharedD2DFactory, false);
  205627. ComSmartPtr <ID2D1Factory> d2dFactory;
  205628. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205629. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205630. };
  205631. juce_ImplementSingleton (SharedD2DFactory)
  205632. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205633. {
  205634. public:
  205635. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205636. : hwnd (hwnd_),
  205637. currentState (0)
  205638. {
  205639. RECT windowRect;
  205640. GetClientRect (hwnd, &windowRect);
  205641. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205642. bounds.setSize (size.width, size.height);
  205643. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205644. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205645. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205646. // xxx check for error
  205647. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205648. }
  205649. ~Direct2DLowLevelGraphicsContext()
  205650. {
  205651. states.clear();
  205652. }
  205653. void resized()
  205654. {
  205655. RECT windowRect;
  205656. GetClientRect (hwnd, &windowRect);
  205657. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205658. renderingTarget->Resize (size);
  205659. bounds.setSize (size.width, size.height);
  205660. }
  205661. void clear()
  205662. {
  205663. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205664. }
  205665. void start()
  205666. {
  205667. renderingTarget->BeginDraw();
  205668. saveState();
  205669. }
  205670. void end()
  205671. {
  205672. states.clear();
  205673. currentState = 0;
  205674. renderingTarget->EndDraw();
  205675. renderingTarget->CheckWindowState();
  205676. }
  205677. bool isVectorDevice() const { return false; }
  205678. void setOrigin (int x, int y)
  205679. {
  205680. currentState->origin.addXY (x, y);
  205681. }
  205682. bool clipToRectangle (const Rectangle<int>& r)
  205683. {
  205684. currentState->clipToRectangle (r);
  205685. return ! isClipEmpty();
  205686. }
  205687. bool clipToRectangleList (const RectangleList& clipRegion)
  205688. {
  205689. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205690. return ! isClipEmpty();
  205691. }
  205692. void excludeClipRectangle (const Rectangle<int>&)
  205693. {
  205694. //xxx
  205695. }
  205696. void clipToPath (const Path& path, const AffineTransform& transform)
  205697. {
  205698. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205699. }
  205700. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205701. {
  205702. currentState->clipToImage (sourceImage,transform);
  205703. }
  205704. bool clipRegionIntersects (const Rectangle<int>& r)
  205705. {
  205706. const Rectangle<int> r2 (r + currentState->origin);
  205707. return currentState->clipRect.intersects (r2);
  205708. }
  205709. const Rectangle<int> getClipBounds() const
  205710. {
  205711. // xxx could this take into account complex clip regions?
  205712. return currentState->clipRect - currentState->origin;
  205713. }
  205714. bool isClipEmpty() const
  205715. {
  205716. return currentState->clipRect.isEmpty();
  205717. }
  205718. void saveState()
  205719. {
  205720. states.add (new SavedState (*this));
  205721. currentState = states.getLast();
  205722. }
  205723. void restoreState()
  205724. {
  205725. jassert (states.size() > 1) //you should never pop the last state!
  205726. states.removeLast (1);
  205727. currentState = states.getLast();
  205728. }
  205729. void setFill (const FillType& fillType)
  205730. {
  205731. currentState->setFill (fillType);
  205732. }
  205733. void setOpacity (float newOpacity)
  205734. {
  205735. currentState->setOpacity (newOpacity);
  205736. }
  205737. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205738. {
  205739. }
  205740. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205741. {
  205742. currentState->createBrush();
  205743. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205744. }
  205745. void fillPath (const Path& p, const AffineTransform& transform)
  205746. {
  205747. currentState->createBrush();
  205748. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205749. if (renderingTarget != 0)
  205750. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205751. }
  205752. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205753. {
  205754. const int x = currentState->origin.getX();
  205755. const int y = currentState->origin.getY();
  205756. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205757. D2D1_SIZE_U size;
  205758. size.width = image.getWidth();
  205759. size.height = image.getHeight();
  205760. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205761. Image img (image.convertedToFormat (Image::ARGB));
  205762. Image::BitmapData bd (img, false);
  205763. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205764. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205765. {
  205766. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205767. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205768. if (tempBitmap != 0)
  205769. renderingTarget->DrawBitmap (tempBitmap);
  205770. }
  205771. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205772. }
  205773. void drawLine (const Line <float>& line)
  205774. {
  205775. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205776. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205777. line.getEnd() + currentState->origin.toFloat());
  205778. currentState->createBrush();
  205779. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205780. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205781. currentState->currentBrush);
  205782. }
  205783. void drawVerticalLine (int x, float top, float bottom)
  205784. {
  205785. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205786. currentState->createBrush();
  205787. x += currentState->origin.getX();
  205788. const int y = currentState->origin.getY();
  205789. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205790. D2D1::Point2F (x, y + bottom),
  205791. currentState->currentBrush);
  205792. }
  205793. void drawHorizontalLine (int y, float left, float right)
  205794. {
  205795. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205796. currentState->createBrush();
  205797. y += currentState->origin.getY();
  205798. const int x = currentState->origin.getX();
  205799. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205800. D2D1::Point2F (x + right, y),
  205801. currentState->currentBrush);
  205802. }
  205803. void setFont (const Font& newFont)
  205804. {
  205805. currentState->setFont (newFont);
  205806. }
  205807. const Font getFont()
  205808. {
  205809. return currentState->font;
  205810. }
  205811. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205812. {
  205813. const float x = currentState->origin.getX();
  205814. const float y = currentState->origin.getY();
  205815. currentState->createBrush();
  205816. currentState->createFont();
  205817. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205818. float hScale = currentState->font.getHorizontalScale();
  205819. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205820. float dpiX = 0, dpiY = 0;
  205821. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205822. UINT32 glyphNum = glyphNumber;
  205823. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205824. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205825. DWRITE_GLYPH_OFFSET offset;
  205826. offset.advanceOffset = 0;
  205827. offset.ascenderOffset = 0;
  205828. float glyphAdvances = 0;
  205829. DWRITE_GLYPH_RUN glyph;
  205830. glyph.fontFace = currentState->currentFontFace;
  205831. glyph.glyphCount = 1;
  205832. glyph.glyphIndices = &glyphNum1;
  205833. glyph.isSideways = FALSE;
  205834. glyph.glyphAdvances = &glyphAdvances;
  205835. glyph.glyphOffsets = &offset;
  205836. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  205837. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  205838. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205839. }
  205840. class SavedState
  205841. {
  205842. public:
  205843. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  205844. : owner (owner_), currentBrush (0),
  205845. fontScaling (1.0f), currentFontFace (0),
  205846. clipsRect (false), shouldClipRect (false),
  205847. clipsRectList (false), shouldClipRectList (false),
  205848. clipsComplex (false), shouldClipComplex (false),
  205849. clipsBitmap (false), shouldClipBitmap (false)
  205850. {
  205851. if (owner.currentState != 0)
  205852. {
  205853. // xxx seems like a very slow way to create one of these, and this is a performance
  205854. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  205855. setFill (owner.currentState->fillType);
  205856. currentBrush = owner.currentState->currentBrush;
  205857. origin = owner.currentState->origin;
  205858. clipRect = owner.currentState->clipRect;
  205859. font = owner.currentState->font;
  205860. currentFontFace = owner.currentState->currentFontFace;
  205861. }
  205862. else
  205863. {
  205864. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  205865. clipRect.setSize (size.width, size.height);
  205866. setFill (FillType (Colours::black));
  205867. }
  205868. }
  205869. ~SavedState()
  205870. {
  205871. clearClip();
  205872. clearFont();
  205873. clearFill();
  205874. clearPathClip();
  205875. clearImageClip();
  205876. complexClipLayer = 0;
  205877. bitmapMaskLayer = 0;
  205878. }
  205879. void clearClip()
  205880. {
  205881. popClips();
  205882. shouldClipRect = false;
  205883. }
  205884. void clipToRectangle (const Rectangle<int>& r)
  205885. {
  205886. clearClip();
  205887. clipRect = r + origin;
  205888. shouldClipRect = true;
  205889. pushClips();
  205890. }
  205891. void clearPathClip()
  205892. {
  205893. popClips();
  205894. if (shouldClipComplex)
  205895. {
  205896. complexClipGeometry = 0;
  205897. shouldClipComplex = false;
  205898. }
  205899. }
  205900. void clipToPath (ID2D1Geometry* geometry)
  205901. {
  205902. clearPathClip();
  205903. if (complexClipLayer == 0)
  205904. owner.renderingTarget->CreateLayer (&complexClipLayer);
  205905. complexClipGeometry = geometry;
  205906. shouldClipComplex = true;
  205907. pushClips();
  205908. }
  205909. void clearRectListClip()
  205910. {
  205911. popClips();
  205912. if (shouldClipRectList)
  205913. {
  205914. rectListGeometry = 0;
  205915. shouldClipRectList = false;
  205916. }
  205917. }
  205918. void clipToRectList (ID2D1Geometry* geometry)
  205919. {
  205920. clearRectListClip();
  205921. if (rectListLayer == 0)
  205922. owner.renderingTarget->CreateLayer (&rectListLayer);
  205923. rectListGeometry = geometry;
  205924. shouldClipRectList = true;
  205925. pushClips();
  205926. }
  205927. void clearImageClip()
  205928. {
  205929. popClips();
  205930. if (shouldClipBitmap)
  205931. {
  205932. maskBitmap = 0;
  205933. bitmapMaskBrush = 0;
  205934. shouldClipBitmap = false;
  205935. }
  205936. }
  205937. void clipToImage (const Image& image, const AffineTransform& transform)
  205938. {
  205939. clearImageClip();
  205940. if (bitmapMaskLayer == 0)
  205941. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  205942. D2D1_BRUSH_PROPERTIES brushProps;
  205943. brushProps.opacity = 1;
  205944. brushProps.transform = transfromToMatrix (transform);
  205945. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  205946. D2D1_SIZE_U size;
  205947. size.width = image.getWidth();
  205948. size.height = image.getHeight();
  205949. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205950. maskImage = image.convertedToFormat (Image::ARGB);
  205951. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  205952. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  205953. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205954. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  205955. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  205956. imageMaskLayerParams = D2D1::LayerParameters();
  205957. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  205958. shouldClipBitmap = true;
  205959. pushClips();
  205960. }
  205961. void popClips()
  205962. {
  205963. if (clipsBitmap)
  205964. {
  205965. owner.renderingTarget->PopLayer();
  205966. clipsBitmap = false;
  205967. }
  205968. if (clipsComplex)
  205969. {
  205970. owner.renderingTarget->PopLayer();
  205971. clipsComplex = false;
  205972. }
  205973. if (clipsRectList)
  205974. {
  205975. owner.renderingTarget->PopLayer();
  205976. clipsRectList = false;
  205977. }
  205978. if (clipsRect)
  205979. {
  205980. owner.renderingTarget->PopAxisAlignedClip();
  205981. clipsRect = false;
  205982. }
  205983. }
  205984. void pushClips()
  205985. {
  205986. if (shouldClipRect && ! clipsRect)
  205987. {
  205988. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  205989. clipsRect = true;
  205990. }
  205991. if (shouldClipRectList && ! clipsRectList)
  205992. {
  205993. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205994. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205995. layerParams.geometricMask = rectListGeometry;
  205996. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  205997. clipsRectList = true;
  205998. }
  205999. if (shouldClipComplex && ! clipsComplex)
  206000. {
  206001. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206002. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206003. layerParams.geometricMask = complexClipGeometry;
  206004. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206005. clipsComplex = true;
  206006. }
  206007. if (shouldClipBitmap && ! clipsBitmap)
  206008. {
  206009. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206010. clipsBitmap = true;
  206011. }
  206012. }
  206013. void setFill (const FillType& newFillType)
  206014. {
  206015. if (fillType != newFillType)
  206016. {
  206017. fillType = newFillType;
  206018. clearFill();
  206019. }
  206020. }
  206021. void clearFont()
  206022. {
  206023. currentFontFace = localFontFace = 0;
  206024. }
  206025. void setFont (const Font& newFont)
  206026. {
  206027. if (font != newFont)
  206028. {
  206029. font = newFont;
  206030. clearFont();
  206031. }
  206032. }
  206033. void createFont()
  206034. {
  206035. // xxx The font shouldn't be managed by the graphics context.
  206036. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206037. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206038. // WindowsTypeface class.
  206039. if (currentFontFace == 0)
  206040. {
  206041. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206042. fontScaling = systemType->getAscent();
  206043. BOOL fontFound;
  206044. uint32 fontIndex;
  206045. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206046. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206047. if (! fontFound)
  206048. fontIndex = 0;
  206049. ComSmartPtr <IDWriteFontFamily> fontFam;
  206050. fonts->GetFontFamily (fontIndex, &fontFam);
  206051. ComSmartPtr <IDWriteFont> font;
  206052. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206053. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206054. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206055. font->CreateFontFace (&localFontFace);
  206056. currentFontFace = localFontFace;
  206057. }
  206058. }
  206059. void setOpacity (float newOpacity)
  206060. {
  206061. fillType.setOpacity (newOpacity);
  206062. if (currentBrush != 0)
  206063. currentBrush->SetOpacity (newOpacity);
  206064. }
  206065. void clearFill()
  206066. {
  206067. gradientStops = 0;
  206068. linearGradient = 0;
  206069. radialGradient = 0;
  206070. bitmap = 0;
  206071. bitmapBrush = 0;
  206072. currentBrush = 0;
  206073. }
  206074. void createBrush()
  206075. {
  206076. if (currentBrush == 0)
  206077. {
  206078. const int x = origin.getX();
  206079. const int y = origin.getY();
  206080. if (fillType.isColour())
  206081. {
  206082. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206083. owner.colourBrush->SetColor (colour);
  206084. currentBrush = owner.colourBrush;
  206085. }
  206086. else if (fillType.isTiledImage())
  206087. {
  206088. D2D1_BRUSH_PROPERTIES brushProps;
  206089. brushProps.opacity = fillType.getOpacity();
  206090. brushProps.transform = transfromToMatrix (fillType.transform);
  206091. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206092. image = fillType.image;
  206093. D2D1_SIZE_U size;
  206094. size.width = image.getWidth();
  206095. size.height = image.getHeight();
  206096. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206097. this->image = image.convertedToFormat (Image::ARGB);
  206098. Image::BitmapData bd (this->image, false);
  206099. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206100. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206101. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206102. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206103. currentBrush = bitmapBrush;
  206104. }
  206105. else if (fillType.isGradient())
  206106. {
  206107. gradientStops = 0;
  206108. D2D1_BRUSH_PROPERTIES brushProps;
  206109. brushProps.opacity = fillType.getOpacity();
  206110. brushProps.transform = transfromToMatrix (fillType.transform);
  206111. const int numColors = fillType.gradient->getNumColours();
  206112. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206113. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206114. {
  206115. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206116. stops[i].position = fillType.gradient->getColourPosition(i);
  206117. }
  206118. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206119. if (fillType.gradient->isRadial)
  206120. {
  206121. radialGradient = 0;
  206122. const Point<float>& p1 = fillType.gradient->point1;
  206123. const Point<float>& p2 = fillType.gradient->point2;
  206124. float r = p1.getDistanceFrom (p2);
  206125. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206126. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206127. D2D1::Point2F (0, 0),
  206128. r, r);
  206129. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206130. currentBrush = radialGradient;
  206131. }
  206132. else
  206133. {
  206134. linearGradient = 0;
  206135. const Point<float>& p1 = fillType.gradient->point1;
  206136. const Point<float>& p2 = fillType.gradient->point2;
  206137. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206138. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206139. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206140. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206141. currentBrush = linearGradient;
  206142. }
  206143. }
  206144. }
  206145. }
  206146. juce_UseDebuggingNewOperator
  206147. //xxx most of these members should probably be private...
  206148. Direct2DLowLevelGraphicsContext& owner;
  206149. Point<int> origin;
  206150. Font font;
  206151. float fontScaling;
  206152. IDWriteFontFace* currentFontFace;
  206153. ComSmartPtr <IDWriteFontFace> localFontFace;
  206154. FillType fillType;
  206155. Image image;
  206156. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206157. Rectangle<int> clipRect;
  206158. bool clipsRect, shouldClipRect;
  206159. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206160. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206161. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206162. bool clipsComplex, shouldClipComplex;
  206163. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206164. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206165. ComSmartPtr <ID2D1Layer> rectListLayer;
  206166. bool clipsRectList, shouldClipRectList;
  206167. Image maskImage;
  206168. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206169. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206170. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206171. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206172. bool clipsBitmap, shouldClipBitmap;
  206173. ID2D1Brush* currentBrush;
  206174. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206175. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206176. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206177. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206178. private:
  206179. SavedState (const SavedState&);
  206180. SavedState& operator= (const SavedState& other);
  206181. };
  206182. juce_UseDebuggingNewOperator
  206183. private:
  206184. HWND hwnd;
  206185. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206186. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206187. Rectangle<int> bounds;
  206188. SavedState* currentState;
  206189. OwnedArray<SavedState> states;
  206190. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206191. {
  206192. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206193. }
  206194. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206195. {
  206196. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206197. }
  206198. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206199. {
  206200. transform.transformPoint (x, y);
  206201. return D2D1::Point2F (x, y);
  206202. }
  206203. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206204. {
  206205. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206206. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206207. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206208. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206209. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206210. }
  206211. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206212. {
  206213. ID2D1PathGeometry* p = 0;
  206214. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206215. ComSmartPtr <ID2D1GeometrySink> sink;
  206216. HRESULT hr = p->Open (&sink); // xxx handle error
  206217. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206218. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206219. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206220. hr = sink->Close();
  206221. return p;
  206222. }
  206223. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206224. {
  206225. Path::Iterator it (path);
  206226. while (it.next())
  206227. {
  206228. switch (it.elementType)
  206229. {
  206230. case Path::Iterator::cubicTo:
  206231. {
  206232. D2D1_BEZIER_SEGMENT seg;
  206233. transform.transformPoint (it.x1, it.y1);
  206234. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206235. transform.transformPoint (it.x2, it.y2);
  206236. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206237. transform.transformPoint(it.x3, it.y3);
  206238. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206239. sink->AddBezier (seg);
  206240. break;
  206241. }
  206242. case Path::Iterator::lineTo:
  206243. {
  206244. transform.transformPoint (it.x1, it.y1);
  206245. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206246. break;
  206247. }
  206248. case Path::Iterator::quadraticTo:
  206249. {
  206250. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206251. transform.transformPoint (it.x1, it.y1);
  206252. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206253. transform.transformPoint (it.x2, it.y2);
  206254. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206255. sink->AddQuadraticBezier (seg);
  206256. break;
  206257. }
  206258. case Path::Iterator::closePath:
  206259. {
  206260. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206261. break;
  206262. }
  206263. case Path::Iterator::startNewSubPath:
  206264. {
  206265. transform.transformPoint (it.x1, it.y1);
  206266. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206267. break;
  206268. }
  206269. }
  206270. }
  206271. }
  206272. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206273. {
  206274. ID2D1PathGeometry* p = 0;
  206275. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206276. ComSmartPtr <ID2D1GeometrySink> sink;
  206277. HRESULT hr = p->Open (&sink);
  206278. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206279. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206280. hr = sink->Close();
  206281. return p;
  206282. }
  206283. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206284. {
  206285. D2D1::Matrix3x2F matrix;
  206286. matrix._11 = transform.mat00;
  206287. matrix._12 = transform.mat10;
  206288. matrix._21 = transform.mat01;
  206289. matrix._22 = transform.mat11;
  206290. matrix._31 = transform.mat02;
  206291. matrix._32 = transform.mat12;
  206292. return matrix;
  206293. }
  206294. };
  206295. #endif
  206296. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206297. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206298. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206299. // compiled on its own).
  206300. #if JUCE_INCLUDED_FILE
  206301. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206302. // these are in the windows SDK, but need to be repeated here for GCC..
  206303. #ifndef GET_APPCOMMAND_LPARAM
  206304. #define FAPPCOMMAND_MASK 0xF000
  206305. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206306. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206307. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206308. #define APPCOMMAND_MEDIA_STOP 13
  206309. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206310. #define WM_APPCOMMAND 0x0319
  206311. #endif
  206312. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206313. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206314. extern bool juce_IsRunningInWine();
  206315. #ifndef ULW_ALPHA
  206316. #define ULW_ALPHA 0x00000002
  206317. #endif
  206318. #ifndef AC_SRC_ALPHA
  206319. #define AC_SRC_ALPHA 0x01
  206320. #endif
  206321. static HPALETTE palette = 0;
  206322. static bool createPaletteIfNeeded = true;
  206323. static bool shouldDeactivateTitleBar = true;
  206324. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  206325. #define WM_TRAYNOTIFY WM_USER + 100
  206326. using ::abs;
  206327. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206328. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206329. bool Desktop::canUseSemiTransparentWindows() throw()
  206330. {
  206331. if (updateLayeredWindow == 0)
  206332. {
  206333. if (! juce_IsRunningInWine())
  206334. {
  206335. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206336. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206337. }
  206338. }
  206339. return updateLayeredWindow != 0;
  206340. }
  206341. const int extendedKeyModifier = 0x10000;
  206342. const int KeyPress::spaceKey = VK_SPACE;
  206343. const int KeyPress::returnKey = VK_RETURN;
  206344. const int KeyPress::escapeKey = VK_ESCAPE;
  206345. const int KeyPress::backspaceKey = VK_BACK;
  206346. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206347. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206348. const int KeyPress::tabKey = VK_TAB;
  206349. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206350. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206351. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206352. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206353. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206354. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206355. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206356. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206357. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206358. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206359. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206360. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206361. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206362. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206363. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206364. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206365. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206366. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206367. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206368. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206369. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206370. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206371. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206372. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206373. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206374. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206375. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206376. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206377. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206378. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206379. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206380. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206381. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206382. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206383. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206384. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206385. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206386. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206387. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206388. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206389. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206390. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206391. const int KeyPress::playKey = 0x30000;
  206392. const int KeyPress::stopKey = 0x30001;
  206393. const int KeyPress::fastForwardKey = 0x30002;
  206394. const int KeyPress::rewindKey = 0x30003;
  206395. class WindowsBitmapImage : public Image::SharedImage
  206396. {
  206397. public:
  206398. HBITMAP hBitmap;
  206399. BITMAPV4HEADER bitmapInfo;
  206400. HDC hdc;
  206401. unsigned char* bitmapData;
  206402. WindowsBitmapImage (const Image::PixelFormat format_,
  206403. const int w, const int h, const bool clearImage)
  206404. : Image::SharedImage (format_, w, h)
  206405. {
  206406. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206407. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206408. zerostruct (bitmapInfo);
  206409. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206410. bitmapInfo.bV4Width = w;
  206411. bitmapInfo.bV4Height = h;
  206412. bitmapInfo.bV4Planes = 1;
  206413. bitmapInfo.bV4CSType = 1;
  206414. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206415. if (format_ == Image::ARGB)
  206416. {
  206417. bitmapInfo.bV4AlphaMask = 0xff000000;
  206418. bitmapInfo.bV4RedMask = 0xff0000;
  206419. bitmapInfo.bV4GreenMask = 0xff00;
  206420. bitmapInfo.bV4BlueMask = 0xff;
  206421. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206422. }
  206423. else
  206424. {
  206425. bitmapInfo.bV4V4Compression = BI_RGB;
  206426. }
  206427. lineStride = -((w * pixelStride + 3) & ~3);
  206428. HDC dc = GetDC (0);
  206429. hdc = CreateCompatibleDC (dc);
  206430. ReleaseDC (0, dc);
  206431. SetMapMode (hdc, MM_TEXT);
  206432. hBitmap = CreateDIBSection (hdc,
  206433. (BITMAPINFO*) &(bitmapInfo),
  206434. DIB_RGB_COLORS,
  206435. (void**) &bitmapData,
  206436. 0, 0);
  206437. SelectObject (hdc, hBitmap);
  206438. if (format_ == Image::ARGB && clearImage)
  206439. zeromem (bitmapData, abs (h * lineStride));
  206440. imageData = bitmapData - (lineStride * (h - 1));
  206441. }
  206442. ~WindowsBitmapImage()
  206443. {
  206444. DeleteDC (hdc);
  206445. DeleteObject (hBitmap);
  206446. }
  206447. Image::ImageType getType() const { return Image::NativeImage; }
  206448. LowLevelGraphicsContext* createLowLevelContext()
  206449. {
  206450. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206451. }
  206452. SharedImage* clone()
  206453. {
  206454. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206455. for (int i = 0; i < height; ++i)
  206456. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206457. return im;
  206458. }
  206459. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206460. const int x, const int y,
  206461. const RectangleList& maskedRegion) throw()
  206462. {
  206463. static HDRAWDIB hdd = 0;
  206464. static bool needToCreateDrawDib = true;
  206465. if (needToCreateDrawDib)
  206466. {
  206467. needToCreateDrawDib = false;
  206468. HDC dc = GetDC (0);
  206469. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206470. ReleaseDC (0, dc);
  206471. // only open if we're not palettised
  206472. if (n > 8)
  206473. hdd = DrawDibOpen();
  206474. }
  206475. if (createPaletteIfNeeded)
  206476. {
  206477. HDC dc = GetDC (0);
  206478. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206479. ReleaseDC (0, dc);
  206480. if (n <= 8)
  206481. palette = CreateHalftonePalette (dc);
  206482. createPaletteIfNeeded = false;
  206483. }
  206484. if (palette != 0)
  206485. {
  206486. SelectPalette (dc, palette, FALSE);
  206487. RealizePalette (dc);
  206488. SetStretchBltMode (dc, HALFTONE);
  206489. }
  206490. SetMapMode (dc, MM_TEXT);
  206491. if (transparent)
  206492. {
  206493. POINT p, pos;
  206494. SIZE size;
  206495. RECT windowBounds;
  206496. GetWindowRect (hwnd, &windowBounds);
  206497. p.x = -x;
  206498. p.y = -y;
  206499. pos.x = windowBounds.left;
  206500. pos.y = windowBounds.top;
  206501. size.cx = windowBounds.right - windowBounds.left;
  206502. size.cy = windowBounds.bottom - windowBounds.top;
  206503. BLENDFUNCTION bf;
  206504. bf.AlphaFormat = AC_SRC_ALPHA;
  206505. bf.BlendFlags = 0;
  206506. bf.BlendOp = AC_SRC_OVER;
  206507. bf.SourceConstantAlpha = 0xff;
  206508. if (! maskedRegion.isEmpty())
  206509. {
  206510. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206511. {
  206512. const Rectangle<int>& r = *i.getRectangle();
  206513. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206514. }
  206515. }
  206516. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206517. }
  206518. else
  206519. {
  206520. int savedDC = 0;
  206521. if (! maskedRegion.isEmpty())
  206522. {
  206523. savedDC = SaveDC (dc);
  206524. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206525. {
  206526. const Rectangle<int>& r = *i.getRectangle();
  206527. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206528. }
  206529. }
  206530. if (hdd == 0)
  206531. {
  206532. StretchDIBits (dc,
  206533. x, y, width, height,
  206534. 0, 0, width, height,
  206535. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206536. DIB_RGB_COLORS, SRCCOPY);
  206537. }
  206538. else
  206539. {
  206540. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206541. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206542. 0, 0, width, height, 0);
  206543. }
  206544. if (! maskedRegion.isEmpty())
  206545. RestoreDC (dc, savedDC);
  206546. }
  206547. }
  206548. juce_UseDebuggingNewOperator
  206549. private:
  206550. WindowsBitmapImage (const WindowsBitmapImage&);
  206551. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206552. };
  206553. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206554. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206555. {
  206556. SHORT k = (SHORT) keyCode;
  206557. if ((keyCode & extendedKeyModifier) == 0
  206558. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206559. k += (SHORT) 'A' - (SHORT) 'a';
  206560. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206561. (SHORT) '+', VK_OEM_PLUS,
  206562. (SHORT) '-', VK_OEM_MINUS,
  206563. (SHORT) '.', VK_OEM_PERIOD,
  206564. (SHORT) ';', VK_OEM_1,
  206565. (SHORT) ':', VK_OEM_1,
  206566. (SHORT) '/', VK_OEM_2,
  206567. (SHORT) '?', VK_OEM_2,
  206568. (SHORT) '[', VK_OEM_4,
  206569. (SHORT) ']', VK_OEM_6 };
  206570. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206571. if (k == translatedValues [i])
  206572. k = translatedValues [i + 1];
  206573. return (GetKeyState (k) & 0x8000) != 0;
  206574. }
  206575. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  206576. {
  206577. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  206578. return callback (userData);
  206579. else
  206580. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  206581. }
  206582. class Win32ComponentPeer : public ComponentPeer
  206583. {
  206584. public:
  206585. enum RenderingEngineType
  206586. {
  206587. softwareRenderingEngine = 0,
  206588. direct2DRenderingEngine
  206589. };
  206590. Win32ComponentPeer (Component* const component,
  206591. const int windowStyleFlags)
  206592. : ComponentPeer (component, windowStyleFlags),
  206593. dontRepaint (false),
  206594. #if JUCE_DIRECT2D
  206595. currentRenderingEngine (direct2DRenderingEngine),
  206596. #else
  206597. currentRenderingEngine (softwareRenderingEngine),
  206598. #endif
  206599. fullScreen (false),
  206600. isDragging (false),
  206601. isMouseOver (false),
  206602. hasCreatedCaret (false),
  206603. currentWindowIcon (0),
  206604. dropTarget (0)
  206605. {
  206606. callFunctionIfNotLocked (&createWindowCallback, this);
  206607. setTitle (component->getName());
  206608. if ((windowStyleFlags & windowHasDropShadow) != 0
  206609. && Desktop::canUseSemiTransparentWindows())
  206610. {
  206611. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206612. if (shadower != 0)
  206613. shadower->setOwner (component);
  206614. }
  206615. }
  206616. ~Win32ComponentPeer()
  206617. {
  206618. setTaskBarIcon (Image());
  206619. shadower = 0;
  206620. // do this before the next bit to avoid messages arriving for this window
  206621. // before it's destroyed
  206622. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206623. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206624. if (currentWindowIcon != 0)
  206625. DestroyIcon (currentWindowIcon);
  206626. if (dropTarget != 0)
  206627. {
  206628. dropTarget->Release();
  206629. dropTarget = 0;
  206630. }
  206631. #if JUCE_DIRECT2D
  206632. direct2DContext = 0;
  206633. #endif
  206634. }
  206635. void* getNativeHandle() const
  206636. {
  206637. return hwnd;
  206638. }
  206639. void setVisible (bool shouldBeVisible)
  206640. {
  206641. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206642. if (shouldBeVisible)
  206643. InvalidateRect (hwnd, 0, 0);
  206644. else
  206645. lastPaintTime = 0;
  206646. }
  206647. void setTitle (const String& title)
  206648. {
  206649. SetWindowText (hwnd, title);
  206650. }
  206651. void setPosition (int x, int y)
  206652. {
  206653. offsetWithinParent (x, y);
  206654. SetWindowPos (hwnd, 0,
  206655. x - windowBorder.getLeft(),
  206656. y - windowBorder.getTop(),
  206657. 0, 0,
  206658. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206659. }
  206660. void repaintNowIfTransparent()
  206661. {
  206662. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206663. handlePaintMessage();
  206664. }
  206665. void updateBorderSize()
  206666. {
  206667. WINDOWINFO info;
  206668. info.cbSize = sizeof (info);
  206669. if (GetWindowInfo (hwnd, &info))
  206670. {
  206671. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206672. info.rcClient.left - info.rcWindow.left,
  206673. info.rcWindow.bottom - info.rcClient.bottom,
  206674. info.rcWindow.right - info.rcClient.right);
  206675. }
  206676. #if JUCE_DIRECT2D
  206677. if (direct2DContext != 0)
  206678. direct2DContext->resized();
  206679. #endif
  206680. }
  206681. void setSize (int w, int h)
  206682. {
  206683. SetWindowPos (hwnd, 0, 0, 0,
  206684. w + windowBorder.getLeftAndRight(),
  206685. h + windowBorder.getTopAndBottom(),
  206686. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206687. updateBorderSize();
  206688. repaintNowIfTransparent();
  206689. }
  206690. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206691. {
  206692. fullScreen = isNowFullScreen;
  206693. offsetWithinParent (x, y);
  206694. SetWindowPos (hwnd, 0,
  206695. x - windowBorder.getLeft(),
  206696. y - windowBorder.getTop(),
  206697. w + windowBorder.getLeftAndRight(),
  206698. h + windowBorder.getTopAndBottom(),
  206699. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206700. updateBorderSize();
  206701. repaintNowIfTransparent();
  206702. }
  206703. const Rectangle<int> getBounds() const
  206704. {
  206705. RECT r;
  206706. GetWindowRect (hwnd, &r);
  206707. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206708. HWND parentH = GetParent (hwnd);
  206709. if (parentH != 0)
  206710. {
  206711. GetWindowRect (parentH, &r);
  206712. bounds.translate (-r.left, -r.top);
  206713. }
  206714. return windowBorder.subtractedFrom (bounds);
  206715. }
  206716. const Point<int> getScreenPosition() const
  206717. {
  206718. RECT r;
  206719. GetWindowRect (hwnd, &r);
  206720. return Point<int> (r.left + windowBorder.getLeft(),
  206721. r.top + windowBorder.getTop());
  206722. }
  206723. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  206724. {
  206725. return relativePosition + getScreenPosition();
  206726. }
  206727. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  206728. {
  206729. return screenPosition - getScreenPosition();
  206730. }
  206731. void setMinimised (bool shouldBeMinimised)
  206732. {
  206733. if (shouldBeMinimised != isMinimised())
  206734. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206735. }
  206736. bool isMinimised() const
  206737. {
  206738. WINDOWPLACEMENT wp;
  206739. wp.length = sizeof (WINDOWPLACEMENT);
  206740. GetWindowPlacement (hwnd, &wp);
  206741. return wp.showCmd == SW_SHOWMINIMIZED;
  206742. }
  206743. void setFullScreen (bool shouldBeFullScreen)
  206744. {
  206745. setMinimised (false);
  206746. if (fullScreen != shouldBeFullScreen)
  206747. {
  206748. fullScreen = shouldBeFullScreen;
  206749. const Component::SafePointer<Component> deletionChecker (component);
  206750. if (! fullScreen)
  206751. {
  206752. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206753. if (hasTitleBar())
  206754. ShowWindow (hwnd, SW_SHOWNORMAL);
  206755. if (! boundsCopy.isEmpty())
  206756. {
  206757. setBounds (boundsCopy.getX(),
  206758. boundsCopy.getY(),
  206759. boundsCopy.getWidth(),
  206760. boundsCopy.getHeight(),
  206761. false);
  206762. }
  206763. }
  206764. else
  206765. {
  206766. if (hasTitleBar())
  206767. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206768. else
  206769. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206770. }
  206771. if (deletionChecker != 0)
  206772. handleMovedOrResized();
  206773. }
  206774. }
  206775. bool isFullScreen() const
  206776. {
  206777. if (! hasTitleBar())
  206778. return fullScreen;
  206779. WINDOWPLACEMENT wp;
  206780. wp.length = sizeof (wp);
  206781. GetWindowPlacement (hwnd, &wp);
  206782. return wp.showCmd == SW_SHOWMAXIMIZED;
  206783. }
  206784. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206785. {
  206786. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  206787. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  206788. return false;
  206789. RECT r;
  206790. GetWindowRect (hwnd, &r);
  206791. POINT p;
  206792. p.x = position.getX() + r.left + windowBorder.getLeft();
  206793. p.y = position.getY() + r.top + windowBorder.getTop();
  206794. HWND w = WindowFromPoint (p);
  206795. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206796. }
  206797. const BorderSize getFrameSize() const
  206798. {
  206799. return windowBorder;
  206800. }
  206801. bool setAlwaysOnTop (bool alwaysOnTop)
  206802. {
  206803. const bool oldDeactivate = shouldDeactivateTitleBar;
  206804. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206805. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206806. 0, 0, 0, 0,
  206807. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206808. shouldDeactivateTitleBar = oldDeactivate;
  206809. if (shadower != 0)
  206810. shadower->componentBroughtToFront (*component);
  206811. return true;
  206812. }
  206813. void toFront (bool makeActive)
  206814. {
  206815. setMinimised (false);
  206816. const bool oldDeactivate = shouldDeactivateTitleBar;
  206817. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206818. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  206819. shouldDeactivateTitleBar = oldDeactivate;
  206820. if (! makeActive)
  206821. {
  206822. // in this case a broughttofront call won't have occured, so do it now..
  206823. handleBroughtToFront();
  206824. }
  206825. }
  206826. void toBehind (ComponentPeer* other)
  206827. {
  206828. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206829. jassert (otherPeer != 0); // wrong type of window?
  206830. if (otherPeer != 0)
  206831. {
  206832. setMinimised (false);
  206833. // must be careful not to try to put a topmost window behind a normal one, or win32
  206834. // promotes the normal one to be topmost!
  206835. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  206836. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206837. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206838. else if (otherPeer->getComponent()->isAlwaysOnTop())
  206839. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  206840. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206841. }
  206842. }
  206843. bool isFocused() const
  206844. {
  206845. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  206846. }
  206847. void grabFocus()
  206848. {
  206849. const bool oldDeactivate = shouldDeactivateTitleBar;
  206850. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206851. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  206852. shouldDeactivateTitleBar = oldDeactivate;
  206853. }
  206854. void textInputRequired (const Point<int>&)
  206855. {
  206856. if (! hasCreatedCaret)
  206857. {
  206858. hasCreatedCaret = true;
  206859. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206860. }
  206861. ShowCaret (hwnd);
  206862. SetCaretPos (0, 0);
  206863. }
  206864. void repaint (const Rectangle<int>& area)
  206865. {
  206866. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  206867. InvalidateRect (hwnd, &r, FALSE);
  206868. }
  206869. void performAnyPendingRepaintsNow()
  206870. {
  206871. MSG m;
  206872. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206873. DispatchMessage (&m);
  206874. }
  206875. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206876. {
  206877. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206878. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  206879. return 0;
  206880. }
  206881. void setTaskBarIcon (const Image& image)
  206882. {
  206883. if (image.isValid())
  206884. {
  206885. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  206886. if (taskBarIcon == 0)
  206887. {
  206888. taskBarIcon = new NOTIFYICONDATA();
  206889. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206890. taskBarIcon->hWnd = (HWND) hwnd;
  206891. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206892. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206893. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206894. taskBarIcon->hIcon = hicon;
  206895. taskBarIcon->szTip[0] = 0;
  206896. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206897. }
  206898. else
  206899. {
  206900. HICON oldIcon = taskBarIcon->hIcon;
  206901. taskBarIcon->hIcon = hicon;
  206902. taskBarIcon->uFlags = NIF_ICON;
  206903. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206904. DestroyIcon (oldIcon);
  206905. }
  206906. DestroyIcon (hicon);
  206907. }
  206908. else if (taskBarIcon != 0)
  206909. {
  206910. taskBarIcon->uFlags = 0;
  206911. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206912. DestroyIcon (taskBarIcon->hIcon);
  206913. taskBarIcon = 0;
  206914. }
  206915. }
  206916. void setTaskBarIconToolTip (const String& toolTip) const
  206917. {
  206918. if (taskBarIcon != 0)
  206919. {
  206920. taskBarIcon->uFlags = NIF_TIP;
  206921. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206922. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206923. }
  206924. }
  206925. bool isInside (HWND h) const
  206926. {
  206927. return GetAncestor (hwnd, GA_ROOT) == h;
  206928. }
  206929. static void updateKeyModifiers() throw()
  206930. {
  206931. int keyMods = 0;
  206932. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  206933. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  206934. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  206935. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  206936. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206937. }
  206938. static void updateModifiersFromWParam (const WPARAM wParam)
  206939. {
  206940. int mouseMods = 0;
  206941. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  206942. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  206943. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  206944. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  206945. updateKeyModifiers();
  206946. }
  206947. static int64 getMouseEventTime()
  206948. {
  206949. static int64 eventTimeOffset = 0;
  206950. static DWORD lastMessageTime = 0;
  206951. const DWORD thisMessageTime = GetMessageTime();
  206952. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  206953. {
  206954. lastMessageTime = thisMessageTime;
  206955. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  206956. }
  206957. return eventTimeOffset + thisMessageTime;
  206958. }
  206959. juce_UseDebuggingNewOperator
  206960. bool dontRepaint;
  206961. static ModifierKeys currentModifiers;
  206962. static ModifierKeys modifiersAtLastCallback;
  206963. private:
  206964. HWND hwnd;
  206965. ScopedPointer<DropShadower> shadower;
  206966. RenderingEngineType currentRenderingEngine;
  206967. #if JUCE_DIRECT2D
  206968. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  206969. #endif
  206970. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  206971. BorderSize windowBorder;
  206972. HICON currentWindowIcon;
  206973. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  206974. IDropTarget* dropTarget;
  206975. class TemporaryImage : public Timer
  206976. {
  206977. public:
  206978. TemporaryImage() {}
  206979. ~TemporaryImage() {}
  206980. const Image& getImage (const bool transparent, const int w, const int h)
  206981. {
  206982. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  206983. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  206984. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  206985. startTimer (3000);
  206986. return image;
  206987. }
  206988. void timerCallback()
  206989. {
  206990. stopTimer();
  206991. image = Image::null;
  206992. }
  206993. private:
  206994. Image image;
  206995. TemporaryImage (const TemporaryImage&);
  206996. TemporaryImage& operator= (const TemporaryImage&);
  206997. };
  206998. TemporaryImage offscreenImageGenerator;
  206999. class WindowClassHolder : public DeletedAtShutdown
  207000. {
  207001. public:
  207002. WindowClassHolder()
  207003. : windowClassName ("JUCE_")
  207004. {
  207005. // this name has to be different for each app/dll instance because otherwise
  207006. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207007. // window class).
  207008. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207009. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207010. TCHAR moduleFile [1024];
  207011. moduleFile[0] = 0;
  207012. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207013. WORD iconNum = 0;
  207014. WNDCLASSEX wcex;
  207015. wcex.cbSize = sizeof (wcex);
  207016. wcex.style = CS_OWNDC;
  207017. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207018. wcex.lpszClassName = windowClassName;
  207019. wcex.cbClsExtra = 0;
  207020. wcex.cbWndExtra = 32;
  207021. wcex.hInstance = moduleHandle;
  207022. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207023. iconNum = 1;
  207024. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207025. wcex.hCursor = 0;
  207026. wcex.hbrBackground = 0;
  207027. wcex.lpszMenuName = 0;
  207028. RegisterClassEx (&wcex);
  207029. }
  207030. ~WindowClassHolder()
  207031. {
  207032. if (ComponentPeer::getNumPeers() == 0)
  207033. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207034. clearSingletonInstance();
  207035. }
  207036. String windowClassName;
  207037. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207038. };
  207039. static void* createWindowCallback (void* userData)
  207040. {
  207041. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207042. return 0;
  207043. }
  207044. void createWindow()
  207045. {
  207046. DWORD exstyle = WS_EX_ACCEPTFILES;
  207047. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207048. if (hasTitleBar())
  207049. {
  207050. type |= WS_OVERLAPPED;
  207051. if ((styleFlags & windowHasCloseButton) != 0)
  207052. {
  207053. type |= WS_SYSMENU;
  207054. }
  207055. else
  207056. {
  207057. // annoyingly, windows won't let you have a min/max button without a close button
  207058. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207059. }
  207060. if ((styleFlags & windowIsResizable) != 0)
  207061. type |= WS_THICKFRAME;
  207062. }
  207063. else
  207064. {
  207065. type |= WS_POPUP | WS_SYSMENU;
  207066. }
  207067. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207068. exstyle |= WS_EX_TOOLWINDOW;
  207069. else
  207070. exstyle |= WS_EX_APPWINDOW;
  207071. if ((styleFlags & windowHasMinimiseButton) != 0)
  207072. type |= WS_MINIMIZEBOX;
  207073. if ((styleFlags & windowHasMaximiseButton) != 0)
  207074. type |= WS_MAXIMIZEBOX;
  207075. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207076. exstyle |= WS_EX_TRANSPARENT;
  207077. if ((styleFlags & windowIsSemiTransparent) != 0
  207078. && Desktop::canUseSemiTransparentWindows())
  207079. exstyle |= WS_EX_LAYERED;
  207080. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  207081. #if JUCE_DIRECT2D
  207082. updateDirect2DContext();
  207083. #endif
  207084. if (hwnd != 0)
  207085. {
  207086. SetWindowLongPtr (hwnd, 0, 0);
  207087. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207088. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207089. if (dropTarget == 0)
  207090. dropTarget = new JuceDropTarget (this);
  207091. RegisterDragDrop (hwnd, dropTarget);
  207092. updateBorderSize();
  207093. // Calling this function here is (for some reason) necessary to make Windows
  207094. // correctly enable the menu items that we specify in the wm_initmenu message.
  207095. GetSystemMenu (hwnd, false);
  207096. }
  207097. else
  207098. {
  207099. jassertfalse;
  207100. }
  207101. }
  207102. static void* destroyWindowCallback (void* handle)
  207103. {
  207104. RevokeDragDrop ((HWND) handle);
  207105. DestroyWindow ((HWND) handle);
  207106. return 0;
  207107. }
  207108. static void* toFrontCallback1 (void* h)
  207109. {
  207110. SetForegroundWindow ((HWND) h);
  207111. return 0;
  207112. }
  207113. static void* toFrontCallback2 (void* h)
  207114. {
  207115. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207116. return 0;
  207117. }
  207118. static void* setFocusCallback (void* h)
  207119. {
  207120. SetFocus ((HWND) h);
  207121. return 0;
  207122. }
  207123. static void* getFocusCallback (void*)
  207124. {
  207125. return GetFocus();
  207126. }
  207127. void offsetWithinParent (int& x, int& y) const
  207128. {
  207129. if (isTransparent())
  207130. {
  207131. HWND parentHwnd = GetParent (hwnd);
  207132. if (parentHwnd != 0)
  207133. {
  207134. RECT parentRect;
  207135. GetWindowRect (parentHwnd, &parentRect);
  207136. x += parentRect.left;
  207137. y += parentRect.top;
  207138. }
  207139. }
  207140. }
  207141. bool isTransparent() const
  207142. {
  207143. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207144. }
  207145. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207146. void setIcon (const Image& newIcon)
  207147. {
  207148. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207149. if (hicon != 0)
  207150. {
  207151. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207152. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207153. if (currentWindowIcon != 0)
  207154. DestroyIcon (currentWindowIcon);
  207155. currentWindowIcon = hicon;
  207156. }
  207157. }
  207158. void handlePaintMessage()
  207159. {
  207160. #if JUCE_DIRECT2D
  207161. if (direct2DContext != 0)
  207162. {
  207163. RECT r;
  207164. if (GetUpdateRect (hwnd, &r, false))
  207165. {
  207166. direct2DContext->start();
  207167. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207168. handlePaint (*direct2DContext);
  207169. direct2DContext->end();
  207170. }
  207171. }
  207172. else
  207173. #endif
  207174. {
  207175. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207176. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207177. PAINTSTRUCT paintStruct;
  207178. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207179. // message and become re-entrant, but that's OK
  207180. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207181. // corrupt the image it's using to paint into, so do a check here.
  207182. static bool reentrant = false;
  207183. if (reentrant)
  207184. {
  207185. DeleteObject (rgn);
  207186. EndPaint (hwnd, &paintStruct);
  207187. return;
  207188. }
  207189. reentrant = true;
  207190. // this is the rectangle to update..
  207191. int x = paintStruct.rcPaint.left;
  207192. int y = paintStruct.rcPaint.top;
  207193. int w = paintStruct.rcPaint.right - x;
  207194. int h = paintStruct.rcPaint.bottom - y;
  207195. const bool transparent = isTransparent();
  207196. if (transparent)
  207197. {
  207198. // it's not possible to have a transparent window with a title bar at the moment!
  207199. jassert (! hasTitleBar());
  207200. RECT r;
  207201. GetWindowRect (hwnd, &r);
  207202. x = y = 0;
  207203. w = r.right - r.left;
  207204. h = r.bottom - r.top;
  207205. }
  207206. if (w > 0 && h > 0)
  207207. {
  207208. clearMaskedRegion();
  207209. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207210. RectangleList contextClip;
  207211. const Rectangle<int> clipBounds (0, 0, w, h);
  207212. bool needToPaintAll = true;
  207213. if (regionType == COMPLEXREGION && ! transparent)
  207214. {
  207215. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207216. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207217. DeleteObject (clipRgn);
  207218. char rgnData [8192];
  207219. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207220. if (res > 0 && res <= sizeof (rgnData))
  207221. {
  207222. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207223. if (hdr->iType == RDH_RECTANGLES
  207224. && hdr->rcBound.right - hdr->rcBound.left >= w
  207225. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207226. {
  207227. needToPaintAll = false;
  207228. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207229. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207230. while (--num >= 0)
  207231. {
  207232. if (rects->right <= x + w && rects->bottom <= y + h)
  207233. {
  207234. // (need to move this one pixel to the left because of a win32 bug)
  207235. const int cx = jmax (x, (int) rects->left - 1);
  207236. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207237. .getIntersection (clipBounds));
  207238. }
  207239. else
  207240. {
  207241. needToPaintAll = true;
  207242. break;
  207243. }
  207244. ++rects;
  207245. }
  207246. }
  207247. }
  207248. }
  207249. if (needToPaintAll)
  207250. {
  207251. contextClip.clear();
  207252. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207253. }
  207254. if (transparent)
  207255. {
  207256. RectangleList::Iterator i (contextClip);
  207257. while (i.next())
  207258. offscreenImage.clear (*i.getRectangle());
  207259. }
  207260. // if the component's not opaque, this won't draw properly unless the platform can support this
  207261. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207262. updateCurrentModifiers();
  207263. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207264. handlePaint (context);
  207265. if (! dontRepaint)
  207266. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207267. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207268. }
  207269. DeleteObject (rgn);
  207270. EndPaint (hwnd, &paintStruct);
  207271. reentrant = false;
  207272. }
  207273. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207274. _fpreset(); // because some graphics cards can unmask FP exceptions
  207275. #endif
  207276. lastPaintTime = Time::getMillisecondCounter();
  207277. }
  207278. void doMouseEvent (const Point<int>& position)
  207279. {
  207280. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207281. }
  207282. const StringArray getAvailableRenderingEngines()
  207283. {
  207284. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207285. #if JUCE_DIRECT2D
  207286. // xxx is this correct? Seems to enable it on Vista too??
  207287. OSVERSIONINFO info;
  207288. zerostruct (info);
  207289. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207290. GetVersionEx (&info);
  207291. if (info.dwMajorVersion >= 6)
  207292. s.add ("Direct2D");
  207293. #endif
  207294. return s;
  207295. }
  207296. int getCurrentRenderingEngine() throw()
  207297. {
  207298. return currentRenderingEngine;
  207299. }
  207300. #if JUCE_DIRECT2D
  207301. void updateDirect2DContext()
  207302. {
  207303. if (currentRenderingEngine != direct2DRenderingEngine)
  207304. direct2DContext = 0;
  207305. else if (direct2DContext == 0)
  207306. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207307. }
  207308. #endif
  207309. void setCurrentRenderingEngine (int index)
  207310. {
  207311. (void) index;
  207312. #if JUCE_DIRECT2D
  207313. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207314. updateDirect2DContext();
  207315. repaint (component->getLocalBounds());
  207316. #endif
  207317. }
  207318. void doMouseMove (const Point<int>& position)
  207319. {
  207320. if (! isMouseOver)
  207321. {
  207322. isMouseOver = true;
  207323. updateKeyModifiers();
  207324. TRACKMOUSEEVENT tme;
  207325. tme.cbSize = sizeof (tme);
  207326. tme.dwFlags = TME_LEAVE;
  207327. tme.hwndTrack = hwnd;
  207328. tme.dwHoverTime = 0;
  207329. if (! TrackMouseEvent (&tme))
  207330. jassertfalse;
  207331. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207332. }
  207333. else if (! isDragging)
  207334. {
  207335. if (! contains (position, false))
  207336. return;
  207337. }
  207338. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207339. static uint32 lastMouseTime = 0;
  207340. const uint32 now = Time::getMillisecondCounter();
  207341. const int maxMouseMovesPerSecond = 60;
  207342. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207343. {
  207344. lastMouseTime = now;
  207345. doMouseEvent (position);
  207346. }
  207347. }
  207348. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207349. {
  207350. if (GetCapture() != hwnd)
  207351. SetCapture (hwnd);
  207352. doMouseMove (position);
  207353. updateModifiersFromWParam (wParam);
  207354. isDragging = true;
  207355. doMouseEvent (position);
  207356. }
  207357. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207358. {
  207359. updateModifiersFromWParam (wParam);
  207360. isDragging = false;
  207361. // release the mouse capture if the user has released all buttons
  207362. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207363. ReleaseCapture();
  207364. doMouseEvent (position);
  207365. }
  207366. void doCaptureChanged()
  207367. {
  207368. if (isDragging)
  207369. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207370. }
  207371. void doMouseExit()
  207372. {
  207373. isMouseOver = false;
  207374. doMouseEvent (getCurrentMousePos());
  207375. }
  207376. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207377. {
  207378. updateKeyModifiers();
  207379. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207380. handleMouseWheel (0, position, getMouseEventTime(),
  207381. isVertical ? 0.0f : amount,
  207382. isVertical ? amount : 0.0f);
  207383. }
  207384. void sendModifierKeyChangeIfNeeded()
  207385. {
  207386. if (modifiersAtLastCallback != currentModifiers)
  207387. {
  207388. modifiersAtLastCallback = currentModifiers;
  207389. handleModifierKeysChange();
  207390. }
  207391. }
  207392. bool doKeyUp (const WPARAM key)
  207393. {
  207394. updateKeyModifiers();
  207395. switch (key)
  207396. {
  207397. case VK_SHIFT:
  207398. case VK_CONTROL:
  207399. case VK_MENU:
  207400. case VK_CAPITAL:
  207401. case VK_LWIN:
  207402. case VK_RWIN:
  207403. case VK_APPS:
  207404. case VK_NUMLOCK:
  207405. case VK_SCROLL:
  207406. case VK_LSHIFT:
  207407. case VK_RSHIFT:
  207408. case VK_LCONTROL:
  207409. case VK_LMENU:
  207410. case VK_RCONTROL:
  207411. case VK_RMENU:
  207412. sendModifierKeyChangeIfNeeded();
  207413. }
  207414. return handleKeyUpOrDown (false)
  207415. || Component::getCurrentlyModalComponent() != 0;
  207416. }
  207417. bool doKeyDown (const WPARAM key)
  207418. {
  207419. updateKeyModifiers();
  207420. bool used = false;
  207421. switch (key)
  207422. {
  207423. case VK_SHIFT:
  207424. case VK_LSHIFT:
  207425. case VK_RSHIFT:
  207426. case VK_CONTROL:
  207427. case VK_LCONTROL:
  207428. case VK_RCONTROL:
  207429. case VK_MENU:
  207430. case VK_LMENU:
  207431. case VK_RMENU:
  207432. case VK_LWIN:
  207433. case VK_RWIN:
  207434. case VK_CAPITAL:
  207435. case VK_NUMLOCK:
  207436. case VK_SCROLL:
  207437. case VK_APPS:
  207438. sendModifierKeyChangeIfNeeded();
  207439. break;
  207440. case VK_LEFT:
  207441. case VK_RIGHT:
  207442. case VK_UP:
  207443. case VK_DOWN:
  207444. case VK_PRIOR:
  207445. case VK_NEXT:
  207446. case VK_HOME:
  207447. case VK_END:
  207448. case VK_DELETE:
  207449. case VK_INSERT:
  207450. case VK_F1:
  207451. case VK_F2:
  207452. case VK_F3:
  207453. case VK_F4:
  207454. case VK_F5:
  207455. case VK_F6:
  207456. case VK_F7:
  207457. case VK_F8:
  207458. case VK_F9:
  207459. case VK_F10:
  207460. case VK_F11:
  207461. case VK_F12:
  207462. case VK_F13:
  207463. case VK_F14:
  207464. case VK_F15:
  207465. case VK_F16:
  207466. used = handleKeyUpOrDown (true);
  207467. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207468. break;
  207469. case VK_ADD:
  207470. case VK_SUBTRACT:
  207471. case VK_MULTIPLY:
  207472. case VK_DIVIDE:
  207473. case VK_SEPARATOR:
  207474. case VK_DECIMAL:
  207475. used = handleKeyUpOrDown (true);
  207476. break;
  207477. default:
  207478. used = handleKeyUpOrDown (true);
  207479. {
  207480. MSG msg;
  207481. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207482. {
  207483. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207484. // manually generate the key-press event that matches this key-down.
  207485. const UINT keyChar = MapVirtualKey (key, 2);
  207486. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207487. }
  207488. }
  207489. break;
  207490. }
  207491. if (Component::getCurrentlyModalComponent() != 0)
  207492. used = true;
  207493. return used;
  207494. }
  207495. bool doKeyChar (int key, const LPARAM flags)
  207496. {
  207497. updateKeyModifiers();
  207498. juce_wchar textChar = (juce_wchar) key;
  207499. const int virtualScanCode = (flags >> 16) & 0xff;
  207500. if (key >= '0' && key <= '9')
  207501. {
  207502. switch (virtualScanCode) // check for a numeric keypad scan-code
  207503. {
  207504. case 0x52:
  207505. case 0x4f:
  207506. case 0x50:
  207507. case 0x51:
  207508. case 0x4b:
  207509. case 0x4c:
  207510. case 0x4d:
  207511. case 0x47:
  207512. case 0x48:
  207513. case 0x49:
  207514. key = (key - '0') + KeyPress::numberPad0;
  207515. break;
  207516. default:
  207517. break;
  207518. }
  207519. }
  207520. else
  207521. {
  207522. // convert the scan code to an unmodified character code..
  207523. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207524. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207525. keyChar = LOWORD (keyChar);
  207526. if (keyChar != 0)
  207527. key = (int) keyChar;
  207528. // avoid sending junk text characters for some control-key combinations
  207529. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207530. textChar = 0;
  207531. }
  207532. return handleKeyPress (key, textChar);
  207533. }
  207534. bool doAppCommand (const LPARAM lParam)
  207535. {
  207536. int key = 0;
  207537. switch (GET_APPCOMMAND_LPARAM (lParam))
  207538. {
  207539. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207540. key = KeyPress::playKey;
  207541. break;
  207542. case APPCOMMAND_MEDIA_STOP:
  207543. key = KeyPress::stopKey;
  207544. break;
  207545. case APPCOMMAND_MEDIA_NEXTTRACK:
  207546. key = KeyPress::fastForwardKey;
  207547. break;
  207548. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207549. key = KeyPress::rewindKey;
  207550. break;
  207551. }
  207552. if (key != 0)
  207553. {
  207554. updateKeyModifiers();
  207555. if (hwnd == GetActiveWindow())
  207556. {
  207557. handleKeyPress (key, 0);
  207558. return true;
  207559. }
  207560. }
  207561. return false;
  207562. }
  207563. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207564. {
  207565. public:
  207566. JuceDropTarget (Win32ComponentPeer* const owner_)
  207567. : owner (owner_)
  207568. {
  207569. }
  207570. ~JuceDropTarget() {}
  207571. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207572. {
  207573. updateFileList (pDataObject);
  207574. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207575. *pdwEffect = DROPEFFECT_COPY;
  207576. return S_OK;
  207577. }
  207578. HRESULT __stdcall DragLeave()
  207579. {
  207580. owner->handleFileDragExit (files);
  207581. return S_OK;
  207582. }
  207583. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207584. {
  207585. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207586. *pdwEffect = DROPEFFECT_COPY;
  207587. return S_OK;
  207588. }
  207589. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207590. {
  207591. updateFileList (pDataObject);
  207592. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207593. *pdwEffect = DROPEFFECT_COPY;
  207594. return S_OK;
  207595. }
  207596. private:
  207597. Win32ComponentPeer* const owner;
  207598. StringArray files;
  207599. void updateFileList (IDataObject* const pDataObject)
  207600. {
  207601. files.clear();
  207602. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207603. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207604. if (pDataObject->GetData (&format, &medium) == S_OK)
  207605. {
  207606. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207607. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207608. unsigned int i = 0;
  207609. if (pDropFiles->fWide)
  207610. {
  207611. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207612. for (;;)
  207613. {
  207614. unsigned int len = 0;
  207615. while (i + len < totalLen && fname [i + len] != 0)
  207616. ++len;
  207617. if (len == 0)
  207618. break;
  207619. files.add (String (fname + i, len));
  207620. i += len + 1;
  207621. }
  207622. }
  207623. else
  207624. {
  207625. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207626. for (;;)
  207627. {
  207628. unsigned int len = 0;
  207629. while (i + len < totalLen && fname [i + len] != 0)
  207630. ++len;
  207631. if (len == 0)
  207632. break;
  207633. files.add (String (fname + i, len));
  207634. i += len + 1;
  207635. }
  207636. }
  207637. GlobalUnlock (medium.hGlobal);
  207638. }
  207639. }
  207640. JuceDropTarget (const JuceDropTarget&);
  207641. JuceDropTarget& operator= (const JuceDropTarget&);
  207642. };
  207643. void doSettingChange()
  207644. {
  207645. Desktop::getInstance().refreshMonitorSizes();
  207646. if (fullScreen && ! isMinimised())
  207647. {
  207648. const Rectangle<int> r (component->getParentMonitorArea());
  207649. SetWindowPos (hwnd, 0,
  207650. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207651. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207652. }
  207653. }
  207654. public:
  207655. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207656. {
  207657. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207658. if (peer != 0)
  207659. return peer->peerWindowProc (h, message, wParam, lParam);
  207660. return DefWindowProcW (h, message, wParam, lParam);
  207661. }
  207662. private:
  207663. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207664. {
  207665. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207666. }
  207667. const Point<int> getCurrentMousePos() throw()
  207668. {
  207669. RECT wr;
  207670. GetWindowRect (hwnd, &wr);
  207671. const DWORD mp = GetMessagePos();
  207672. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207673. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207674. }
  207675. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207676. {
  207677. if (isValidPeer (this))
  207678. {
  207679. switch (message)
  207680. {
  207681. case WM_NCHITTEST:
  207682. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207683. return HTTRANSPARENT;
  207684. if (hasTitleBar())
  207685. break;
  207686. return HTCLIENT;
  207687. case WM_PAINT:
  207688. handlePaintMessage();
  207689. return 0;
  207690. case WM_NCPAINT:
  207691. if (wParam != 1)
  207692. handlePaintMessage();
  207693. if (hasTitleBar())
  207694. break;
  207695. return 0;
  207696. case WM_ERASEBKGND:
  207697. case WM_NCCALCSIZE:
  207698. if (hasTitleBar())
  207699. break;
  207700. return 1;
  207701. case WM_MOUSEMOVE:
  207702. doMouseMove (getPointFromLParam (lParam));
  207703. return 0;
  207704. case WM_MOUSELEAVE:
  207705. doMouseExit();
  207706. return 0;
  207707. case WM_LBUTTONDOWN:
  207708. case WM_MBUTTONDOWN:
  207709. case WM_RBUTTONDOWN:
  207710. doMouseDown (getPointFromLParam (lParam), wParam);
  207711. return 0;
  207712. case WM_LBUTTONUP:
  207713. case WM_MBUTTONUP:
  207714. case WM_RBUTTONUP:
  207715. doMouseUp (getPointFromLParam (lParam), wParam);
  207716. return 0;
  207717. case WM_CAPTURECHANGED:
  207718. doCaptureChanged();
  207719. return 0;
  207720. case WM_NCMOUSEMOVE:
  207721. if (hasTitleBar())
  207722. break;
  207723. return 0;
  207724. case 0x020A: /* WM_MOUSEWHEEL */
  207725. doMouseWheel (getCurrentMousePos(), wParam, true);
  207726. return 0;
  207727. case 0x020E: /* WM_MOUSEHWHEEL */
  207728. doMouseWheel (getCurrentMousePos(), wParam, false);
  207729. return 0;
  207730. case WM_WINDOWPOSCHANGING:
  207731. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207732. {
  207733. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  207734. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  207735. {
  207736. if (constrainer != 0)
  207737. {
  207738. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  207739. component->getY() - windowBorder.getTop(),
  207740. component->getWidth() + windowBorder.getLeftAndRight(),
  207741. component->getHeight() + windowBorder.getTopAndBottom());
  207742. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207743. constrainer->checkBounds (pos, current,
  207744. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207745. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207746. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207747. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207748. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207749. wp->x = pos.getX();
  207750. wp->y = pos.getY();
  207751. wp->cx = pos.getWidth();
  207752. wp->cy = pos.getHeight();
  207753. }
  207754. }
  207755. }
  207756. return 0;
  207757. case WM_WINDOWPOSCHANGED:
  207758. handleMovedOrResized();
  207759. if (dontRepaint)
  207760. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207761. return 0;
  207762. case WM_KEYDOWN:
  207763. case WM_SYSKEYDOWN:
  207764. if (doKeyDown (wParam))
  207765. return 0;
  207766. break;
  207767. case WM_KEYUP:
  207768. case WM_SYSKEYUP:
  207769. if (doKeyUp (wParam))
  207770. return 0;
  207771. break;
  207772. case WM_CHAR:
  207773. if (doKeyChar ((int) wParam, lParam))
  207774. return 0;
  207775. break;
  207776. case WM_APPCOMMAND:
  207777. if (doAppCommand (lParam))
  207778. return TRUE;
  207779. break;
  207780. case WM_SETFOCUS:
  207781. updateKeyModifiers();
  207782. handleFocusGain();
  207783. break;
  207784. case WM_KILLFOCUS:
  207785. if (hasCreatedCaret)
  207786. {
  207787. hasCreatedCaret = false;
  207788. DestroyCaret();
  207789. }
  207790. handleFocusLoss();
  207791. break;
  207792. case WM_ACTIVATEAPP:
  207793. // Windows does weird things to process priority when you swap apps,
  207794. // so this forces an update when the app is brought to the front
  207795. if (wParam != FALSE)
  207796. juce_repeatLastProcessPriority();
  207797. else
  207798. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  207799. juce_CheckCurrentlyFocusedTopLevelWindow();
  207800. modifiersAtLastCallback = -1;
  207801. return 0;
  207802. case WM_ACTIVATE:
  207803. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207804. {
  207805. modifiersAtLastCallback = -1;
  207806. updateKeyModifiers();
  207807. if (isMinimised())
  207808. {
  207809. component->repaint();
  207810. handleMovedOrResized();
  207811. if (! ComponentPeer::isValidPeer (this))
  207812. return 0;
  207813. }
  207814. if (LOWORD (wParam) == WA_CLICKACTIVE
  207815. && component->isCurrentlyBlockedByAnotherModalComponent())
  207816. {
  207817. const Point<int> mousePos (component->getMouseXYRelative());
  207818. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  207819. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207820. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207821. return 0;
  207822. }
  207823. handleBroughtToFront();
  207824. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207825. Component::getCurrentlyModalComponent()->toFront (true);
  207826. return 0;
  207827. }
  207828. break;
  207829. case WM_NCACTIVATE:
  207830. // while a temporary window is being shown, prevent Windows from deactivating the
  207831. // title bars of our main windows.
  207832. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207833. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207834. break;
  207835. case WM_MOUSEACTIVATE:
  207836. if (! component->getMouseClickGrabsKeyboardFocus())
  207837. return MA_NOACTIVATE;
  207838. break;
  207839. case WM_SHOWWINDOW:
  207840. if (wParam != 0)
  207841. handleBroughtToFront();
  207842. break;
  207843. case WM_CLOSE:
  207844. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  207845. handleUserClosingWindow();
  207846. return 0;
  207847. case WM_QUERYENDSESSION:
  207848. if (JUCEApplication::getInstance() != 0)
  207849. {
  207850. JUCEApplication::getInstance()->systemRequestedQuit();
  207851. return MessageManager::getInstance()->hasStopMessageBeenSent();
  207852. }
  207853. return TRUE;
  207854. case WM_TRAYNOTIFY:
  207855. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207856. {
  207857. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207858. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207859. {
  207860. Component* const current = Component::getCurrentlyModalComponent();
  207861. if (current != 0)
  207862. current->inputAttemptWhenModal();
  207863. }
  207864. }
  207865. else
  207866. {
  207867. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207868. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207869. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207870. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207871. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207872. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207873. eventMods = eventMods.withoutMouseButtons();
  207874. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207875. Point<int>(), eventMods, component, component, getMouseEventTime(),
  207876. Point<int>(), getMouseEventTime(), 1, false);
  207877. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207878. {
  207879. SetFocus (hwnd);
  207880. SetForegroundWindow (hwnd);
  207881. component->mouseDown (e);
  207882. }
  207883. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207884. {
  207885. component->mouseUp (e);
  207886. }
  207887. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207888. {
  207889. component->mouseDoubleClick (e);
  207890. }
  207891. else if (lParam == WM_MOUSEMOVE)
  207892. {
  207893. component->mouseMove (e);
  207894. }
  207895. }
  207896. break;
  207897. case WM_SYNCPAINT:
  207898. return 0;
  207899. case WM_PALETTECHANGED:
  207900. InvalidateRect (h, 0, 0);
  207901. break;
  207902. case WM_DISPLAYCHANGE:
  207903. InvalidateRect (h, 0, 0);
  207904. createPaletteIfNeeded = true;
  207905. // intentional fall-through...
  207906. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207907. doSettingChange();
  207908. break;
  207909. case WM_INITMENU:
  207910. if (! hasTitleBar())
  207911. {
  207912. if (isFullScreen())
  207913. {
  207914. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207915. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207916. }
  207917. else if (! isMinimised())
  207918. {
  207919. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207920. }
  207921. }
  207922. break;
  207923. case WM_SYSCOMMAND:
  207924. switch (wParam & 0xfff0)
  207925. {
  207926. case SC_CLOSE:
  207927. if (sendInputAttemptWhenModalMessage())
  207928. return 0;
  207929. if (hasTitleBar())
  207930. {
  207931. PostMessage (h, WM_CLOSE, 0, 0);
  207932. return 0;
  207933. }
  207934. break;
  207935. case SC_KEYMENU:
  207936. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  207937. // obscure situations that can arise if a modal loop is started from an alt-key
  207938. // keypress).
  207939. if (hasTitleBar() && h == GetCapture())
  207940. ReleaseCapture();
  207941. break;
  207942. case SC_MAXIMIZE:
  207943. if (sendInputAttemptWhenModalMessage())
  207944. return 0;
  207945. setFullScreen (true);
  207946. return 0;
  207947. case SC_MINIMIZE:
  207948. if (sendInputAttemptWhenModalMessage())
  207949. return 0;
  207950. if (! hasTitleBar())
  207951. {
  207952. setMinimised (true);
  207953. return 0;
  207954. }
  207955. break;
  207956. case SC_RESTORE:
  207957. if (sendInputAttemptWhenModalMessage())
  207958. return 0;
  207959. if (hasTitleBar())
  207960. {
  207961. if (isFullScreen())
  207962. {
  207963. setFullScreen (false);
  207964. return 0;
  207965. }
  207966. }
  207967. else
  207968. {
  207969. if (isMinimised())
  207970. setMinimised (false);
  207971. else if (isFullScreen())
  207972. setFullScreen (false);
  207973. return 0;
  207974. }
  207975. break;
  207976. }
  207977. break;
  207978. case WM_NCLBUTTONDOWN:
  207979. case WM_NCRBUTTONDOWN:
  207980. case WM_NCMBUTTONDOWN:
  207981. sendInputAttemptWhenModalMessage();
  207982. break;
  207983. //case WM_IME_STARTCOMPOSITION;
  207984. // return 0;
  207985. case WM_GETDLGCODE:
  207986. return DLGC_WANTALLKEYS;
  207987. default:
  207988. break;
  207989. }
  207990. }
  207991. return DefWindowProcW (h, message, wParam, lParam);
  207992. }
  207993. bool sendInputAttemptWhenModalMessage()
  207994. {
  207995. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207996. {
  207997. Component* const current = Component::getCurrentlyModalComponent();
  207998. if (current != 0)
  207999. current->inputAttemptWhenModal();
  208000. return true;
  208001. }
  208002. return false;
  208003. }
  208004. Win32ComponentPeer (const Win32ComponentPeer&);
  208005. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208006. };
  208007. ModifierKeys Win32ComponentPeer::currentModifiers;
  208008. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208009. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  208010. {
  208011. return new Win32ComponentPeer (this, styleFlags);
  208012. }
  208013. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208014. void ModifierKeys::updateCurrentModifiers() throw()
  208015. {
  208016. currentModifiers = Win32ComponentPeer::currentModifiers;
  208017. }
  208018. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208019. {
  208020. Win32ComponentPeer::updateKeyModifiers();
  208021. int keyMods = 0;
  208022. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  208023. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  208024. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  208025. Win32ComponentPeer::currentModifiers
  208026. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  208027. return Win32ComponentPeer::currentModifiers;
  208028. }
  208029. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208030. {
  208031. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208032. if (wp != 0)
  208033. wp->setTaskBarIcon (newImage);
  208034. }
  208035. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208036. {
  208037. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208038. if (wp != 0)
  208039. wp->setTaskBarIconToolTip (tooltip);
  208040. }
  208041. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208042. {
  208043. DWORD val = GetWindowLong (h, styleType);
  208044. if (bitIsSet)
  208045. val |= feature;
  208046. else
  208047. val &= ~feature;
  208048. SetWindowLongPtr (h, styleType, val);
  208049. SetWindowPos (h, 0, 0, 0, 0, 0,
  208050. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208051. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208052. }
  208053. bool Process::isForegroundProcess()
  208054. {
  208055. HWND fg = GetForegroundWindow();
  208056. if (fg == 0)
  208057. return true;
  208058. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208059. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208060. // have to see if any of our windows are children of the foreground window
  208061. fg = GetAncestor (fg, GA_ROOT);
  208062. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208063. {
  208064. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208065. if (wp != 0 && wp->isInside (fg))
  208066. return true;
  208067. }
  208068. return false;
  208069. }
  208070. bool AlertWindow::showNativeDialogBox (const String& title,
  208071. const String& bodyText,
  208072. bool isOkCancel)
  208073. {
  208074. return MessageBox (0, bodyText, title,
  208075. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208076. : MB_OK)) == IDOK;
  208077. }
  208078. void Desktop::createMouseInputSources()
  208079. {
  208080. mouseSources.add (new MouseInputSource (0, true));
  208081. }
  208082. const Point<int> Desktop::getMousePosition()
  208083. {
  208084. POINT mousePos;
  208085. GetCursorPos (&mousePos);
  208086. return Point<int> (mousePos.x, mousePos.y);
  208087. }
  208088. void Desktop::setMousePosition (const Point<int>& newPosition)
  208089. {
  208090. SetCursorPos (newPosition.getX(), newPosition.getY());
  208091. }
  208092. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208093. {
  208094. return createSoftwareImage (format, width, height, clearImage);
  208095. }
  208096. class ScreenSaverDefeater : public Timer,
  208097. public DeletedAtShutdown
  208098. {
  208099. public:
  208100. ScreenSaverDefeater()
  208101. {
  208102. startTimer (10000);
  208103. timerCallback();
  208104. }
  208105. ~ScreenSaverDefeater() {}
  208106. void timerCallback()
  208107. {
  208108. if (Process::isForegroundProcess())
  208109. {
  208110. // simulate a shift key getting pressed..
  208111. INPUT input[2];
  208112. input[0].type = INPUT_KEYBOARD;
  208113. input[0].ki.wVk = VK_SHIFT;
  208114. input[0].ki.dwFlags = 0;
  208115. input[0].ki.dwExtraInfo = 0;
  208116. input[1].type = INPUT_KEYBOARD;
  208117. input[1].ki.wVk = VK_SHIFT;
  208118. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208119. input[1].ki.dwExtraInfo = 0;
  208120. SendInput (2, input, sizeof (INPUT));
  208121. }
  208122. }
  208123. };
  208124. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208125. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208126. {
  208127. if (isEnabled)
  208128. deleteAndZero (screenSaverDefeater);
  208129. else if (screenSaverDefeater == 0)
  208130. screenSaverDefeater = new ScreenSaverDefeater();
  208131. }
  208132. bool Desktop::isScreenSaverEnabled()
  208133. {
  208134. return screenSaverDefeater == 0;
  208135. }
  208136. /* (The code below is the "correct" way to disable the screen saver, but it
  208137. completely fails on winXP when the saver is password-protected...)
  208138. static bool juce_screenSaverEnabled = true;
  208139. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208140. {
  208141. juce_screenSaverEnabled = isEnabled;
  208142. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208143. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208144. }
  208145. bool Desktop::isScreenSaverEnabled() throw()
  208146. {
  208147. return juce_screenSaverEnabled;
  208148. }
  208149. */
  208150. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208151. {
  208152. if (enableOrDisable)
  208153. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208154. }
  208155. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208156. {
  208157. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208158. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208159. return TRUE;
  208160. }
  208161. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208162. {
  208163. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208164. // make sure the first in the list is the main monitor
  208165. for (int i = 1; i < monitorCoords.size(); ++i)
  208166. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208167. monitorCoords.swap (i, 0);
  208168. if (monitorCoords.size() == 0)
  208169. {
  208170. RECT r;
  208171. GetWindowRect (GetDesktopWindow(), &r);
  208172. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208173. }
  208174. if (clipToWorkArea)
  208175. {
  208176. // clip the main monitor to the active non-taskbar area
  208177. RECT r;
  208178. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208179. Rectangle<int>& screen = monitorCoords.getReference (0);
  208180. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208181. jmax (screen.getY(), (int) r.top));
  208182. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208183. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208184. }
  208185. }
  208186. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  208187. {
  208188. Image im;
  208189. if (bitmap != 0)
  208190. {
  208191. BITMAP bm;
  208192. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208193. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208194. {
  208195. HDC tempDC = GetDC (0);
  208196. HDC dc = CreateCompatibleDC (tempDC);
  208197. ReleaseDC (0, tempDC);
  208198. SelectObject (dc, bitmap);
  208199. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208200. Image::BitmapData imageData (im, true);
  208201. for (int y = bm.bmHeight; --y >= 0;)
  208202. {
  208203. for (int x = bm.bmWidth; --x >= 0;)
  208204. {
  208205. COLORREF col = GetPixel (dc, x, y);
  208206. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  208207. (uint8) GetGValue (col),
  208208. (uint8) GetBValue (col)));
  208209. }
  208210. }
  208211. DeleteDC (dc);
  208212. }
  208213. }
  208214. return im;
  208215. }
  208216. static const Image createImageFromHICON (HICON icon)
  208217. {
  208218. ICONINFO info;
  208219. if (GetIconInfo (icon, &info))
  208220. {
  208221. Image mask (createImageFromHBITMAP (info.hbmMask));
  208222. Image image (createImageFromHBITMAP (info.hbmColor));
  208223. if (mask.isValid() && image.isValid())
  208224. {
  208225. for (int y = image.getHeight(); --y >= 0;)
  208226. {
  208227. for (int x = image.getWidth(); --x >= 0;)
  208228. {
  208229. const float brightness = mask.getPixelAt (x, y).getBrightness();
  208230. if (brightness > 0.0f)
  208231. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  208232. }
  208233. }
  208234. return image;
  208235. }
  208236. }
  208237. return Image::null;
  208238. }
  208239. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  208240. {
  208241. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208242. Image bitmap (nativeBitmap);
  208243. {
  208244. Graphics g (bitmap);
  208245. g.drawImageAt (image, 0, 0);
  208246. }
  208247. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208248. ICONINFO info;
  208249. info.fIcon = isIcon;
  208250. info.xHotspot = hotspotX;
  208251. info.yHotspot = hotspotY;
  208252. info.hbmMask = mask;
  208253. info.hbmColor = nativeBitmap->hBitmap;
  208254. HICON hi = CreateIconIndirect (&info);
  208255. DeleteObject (mask);
  208256. return hi;
  208257. }
  208258. const Image juce_createIconForFile (const File& file)
  208259. {
  208260. Image image;
  208261. WCHAR filename [1024];
  208262. file.getFullPathName().copyToUnicode (filename, 1023);
  208263. WORD iconNum = 0;
  208264. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208265. filename, &iconNum);
  208266. if (icon != 0)
  208267. {
  208268. image = createImageFromHICON (icon);
  208269. DestroyIcon (icon);
  208270. }
  208271. return image;
  208272. }
  208273. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208274. {
  208275. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208276. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208277. Image im (image);
  208278. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208279. {
  208280. im = im.rescaled (maxW, maxH);
  208281. hotspotX = (hotspotX * maxW) / image.getWidth();
  208282. hotspotY = (hotspotY * maxH) / image.getHeight();
  208283. }
  208284. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208285. }
  208286. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208287. {
  208288. if (cursorHandle != 0 && ! isStandard)
  208289. DestroyCursor ((HCURSOR) cursorHandle);
  208290. }
  208291. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208292. {
  208293. LPCTSTR cursorName = IDC_ARROW;
  208294. switch (type)
  208295. {
  208296. case NormalCursor: break;
  208297. case NoCursor: return 0;
  208298. case WaitCursor: cursorName = IDC_WAIT; break;
  208299. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208300. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208301. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208302. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208303. case LeftRightResizeCursor:
  208304. case LeftEdgeResizeCursor:
  208305. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208306. case UpDownResizeCursor:
  208307. case TopEdgeResizeCursor:
  208308. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208309. case TopLeftCornerResizeCursor:
  208310. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208311. case TopRightCornerResizeCursor:
  208312. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208313. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208314. case DraggingHandCursor:
  208315. {
  208316. static void* dragHandCursor = 0;
  208317. if (dragHandCursor == 0)
  208318. {
  208319. static const unsigned char dragHandData[] =
  208320. { 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,
  208321. 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,
  208322. 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 };
  208323. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208324. }
  208325. return dragHandCursor;
  208326. }
  208327. default:
  208328. jassertfalse; break;
  208329. }
  208330. HCURSOR cursorH = LoadCursor (0, cursorName);
  208331. if (cursorH == 0)
  208332. cursorH = LoadCursor (0, IDC_ARROW);
  208333. return cursorH;
  208334. }
  208335. void MouseCursor::showInWindow (ComponentPeer*) const
  208336. {
  208337. SetCursor ((HCURSOR) getHandle());
  208338. }
  208339. void MouseCursor::showInAllWindows() const
  208340. {
  208341. showInWindow (0);
  208342. }
  208343. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208344. {
  208345. public:
  208346. JuceDropSource() {}
  208347. ~JuceDropSource() {}
  208348. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208349. {
  208350. if (escapePressed)
  208351. return DRAGDROP_S_CANCEL;
  208352. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208353. return DRAGDROP_S_DROP;
  208354. return S_OK;
  208355. }
  208356. HRESULT __stdcall GiveFeedback (DWORD)
  208357. {
  208358. return DRAGDROP_S_USEDEFAULTCURSORS;
  208359. }
  208360. };
  208361. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208362. {
  208363. public:
  208364. JuceEnumFormatEtc (const FORMATETC* const format_)
  208365. : format (format_),
  208366. index (0)
  208367. {
  208368. }
  208369. ~JuceEnumFormatEtc() {}
  208370. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208371. {
  208372. if (result == 0)
  208373. return E_POINTER;
  208374. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208375. newOne->index = index;
  208376. *result = newOne;
  208377. return S_OK;
  208378. }
  208379. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208380. {
  208381. if (pceltFetched != 0)
  208382. *pceltFetched = 0;
  208383. else if (celt != 1)
  208384. return S_FALSE;
  208385. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208386. {
  208387. copyFormatEtc (lpFormatEtc [0], *format);
  208388. ++index;
  208389. if (pceltFetched != 0)
  208390. *pceltFetched = 1;
  208391. return S_OK;
  208392. }
  208393. return S_FALSE;
  208394. }
  208395. HRESULT __stdcall Skip (ULONG celt)
  208396. {
  208397. if (index + (int) celt >= 1)
  208398. return S_FALSE;
  208399. index += celt;
  208400. return S_OK;
  208401. }
  208402. HRESULT __stdcall Reset()
  208403. {
  208404. index = 0;
  208405. return S_OK;
  208406. }
  208407. private:
  208408. const FORMATETC* const format;
  208409. int index;
  208410. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208411. {
  208412. dest = source;
  208413. if (source.ptd != 0)
  208414. {
  208415. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208416. *(dest.ptd) = *(source.ptd);
  208417. }
  208418. }
  208419. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208420. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208421. };
  208422. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208423. {
  208424. public:
  208425. JuceDataObject (JuceDropSource* const dropSource_,
  208426. const FORMATETC* const format_,
  208427. const STGMEDIUM* const medium_)
  208428. : dropSource (dropSource_),
  208429. format (format_),
  208430. medium (medium_)
  208431. {
  208432. }
  208433. virtual ~JuceDataObject()
  208434. {
  208435. jassert (refCount == 0);
  208436. }
  208437. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  208438. {
  208439. if ((pFormatEtc->tymed & format->tymed) != 0
  208440. && pFormatEtc->cfFormat == format->cfFormat
  208441. && pFormatEtc->dwAspect == format->dwAspect)
  208442. {
  208443. pMedium->tymed = format->tymed;
  208444. pMedium->pUnkForRelease = 0;
  208445. if (format->tymed == TYMED_HGLOBAL)
  208446. {
  208447. const SIZE_T len = GlobalSize (medium->hGlobal);
  208448. void* const src = GlobalLock (medium->hGlobal);
  208449. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208450. memcpy (dst, src, len);
  208451. GlobalUnlock (medium->hGlobal);
  208452. pMedium->hGlobal = dst;
  208453. return S_OK;
  208454. }
  208455. }
  208456. return DV_E_FORMATETC;
  208457. }
  208458. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  208459. {
  208460. if (f == 0)
  208461. return E_INVALIDARG;
  208462. if (f->tymed == format->tymed
  208463. && f->cfFormat == format->cfFormat
  208464. && f->dwAspect == format->dwAspect)
  208465. return S_OK;
  208466. return DV_E_FORMATETC;
  208467. }
  208468. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  208469. {
  208470. pFormatEtcOut->ptd = 0;
  208471. return E_NOTIMPL;
  208472. }
  208473. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  208474. {
  208475. if (result == 0)
  208476. return E_POINTER;
  208477. if (direction == DATADIR_GET)
  208478. {
  208479. *result = new JuceEnumFormatEtc (format);
  208480. return S_OK;
  208481. }
  208482. *result = 0;
  208483. return E_NOTIMPL;
  208484. }
  208485. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  208486. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  208487. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  208488. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208489. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  208490. private:
  208491. JuceDropSource* const dropSource;
  208492. const FORMATETC* const format;
  208493. const STGMEDIUM* const medium;
  208494. JuceDataObject (const JuceDataObject&);
  208495. JuceDataObject& operator= (const JuceDataObject&);
  208496. };
  208497. static HDROP createHDrop (const StringArray& fileNames)
  208498. {
  208499. int totalChars = 0;
  208500. for (int i = fileNames.size(); --i >= 0;)
  208501. totalChars += fileNames[i].length() + 1;
  208502. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208503. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208504. if (hDrop != 0)
  208505. {
  208506. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208507. pDropFiles->pFiles = sizeof (DROPFILES);
  208508. pDropFiles->fWide = true;
  208509. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  208510. for (int i = 0; i < fileNames.size(); ++i)
  208511. {
  208512. fileNames[i].copyToUnicode (fname, 2048);
  208513. fname += fileNames[i].length() + 1;
  208514. }
  208515. *fname = 0;
  208516. GlobalUnlock (hDrop);
  208517. }
  208518. return hDrop;
  208519. }
  208520. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208521. {
  208522. JuceDropSource* const source = new JuceDropSource();
  208523. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208524. DWORD effect;
  208525. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208526. data->Release();
  208527. source->Release();
  208528. return res == DRAGDROP_S_DROP;
  208529. }
  208530. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208531. {
  208532. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208533. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208534. medium.hGlobal = createHDrop (files);
  208535. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208536. : DROPEFFECT_COPY);
  208537. }
  208538. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208539. {
  208540. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208541. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208542. const int numChars = text.length();
  208543. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208544. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208545. text.copyToUnicode (data, numChars + 1);
  208546. format.cfFormat = CF_UNICODETEXT;
  208547. GlobalUnlock (medium.hGlobal);
  208548. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208549. }
  208550. #endif
  208551. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208552. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208553. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208554. // compiled on its own).
  208555. #if JUCE_INCLUDED_FILE
  208556. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  208557. namespace FileChooserHelpers
  208558. {
  208559. static const void* defaultDirPath = 0;
  208560. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  208561. static Component* currentExtraFileWin = 0;
  208562. static bool areThereAnyAlwaysOnTopWindows()
  208563. {
  208564. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208565. {
  208566. Component* c = Desktop::getInstance().getComponent (i);
  208567. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208568. return true;
  208569. }
  208570. return false;
  208571. }
  208572. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  208573. {
  208574. if (msg == BFFM_INITIALIZED)
  208575. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  208576. else if (msg == BFFM_VALIDATEFAILEDW)
  208577. returnedString = (LPCWSTR) lParam;
  208578. else if (msg == BFFM_VALIDATEFAILEDA)
  208579. returnedString = (const char*) lParam;
  208580. return 0;
  208581. }
  208582. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208583. {
  208584. if (currentExtraFileWin != 0)
  208585. {
  208586. if (uiMsg == WM_INITDIALOG)
  208587. {
  208588. HWND dialogH = GetParent (hdlg);
  208589. jassert (dialogH != 0);
  208590. if (dialogH == 0)
  208591. dialogH = hdlg;
  208592. RECT r, cr;
  208593. GetWindowRect (dialogH, &r);
  208594. GetClientRect (dialogH, &cr);
  208595. SetWindowPos (dialogH, 0,
  208596. r.left, r.top,
  208597. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  208598. jmax (150, (int) (r.bottom - r.top)),
  208599. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208600. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  208601. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  208602. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  208603. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  208604. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  208605. }
  208606. else if (uiMsg == WM_NOTIFY)
  208607. {
  208608. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208609. if (ofn->hdr.code == CDN_SELCHANGE)
  208610. {
  208611. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  208612. if (comp != 0)
  208613. {
  208614. TCHAR path [MAX_PATH * 2];
  208615. path[0] = 0;
  208616. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208617. const String fn ((const WCHAR*) path);
  208618. comp->selectedFileChanged (File (fn));
  208619. }
  208620. }
  208621. }
  208622. }
  208623. return 0;
  208624. }
  208625. class FPComponentHolder : public Component
  208626. {
  208627. public:
  208628. FPComponentHolder()
  208629. {
  208630. setVisible (true);
  208631. setOpaque (true);
  208632. }
  208633. ~FPComponentHolder()
  208634. {
  208635. }
  208636. void paint (Graphics& g)
  208637. {
  208638. g.fillAll (Colours::lightgrey);
  208639. }
  208640. private:
  208641. FPComponentHolder (const FPComponentHolder&);
  208642. FPComponentHolder& operator= (const FPComponentHolder&);
  208643. };
  208644. }
  208645. void FileChooser::showPlatformDialog (Array<File>& results,
  208646. const String& title,
  208647. const File& currentFileOrDirectory,
  208648. const String& filter,
  208649. bool selectsDirectory,
  208650. bool /*selectsFiles*/,
  208651. bool isSaveDialogue,
  208652. bool warnAboutOverwritingExistingFiles,
  208653. bool selectMultipleFiles,
  208654. FilePreviewComponent* extraInfoComponent)
  208655. {
  208656. using namespace FileChooserHelpers;
  208657. const int numCharsAvailable = 32768;
  208658. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  208659. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  208660. int fnameIdx = 0;
  208661. JUCE_TRY
  208662. {
  208663. // use a modal window as the parent for this dialog box
  208664. // to block input from other app windows
  208665. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208666. Component w (String::empty);
  208667. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208668. mainMon.getY() + mainMon.getHeight() / 4,
  208669. 0, 0);
  208670. w.setOpaque (true);
  208671. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208672. w.addToDesktop (0);
  208673. if (extraInfoComponent == 0)
  208674. w.enterModalState();
  208675. String initialDir;
  208676. if (currentFileOrDirectory.isDirectory())
  208677. {
  208678. initialDir = currentFileOrDirectory.getFullPathName();
  208679. }
  208680. else
  208681. {
  208682. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  208683. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208684. }
  208685. if (currentExtraFileWin->isValidComponent())
  208686. {
  208687. jassertfalse;
  208688. return;
  208689. }
  208690. if (selectsDirectory)
  208691. {
  208692. LPITEMIDLIST list = 0;
  208693. filenameSpace.fillWith (0);
  208694. {
  208695. BROWSEINFO bi;
  208696. zerostruct (bi);
  208697. bi.hwndOwner = (HWND) w.getWindowHandle();
  208698. bi.pszDisplayName = fname;
  208699. bi.lpszTitle = title;
  208700. bi.lpfn = browseCallbackProc;
  208701. #ifdef BIF_USENEWUI
  208702. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208703. #else
  208704. bi.ulFlags = 0x50;
  208705. #endif
  208706. defaultDirPath = (const WCHAR*) initialDir;
  208707. list = SHBrowseForFolder (&bi);
  208708. if (! SHGetPathFromIDListW (list, fname))
  208709. {
  208710. fname[0] = 0;
  208711. returnedString = String::empty;
  208712. }
  208713. }
  208714. LPMALLOC al;
  208715. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208716. al->Free (list);
  208717. defaultDirPath = 0;
  208718. if (returnedString.isNotEmpty())
  208719. {
  208720. const String stringFName (fname);
  208721. results.add (File (stringFName).getSiblingFile (returnedString));
  208722. returnedString = String::empty;
  208723. return;
  208724. }
  208725. }
  208726. else
  208727. {
  208728. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208729. if (warnAboutOverwritingExistingFiles)
  208730. flags |= OFN_OVERWRITEPROMPT;
  208731. if (selectMultipleFiles)
  208732. flags |= OFN_ALLOWMULTISELECT;
  208733. if (extraInfoComponent != 0)
  208734. {
  208735. flags |= OFN_ENABLEHOOK;
  208736. currentExtraFileWin = new FPComponentHolder();
  208737. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  208738. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  208739. extraInfoComponent->getHeight());
  208740. currentExtraFileWin->addToDesktop (0);
  208741. currentExtraFileWin->enterModalState();
  208742. }
  208743. {
  208744. WCHAR filters [1024];
  208745. zeromem (filters, sizeof (filters));
  208746. filter.copyToUnicode (filters, 1024);
  208747. filter.copyToUnicode (filters + filter.length() + 1,
  208748. 1022 - filter.length());
  208749. OPENFILENAMEW of;
  208750. zerostruct (of);
  208751. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208752. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208753. #else
  208754. of.lStructSize = sizeof (of);
  208755. #endif
  208756. of.hwndOwner = (HWND) w.getWindowHandle();
  208757. of.lpstrFilter = filters;
  208758. of.nFilterIndex = 1;
  208759. of.lpstrFile = fname;
  208760. of.nMaxFile = numCharsAvailable;
  208761. of.lpstrInitialDir = initialDir;
  208762. of.lpstrTitle = title;
  208763. of.Flags = flags;
  208764. if (extraInfoComponent != 0)
  208765. of.lpfnHook = &openCallback;
  208766. if (isSaveDialogue)
  208767. {
  208768. if (! GetSaveFileName (&of))
  208769. fname[0] = 0;
  208770. else
  208771. fnameIdx = of.nFileOffset;
  208772. }
  208773. else
  208774. {
  208775. if (! GetOpenFileName (&of))
  208776. fname[0] = 0;
  208777. else
  208778. fnameIdx = of.nFileOffset;
  208779. }
  208780. }
  208781. }
  208782. }
  208783. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  208784. catch (...)
  208785. {
  208786. fname[0] = 0;
  208787. }
  208788. #endif
  208789. deleteAndZero (currentExtraFileWin);
  208790. const WCHAR* const files = fname;
  208791. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  208792. {
  208793. const WCHAR* filename = files + fnameIdx;
  208794. while (*filename != 0)
  208795. {
  208796. const String filepath (String (files) + "\\" + String (filename));
  208797. results.add (File (filepath));
  208798. filename += CharacterFunctions::length (filename) + 1;
  208799. }
  208800. }
  208801. else if (files[0] != 0)
  208802. {
  208803. results.add (File (files));
  208804. }
  208805. }
  208806. #endif
  208807. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208808. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208809. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208810. // compiled on its own).
  208811. #if JUCE_INCLUDED_FILE
  208812. void SystemClipboard::copyTextToClipboard (const String& text)
  208813. {
  208814. if (OpenClipboard (0) != 0)
  208815. {
  208816. if (EmptyClipboard() != 0)
  208817. {
  208818. const int len = text.length();
  208819. if (len > 0)
  208820. {
  208821. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  208822. (len + 1) * sizeof (wchar_t));
  208823. if (bufH != 0)
  208824. {
  208825. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208826. text.copyToUnicode (data, len);
  208827. GlobalUnlock (bufH);
  208828. SetClipboardData (CF_UNICODETEXT, bufH);
  208829. }
  208830. }
  208831. }
  208832. CloseClipboard();
  208833. }
  208834. }
  208835. const String SystemClipboard::getTextFromClipboard()
  208836. {
  208837. String result;
  208838. if (OpenClipboard (0) != 0)
  208839. {
  208840. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208841. if (bufH != 0)
  208842. {
  208843. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  208844. if (data != 0)
  208845. {
  208846. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  208847. GlobalUnlock (bufH);
  208848. }
  208849. }
  208850. CloseClipboard();
  208851. }
  208852. return result;
  208853. }
  208854. #endif
  208855. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208856. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  208857. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208858. // compiled on its own).
  208859. #if JUCE_INCLUDED_FILE
  208860. namespace ActiveXHelpers
  208861. {
  208862. class JuceIStorage : public ComBaseClassHelper <IStorage>
  208863. {
  208864. public:
  208865. JuceIStorage() {}
  208866. ~JuceIStorage() {}
  208867. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208868. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208869. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208870. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208871. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208872. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208873. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208874. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208875. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208876. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208877. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208878. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208879. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208880. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208881. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208882. juce_UseDebuggingNewOperator
  208883. };
  208884. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  208885. {
  208886. HWND window;
  208887. public:
  208888. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  208889. ~JuceOleInPlaceFrame() {}
  208890. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208891. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208892. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208893. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208894. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208895. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208896. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208897. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208898. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208899. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208900. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208901. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208902. juce_UseDebuggingNewOperator
  208903. };
  208904. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  208905. {
  208906. HWND window;
  208907. JuceOleInPlaceFrame* frame;
  208908. public:
  208909. JuceIOleInPlaceSite (HWND window_)
  208910. : window (window_),
  208911. frame (new JuceOleInPlaceFrame (window))
  208912. {}
  208913. ~JuceIOleInPlaceSite()
  208914. {
  208915. frame->Release();
  208916. }
  208917. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208918. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208919. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208920. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208921. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208922. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208923. {
  208924. *lplpFrame = frame;
  208925. *lplpDoc = 0;
  208926. lpFrameInfo->fMDIApp = FALSE;
  208927. lpFrameInfo->hwndFrame = window;
  208928. lpFrameInfo->haccel = 0;
  208929. lpFrameInfo->cAccelEntries = 0;
  208930. return S_OK;
  208931. }
  208932. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208933. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208934. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208935. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208936. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208937. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  208938. juce_UseDebuggingNewOperator
  208939. };
  208940. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  208941. {
  208942. JuceIOleInPlaceSite* inplaceSite;
  208943. public:
  208944. JuceIOleClientSite (HWND window)
  208945. : inplaceSite (new JuceIOleInPlaceSite (window))
  208946. {}
  208947. ~JuceIOleClientSite()
  208948. {
  208949. inplaceSite->Release();
  208950. }
  208951. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  208952. {
  208953. if (type == IID_IOleInPlaceSite)
  208954. {
  208955. inplaceSite->AddRef();
  208956. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  208957. return S_OK;
  208958. }
  208959. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  208960. }
  208961. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  208962. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  208963. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  208964. HRESULT __stdcall ShowObject() { return S_OK; }
  208965. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  208966. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  208967. juce_UseDebuggingNewOperator
  208968. };
  208969. static Array<ActiveXControlComponent*> activeXComps;
  208970. static HWND getHWND (const ActiveXControlComponent* const component)
  208971. {
  208972. HWND hwnd = 0;
  208973. const IID iid = IID_IOleWindow;
  208974. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  208975. if (window != 0)
  208976. {
  208977. window->GetWindow (&hwnd);
  208978. window->Release();
  208979. }
  208980. return hwnd;
  208981. }
  208982. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  208983. {
  208984. RECT activeXRect, peerRect;
  208985. GetWindowRect (hwnd, &activeXRect);
  208986. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  208987. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  208988. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  208989. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  208990. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  208991. switch (message)
  208992. {
  208993. case WM_MOUSEMOVE:
  208994. case WM_LBUTTONDOWN:
  208995. case WM_MBUTTONDOWN:
  208996. case WM_RBUTTONDOWN:
  208997. case WM_LBUTTONUP:
  208998. case WM_MBUTTONUP:
  208999. case WM_RBUTTONUP:
  209000. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209001. break;
  209002. default:
  209003. break;
  209004. }
  209005. }
  209006. }
  209007. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209008. {
  209009. ActiveXControlComponent* const owner;
  209010. bool wasShowing;
  209011. public:
  209012. HWND controlHWND;
  209013. IStorage* storage;
  209014. IOleClientSite* clientSite;
  209015. IOleObject* control;
  209016. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  209017. : ComponentMovementWatcher (owner_),
  209018. owner (owner_),
  209019. wasShowing (owner_ != 0 && owner_->isShowing()),
  209020. controlHWND (0),
  209021. storage (new ActiveXHelpers::JuceIStorage()),
  209022. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209023. control (0)
  209024. {
  209025. }
  209026. ~Pimpl()
  209027. {
  209028. if (control != 0)
  209029. {
  209030. control->Close (OLECLOSE_NOSAVE);
  209031. control->Release();
  209032. }
  209033. clientSite->Release();
  209034. storage->Release();
  209035. }
  209036. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209037. {
  209038. Component* const topComp = owner->getTopLevelComponent();
  209039. if (topComp->getPeer() != 0)
  209040. {
  209041. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  209042. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  209043. }
  209044. }
  209045. void componentPeerChanged()
  209046. {
  209047. const bool isShowingNow = owner->isShowing();
  209048. if (wasShowing != isShowingNow)
  209049. {
  209050. wasShowing = isShowingNow;
  209051. owner->setControlVisible (isShowingNow);
  209052. }
  209053. componentMovedOrResized (true, true);
  209054. }
  209055. void componentVisibilityChanged (Component&)
  209056. {
  209057. componentPeerChanged();
  209058. }
  209059. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209060. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209061. {
  209062. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209063. {
  209064. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209065. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209066. {
  209067. switch (message)
  209068. {
  209069. case WM_MOUSEMOVE:
  209070. case WM_LBUTTONDOWN:
  209071. case WM_MBUTTONDOWN:
  209072. case WM_RBUTTONDOWN:
  209073. case WM_LBUTTONUP:
  209074. case WM_MBUTTONUP:
  209075. case WM_RBUTTONUP:
  209076. case WM_LBUTTONDBLCLK:
  209077. case WM_MBUTTONDBLCLK:
  209078. case WM_RBUTTONDBLCLK:
  209079. if (ax->isShowing())
  209080. {
  209081. ComponentPeer* const peer = ax->getPeer();
  209082. if (peer != 0)
  209083. {
  209084. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209085. if (! ax->areMouseEventsAllowed())
  209086. return 0;
  209087. }
  209088. }
  209089. break;
  209090. default:
  209091. break;
  209092. }
  209093. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209094. }
  209095. }
  209096. return DefWindowProc (hwnd, message, wParam, lParam);
  209097. }
  209098. };
  209099. ActiveXControlComponent::ActiveXControlComponent()
  209100. : originalWndProc (0),
  209101. mouseEventsAllowed (true)
  209102. {
  209103. ActiveXHelpers::activeXComps.add (this);
  209104. }
  209105. ActiveXControlComponent::~ActiveXControlComponent()
  209106. {
  209107. deleteControl();
  209108. ActiveXHelpers::activeXComps.removeValue (this);
  209109. }
  209110. void ActiveXControlComponent::paint (Graphics& g)
  209111. {
  209112. if (control == 0)
  209113. g.fillAll (Colours::lightgrey);
  209114. }
  209115. bool ActiveXControlComponent::createControl (const void* controlIID)
  209116. {
  209117. deleteControl();
  209118. ComponentPeer* const peer = getPeer();
  209119. // the component must have already been added to a real window when you call this!
  209120. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209121. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209122. {
  209123. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209124. HWND hwnd = (HWND) peer->getNativeHandle();
  209125. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  209126. HRESULT hr;
  209127. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209128. newControl->clientSite, newControl->storage,
  209129. (void**) &(newControl->control))) == S_OK)
  209130. {
  209131. newControl->control->SetHostNames (L"Juce", 0);
  209132. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209133. {
  209134. RECT rect;
  209135. rect.left = pos.getX();
  209136. rect.top = pos.getY();
  209137. rect.right = pos.getX() + getWidth();
  209138. rect.bottom = pos.getY() + getHeight();
  209139. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209140. {
  209141. control = newControl;
  209142. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209143. control->controlHWND = ActiveXHelpers::getHWND (this);
  209144. if (control->controlHWND != 0)
  209145. {
  209146. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209147. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209148. }
  209149. return true;
  209150. }
  209151. }
  209152. }
  209153. }
  209154. return false;
  209155. }
  209156. void ActiveXControlComponent::deleteControl()
  209157. {
  209158. control = 0;
  209159. originalWndProc = 0;
  209160. }
  209161. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209162. {
  209163. void* result = 0;
  209164. if (control != 0 && control->control != 0
  209165. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209166. return result;
  209167. return 0;
  209168. }
  209169. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209170. {
  209171. if (control->controlHWND != 0)
  209172. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209173. }
  209174. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209175. {
  209176. if (control->controlHWND != 0)
  209177. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209178. }
  209179. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209180. {
  209181. mouseEventsAllowed = eventsCanReachControl;
  209182. }
  209183. #endif
  209184. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209185. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209186. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209187. // compiled on its own).
  209188. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209189. using namespace QTOLibrary;
  209190. using namespace QTOControlLib;
  209191. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209192. static bool isQTAvailable = false;
  209193. class QuickTimeMovieComponent::Pimpl
  209194. {
  209195. public:
  209196. Pimpl() : dataHandle (0)
  209197. {
  209198. }
  209199. ~Pimpl()
  209200. {
  209201. clearHandle();
  209202. }
  209203. void clearHandle()
  209204. {
  209205. if (dataHandle != 0)
  209206. {
  209207. DisposeHandle (dataHandle);
  209208. dataHandle = 0;
  209209. }
  209210. }
  209211. IQTControlPtr qtControl;
  209212. IQTMoviePtr qtMovie;
  209213. Handle dataHandle;
  209214. };
  209215. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209216. : movieLoaded (false),
  209217. controllerVisible (true)
  209218. {
  209219. pimpl = new Pimpl();
  209220. setMouseEventsAllowed (false);
  209221. }
  209222. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209223. {
  209224. closeMovie();
  209225. pimpl->qtControl = 0;
  209226. deleteControl();
  209227. pimpl = 0;
  209228. }
  209229. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209230. {
  209231. if (! isQTAvailable)
  209232. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209233. return isQTAvailable;
  209234. }
  209235. void QuickTimeMovieComponent::createControlIfNeeded()
  209236. {
  209237. if (isShowing() && ! isControlCreated())
  209238. {
  209239. const IID qtIID = __uuidof (QTControl);
  209240. if (createControl (&qtIID))
  209241. {
  209242. const IID qtInterfaceIID = __uuidof (IQTControl);
  209243. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209244. if (pimpl->qtControl != 0)
  209245. {
  209246. pimpl->qtControl->Release(); // it has one ref too many at this point
  209247. pimpl->qtControl->QuickTimeInitialize();
  209248. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209249. if (movieFile != File::nonexistent)
  209250. loadMovie (movieFile, controllerVisible);
  209251. }
  209252. }
  209253. }
  209254. }
  209255. bool QuickTimeMovieComponent::isControlCreated() const
  209256. {
  209257. return isControlOpen();
  209258. }
  209259. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209260. const bool isControllerVisible)
  209261. {
  209262. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209263. movieFile = File::nonexistent;
  209264. movieLoaded = false;
  209265. pimpl->qtMovie = 0;
  209266. controllerVisible = isControllerVisible;
  209267. createControlIfNeeded();
  209268. if (isControlCreated())
  209269. {
  209270. if (pimpl->qtControl != 0)
  209271. {
  209272. pimpl->qtControl->Put_MovieHandle (0);
  209273. pimpl->clearHandle();
  209274. Movie movie;
  209275. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209276. {
  209277. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209278. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209279. if (pimpl->qtMovie != 0)
  209280. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209281. : qtMovieControllerTypeNone);
  209282. }
  209283. if (movie == 0)
  209284. pimpl->clearHandle();
  209285. }
  209286. movieLoaded = (pimpl->qtMovie != 0);
  209287. }
  209288. else
  209289. {
  209290. // You're trying to open a movie when the control hasn't yet been created, probably because
  209291. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209292. jassertfalse;
  209293. }
  209294. return movieLoaded;
  209295. }
  209296. void QuickTimeMovieComponent::closeMovie()
  209297. {
  209298. stop();
  209299. movieFile = File::nonexistent;
  209300. movieLoaded = false;
  209301. pimpl->qtMovie = 0;
  209302. if (pimpl->qtControl != 0)
  209303. pimpl->qtControl->Put_MovieHandle (0);
  209304. pimpl->clearHandle();
  209305. }
  209306. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209307. {
  209308. return movieFile;
  209309. }
  209310. bool QuickTimeMovieComponent::isMovieOpen() const
  209311. {
  209312. return movieLoaded;
  209313. }
  209314. double QuickTimeMovieComponent::getMovieDuration() const
  209315. {
  209316. if (pimpl->qtMovie != 0)
  209317. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209318. return 0.0;
  209319. }
  209320. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209321. {
  209322. if (pimpl->qtMovie != 0)
  209323. {
  209324. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209325. width = r.right - r.left;
  209326. height = r.bottom - r.top;
  209327. }
  209328. else
  209329. {
  209330. width = height = 0;
  209331. }
  209332. }
  209333. void QuickTimeMovieComponent::play()
  209334. {
  209335. if (pimpl->qtMovie != 0)
  209336. pimpl->qtMovie->Play();
  209337. }
  209338. void QuickTimeMovieComponent::stop()
  209339. {
  209340. if (pimpl->qtMovie != 0)
  209341. pimpl->qtMovie->Stop();
  209342. }
  209343. bool QuickTimeMovieComponent::isPlaying() const
  209344. {
  209345. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209346. }
  209347. void QuickTimeMovieComponent::setPosition (const double seconds)
  209348. {
  209349. if (pimpl->qtMovie != 0)
  209350. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209351. }
  209352. double QuickTimeMovieComponent::getPosition() const
  209353. {
  209354. if (pimpl->qtMovie != 0)
  209355. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209356. return 0.0;
  209357. }
  209358. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209359. {
  209360. if (pimpl->qtMovie != 0)
  209361. pimpl->qtMovie->PutRate (newSpeed);
  209362. }
  209363. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209364. {
  209365. if (pimpl->qtMovie != 0)
  209366. {
  209367. pimpl->qtMovie->PutAudioVolume (newVolume);
  209368. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209369. }
  209370. }
  209371. float QuickTimeMovieComponent::getMovieVolume() const
  209372. {
  209373. if (pimpl->qtMovie != 0)
  209374. return pimpl->qtMovie->GetAudioVolume();
  209375. return 0.0f;
  209376. }
  209377. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209378. {
  209379. if (pimpl->qtMovie != 0)
  209380. pimpl->qtMovie->PutLoop (shouldLoop);
  209381. }
  209382. bool QuickTimeMovieComponent::isLooping() const
  209383. {
  209384. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209385. }
  209386. bool QuickTimeMovieComponent::isControllerVisible() const
  209387. {
  209388. return controllerVisible;
  209389. }
  209390. void QuickTimeMovieComponent::parentHierarchyChanged()
  209391. {
  209392. createControlIfNeeded();
  209393. QTCompBaseClass::parentHierarchyChanged();
  209394. }
  209395. void QuickTimeMovieComponent::visibilityChanged()
  209396. {
  209397. createControlIfNeeded();
  209398. QTCompBaseClass::visibilityChanged();
  209399. }
  209400. void QuickTimeMovieComponent::paint (Graphics& g)
  209401. {
  209402. if (! isControlCreated())
  209403. g.fillAll (Colours::black);
  209404. }
  209405. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209406. {
  209407. Handle dataRef = 0;
  209408. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209409. if (err == noErr)
  209410. {
  209411. Str255 suffix;
  209412. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209413. StringPtr name = suffix;
  209414. err = PtrAndHand (name, dataRef, name[0] + 1);
  209415. if (err == noErr)
  209416. {
  209417. long atoms[3];
  209418. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209419. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209420. atoms[2] = EndianU32_NtoB (MovieFileType);
  209421. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209422. if (err == noErr)
  209423. return dataRef;
  209424. }
  209425. DisposeHandle (dataRef);
  209426. }
  209427. return 0;
  209428. }
  209429. static CFStringRef juceStringToCFString (const String& s)
  209430. {
  209431. const int len = s.length();
  209432. const juce_wchar* const t = s;
  209433. HeapBlock <UniChar> temp (len + 2);
  209434. for (int i = 0; i <= len; ++i)
  209435. temp[i] = t[i];
  209436. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209437. }
  209438. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209439. {
  209440. Boolean trueBool = true;
  209441. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209442. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209443. props[prop].propValueSize = sizeof (trueBool);
  209444. props[prop].propValueAddress = &trueBool;
  209445. ++prop;
  209446. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209447. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209448. props[prop].propValueSize = sizeof (trueBool);
  209449. props[prop].propValueAddress = &trueBool;
  209450. ++prop;
  209451. Boolean isActive = true;
  209452. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209453. props[prop].propID = kQTNewMoviePropertyID_Active;
  209454. props[prop].propValueSize = sizeof (isActive);
  209455. props[prop].propValueAddress = &isActive;
  209456. ++prop;
  209457. MacSetPort (0);
  209458. jassert (prop <= 5);
  209459. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209460. return err == noErr;
  209461. }
  209462. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209463. {
  209464. if (input == 0)
  209465. return false;
  209466. dataHandle = 0;
  209467. bool ok = false;
  209468. QTNewMoviePropertyElement props[5];
  209469. zeromem (props, sizeof (props));
  209470. int prop = 0;
  209471. DataReferenceRecord dr;
  209472. props[prop].propClass = kQTPropertyClass_DataLocation;
  209473. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209474. props[prop].propValueSize = sizeof (dr);
  209475. props[prop].propValueAddress = &dr;
  209476. ++prop;
  209477. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209478. if (fin != 0)
  209479. {
  209480. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209481. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209482. &dr.dataRef, &dr.dataRefType);
  209483. ok = openMovie (props, prop, movie);
  209484. DisposeHandle (dr.dataRef);
  209485. CFRelease (filePath);
  209486. }
  209487. else
  209488. {
  209489. // sanity-check because this currently needs to load the whole stream into memory..
  209490. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209491. dataHandle = NewHandle ((Size) input->getTotalLength());
  209492. HLock (dataHandle);
  209493. // read the entire stream into memory - this is a pain, but can't get it to work
  209494. // properly using a custom callback to supply the data.
  209495. input->read (*dataHandle, (int) input->getTotalLength());
  209496. HUnlock (dataHandle);
  209497. // different types to get QT to try. (We should really be a bit smarter here by
  209498. // working out in advance which one the stream contains, rather than just trying
  209499. // each one)
  209500. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209501. "\04.avi", "\04.m4a" };
  209502. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209503. {
  209504. /* // this fails for some bizarre reason - it can be bodged to work with
  209505. // movies, but can't seem to do it for other file types..
  209506. QTNewMovieUserProcRecord procInfo;
  209507. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209508. procInfo.getMovieUserProcRefcon = this;
  209509. procInfo.defaultDataRef.dataRef = dataRef;
  209510. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209511. props[prop].propClass = kQTPropertyClass_DataLocation;
  209512. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209513. props[prop].propValueSize = sizeof (procInfo);
  209514. props[prop].propValueAddress = (void*) &procInfo;
  209515. ++prop; */
  209516. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209517. dr.dataRefType = HandleDataHandlerSubType;
  209518. ok = openMovie (props, prop, movie);
  209519. DisposeHandle (dr.dataRef);
  209520. }
  209521. }
  209522. return ok;
  209523. }
  209524. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209525. const bool isControllerVisible)
  209526. {
  209527. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209528. movieFile = movieFile_;
  209529. return ok;
  209530. }
  209531. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209532. const bool isControllerVisible)
  209533. {
  209534. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209535. }
  209536. void QuickTimeMovieComponent::goToStart()
  209537. {
  209538. setPosition (0.0);
  209539. }
  209540. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209541. const RectanglePlacement& placement)
  209542. {
  209543. int normalWidth, normalHeight;
  209544. getMovieNormalSize (normalWidth, normalHeight);
  209545. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209546. {
  209547. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209548. placement.applyTo (x, y, w, h,
  209549. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209550. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209551. if (w > 0 && h > 0)
  209552. {
  209553. setBounds (roundToInt (x), roundToInt (y),
  209554. roundToInt (w), roundToInt (h));
  209555. }
  209556. }
  209557. else
  209558. {
  209559. setBounds (spaceToFitWithin);
  209560. }
  209561. }
  209562. #endif
  209563. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209564. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209565. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209566. // compiled on its own).
  209567. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209568. class WebBrowserComponentInternal : public ActiveXControlComponent
  209569. {
  209570. public:
  209571. WebBrowserComponentInternal()
  209572. : browser (0),
  209573. connectionPoint (0),
  209574. adviseCookie (0)
  209575. {
  209576. }
  209577. ~WebBrowserComponentInternal()
  209578. {
  209579. if (connectionPoint != 0)
  209580. connectionPoint->Unadvise (adviseCookie);
  209581. if (browser != 0)
  209582. browser->Release();
  209583. }
  209584. void createBrowser()
  209585. {
  209586. createControl (&CLSID_WebBrowser);
  209587. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209588. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209589. if (connectionPointContainer != 0)
  209590. {
  209591. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209592. &connectionPoint);
  209593. if (connectionPoint != 0)
  209594. {
  209595. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209596. jassert (owner != 0);
  209597. EventHandler* handler = new EventHandler (owner);
  209598. connectionPoint->Advise (handler, &adviseCookie);
  209599. handler->Release();
  209600. }
  209601. }
  209602. }
  209603. void goToURL (const String& url,
  209604. const StringArray* headers,
  209605. const MemoryBlock* postData)
  209606. {
  209607. if (browser != 0)
  209608. {
  209609. LPSAFEARRAY sa = 0;
  209610. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209611. VariantInit (&flags);
  209612. VariantInit (&frame);
  209613. VariantInit (&postDataVar);
  209614. VariantInit (&headersVar);
  209615. if (headers != 0)
  209616. {
  209617. V_VT (&headersVar) = VT_BSTR;
  209618. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209619. }
  209620. if (postData != 0 && postData->getSize() > 0)
  209621. {
  209622. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209623. if (sa != 0)
  209624. {
  209625. void* data = 0;
  209626. SafeArrayAccessData (sa, &data);
  209627. jassert (data != 0);
  209628. if (data != 0)
  209629. {
  209630. postData->copyTo (data, 0, postData->getSize());
  209631. SafeArrayUnaccessData (sa);
  209632. VARIANT postDataVar2;
  209633. VariantInit (&postDataVar2);
  209634. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209635. V_ARRAY (&postDataVar2) = sa;
  209636. postDataVar = postDataVar2;
  209637. }
  209638. }
  209639. }
  209640. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209641. &flags, &frame,
  209642. &postDataVar, &headersVar);
  209643. if (sa != 0)
  209644. SafeArrayDestroy (sa);
  209645. VariantClear (&flags);
  209646. VariantClear (&frame);
  209647. VariantClear (&postDataVar);
  209648. VariantClear (&headersVar);
  209649. }
  209650. }
  209651. IWebBrowser2* browser;
  209652. juce_UseDebuggingNewOperator
  209653. private:
  209654. IConnectionPoint* connectionPoint;
  209655. DWORD adviseCookie;
  209656. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209657. public ComponentMovementWatcher
  209658. {
  209659. public:
  209660. EventHandler (WebBrowserComponent* owner_)
  209661. : ComponentMovementWatcher (owner_),
  209662. owner (owner_)
  209663. {
  209664. }
  209665. ~EventHandler()
  209666. {
  209667. }
  209668. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  209669. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  209670. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  209671. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  209672. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  209673. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  209674. UINT __RPC_FAR* /*puArgErr*/)
  209675. {
  209676. switch (dispIdMember)
  209677. {
  209678. case DISPID_BEFORENAVIGATE2:
  209679. {
  209680. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209681. String url;
  209682. if ((vurl->vt & VT_BYREF) != 0)
  209683. url = *vurl->pbstrVal;
  209684. else
  209685. url = vurl->bstrVal;
  209686. *pDispParams->rgvarg->pboolVal
  209687. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209688. : VARIANT_TRUE;
  209689. return S_OK;
  209690. }
  209691. default:
  209692. break;
  209693. }
  209694. return E_NOTIMPL;
  209695. }
  209696. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209697. void componentPeerChanged() {}
  209698. void componentVisibilityChanged (Component&)
  209699. {
  209700. owner->visibilityChanged();
  209701. }
  209702. juce_UseDebuggingNewOperator
  209703. private:
  209704. WebBrowserComponent* const owner;
  209705. EventHandler (const EventHandler&);
  209706. EventHandler& operator= (const EventHandler&);
  209707. };
  209708. };
  209709. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209710. : browser (0),
  209711. blankPageShown (false),
  209712. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209713. {
  209714. setOpaque (true);
  209715. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209716. }
  209717. WebBrowserComponent::~WebBrowserComponent()
  209718. {
  209719. delete browser;
  209720. }
  209721. void WebBrowserComponent::goToURL (const String& url,
  209722. const StringArray* headers,
  209723. const MemoryBlock* postData)
  209724. {
  209725. lastURL = url;
  209726. lastHeaders.clear();
  209727. if (headers != 0)
  209728. lastHeaders = *headers;
  209729. lastPostData.setSize (0);
  209730. if (postData != 0)
  209731. lastPostData = *postData;
  209732. blankPageShown = false;
  209733. browser->goToURL (url, headers, postData);
  209734. }
  209735. void WebBrowserComponent::stop()
  209736. {
  209737. if (browser->browser != 0)
  209738. browser->browser->Stop();
  209739. }
  209740. void WebBrowserComponent::goBack()
  209741. {
  209742. lastURL = String::empty;
  209743. blankPageShown = false;
  209744. if (browser->browser != 0)
  209745. browser->browser->GoBack();
  209746. }
  209747. void WebBrowserComponent::goForward()
  209748. {
  209749. lastURL = String::empty;
  209750. if (browser->browser != 0)
  209751. browser->browser->GoForward();
  209752. }
  209753. void WebBrowserComponent::refresh()
  209754. {
  209755. if (browser->browser != 0)
  209756. browser->browser->Refresh();
  209757. }
  209758. void WebBrowserComponent::paint (Graphics& g)
  209759. {
  209760. if (browser->browser == 0)
  209761. g.fillAll (Colours::white);
  209762. }
  209763. void WebBrowserComponent::checkWindowAssociation()
  209764. {
  209765. if (isShowing())
  209766. {
  209767. if (browser->browser == 0 && getPeer() != 0)
  209768. {
  209769. browser->createBrowser();
  209770. reloadLastURL();
  209771. }
  209772. else
  209773. {
  209774. if (blankPageShown)
  209775. goBack();
  209776. }
  209777. }
  209778. else
  209779. {
  209780. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209781. {
  209782. // when the component becomes invisible, some stuff like flash
  209783. // carries on playing audio, so we need to force it onto a blank
  209784. // page to avoid this..
  209785. blankPageShown = true;
  209786. browser->goToURL ("about:blank", 0, 0);
  209787. }
  209788. }
  209789. }
  209790. void WebBrowserComponent::reloadLastURL()
  209791. {
  209792. if (lastURL.isNotEmpty())
  209793. {
  209794. goToURL (lastURL, &lastHeaders, &lastPostData);
  209795. lastURL = String::empty;
  209796. }
  209797. }
  209798. void WebBrowserComponent::parentHierarchyChanged()
  209799. {
  209800. checkWindowAssociation();
  209801. }
  209802. void WebBrowserComponent::resized()
  209803. {
  209804. browser->setSize (getWidth(), getHeight());
  209805. }
  209806. void WebBrowserComponent::visibilityChanged()
  209807. {
  209808. checkWindowAssociation();
  209809. }
  209810. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209811. {
  209812. return true;
  209813. }
  209814. #endif
  209815. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209816. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209817. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209818. // compiled on its own).
  209819. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209820. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209821. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209822. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209823. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209824. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209825. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209826. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209827. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209828. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209829. #define WGL_ACCELERATION_ARB 0x2003
  209830. #define WGL_SWAP_METHOD_ARB 0x2007
  209831. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209832. #define WGL_PIXEL_TYPE_ARB 0x2013
  209833. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209834. #define WGL_COLOR_BITS_ARB 0x2014
  209835. #define WGL_RED_BITS_ARB 0x2015
  209836. #define WGL_GREEN_BITS_ARB 0x2017
  209837. #define WGL_BLUE_BITS_ARB 0x2019
  209838. #define WGL_ALPHA_BITS_ARB 0x201B
  209839. #define WGL_DEPTH_BITS_ARB 0x2022
  209840. #define WGL_STENCIL_BITS_ARB 0x2023
  209841. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209842. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209843. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209844. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209845. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209846. #define WGL_STEREO_ARB 0x2012
  209847. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209848. #define WGL_SAMPLES_ARB 0x2042
  209849. #define WGL_TYPE_RGBA_ARB 0x202B
  209850. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209851. {
  209852. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209853. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  209854. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  209855. else
  209856. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  209857. }
  209858. class WindowedGLContext : public OpenGLContext
  209859. {
  209860. public:
  209861. WindowedGLContext (Component* const component_,
  209862. HGLRC contextToShareWith,
  209863. const OpenGLPixelFormat& pixelFormat)
  209864. : renderContext (0),
  209865. dc (0),
  209866. component (component_)
  209867. {
  209868. jassert (component != 0);
  209869. createNativeWindow();
  209870. // Use a default pixel format that should be supported everywhere
  209871. PIXELFORMATDESCRIPTOR pfd;
  209872. zerostruct (pfd);
  209873. pfd.nSize = sizeof (pfd);
  209874. pfd.nVersion = 1;
  209875. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  209876. pfd.iPixelType = PFD_TYPE_RGBA;
  209877. pfd.cColorBits = 24;
  209878. pfd.cDepthBits = 16;
  209879. const int format = ChoosePixelFormat (dc, &pfd);
  209880. if (format != 0)
  209881. SetPixelFormat (dc, format, &pfd);
  209882. renderContext = wglCreateContext (dc);
  209883. makeActive();
  209884. setPixelFormat (pixelFormat);
  209885. if (contextToShareWith != 0 && renderContext != 0)
  209886. wglShareLists (contextToShareWith, renderContext);
  209887. }
  209888. ~WindowedGLContext()
  209889. {
  209890. deleteContext();
  209891. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209892. nativeWindow = 0;
  209893. }
  209894. void deleteContext()
  209895. {
  209896. makeInactive();
  209897. if (renderContext != 0)
  209898. {
  209899. wglDeleteContext (renderContext);
  209900. renderContext = 0;
  209901. }
  209902. }
  209903. bool makeActive() const throw()
  209904. {
  209905. jassert (renderContext != 0);
  209906. return wglMakeCurrent (dc, renderContext) != 0;
  209907. }
  209908. bool makeInactive() const throw()
  209909. {
  209910. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  209911. }
  209912. bool isActive() const throw()
  209913. {
  209914. return wglGetCurrentContext() == renderContext;
  209915. }
  209916. const OpenGLPixelFormat getPixelFormat() const
  209917. {
  209918. OpenGLPixelFormat pf;
  209919. makeActive();
  209920. StringArray availableExtensions;
  209921. getWglExtensions (dc, availableExtensions);
  209922. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  209923. return pf;
  209924. }
  209925. void* getRawContext() const throw()
  209926. {
  209927. return renderContext;
  209928. }
  209929. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  209930. {
  209931. makeActive();
  209932. PIXELFORMATDESCRIPTOR pfd;
  209933. zerostruct (pfd);
  209934. pfd.nSize = sizeof (pfd);
  209935. pfd.nVersion = 1;
  209936. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  209937. pfd.iPixelType = PFD_TYPE_RGBA;
  209938. pfd.iLayerType = PFD_MAIN_PLANE;
  209939. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  209940. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  209941. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  209942. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  209943. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  209944. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  209945. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  209946. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  209947. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  209948. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  209949. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  209950. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  209951. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  209952. int format = 0;
  209953. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  209954. StringArray availableExtensions;
  209955. getWglExtensions (dc, availableExtensions);
  209956. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  209957. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  209958. {
  209959. int attributes[64];
  209960. int n = 0;
  209961. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  209962. attributes[n++] = GL_TRUE;
  209963. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  209964. attributes[n++] = GL_TRUE;
  209965. attributes[n++] = WGL_ACCELERATION_ARB;
  209966. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  209967. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  209968. attributes[n++] = GL_TRUE;
  209969. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  209970. attributes[n++] = WGL_TYPE_RGBA_ARB;
  209971. attributes[n++] = WGL_COLOR_BITS_ARB;
  209972. attributes[n++] = pfd.cColorBits;
  209973. attributes[n++] = WGL_RED_BITS_ARB;
  209974. attributes[n++] = pixelFormat.redBits;
  209975. attributes[n++] = WGL_GREEN_BITS_ARB;
  209976. attributes[n++] = pixelFormat.greenBits;
  209977. attributes[n++] = WGL_BLUE_BITS_ARB;
  209978. attributes[n++] = pixelFormat.blueBits;
  209979. attributes[n++] = WGL_ALPHA_BITS_ARB;
  209980. attributes[n++] = pixelFormat.alphaBits;
  209981. attributes[n++] = WGL_DEPTH_BITS_ARB;
  209982. attributes[n++] = pixelFormat.depthBufferBits;
  209983. if (pixelFormat.stencilBufferBits > 0)
  209984. {
  209985. attributes[n++] = WGL_STENCIL_BITS_ARB;
  209986. attributes[n++] = pixelFormat.stencilBufferBits;
  209987. }
  209988. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  209989. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  209990. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  209991. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  209992. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  209993. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  209994. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  209995. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  209996. if (availableExtensions.contains ("WGL_ARB_multisample")
  209997. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  209998. {
  209999. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210000. attributes[n++] = 1;
  210001. attributes[n++] = WGL_SAMPLES_ARB;
  210002. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210003. }
  210004. attributes[n++] = 0;
  210005. UINT formatsCount;
  210006. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210007. (void) ok;
  210008. jassert (ok);
  210009. }
  210010. else
  210011. {
  210012. format = ChoosePixelFormat (dc, &pfd);
  210013. }
  210014. if (format != 0)
  210015. {
  210016. makeInactive();
  210017. // win32 can't change the pixel format of a window, so need to delete the
  210018. // old one and create a new one..
  210019. jassert (nativeWindow != 0);
  210020. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210021. nativeWindow = 0;
  210022. createNativeWindow();
  210023. if (SetPixelFormat (dc, format, &pfd))
  210024. {
  210025. wglDeleteContext (renderContext);
  210026. renderContext = wglCreateContext (dc);
  210027. jassert (renderContext != 0);
  210028. return renderContext != 0;
  210029. }
  210030. }
  210031. return false;
  210032. }
  210033. void updateWindowPosition (int x, int y, int w, int h, int)
  210034. {
  210035. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210036. x, y, w, h,
  210037. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210038. }
  210039. void repaint()
  210040. {
  210041. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210042. }
  210043. void swapBuffers()
  210044. {
  210045. SwapBuffers (dc);
  210046. }
  210047. bool setSwapInterval (int numFramesPerSwap)
  210048. {
  210049. makeActive();
  210050. StringArray availableExtensions;
  210051. getWglExtensions (dc, availableExtensions);
  210052. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210053. return availableExtensions.contains ("WGL_EXT_swap_control")
  210054. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210055. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210056. }
  210057. int getSwapInterval() const
  210058. {
  210059. makeActive();
  210060. StringArray availableExtensions;
  210061. getWglExtensions (dc, availableExtensions);
  210062. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210063. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210064. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210065. return wglGetSwapIntervalEXT();
  210066. return 0;
  210067. }
  210068. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210069. {
  210070. jassert (isActive());
  210071. StringArray availableExtensions;
  210072. getWglExtensions (dc, availableExtensions);
  210073. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210074. int numTypes = 0;
  210075. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210076. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210077. {
  210078. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210079. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210080. jassertfalse;
  210081. }
  210082. else
  210083. {
  210084. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210085. }
  210086. OpenGLPixelFormat pf;
  210087. for (int i = 0; i < numTypes; ++i)
  210088. {
  210089. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210090. {
  210091. bool alreadyListed = false;
  210092. for (int j = results.size(); --j >= 0;)
  210093. if (pf == *results.getUnchecked(j))
  210094. alreadyListed = true;
  210095. if (! alreadyListed)
  210096. results.add (new OpenGLPixelFormat (pf));
  210097. }
  210098. }
  210099. }
  210100. void* getNativeWindowHandle() const
  210101. {
  210102. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210103. }
  210104. juce_UseDebuggingNewOperator
  210105. HGLRC renderContext;
  210106. private:
  210107. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210108. Component* const component;
  210109. HDC dc;
  210110. void createNativeWindow()
  210111. {
  210112. nativeWindow = new Win32ComponentPeer (component, 0);
  210113. nativeWindow->dontRepaint = true;
  210114. nativeWindow->setVisible (true);
  210115. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  210116. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210117. if (peer != 0)
  210118. {
  210119. SetParent (hwnd, (HWND) peer->getNativeHandle());
  210120. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  210121. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  210122. }
  210123. dc = GetDC (hwnd);
  210124. }
  210125. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210126. OpenGLPixelFormat& result,
  210127. const StringArray& availableExtensions) const throw()
  210128. {
  210129. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210130. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210131. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210132. {
  210133. int attributes[32];
  210134. int numAttributes = 0;
  210135. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210136. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210137. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210138. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210139. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210140. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210141. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210142. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210143. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210144. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210145. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210146. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210147. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210148. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210149. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210150. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210151. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210152. int values[32];
  210153. zeromem (values, sizeof (values));
  210154. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210155. {
  210156. int n = 0;
  210157. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210158. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210159. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210160. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210161. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210162. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210163. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210164. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210165. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210166. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210167. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210168. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210169. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210170. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210171. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210172. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210173. return isValidFormat;
  210174. }
  210175. else
  210176. {
  210177. jassertfalse;
  210178. }
  210179. }
  210180. else
  210181. {
  210182. PIXELFORMATDESCRIPTOR pfd;
  210183. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210184. {
  210185. result.redBits = pfd.cRedBits;
  210186. result.greenBits = pfd.cGreenBits;
  210187. result.blueBits = pfd.cBlueBits;
  210188. result.alphaBits = pfd.cAlphaBits;
  210189. result.depthBufferBits = pfd.cDepthBits;
  210190. result.stencilBufferBits = pfd.cStencilBits;
  210191. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210192. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210193. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210194. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210195. result.fullSceneAntiAliasingNumSamples = 0;
  210196. return true;
  210197. }
  210198. else
  210199. {
  210200. jassertfalse;
  210201. }
  210202. }
  210203. return false;
  210204. }
  210205. WindowedGLContext (const WindowedGLContext&);
  210206. WindowedGLContext& operator= (const WindowedGLContext&);
  210207. };
  210208. OpenGLContext* OpenGLComponent::createContext()
  210209. {
  210210. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210211. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210212. preferredPixelFormat));
  210213. return (c->renderContext != 0) ? c.release() : 0;
  210214. }
  210215. void* OpenGLComponent::getNativeWindowHandle() const
  210216. {
  210217. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210218. }
  210219. void juce_glViewport (const int w, const int h)
  210220. {
  210221. glViewport (0, 0, w, h);
  210222. }
  210223. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210224. OwnedArray <OpenGLPixelFormat>& results)
  210225. {
  210226. Component tempComp;
  210227. {
  210228. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210229. wc.makeActive();
  210230. wc.findAlternativeOpenGLPixelFormats (results);
  210231. }
  210232. }
  210233. #endif
  210234. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210235. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210236. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210237. // compiled on its own).
  210238. #if JUCE_INCLUDED_FILE
  210239. #if JUCE_USE_CDREADER
  210240. namespace CDReaderHelpers
  210241. {
  210242. //***************************************************************************
  210243. // %%% TARGET STATUS VALUES %%%
  210244. //***************************************************************************
  210245. #define STATUS_GOOD 0x00 // Status Good
  210246. #define STATUS_CHKCOND 0x02 // Check Condition
  210247. #define STATUS_CONDMET 0x04 // Condition Met
  210248. #define STATUS_BUSY 0x08 // Busy
  210249. #define STATUS_INTERM 0x10 // Intermediate
  210250. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210251. #define STATUS_RESCONF 0x18 // Reservation conflict
  210252. #define STATUS_COMTERM 0x22 // Command Terminated
  210253. #define STATUS_QFULL 0x28 // Queue full
  210254. //***************************************************************************
  210255. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210256. //***************************************************************************
  210257. #define MAXLUN 7 // Maximum Logical Unit Id
  210258. #define MAXTARG 7 // Maximum Target Id
  210259. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210260. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210261. //***************************************************************************
  210262. // %%% Commands for all Device Types %%%
  210263. //***************************************************************************
  210264. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210265. #define SCSI_COMPARE 0x39 // Compare (O)
  210266. #define SCSI_COPY 0x18 // Copy (O)
  210267. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210268. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210269. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210270. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210271. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210272. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210273. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210274. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210275. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210276. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210277. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210278. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210279. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210280. //***************************************************************************
  210281. // %%% Commands Unique to Direct Access Devices %%%
  210282. //***************************************************************************
  210283. #define SCSI_COMPARE 0x39 // Compare (O)
  210284. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210285. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210286. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210287. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210288. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210289. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210290. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210291. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210292. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210293. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210294. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210295. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210296. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210297. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210298. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210299. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210300. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210301. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210302. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210303. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210304. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210305. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210306. #define SCSI_VERIFY 0x2F // Verify (O)
  210307. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210308. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210309. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210310. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210311. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210312. //***************************************************************************
  210313. // %%% Commands Unique to Sequential Access Devices %%%
  210314. //***************************************************************************
  210315. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210316. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210317. #define SCSI_LOCATE 0x2B // Locate (O)
  210318. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210319. #define SCSI_READ_POS 0x34 // Read Position (O)
  210320. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210321. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210322. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210323. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210324. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210325. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210326. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210327. //***************************************************************************
  210328. // %%% Commands Unique to Printer Devices %%%
  210329. //***************************************************************************
  210330. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210331. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210332. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210333. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210334. //***************************************************************************
  210335. // %%% Commands Unique to Processor Devices %%%
  210336. //***************************************************************************
  210337. #define SCSI_RECEIVE 0x08 // Receive (O)
  210338. #define SCSI_SEND 0x0A // Send (O)
  210339. //***************************************************************************
  210340. // %%% Commands Unique to Write-Once Devices %%%
  210341. //***************************************************************************
  210342. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210343. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210344. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210345. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210346. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210347. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210348. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210349. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210350. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210351. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210352. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210353. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210354. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210355. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210356. //***************************************************************************
  210357. // %%% Commands Unique to CD-ROM Devices %%%
  210358. //***************************************************************************
  210359. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210360. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210361. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210362. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210363. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210364. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210365. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210366. #define SCSI_READHEADER 0x44 // Read Header (O)
  210367. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210368. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210369. //***************************************************************************
  210370. // %%% Commands Unique to Scanner Devices %%%
  210371. //***************************************************************************
  210372. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210373. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210374. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210375. #define SCSI_SCAN 0x1B // Scan (O)
  210376. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210377. //***************************************************************************
  210378. // %%% Commands Unique to Optical Memory Devices %%%
  210379. //***************************************************************************
  210380. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210381. //***************************************************************************
  210382. // %%% Commands Unique to Medium Changer Devices %%%
  210383. //***************************************************************************
  210384. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210385. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210386. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210387. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210388. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210389. //***************************************************************************
  210390. // %%% Commands Unique to Communication Devices %%%
  210391. //***************************************************************************
  210392. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210393. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210394. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210395. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210396. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210397. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210398. //***************************************************************************
  210399. // %%% Request Sense Data Format %%%
  210400. //***************************************************************************
  210401. typedef struct {
  210402. BYTE ErrorCode; // Error Code (70H or 71H)
  210403. BYTE SegmentNum; // Number of current segment descriptor
  210404. BYTE SenseKey; // Sense Key(See bit definitions too)
  210405. BYTE InfoByte0; // Information MSB
  210406. BYTE InfoByte1; // Information MID
  210407. BYTE InfoByte2; // Information MID
  210408. BYTE InfoByte3; // Information LSB
  210409. BYTE AddSenLen; // Additional Sense Length
  210410. BYTE ComSpecInf0; // Command Specific Information MSB
  210411. BYTE ComSpecInf1; // Command Specific Information MID
  210412. BYTE ComSpecInf2; // Command Specific Information MID
  210413. BYTE ComSpecInf3; // Command Specific Information LSB
  210414. BYTE AddSenseCode; // Additional Sense Code
  210415. BYTE AddSenQual; // Additional Sense Code Qualifier
  210416. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210417. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210418. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210419. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210420. BYTE AddSenseBytes; // Additional Sense Bytes
  210421. } SENSE_DATA_FMT;
  210422. //***************************************************************************
  210423. // %%% REQUEST SENSE ERROR CODE %%%
  210424. //***************************************************************************
  210425. #define SERROR_CURRENT 0x70 // Current Errors
  210426. #define SERROR_DEFERED 0x71 // Deferred Errors
  210427. //***************************************************************************
  210428. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210429. //***************************************************************************
  210430. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210431. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210432. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210433. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210434. //***************************************************************************
  210435. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210436. //***************************************************************************
  210437. #define KEY_NOSENSE 0x00 // No Sense
  210438. #define KEY_RECERROR 0x01 // Recovered Error
  210439. #define KEY_NOTREADY 0x02 // Not Ready
  210440. #define KEY_MEDIUMERR 0x03 // Medium Error
  210441. #define KEY_HARDERROR 0x04 // Hardware Error
  210442. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210443. #define KEY_UNITATT 0x06 // Unit Attention
  210444. #define KEY_DATAPROT 0x07 // Data Protect
  210445. #define KEY_BLANKCHK 0x08 // Blank Check
  210446. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210447. #define KEY_COPYABORT 0x0A // Copy Abort
  210448. #define KEY_EQUAL 0x0C // Equal (Search)
  210449. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210450. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210451. #define KEY_RESERVED 0x0F // Reserved
  210452. //***************************************************************************
  210453. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210454. //***************************************************************************
  210455. #define DTYPE_DASD 0x00 // Disk Device
  210456. #define DTYPE_SEQD 0x01 // Tape Device
  210457. #define DTYPE_PRNT 0x02 // Printer
  210458. #define DTYPE_PROC 0x03 // Processor
  210459. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210460. #define DTYPE_CROM 0x05 // CD-ROM device
  210461. #define DTYPE_SCAN 0x06 // Scanner device
  210462. #define DTYPE_OPTI 0x07 // Optical memory device
  210463. #define DTYPE_JUKE 0x08 // Medium Changer device
  210464. #define DTYPE_COMM 0x09 // Communications device
  210465. #define DTYPE_RESL 0x0A // Reserved (low)
  210466. #define DTYPE_RESH 0x1E // Reserved (high)
  210467. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210468. //***************************************************************************
  210469. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210470. //***************************************************************************
  210471. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210472. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210473. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210474. #define ANSI_RESLO 0x3 // Reserved (low)
  210475. #define ANSI_RESHI 0x7 // Reserved (high)
  210476. typedef struct
  210477. {
  210478. USHORT Length;
  210479. UCHAR ScsiStatus;
  210480. UCHAR PathId;
  210481. UCHAR TargetId;
  210482. UCHAR Lun;
  210483. UCHAR CdbLength;
  210484. UCHAR SenseInfoLength;
  210485. UCHAR DataIn;
  210486. ULONG DataTransferLength;
  210487. ULONG TimeOutValue;
  210488. ULONG DataBufferOffset;
  210489. ULONG SenseInfoOffset;
  210490. UCHAR Cdb[16];
  210491. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210492. typedef struct
  210493. {
  210494. USHORT Length;
  210495. UCHAR ScsiStatus;
  210496. UCHAR PathId;
  210497. UCHAR TargetId;
  210498. UCHAR Lun;
  210499. UCHAR CdbLength;
  210500. UCHAR SenseInfoLength;
  210501. UCHAR DataIn;
  210502. ULONG DataTransferLength;
  210503. ULONG TimeOutValue;
  210504. PVOID DataBuffer;
  210505. ULONG SenseInfoOffset;
  210506. UCHAR Cdb[16];
  210507. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210508. typedef struct
  210509. {
  210510. SCSI_PASS_THROUGH_DIRECT spt;
  210511. ULONG Filler;
  210512. UCHAR ucSenseBuf[32];
  210513. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210514. typedef struct
  210515. {
  210516. ULONG Length;
  210517. UCHAR PortNumber;
  210518. UCHAR PathId;
  210519. UCHAR TargetId;
  210520. UCHAR Lun;
  210521. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210522. #define METHOD_BUFFERED 0
  210523. #define METHOD_IN_DIRECT 1
  210524. #define METHOD_OUT_DIRECT 2
  210525. #define METHOD_NEITHER 3
  210526. #define FILE_ANY_ACCESS 0
  210527. #ifndef FILE_READ_ACCESS
  210528. #define FILE_READ_ACCESS (0x0001)
  210529. #endif
  210530. #ifndef FILE_WRITE_ACCESS
  210531. #define FILE_WRITE_ACCESS (0x0002)
  210532. #endif
  210533. #define IOCTL_SCSI_BASE 0x00000004
  210534. #define SCSI_IOCTL_DATA_OUT 0
  210535. #define SCSI_IOCTL_DATA_IN 1
  210536. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210537. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210538. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210539. )
  210540. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210541. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210542. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210543. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210544. #define SENSE_LEN 14
  210545. #define SRB_DIR_SCSI 0x00
  210546. #define SRB_POSTING 0x01
  210547. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210548. #define SRB_DIR_IN 0x08
  210549. #define SRB_DIR_OUT 0x10
  210550. #define SRB_EVENT_NOTIFY 0x40
  210551. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210552. #define MAX_SRB_TIMEOUT 1080001u
  210553. #define DEFAULT_SRB_TIMEOUT 1080001u
  210554. #define SC_HA_INQUIRY 0x00
  210555. #define SC_GET_DEV_TYPE 0x01
  210556. #define SC_EXEC_SCSI_CMD 0x02
  210557. #define SC_ABORT_SRB 0x03
  210558. #define SC_RESET_DEV 0x04
  210559. #define SC_SET_HA_PARMS 0x05
  210560. #define SC_GET_DISK_INFO 0x06
  210561. #define SC_RESCAN_SCSI_BUS 0x07
  210562. #define SC_GETSET_TIMEOUTS 0x08
  210563. #define SS_PENDING 0x00
  210564. #define SS_COMP 0x01
  210565. #define SS_ABORTED 0x02
  210566. #define SS_ABORT_FAIL 0x03
  210567. #define SS_ERR 0x04
  210568. #define SS_INVALID_CMD 0x80
  210569. #define SS_INVALID_HA 0x81
  210570. #define SS_NO_DEVICE 0x82
  210571. #define SS_INVALID_SRB 0xE0
  210572. #define SS_OLD_MANAGER 0xE1
  210573. #define SS_BUFFER_ALIGN 0xE1
  210574. #define SS_ILLEGAL_MODE 0xE2
  210575. #define SS_NO_ASPI 0xE3
  210576. #define SS_FAILED_INIT 0xE4
  210577. #define SS_ASPI_IS_BUSY 0xE5
  210578. #define SS_BUFFER_TO_BIG 0xE6
  210579. #define SS_BUFFER_TOO_BIG 0xE6
  210580. #define SS_MISMATCHED_COMPONENTS 0xE7
  210581. #define SS_NO_ADAPTERS 0xE8
  210582. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210583. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210584. #define SS_BAD_INSTALL 0xEB
  210585. #define HASTAT_OK 0x00
  210586. #define HASTAT_SEL_TO 0x11
  210587. #define HASTAT_DO_DU 0x12
  210588. #define HASTAT_BUS_FREE 0x13
  210589. #define HASTAT_PHASE_ERR 0x14
  210590. #define HASTAT_TIMEOUT 0x09
  210591. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210592. #define HASTAT_MESSAGE_REJECT 0x0D
  210593. #define HASTAT_BUS_RESET 0x0E
  210594. #define HASTAT_PARITY_ERROR 0x0F
  210595. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210596. #define PACKED
  210597. #pragma pack(1)
  210598. typedef struct
  210599. {
  210600. BYTE SRB_Cmd;
  210601. BYTE SRB_Status;
  210602. BYTE SRB_HaID;
  210603. BYTE SRB_Flags;
  210604. DWORD SRB_Hdr_Rsvd;
  210605. BYTE HA_Count;
  210606. BYTE HA_SCSI_ID;
  210607. BYTE HA_ManagerId[16];
  210608. BYTE HA_Identifier[16];
  210609. BYTE HA_Unique[16];
  210610. WORD HA_Rsvd1;
  210611. BYTE pad[20];
  210612. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210613. typedef struct
  210614. {
  210615. BYTE SRB_Cmd;
  210616. BYTE SRB_Status;
  210617. BYTE SRB_HaID;
  210618. BYTE SRB_Flags;
  210619. DWORD SRB_Hdr_Rsvd;
  210620. BYTE SRB_Target;
  210621. BYTE SRB_Lun;
  210622. BYTE SRB_DeviceType;
  210623. BYTE SRB_Rsvd1;
  210624. BYTE pad[68];
  210625. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210626. typedef struct
  210627. {
  210628. BYTE SRB_Cmd;
  210629. BYTE SRB_Status;
  210630. BYTE SRB_HaID;
  210631. BYTE SRB_Flags;
  210632. DWORD SRB_Hdr_Rsvd;
  210633. BYTE SRB_Target;
  210634. BYTE SRB_Lun;
  210635. WORD SRB_Rsvd1;
  210636. DWORD SRB_BufLen;
  210637. BYTE FAR *SRB_BufPointer;
  210638. BYTE SRB_SenseLen;
  210639. BYTE SRB_CDBLen;
  210640. BYTE SRB_HaStat;
  210641. BYTE SRB_TargStat;
  210642. VOID FAR *SRB_PostProc;
  210643. BYTE SRB_Rsvd2[20];
  210644. BYTE CDBByte[16];
  210645. BYTE SenseArea[SENSE_LEN+2];
  210646. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210647. typedef struct
  210648. {
  210649. BYTE SRB_Cmd;
  210650. BYTE SRB_Status;
  210651. BYTE SRB_HaId;
  210652. BYTE SRB_Flags;
  210653. DWORD SRB_Hdr_Rsvd;
  210654. } PACKED SRB, *PSRB, FAR *LPSRB;
  210655. #pragma pack()
  210656. struct CDDeviceInfo
  210657. {
  210658. char vendor[9];
  210659. char productId[17];
  210660. char rev[5];
  210661. char vendorSpec[21];
  210662. BYTE ha;
  210663. BYTE tgt;
  210664. BYTE lun;
  210665. char scsiDriveLetter; // will be 0 if not using scsi
  210666. };
  210667. class CDReadBuffer
  210668. {
  210669. public:
  210670. int startFrame;
  210671. int numFrames;
  210672. int dataStartOffset;
  210673. int dataLength;
  210674. int bufferSize;
  210675. HeapBlock<BYTE> buffer;
  210676. int index;
  210677. bool wantsIndex;
  210678. CDReadBuffer (const int numberOfFrames)
  210679. : startFrame (0),
  210680. numFrames (0),
  210681. dataStartOffset (0),
  210682. dataLength (0),
  210683. bufferSize (2352 * numberOfFrames),
  210684. buffer (bufferSize),
  210685. index (0),
  210686. wantsIndex (false)
  210687. {
  210688. }
  210689. bool isZero() const throw()
  210690. {
  210691. BYTE* p = buffer + dataStartOffset;
  210692. for (int i = dataLength; --i >= 0;)
  210693. if (*p++ != 0)
  210694. return false;
  210695. return true;
  210696. }
  210697. };
  210698. class CDDeviceHandle;
  210699. class CDController
  210700. {
  210701. public:
  210702. CDController();
  210703. virtual ~CDController();
  210704. virtual bool read (CDReadBuffer* t) = 0;
  210705. virtual void shutDown();
  210706. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210707. int getLastIndex();
  210708. public:
  210709. bool initialised;
  210710. CDDeviceHandle* deviceInfo;
  210711. int framesToCheck, framesOverlap;
  210712. void prepare (SRB_ExecSCSICmd& s);
  210713. void perform (SRB_ExecSCSICmd& s);
  210714. void setPaused (bool paused);
  210715. };
  210716. #pragma pack(1)
  210717. struct TOCTRACK
  210718. {
  210719. BYTE rsvd;
  210720. BYTE ADR;
  210721. BYTE trackNumber;
  210722. BYTE rsvd2;
  210723. BYTE addr[4];
  210724. };
  210725. struct TOC
  210726. {
  210727. WORD tocLen;
  210728. BYTE firstTrack;
  210729. BYTE lastTrack;
  210730. TOCTRACK tracks[100];
  210731. };
  210732. #pragma pack()
  210733. enum
  210734. {
  210735. READTYPE_ANY = 0,
  210736. READTYPE_ATAPI1 = 1,
  210737. READTYPE_ATAPI2 = 2,
  210738. READTYPE_READ6 = 3,
  210739. READTYPE_READ10 = 4,
  210740. READTYPE_READ_D8 = 5,
  210741. READTYPE_READ_D4 = 6,
  210742. READTYPE_READ_D4_1 = 7,
  210743. READTYPE_READ10_2 = 8
  210744. };
  210745. class CDDeviceHandle
  210746. {
  210747. public:
  210748. CDDeviceHandle (const CDDeviceInfo* const device)
  210749. : scsiHandle (0),
  210750. readType (READTYPE_ANY),
  210751. controller (0)
  210752. {
  210753. memcpy (&info, device, sizeof (info));
  210754. }
  210755. ~CDDeviceHandle()
  210756. {
  210757. if (controller != 0)
  210758. {
  210759. controller->shutDown();
  210760. controller = 0;
  210761. }
  210762. if (scsiHandle != 0)
  210763. CloseHandle (scsiHandle);
  210764. }
  210765. bool readTOC (TOC* lpToc);
  210766. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  210767. void openDrawer (bool shouldBeOpen);
  210768. CDDeviceInfo info;
  210769. HANDLE scsiHandle;
  210770. BYTE readType;
  210771. private:
  210772. ScopedPointer<CDController> controller;
  210773. bool testController (const int readType,
  210774. CDController* const newController,
  210775. CDReadBuffer* const bufferToUse);
  210776. };
  210777. DWORD (*fGetASPI32SupportInfo)(void);
  210778. DWORD (*fSendASPI32Command)(LPSRB);
  210779. static HINSTANCE winAspiLib = 0;
  210780. static bool usingScsi = false;
  210781. static bool initialised = false;
  210782. static bool InitialiseCDRipper()
  210783. {
  210784. if (! initialised)
  210785. {
  210786. initialised = true;
  210787. OSVERSIONINFO info;
  210788. info.dwOSVersionInfoSize = sizeof (info);
  210789. GetVersionEx (&info);
  210790. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  210791. if (! usingScsi)
  210792. {
  210793. fGetASPI32SupportInfo = 0;
  210794. fSendASPI32Command = 0;
  210795. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  210796. if (winAspiLib != 0)
  210797. {
  210798. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  210799. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  210800. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  210801. return false;
  210802. }
  210803. else
  210804. {
  210805. usingScsi = true;
  210806. }
  210807. }
  210808. }
  210809. return true;
  210810. }
  210811. static void DeinitialiseCDRipper()
  210812. {
  210813. if (winAspiLib != 0)
  210814. {
  210815. fGetASPI32SupportInfo = 0;
  210816. fSendASPI32Command = 0;
  210817. FreeLibrary (winAspiLib);
  210818. winAspiLib = 0;
  210819. }
  210820. initialised = false;
  210821. }
  210822. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  210823. {
  210824. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210825. OSVERSIONINFO info;
  210826. info.dwOSVersionInfoSize = sizeof (info);
  210827. GetVersionEx (&info);
  210828. DWORD flags = GENERIC_READ;
  210829. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  210830. flags = GENERIC_READ | GENERIC_WRITE;
  210831. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210832. if (h == INVALID_HANDLE_VALUE)
  210833. {
  210834. flags ^= GENERIC_WRITE;
  210835. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210836. }
  210837. return h;
  210838. }
  210839. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  210840. const char driveLetter,
  210841. HANDLE& deviceHandle,
  210842. const bool retryOnFailure = true)
  210843. {
  210844. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210845. zerostruct (s);
  210846. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210847. s.spt.CdbLength = srb->SRB_CDBLen;
  210848. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210849. ? SCSI_IOCTL_DATA_IN
  210850. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210851. ? SCSI_IOCTL_DATA_OUT
  210852. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210853. s.spt.DataTransferLength = srb->SRB_BufLen;
  210854. s.spt.TimeOutValue = 5;
  210855. s.spt.DataBuffer = srb->SRB_BufPointer;
  210856. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210857. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210858. srb->SRB_Status = SS_ERR;
  210859. srb->SRB_TargStat = 0x0004;
  210860. DWORD bytesReturned = 0;
  210861. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210862. &s, sizeof (s),
  210863. &s, sizeof (s),
  210864. &bytesReturned, 0) != 0)
  210865. {
  210866. srb->SRB_Status = SS_COMP;
  210867. }
  210868. else if (retryOnFailure)
  210869. {
  210870. const DWORD error = GetLastError();
  210871. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210872. {
  210873. if (error != ERROR_INVALID_HANDLE)
  210874. CloseHandle (deviceHandle);
  210875. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  210876. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210877. }
  210878. }
  210879. return srb->SRB_Status;
  210880. }
  210881. // Controller types..
  210882. class ControllerType1 : public CDController
  210883. {
  210884. public:
  210885. ControllerType1() {}
  210886. ~ControllerType1() {}
  210887. bool read (CDReadBuffer* rb)
  210888. {
  210889. if (rb->numFrames * 2352 > rb->bufferSize)
  210890. return false;
  210891. SRB_ExecSCSICmd s;
  210892. prepare (s);
  210893. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210894. s.SRB_BufLen = rb->bufferSize;
  210895. s.SRB_BufPointer = rb->buffer;
  210896. s.SRB_CDBLen = 12;
  210897. s.CDBByte[0] = 0xBE;
  210898. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  210899. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  210900. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  210901. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  210902. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  210903. perform (s);
  210904. if (s.SRB_Status != SS_COMP)
  210905. return false;
  210906. rb->dataLength = rb->numFrames * 2352;
  210907. rb->dataStartOffset = 0;
  210908. return true;
  210909. }
  210910. };
  210911. class ControllerType2 : public CDController
  210912. {
  210913. public:
  210914. ControllerType2() {}
  210915. ~ControllerType2() {}
  210916. void shutDown()
  210917. {
  210918. if (initialised)
  210919. {
  210920. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210921. SRB_ExecSCSICmd s;
  210922. prepare (s);
  210923. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210924. s.SRB_BufLen = 0x0C;
  210925. s.SRB_BufPointer = bufPointer;
  210926. s.SRB_CDBLen = 6;
  210927. s.CDBByte[0] = 0x15;
  210928. s.CDBByte[4] = 0x0C;
  210929. perform (s);
  210930. }
  210931. }
  210932. bool init()
  210933. {
  210934. SRB_ExecSCSICmd s;
  210935. s.SRB_Status = SS_ERR;
  210936. if (deviceInfo->readType == READTYPE_READ10_2)
  210937. {
  210938. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210939. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210940. for (int i = 0; i < 2; ++i)
  210941. {
  210942. prepare (s);
  210943. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210944. s.SRB_BufLen = 0x14;
  210945. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  210946. s.SRB_CDBLen = 6;
  210947. s.CDBByte[0] = 0x15;
  210948. s.CDBByte[1] = 0x10;
  210949. s.CDBByte[4] = 0x14;
  210950. perform (s);
  210951. if (s.SRB_Status != SS_COMP)
  210952. return false;
  210953. }
  210954. }
  210955. else
  210956. {
  210957. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  210958. prepare (s);
  210959. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210960. s.SRB_BufLen = 0x0C;
  210961. s.SRB_BufPointer = bufPointer;
  210962. s.SRB_CDBLen = 6;
  210963. s.CDBByte[0] = 0x15;
  210964. s.CDBByte[4] = 0x0C;
  210965. perform (s);
  210966. }
  210967. return s.SRB_Status == SS_COMP;
  210968. }
  210969. bool read (CDReadBuffer* rb)
  210970. {
  210971. if (rb->numFrames * 2352 > rb->bufferSize)
  210972. return false;
  210973. if (!initialised)
  210974. {
  210975. initialised = init();
  210976. if (!initialised)
  210977. return false;
  210978. }
  210979. SRB_ExecSCSICmd s;
  210980. prepare (s);
  210981. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210982. s.SRB_BufLen = rb->bufferSize;
  210983. s.SRB_BufPointer = rb->buffer;
  210984. s.SRB_CDBLen = 10;
  210985. s.CDBByte[0] = 0x28;
  210986. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  210987. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  210988. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  210989. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  210990. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  210991. perform (s);
  210992. if (s.SRB_Status != SS_COMP)
  210993. return false;
  210994. rb->dataLength = rb->numFrames * 2352;
  210995. rb->dataStartOffset = 0;
  210996. return true;
  210997. }
  210998. };
  210999. class ControllerType3 : public CDController
  211000. {
  211001. public:
  211002. ControllerType3() {}
  211003. ~ControllerType3() {}
  211004. bool read (CDReadBuffer* rb)
  211005. {
  211006. if (rb->numFrames * 2352 > rb->bufferSize)
  211007. return false;
  211008. if (!initialised)
  211009. {
  211010. setPaused (false);
  211011. initialised = true;
  211012. }
  211013. SRB_ExecSCSICmd s;
  211014. prepare (s);
  211015. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211016. s.SRB_BufLen = rb->numFrames * 2352;
  211017. s.SRB_BufPointer = rb->buffer;
  211018. s.SRB_CDBLen = 12;
  211019. s.CDBByte[0] = 0xD8;
  211020. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211021. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211022. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211023. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211024. perform (s);
  211025. if (s.SRB_Status != SS_COMP)
  211026. return false;
  211027. rb->dataLength = rb->numFrames * 2352;
  211028. rb->dataStartOffset = 0;
  211029. return true;
  211030. }
  211031. };
  211032. class ControllerType4 : public CDController
  211033. {
  211034. public:
  211035. ControllerType4() {}
  211036. ~ControllerType4() {}
  211037. bool selectD4Mode()
  211038. {
  211039. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211040. SRB_ExecSCSICmd s;
  211041. prepare (s);
  211042. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211043. s.SRB_CDBLen = 6;
  211044. s.SRB_BufLen = 12;
  211045. s.SRB_BufPointer = bufPointer;
  211046. s.CDBByte[0] = 0x15;
  211047. s.CDBByte[1] = 0x10;
  211048. s.CDBByte[4] = 0x08;
  211049. perform (s);
  211050. return s.SRB_Status == SS_COMP;
  211051. }
  211052. bool read (CDReadBuffer* rb)
  211053. {
  211054. if (rb->numFrames * 2352 > rb->bufferSize)
  211055. return false;
  211056. if (!initialised)
  211057. {
  211058. setPaused (true);
  211059. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211060. selectD4Mode();
  211061. initialised = true;
  211062. }
  211063. SRB_ExecSCSICmd s;
  211064. prepare (s);
  211065. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211066. s.SRB_BufLen = rb->bufferSize;
  211067. s.SRB_BufPointer = rb->buffer;
  211068. s.SRB_CDBLen = 10;
  211069. s.CDBByte[0] = 0xD4;
  211070. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211071. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211072. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211073. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211074. perform (s);
  211075. if (s.SRB_Status != SS_COMP)
  211076. return false;
  211077. rb->dataLength = rb->numFrames * 2352;
  211078. rb->dataStartOffset = 0;
  211079. return true;
  211080. }
  211081. };
  211082. CDController::CDController() : initialised (false)
  211083. {
  211084. }
  211085. CDController::~CDController()
  211086. {
  211087. }
  211088. void CDController::prepare (SRB_ExecSCSICmd& s)
  211089. {
  211090. zerostruct (s);
  211091. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211092. s.SRB_HaID = deviceInfo->info.ha;
  211093. s.SRB_Target = deviceInfo->info.tgt;
  211094. s.SRB_Lun = deviceInfo->info.lun;
  211095. s.SRB_SenseLen = SENSE_LEN;
  211096. }
  211097. void CDController::perform (SRB_ExecSCSICmd& s)
  211098. {
  211099. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211100. s.SRB_PostProc = event;
  211101. ResetEvent (event);
  211102. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211103. deviceInfo->info.scsiDriveLetter,
  211104. deviceInfo->scsiHandle)
  211105. : fSendASPI32Command ((LPSRB)&s);
  211106. if (status == SS_PENDING)
  211107. WaitForSingleObject (event, 4000);
  211108. CloseHandle (event);
  211109. }
  211110. void CDController::setPaused (bool paused)
  211111. {
  211112. SRB_ExecSCSICmd s;
  211113. prepare (s);
  211114. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211115. s.SRB_CDBLen = 10;
  211116. s.CDBByte[0] = 0x4B;
  211117. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211118. perform (s);
  211119. }
  211120. void CDController::shutDown()
  211121. {
  211122. }
  211123. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211124. {
  211125. if (overlapBuffer != 0)
  211126. {
  211127. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211128. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211129. if (doJitter
  211130. && overlapBuffer->startFrame > 0
  211131. && overlapBuffer->numFrames > 0
  211132. && overlapBuffer->dataLength > 0)
  211133. {
  211134. const int numFrames = rb->numFrames;
  211135. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211136. {
  211137. rb->startFrame -= framesOverlap;
  211138. if (framesToCheck < framesOverlap
  211139. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211140. rb->numFrames += framesOverlap;
  211141. }
  211142. else
  211143. {
  211144. overlapBuffer->dataLength = 0;
  211145. overlapBuffer->startFrame = 0;
  211146. overlapBuffer->numFrames = 0;
  211147. }
  211148. }
  211149. if (! read (rb))
  211150. return false;
  211151. if (doJitter)
  211152. {
  211153. const int checkLen = framesToCheck * 2352;
  211154. const int maxToCheck = rb->dataLength - checkLen;
  211155. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211156. return true;
  211157. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211158. bool found = false;
  211159. for (int i = 0; i < maxToCheck; ++i)
  211160. {
  211161. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211162. {
  211163. i += checkLen;
  211164. rb->dataStartOffset = i;
  211165. rb->dataLength -= i;
  211166. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211167. found = true;
  211168. break;
  211169. }
  211170. }
  211171. rb->numFrames = rb->dataLength / 2352;
  211172. rb->dataLength = 2352 * rb->numFrames;
  211173. if (!found)
  211174. return false;
  211175. }
  211176. if (canDoJitter)
  211177. {
  211178. memcpy (overlapBuffer->buffer,
  211179. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211180. 2352 * framesToCheck);
  211181. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211182. overlapBuffer->numFrames = framesToCheck;
  211183. overlapBuffer->dataLength = 2352 * framesToCheck;
  211184. overlapBuffer->dataStartOffset = 0;
  211185. }
  211186. else
  211187. {
  211188. overlapBuffer->startFrame = 0;
  211189. overlapBuffer->numFrames = 0;
  211190. overlapBuffer->dataLength = 0;
  211191. }
  211192. return true;
  211193. }
  211194. else
  211195. {
  211196. return read (rb);
  211197. }
  211198. }
  211199. int CDController::getLastIndex()
  211200. {
  211201. char qdata[100];
  211202. SRB_ExecSCSICmd s;
  211203. prepare (s);
  211204. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211205. s.SRB_BufLen = sizeof (qdata);
  211206. s.SRB_BufPointer = (BYTE*)qdata;
  211207. s.SRB_CDBLen = 12;
  211208. s.CDBByte[0] = 0x42;
  211209. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211210. s.CDBByte[2] = 64;
  211211. s.CDBByte[3] = 1; // get current position
  211212. s.CDBByte[7] = 0;
  211213. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211214. perform (s);
  211215. if (s.SRB_Status == SS_COMP)
  211216. return qdata[7];
  211217. return 0;
  211218. }
  211219. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211220. {
  211221. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211222. SRB_ExecSCSICmd s;
  211223. zerostruct (s);
  211224. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211225. s.SRB_HaID = info.ha;
  211226. s.SRB_Target = info.tgt;
  211227. s.SRB_Lun = info.lun;
  211228. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211229. s.SRB_BufLen = 0x324;
  211230. s.SRB_BufPointer = (BYTE*)lpToc;
  211231. s.SRB_SenseLen = 0x0E;
  211232. s.SRB_CDBLen = 0x0A;
  211233. s.SRB_PostProc = event;
  211234. s.CDBByte[0] = 0x43;
  211235. s.CDBByte[1] = 0x00;
  211236. s.CDBByte[7] = 0x03;
  211237. s.CDBByte[8] = 0x24;
  211238. ResetEvent (event);
  211239. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211240. : fSendASPI32Command ((LPSRB)&s);
  211241. if (status == SS_PENDING)
  211242. WaitForSingleObject (event, 4000);
  211243. CloseHandle (event);
  211244. return (s.SRB_Status == SS_COMP);
  211245. }
  211246. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211247. CDReadBuffer* const overlapBuffer)
  211248. {
  211249. if (controller == 0)
  211250. {
  211251. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211252. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211253. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211254. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211255. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211256. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211257. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211258. }
  211259. buffer->index = 0;
  211260. if ((controller != 0)
  211261. && controller->readAudio (buffer, overlapBuffer))
  211262. {
  211263. if (buffer->wantsIndex)
  211264. buffer->index = controller->getLastIndex();
  211265. return true;
  211266. }
  211267. return false;
  211268. }
  211269. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211270. {
  211271. if (shouldBeOpen)
  211272. {
  211273. if (controller != 0)
  211274. {
  211275. controller->shutDown();
  211276. controller = 0;
  211277. }
  211278. if (scsiHandle != 0)
  211279. {
  211280. CloseHandle (scsiHandle);
  211281. scsiHandle = 0;
  211282. }
  211283. }
  211284. SRB_ExecSCSICmd s;
  211285. zerostruct (s);
  211286. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211287. s.SRB_HaID = info.ha;
  211288. s.SRB_Target = info.tgt;
  211289. s.SRB_Lun = info.lun;
  211290. s.SRB_SenseLen = SENSE_LEN;
  211291. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211292. s.SRB_BufLen = 0;
  211293. s.SRB_BufPointer = 0;
  211294. s.SRB_CDBLen = 12;
  211295. s.CDBByte[0] = 0x1b;
  211296. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211297. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211298. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211299. s.SRB_PostProc = event;
  211300. ResetEvent (event);
  211301. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211302. : fSendASPI32Command ((LPSRB)&s);
  211303. if (status == SS_PENDING)
  211304. WaitForSingleObject (event, 4000);
  211305. CloseHandle (event);
  211306. }
  211307. bool CDDeviceHandle::testController (const int type,
  211308. CDController* const newController,
  211309. CDReadBuffer* const rb)
  211310. {
  211311. controller = newController;
  211312. readType = (BYTE)type;
  211313. controller->deviceInfo = this;
  211314. controller->framesToCheck = 1;
  211315. controller->framesOverlap = 3;
  211316. bool passed = false;
  211317. memset (rb->buffer, 0xcd, rb->bufferSize);
  211318. if (controller->read (rb))
  211319. {
  211320. passed = true;
  211321. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211322. int wrong = 0;
  211323. for (int i = rb->dataLength / 4; --i >= 0;)
  211324. {
  211325. if (*p++ == (int) 0xcdcdcdcd)
  211326. {
  211327. if (++wrong == 4)
  211328. {
  211329. passed = false;
  211330. break;
  211331. }
  211332. }
  211333. else
  211334. {
  211335. wrong = 0;
  211336. }
  211337. }
  211338. }
  211339. if (! passed)
  211340. {
  211341. controller->shutDown();
  211342. controller = 0;
  211343. }
  211344. return passed;
  211345. }
  211346. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211347. {
  211348. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211349. const int bufSize = 128;
  211350. BYTE buffer[bufSize];
  211351. zeromem (buffer, bufSize);
  211352. SRB_ExecSCSICmd s;
  211353. zerostruct (s);
  211354. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211355. s.SRB_HaID = ha;
  211356. s.SRB_Target = tgt;
  211357. s.SRB_Lun = lun;
  211358. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211359. s.SRB_BufLen = bufSize;
  211360. s.SRB_BufPointer = buffer;
  211361. s.SRB_SenseLen = SENSE_LEN;
  211362. s.SRB_CDBLen = 6;
  211363. s.SRB_PostProc = event;
  211364. s.CDBByte[0] = SCSI_INQUIRY;
  211365. s.CDBByte[4] = 100;
  211366. ResetEvent (event);
  211367. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211368. WaitForSingleObject (event, 4000);
  211369. CloseHandle (event);
  211370. if (s.SRB_Status == SS_COMP)
  211371. {
  211372. memcpy (dev->vendor, &buffer[8], 8);
  211373. memcpy (dev->productId, &buffer[16], 16);
  211374. memcpy (dev->rev, &buffer[32], 4);
  211375. memcpy (dev->vendorSpec, &buffer[36], 20);
  211376. }
  211377. }
  211378. static int FindCDDevices (CDDeviceInfo* const list,
  211379. int maxItems)
  211380. {
  211381. int count = 0;
  211382. if (usingScsi)
  211383. {
  211384. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211385. {
  211386. TCHAR drivePath[8];
  211387. drivePath[0] = driveLetter;
  211388. drivePath[1] = ':';
  211389. drivePath[2] = '\\';
  211390. drivePath[3] = 0;
  211391. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211392. {
  211393. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211394. if (h != INVALID_HANDLE_VALUE)
  211395. {
  211396. BYTE buffer[100], passThroughStruct[1024];
  211397. zeromem (buffer, sizeof (buffer));
  211398. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211399. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211400. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211401. p->spt.CdbLength = 6;
  211402. p->spt.SenseInfoLength = 24;
  211403. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211404. p->spt.DataTransferLength = 100;
  211405. p->spt.TimeOutValue = 2;
  211406. p->spt.DataBuffer = buffer;
  211407. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211408. p->spt.Cdb[0] = 0x12;
  211409. p->spt.Cdb[4] = 100;
  211410. DWORD bytesReturned = 0;
  211411. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211412. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211413. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211414. &bytesReturned, 0) != 0)
  211415. {
  211416. zeromem (&list[count], sizeof (CDDeviceInfo));
  211417. list[count].scsiDriveLetter = driveLetter;
  211418. memcpy (list[count].vendor, &buffer[8], 8);
  211419. memcpy (list[count].productId, &buffer[16], 16);
  211420. memcpy (list[count].rev, &buffer[32], 4);
  211421. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211422. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211423. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211424. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211425. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211426. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211427. &bytesReturned, 0) != 0)
  211428. {
  211429. list[count].ha = scsiAddr->PortNumber;
  211430. list[count].tgt = scsiAddr->TargetId;
  211431. list[count].lun = scsiAddr->Lun;
  211432. ++count;
  211433. }
  211434. }
  211435. CloseHandle (h);
  211436. }
  211437. }
  211438. }
  211439. }
  211440. else
  211441. {
  211442. const DWORD d = fGetASPI32SupportInfo();
  211443. BYTE status = HIBYTE (LOWORD (d));
  211444. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211445. return 0;
  211446. const int numAdapters = LOBYTE (LOWORD (d));
  211447. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211448. {
  211449. SRB_HAInquiry s;
  211450. zerostruct (s);
  211451. s.SRB_Cmd = SC_HA_INQUIRY;
  211452. s.SRB_HaID = ha;
  211453. fSendASPI32Command ((LPSRB)&s);
  211454. if (s.SRB_Status == SS_COMP)
  211455. {
  211456. maxItems = (int)s.HA_Unique[3];
  211457. if (maxItems == 0)
  211458. maxItems = 8;
  211459. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211460. {
  211461. for (BYTE lun = 0; lun < 8; ++lun)
  211462. {
  211463. SRB_GDEVBlock sb;
  211464. zerostruct (sb);
  211465. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211466. sb.SRB_HaID = ha;
  211467. sb.SRB_Target = tgt;
  211468. sb.SRB_Lun = lun;
  211469. fSendASPI32Command ((LPSRB) &sb);
  211470. if (sb.SRB_Status == SS_COMP
  211471. && sb.SRB_DeviceType == DTYPE_CROM)
  211472. {
  211473. zeromem (&list[count], sizeof (CDDeviceInfo));
  211474. list[count].ha = ha;
  211475. list[count].tgt = tgt;
  211476. list[count].lun = lun;
  211477. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211478. ++count;
  211479. }
  211480. }
  211481. }
  211482. }
  211483. }
  211484. }
  211485. return count;
  211486. }
  211487. static int ripperUsers = 0;
  211488. static bool initialisedOk = false;
  211489. class DeinitialiseTimer : private Timer,
  211490. private DeletedAtShutdown
  211491. {
  211492. DeinitialiseTimer (const DeinitialiseTimer&);
  211493. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211494. public:
  211495. DeinitialiseTimer()
  211496. {
  211497. startTimer (4000);
  211498. }
  211499. ~DeinitialiseTimer()
  211500. {
  211501. if (--ripperUsers == 0)
  211502. DeinitialiseCDRipper();
  211503. }
  211504. void timerCallback()
  211505. {
  211506. delete this;
  211507. }
  211508. juce_UseDebuggingNewOperator
  211509. };
  211510. static void incUserCount()
  211511. {
  211512. if (ripperUsers++ == 0)
  211513. initialisedOk = InitialiseCDRipper();
  211514. }
  211515. static void decUserCount()
  211516. {
  211517. new DeinitialiseTimer();
  211518. }
  211519. struct CDDeviceWrapper
  211520. {
  211521. ScopedPointer<CDDeviceHandle> cdH;
  211522. ScopedPointer<CDReadBuffer> overlapBuffer;
  211523. bool jitter;
  211524. };
  211525. static int getAddressOf (const TOCTRACK* const t)
  211526. {
  211527. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211528. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211529. }
  211530. static const int samplesPerFrame = 44100 / 75;
  211531. static const int bytesPerFrame = samplesPerFrame * 4;
  211532. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211533. {
  211534. SRB_GDEVBlock s;
  211535. zerostruct (s);
  211536. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211537. s.SRB_HaID = device->ha;
  211538. s.SRB_Target = device->tgt;
  211539. s.SRB_Lun = device->lun;
  211540. if (usingScsi)
  211541. {
  211542. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211543. if (h != INVALID_HANDLE_VALUE)
  211544. {
  211545. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211546. cdh->scsiHandle = h;
  211547. return cdh;
  211548. }
  211549. }
  211550. else
  211551. {
  211552. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211553. && s.SRB_DeviceType == DTYPE_CROM)
  211554. {
  211555. return new CDDeviceHandle (device);
  211556. }
  211557. }
  211558. return 0;
  211559. }
  211560. }
  211561. const StringArray AudioCDReader::getAvailableCDNames()
  211562. {
  211563. using namespace CDReaderHelpers;
  211564. StringArray results;
  211565. incUserCount();
  211566. if (initialisedOk)
  211567. {
  211568. CDDeviceInfo list[8];
  211569. const int num = FindCDDevices (list, 8);
  211570. decUserCount();
  211571. for (int i = 0; i < num; ++i)
  211572. {
  211573. String s;
  211574. if (list[i].scsiDriveLetter > 0)
  211575. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211576. s << String (list[i].vendor).trim()
  211577. << ' ' << String (list[i].productId).trim()
  211578. << ' ' << String (list[i].rev).trim();
  211579. results.add (s);
  211580. }
  211581. }
  211582. return results;
  211583. }
  211584. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211585. {
  211586. using namespace CDReaderHelpers;
  211587. incUserCount();
  211588. if (initialisedOk)
  211589. {
  211590. CDDeviceInfo list[8];
  211591. const int num = FindCDDevices (list, 8);
  211592. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211593. {
  211594. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211595. if (handle != 0)
  211596. {
  211597. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211598. d->cdH = handle;
  211599. d->overlapBuffer = new CDReadBuffer(3);
  211600. return new AudioCDReader (d);
  211601. }
  211602. }
  211603. }
  211604. decUserCount();
  211605. return 0;
  211606. }
  211607. AudioCDReader::AudioCDReader (void* handle_)
  211608. : AudioFormatReader (0, "CD Audio"),
  211609. handle (handle_),
  211610. indexingEnabled (false),
  211611. lastIndex (0),
  211612. firstFrameInBuffer (0),
  211613. samplesInBuffer (0)
  211614. {
  211615. using namespace CDReaderHelpers;
  211616. jassert (handle_ != 0);
  211617. refreshTrackLengths();
  211618. sampleRate = 44100.0;
  211619. bitsPerSample = 16;
  211620. numChannels = 2;
  211621. usesFloatingPointData = false;
  211622. buffer.setSize (4 * bytesPerFrame, true);
  211623. }
  211624. AudioCDReader::~AudioCDReader()
  211625. {
  211626. using namespace CDReaderHelpers;
  211627. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211628. delete device;
  211629. decUserCount();
  211630. }
  211631. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211632. int64 startSampleInFile, int numSamples)
  211633. {
  211634. using namespace CDReaderHelpers;
  211635. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211636. bool ok = true;
  211637. while (numSamples > 0)
  211638. {
  211639. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211640. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211641. if (startSampleInFile >= bufferStartSample
  211642. && startSampleInFile < bufferEndSample)
  211643. {
  211644. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211645. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211646. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211647. const short* src = (const short*) buffer.getData();
  211648. src += 2 * (startSampleInFile - bufferStartSample);
  211649. for (int i = 0; i < toDo; ++i)
  211650. {
  211651. l[i] = src [i << 1] << 16;
  211652. if (r != 0)
  211653. r[i] = src [(i << 1) + 1] << 16;
  211654. }
  211655. startOffsetInDestBuffer += toDo;
  211656. startSampleInFile += toDo;
  211657. numSamples -= toDo;
  211658. }
  211659. else
  211660. {
  211661. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211662. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211663. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211664. {
  211665. device->overlapBuffer->dataLength = 0;
  211666. device->overlapBuffer->startFrame = 0;
  211667. device->overlapBuffer->numFrames = 0;
  211668. device->jitter = false;
  211669. }
  211670. firstFrameInBuffer = frameNeeded;
  211671. lastIndex = 0;
  211672. CDReadBuffer readBuffer (framesInBuffer + 4);
  211673. readBuffer.wantsIndex = indexingEnabled;
  211674. int i;
  211675. for (i = 5; --i >= 0;)
  211676. {
  211677. readBuffer.startFrame = frameNeeded;
  211678. readBuffer.numFrames = framesInBuffer;
  211679. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211680. break;
  211681. else
  211682. device->overlapBuffer->dataLength = 0;
  211683. }
  211684. if (i >= 0)
  211685. {
  211686. memcpy ((char*) buffer.getData(),
  211687. readBuffer.buffer + readBuffer.dataStartOffset,
  211688. readBuffer.dataLength);
  211689. samplesInBuffer = readBuffer.dataLength >> 2;
  211690. lastIndex = readBuffer.index;
  211691. }
  211692. else
  211693. {
  211694. int* l = destSamples[0] + startOffsetInDestBuffer;
  211695. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211696. while (--numSamples >= 0)
  211697. {
  211698. *l++ = 0;
  211699. if (r != 0)
  211700. *r++ = 0;
  211701. }
  211702. // sometimes the read fails for just the very last couple of blocks, so
  211703. // we'll ignore and errors in the last half-second of the disk..
  211704. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211705. break;
  211706. }
  211707. }
  211708. }
  211709. return ok;
  211710. }
  211711. bool AudioCDReader::isCDStillPresent() const
  211712. {
  211713. using namespace CDReaderHelpers;
  211714. TOC toc;
  211715. zerostruct (toc);
  211716. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  211717. }
  211718. void AudioCDReader::refreshTrackLengths()
  211719. {
  211720. using namespace CDReaderHelpers;
  211721. trackStartSamples.clear();
  211722. zeromem (audioTracks, sizeof (audioTracks));
  211723. TOC toc;
  211724. zerostruct (toc);
  211725. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  211726. {
  211727. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211728. for (int i = 0; i <= numTracks; ++i)
  211729. {
  211730. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  211731. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211732. }
  211733. }
  211734. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211735. }
  211736. bool AudioCDReader::isTrackAudio (int trackNum) const
  211737. {
  211738. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211739. }
  211740. void AudioCDReader::enableIndexScanning (bool b)
  211741. {
  211742. indexingEnabled = b;
  211743. }
  211744. int AudioCDReader::getLastIndex() const
  211745. {
  211746. return lastIndex;
  211747. }
  211748. const int framesPerIndexRead = 4;
  211749. int AudioCDReader::getIndexAt (int samplePos)
  211750. {
  211751. using namespace CDReaderHelpers;
  211752. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211753. const int frameNeeded = samplePos / samplesPerFrame;
  211754. device->overlapBuffer->dataLength = 0;
  211755. device->overlapBuffer->startFrame = 0;
  211756. device->overlapBuffer->numFrames = 0;
  211757. device->jitter = false;
  211758. firstFrameInBuffer = 0;
  211759. lastIndex = 0;
  211760. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211761. readBuffer.wantsIndex = true;
  211762. int i;
  211763. for (i = 5; --i >= 0;)
  211764. {
  211765. readBuffer.startFrame = frameNeeded;
  211766. readBuffer.numFrames = framesPerIndexRead;
  211767. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211768. break;
  211769. }
  211770. if (i >= 0)
  211771. return readBuffer.index;
  211772. return -1;
  211773. }
  211774. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211775. {
  211776. using namespace CDReaderHelpers;
  211777. Array <int> indexes;
  211778. const int trackStart = getPositionOfTrackStart (trackNumber);
  211779. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211780. bool needToScan = true;
  211781. if (trackEnd - trackStart > 20 * 44100)
  211782. {
  211783. // check the end of the track for indexes before scanning the whole thing
  211784. needToScan = false;
  211785. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211786. bool seenAnIndex = false;
  211787. while (pos <= trackEnd - samplesPerFrame)
  211788. {
  211789. const int index = getIndexAt (pos);
  211790. if (index == 0)
  211791. {
  211792. // lead-out, so skip back a bit if we've not found any indexes yet..
  211793. if (seenAnIndex)
  211794. break;
  211795. pos -= 44100 * 5;
  211796. if (pos < trackStart)
  211797. break;
  211798. }
  211799. else
  211800. {
  211801. if (index > 0)
  211802. seenAnIndex = true;
  211803. if (index > 1)
  211804. {
  211805. needToScan = true;
  211806. break;
  211807. }
  211808. pos += samplesPerFrame * framesPerIndexRead;
  211809. }
  211810. }
  211811. }
  211812. if (needToScan)
  211813. {
  211814. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211815. int pos = trackStart;
  211816. int last = -1;
  211817. while (pos < trackEnd - samplesPerFrame * 10)
  211818. {
  211819. const int frameNeeded = pos / samplesPerFrame;
  211820. device->overlapBuffer->dataLength = 0;
  211821. device->overlapBuffer->startFrame = 0;
  211822. device->overlapBuffer->numFrames = 0;
  211823. device->jitter = false;
  211824. firstFrameInBuffer = 0;
  211825. CDReadBuffer readBuffer (4);
  211826. readBuffer.wantsIndex = true;
  211827. int i;
  211828. for (i = 5; --i >= 0;)
  211829. {
  211830. readBuffer.startFrame = frameNeeded;
  211831. readBuffer.numFrames = framesPerIndexRead;
  211832. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211833. break;
  211834. }
  211835. if (i < 0)
  211836. break;
  211837. if (readBuffer.index > last && readBuffer.index > 1)
  211838. {
  211839. last = readBuffer.index;
  211840. indexes.add (pos);
  211841. }
  211842. pos += samplesPerFrame * framesPerIndexRead;
  211843. }
  211844. indexes.removeValue (trackStart);
  211845. }
  211846. return indexes;
  211847. }
  211848. void AudioCDReader::ejectDisk()
  211849. {
  211850. using namespace CDReaderHelpers;
  211851. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  211852. }
  211853. #endif
  211854. #if JUCE_USE_CDBURNER
  211855. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211856. {
  211857. CoInitialize (0);
  211858. IDiscMaster* dm;
  211859. IDiscRecorder* result = 0;
  211860. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211861. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211862. IID_IDiscMaster,
  211863. (void**) &dm)))
  211864. {
  211865. if (SUCCEEDED (dm->Open()))
  211866. {
  211867. IEnumDiscRecorders* drEnum = 0;
  211868. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211869. {
  211870. IDiscRecorder* dr = 0;
  211871. DWORD dummy;
  211872. int index = 0;
  211873. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211874. {
  211875. if (indexToOpen == index)
  211876. {
  211877. result = dr;
  211878. break;
  211879. }
  211880. else if (list != 0)
  211881. {
  211882. BSTR path;
  211883. if (SUCCEEDED (dr->GetPath (&path)))
  211884. list->add ((const WCHAR*) path);
  211885. }
  211886. ++index;
  211887. dr->Release();
  211888. }
  211889. drEnum->Release();
  211890. }
  211891. if (master == 0)
  211892. dm->Close();
  211893. }
  211894. if (master != 0)
  211895. *master = dm;
  211896. else
  211897. dm->Release();
  211898. }
  211899. return result;
  211900. }
  211901. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211902. public Timer
  211903. {
  211904. public:
  211905. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211906. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211907. listener (0), progress (0), shouldCancel (false)
  211908. {
  211909. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211910. jassert (SUCCEEDED (hr));
  211911. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211912. //jassert (SUCCEEDED (hr));
  211913. lastState = getDiskState();
  211914. startTimer (2000);
  211915. }
  211916. ~Pimpl() {}
  211917. void releaseObjects()
  211918. {
  211919. discRecorder->Close();
  211920. if (redbook != 0)
  211921. redbook->Release();
  211922. discRecorder->Release();
  211923. discMaster->Release();
  211924. Release();
  211925. }
  211926. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211927. {
  211928. if (listener != 0 && ! shouldCancel)
  211929. shouldCancel = listener->audioCDBurnProgress (progress);
  211930. *pbCancel = shouldCancel;
  211931. return S_OK;
  211932. }
  211933. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211934. {
  211935. progress = nCompleted / (float) nTotal;
  211936. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211937. return E_NOTIMPL;
  211938. }
  211939. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211940. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211941. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211942. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211943. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211944. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211945. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211946. class ScopedDiscOpener
  211947. {
  211948. public:
  211949. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211950. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211951. private:
  211952. Pimpl& pimpl;
  211953. ScopedDiscOpener (const ScopedDiscOpener&);
  211954. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  211955. };
  211956. DiskState getDiskState()
  211957. {
  211958. const ScopedDiscOpener opener (*this);
  211959. long type, flags;
  211960. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211961. if (FAILED (hr))
  211962. return unknown;
  211963. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211964. return writableDiskPresent;
  211965. if (type == 0)
  211966. return noDisc;
  211967. else
  211968. return readOnlyDiskPresent;
  211969. }
  211970. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211971. {
  211972. ComSmartPtr<IPropertyStorage> prop;
  211973. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  211974. return defaultReturn;
  211975. PROPSPEC iPropSpec;
  211976. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211977. iPropSpec.lpwstr = name;
  211978. PROPVARIANT iPropVariant;
  211979. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211980. ? defaultReturn : (int) iPropVariant.lVal;
  211981. }
  211982. bool setIntProperty (const LPOLESTR name, const int value) const
  211983. {
  211984. ComSmartPtr<IPropertyStorage> prop;
  211985. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  211986. return false;
  211987. PROPSPEC iPropSpec;
  211988. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211989. iPropSpec.lpwstr = name;
  211990. PROPVARIANT iPropVariant;
  211991. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211992. return false;
  211993. iPropVariant.lVal = (long) value;
  211994. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211995. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211996. }
  211997. void timerCallback()
  211998. {
  211999. const DiskState state = getDiskState();
  212000. if (state != lastState)
  212001. {
  212002. lastState = state;
  212003. owner.sendChangeMessage (&owner);
  212004. }
  212005. }
  212006. AudioCDBurner& owner;
  212007. DiskState lastState;
  212008. IDiscMaster* discMaster;
  212009. IDiscRecorder* discRecorder;
  212010. IRedbookDiscMaster* redbook;
  212011. AudioCDBurner::BurnProgressListener* listener;
  212012. float progress;
  212013. bool shouldCancel;
  212014. };
  212015. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212016. {
  212017. IDiscMaster* discMaster = 0;
  212018. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  212019. if (discRecorder != 0)
  212020. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212021. }
  212022. AudioCDBurner::~AudioCDBurner()
  212023. {
  212024. if (pimpl != 0)
  212025. pimpl.release()->releaseObjects();
  212026. }
  212027. const StringArray AudioCDBurner::findAvailableDevices()
  212028. {
  212029. StringArray devs;
  212030. enumCDBurners (&devs, -1, 0);
  212031. return devs;
  212032. }
  212033. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212034. {
  212035. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212036. if (b->pimpl == 0)
  212037. b = 0;
  212038. return b.release();
  212039. }
  212040. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212041. {
  212042. return pimpl->getDiskState();
  212043. }
  212044. bool AudioCDBurner::isDiskPresent() const
  212045. {
  212046. return getDiskState() == writableDiskPresent;
  212047. }
  212048. bool AudioCDBurner::openTray()
  212049. {
  212050. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212051. return SUCCEEDED (pimpl->discRecorder->Eject());
  212052. }
  212053. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212054. {
  212055. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212056. DiskState oldState = getDiskState();
  212057. DiskState newState = oldState;
  212058. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212059. {
  212060. newState = getDiskState();
  212061. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212062. }
  212063. return newState;
  212064. }
  212065. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212066. {
  212067. Array<int> results;
  212068. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212069. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212070. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212071. if (speeds[i] <= maxSpeed)
  212072. results.add (speeds[i]);
  212073. results.addIfNotAlreadyThere (maxSpeed);
  212074. return results;
  212075. }
  212076. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212077. {
  212078. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212079. return false;
  212080. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212081. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212082. }
  212083. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212084. {
  212085. long blocksFree = 0;
  212086. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212087. return blocksFree;
  212088. }
  212089. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212090. bool performFakeBurnForTesting, int writeSpeed)
  212091. {
  212092. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212093. pimpl->listener = listener;
  212094. pimpl->progress = 0;
  212095. pimpl->shouldCancel = false;
  212096. UINT_PTR cookie;
  212097. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212098. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212099. ejectDiscAfterwards);
  212100. String error;
  212101. if (hr != S_OK)
  212102. {
  212103. const char* e = "Couldn't open or write to the CD device";
  212104. if (hr == IMAPI_E_USERABORT)
  212105. e = "User cancelled the write operation";
  212106. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212107. e = "No Disk present";
  212108. error = e;
  212109. }
  212110. pimpl->discMaster->ProgressUnadvise (cookie);
  212111. pimpl->listener = 0;
  212112. return error;
  212113. }
  212114. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212115. {
  212116. if (audioSource == 0)
  212117. return false;
  212118. ScopedPointer<AudioSource> source (audioSource);
  212119. long bytesPerBlock;
  212120. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212121. const int samplesPerBlock = bytesPerBlock / 4;
  212122. bool ok = true;
  212123. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212124. HeapBlock <byte> buffer (bytesPerBlock);
  212125. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212126. int samplesDone = 0;
  212127. source->prepareToPlay (samplesPerBlock, 44100.0);
  212128. while (ok)
  212129. {
  212130. {
  212131. AudioSourceChannelInfo info;
  212132. info.buffer = &sourceBuffer;
  212133. info.numSamples = samplesPerBlock;
  212134. info.startSample = 0;
  212135. sourceBuffer.clear();
  212136. source->getNextAudioBlock (info);
  212137. }
  212138. zeromem (buffer, bytesPerBlock);
  212139. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  212140. buffer, samplesPerBlock, 4);
  212141. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  212142. buffer + 2, samplesPerBlock, 4);
  212143. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212144. if (FAILED (hr))
  212145. ok = false;
  212146. samplesDone += samplesPerBlock;
  212147. if (samplesDone >= numSamples)
  212148. break;
  212149. }
  212150. hr = pimpl->redbook->CloseAudioTrack();
  212151. return ok && hr == S_OK;
  212152. }
  212153. #endif
  212154. #endif
  212155. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212156. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212157. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212158. // compiled on its own).
  212159. #if JUCE_INCLUDED_FILE
  212160. using ::free;
  212161. namespace MidiConstants
  212162. {
  212163. static const int midiBufferSize = 1024 * 10;
  212164. static const int numInHeaders = 32;
  212165. static const int inBufferSize = 256;
  212166. }
  212167. class MidiInThread : public Thread
  212168. {
  212169. public:
  212170. MidiInThread (MidiInput* const input_,
  212171. MidiInputCallback* const callback_)
  212172. : Thread ("Juce Midi"),
  212173. hIn (0),
  212174. input (input_),
  212175. callback (callback_),
  212176. isStarted (false),
  212177. startTime (0),
  212178. pendingLength(0)
  212179. {
  212180. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  212181. {
  212182. zeromem (&hdr[i], sizeof (MIDIHDR));
  212183. hdr[i].lpData = inData[i];
  212184. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  212185. }
  212186. };
  212187. ~MidiInThread()
  212188. {
  212189. stop();
  212190. if (hIn != 0)
  212191. {
  212192. int count = 5;
  212193. while (--count >= 0)
  212194. {
  212195. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  212196. break;
  212197. Sleep (20);
  212198. }
  212199. }
  212200. }
  212201. void handle (const uint32 message, const uint32 timeStamp)
  212202. {
  212203. const int byte = message & 0xff;
  212204. if (byte < 0x80)
  212205. return;
  212206. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  212207. const double time = timeStampToTime (timeStamp);
  212208. {
  212209. const ScopedLock sl (lock);
  212210. if (pendingLength < MidiConstants::midiBufferSize - 12)
  212211. {
  212212. char* const p = pending + pendingLength;
  212213. *(double*) p = time;
  212214. *(uint32*) (p + 8) = numBytes;
  212215. *(uint32*) (p + 12) = message;
  212216. pendingLength += 12 + numBytes;
  212217. }
  212218. else
  212219. {
  212220. jassertfalse; // midi buffer overflow! You might need to increase the size..
  212221. }
  212222. }
  212223. notify();
  212224. }
  212225. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212226. {
  212227. const int num = hdr->dwBytesRecorded;
  212228. if (num > 0)
  212229. {
  212230. const double time = timeStampToTime (timeStamp);
  212231. {
  212232. const ScopedLock sl (lock);
  212233. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  212234. {
  212235. char* const p = pending + pendingLength;
  212236. *(double*) p = time;
  212237. *(uint32*) (p + 8) = num;
  212238. memcpy (p + 12, hdr->lpData, num);
  212239. pendingLength += 12 + num;
  212240. }
  212241. else
  212242. {
  212243. jassertfalse; // midi buffer overflow! You might need to increase the size..
  212244. }
  212245. }
  212246. notify();
  212247. }
  212248. }
  212249. void writeBlock (const int i)
  212250. {
  212251. hdr[i].dwBytesRecorded = 0;
  212252. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  212253. jassert (res == MMSYSERR_NOERROR);
  212254. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  212255. jassert (res == MMSYSERR_NOERROR);
  212256. }
  212257. void run()
  212258. {
  212259. MemoryBlock pendingCopy (64);
  212260. while (! threadShouldExit())
  212261. {
  212262. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  212263. {
  212264. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212265. {
  212266. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  212267. (void) res;
  212268. jassert (res == MMSYSERR_NOERROR);
  212269. writeBlock (i);
  212270. }
  212271. }
  212272. int len;
  212273. {
  212274. const ScopedLock sl (lock);
  212275. len = pendingLength;
  212276. if (len > 0)
  212277. {
  212278. pendingCopy.ensureSize (len);
  212279. pendingCopy.copyFrom (pending, 0, len);
  212280. pendingLength = 0;
  212281. }
  212282. }
  212283. //xxx needs to figure out if blocks are broken up or not
  212284. if (len == 0)
  212285. {
  212286. wait (500);
  212287. }
  212288. else
  212289. {
  212290. const char* p = (const char*) pendingCopy.getData();
  212291. while (len > 0)
  212292. {
  212293. const double time = *(const double*) p;
  212294. const int messageLen = *(const int*) (p + 8);
  212295. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  212296. callback->handleIncomingMidiMessage (input, message);
  212297. p += 12 + messageLen;
  212298. len -= 12 + messageLen;
  212299. }
  212300. }
  212301. }
  212302. }
  212303. void start()
  212304. {
  212305. jassert (hIn != 0);
  212306. if (hIn != 0 && ! isStarted)
  212307. {
  212308. stop();
  212309. activeMidiThreads.addIfNotAlreadyThere (this);
  212310. int i;
  212311. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  212312. writeBlock (i);
  212313. startTime = Time::getMillisecondCounter();
  212314. MMRESULT res = midiInStart (hIn);
  212315. jassert (res == MMSYSERR_NOERROR);
  212316. if (res == MMSYSERR_NOERROR)
  212317. {
  212318. isStarted = true;
  212319. pendingLength = 0;
  212320. startThread (6);
  212321. }
  212322. }
  212323. }
  212324. void stop()
  212325. {
  212326. if (isStarted)
  212327. {
  212328. stopThread (5000);
  212329. midiInReset (hIn);
  212330. midiInStop (hIn);
  212331. activeMidiThreads.removeValue (this);
  212332. { const ScopedLock sl (lock); }
  212333. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  212334. {
  212335. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212336. {
  212337. int c = 10;
  212338. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  212339. Sleep (20);
  212340. jassert (c >= 0);
  212341. }
  212342. }
  212343. isStarted = false;
  212344. pendingLength = 0;
  212345. }
  212346. }
  212347. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212348. {
  212349. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  212350. if (thread != 0 && activeMidiThreads.contains (thread))
  212351. {
  212352. if (uMsg == MIM_DATA)
  212353. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  212354. else if (uMsg == MIM_LONGDATA)
  212355. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212356. }
  212357. }
  212358. juce_UseDebuggingNewOperator
  212359. HMIDIIN hIn;
  212360. private:
  212361. static Array <void*, CriticalSection> activeMidiThreads;
  212362. MidiInput* input;
  212363. MidiInputCallback* callback;
  212364. bool isStarted;
  212365. uint32 startTime;
  212366. CriticalSection lock;
  212367. MIDIHDR hdr [MidiConstants::numInHeaders];
  212368. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  212369. int pendingLength;
  212370. char pending [MidiConstants::midiBufferSize];
  212371. double timeStampToTime (uint32 timeStamp)
  212372. {
  212373. timeStamp += startTime;
  212374. const uint32 now = Time::getMillisecondCounter();
  212375. if (timeStamp > now)
  212376. {
  212377. if (timeStamp > now + 2)
  212378. --startTime;
  212379. timeStamp = now;
  212380. }
  212381. return 0.001 * timeStamp;
  212382. }
  212383. MidiInThread (const MidiInThread&);
  212384. MidiInThread& operator= (const MidiInThread&);
  212385. };
  212386. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  212387. const StringArray MidiInput::getDevices()
  212388. {
  212389. StringArray s;
  212390. const int num = midiInGetNumDevs();
  212391. for (int i = 0; i < num; ++i)
  212392. {
  212393. MIDIINCAPS mc;
  212394. zerostruct (mc);
  212395. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212396. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212397. }
  212398. return s;
  212399. }
  212400. int MidiInput::getDefaultDeviceIndex()
  212401. {
  212402. return 0;
  212403. }
  212404. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212405. {
  212406. if (callback == 0)
  212407. return 0;
  212408. UINT deviceId = MIDI_MAPPER;
  212409. int n = 0;
  212410. String name;
  212411. const int num = midiInGetNumDevs();
  212412. for (int i = 0; i < num; ++i)
  212413. {
  212414. MIDIINCAPS mc;
  212415. zerostruct (mc);
  212416. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212417. {
  212418. if (index == n)
  212419. {
  212420. deviceId = i;
  212421. name = String (mc.szPname, sizeof (mc.szPname));
  212422. break;
  212423. }
  212424. ++n;
  212425. }
  212426. }
  212427. ScopedPointer <MidiInput> in (new MidiInput (name));
  212428. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  212429. HMIDIIN h;
  212430. HRESULT err = midiInOpen (&h, deviceId,
  212431. (DWORD_PTR) &MidiInThread::midiInCallback,
  212432. (DWORD_PTR) (MidiInThread*) thread,
  212433. CALLBACK_FUNCTION);
  212434. if (err == MMSYSERR_NOERROR)
  212435. {
  212436. thread->hIn = h;
  212437. in->internal = thread.release();
  212438. return in.release();
  212439. }
  212440. return 0;
  212441. }
  212442. MidiInput::MidiInput (const String& name_)
  212443. : name (name_),
  212444. internal (0)
  212445. {
  212446. }
  212447. MidiInput::~MidiInput()
  212448. {
  212449. delete static_cast <MidiInThread*> (internal);
  212450. }
  212451. void MidiInput::start()
  212452. {
  212453. static_cast <MidiInThread*> (internal)->start();
  212454. }
  212455. void MidiInput::stop()
  212456. {
  212457. static_cast <MidiInThread*> (internal)->stop();
  212458. }
  212459. struct MidiOutHandle
  212460. {
  212461. int refCount;
  212462. UINT deviceId;
  212463. HMIDIOUT handle;
  212464. static Array<MidiOutHandle*> activeHandles;
  212465. juce_UseDebuggingNewOperator
  212466. };
  212467. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212468. const StringArray MidiOutput::getDevices()
  212469. {
  212470. StringArray s;
  212471. const int num = midiOutGetNumDevs();
  212472. for (int i = 0; i < num; ++i)
  212473. {
  212474. MIDIOUTCAPS mc;
  212475. zerostruct (mc);
  212476. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212477. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212478. }
  212479. return s;
  212480. }
  212481. int MidiOutput::getDefaultDeviceIndex()
  212482. {
  212483. const int num = midiOutGetNumDevs();
  212484. int n = 0;
  212485. for (int i = 0; i < num; ++i)
  212486. {
  212487. MIDIOUTCAPS mc;
  212488. zerostruct (mc);
  212489. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212490. {
  212491. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212492. return n;
  212493. ++n;
  212494. }
  212495. }
  212496. return 0;
  212497. }
  212498. MidiOutput* MidiOutput::openDevice (int index)
  212499. {
  212500. UINT deviceId = MIDI_MAPPER;
  212501. const int num = midiOutGetNumDevs();
  212502. int i, n = 0;
  212503. for (i = 0; i < num; ++i)
  212504. {
  212505. MIDIOUTCAPS mc;
  212506. zerostruct (mc);
  212507. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212508. {
  212509. // use the microsoft sw synth as a default - best not to allow deviceId
  212510. // to be MIDI_MAPPER, or else device sharing breaks
  212511. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212512. deviceId = i;
  212513. if (index == n)
  212514. {
  212515. deviceId = i;
  212516. break;
  212517. }
  212518. ++n;
  212519. }
  212520. }
  212521. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212522. {
  212523. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212524. if (han != 0 && han->deviceId == deviceId)
  212525. {
  212526. han->refCount++;
  212527. MidiOutput* const out = new MidiOutput();
  212528. out->internal = han;
  212529. return out;
  212530. }
  212531. }
  212532. for (i = 4; --i >= 0;)
  212533. {
  212534. HMIDIOUT h = 0;
  212535. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212536. if (res == MMSYSERR_NOERROR)
  212537. {
  212538. MidiOutHandle* const han = new MidiOutHandle();
  212539. han->deviceId = deviceId;
  212540. han->refCount = 1;
  212541. han->handle = h;
  212542. MidiOutHandle::activeHandles.add (han);
  212543. MidiOutput* const out = new MidiOutput();
  212544. out->internal = han;
  212545. return out;
  212546. }
  212547. else if (res == MMSYSERR_ALLOCATED)
  212548. {
  212549. Sleep (100);
  212550. }
  212551. else
  212552. {
  212553. break;
  212554. }
  212555. }
  212556. return 0;
  212557. }
  212558. MidiOutput::~MidiOutput()
  212559. {
  212560. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212561. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212562. {
  212563. midiOutClose (h->handle);
  212564. MidiOutHandle::activeHandles.removeValue (h);
  212565. delete h;
  212566. }
  212567. }
  212568. void MidiOutput::reset()
  212569. {
  212570. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212571. midiOutReset (h->handle);
  212572. }
  212573. bool MidiOutput::getVolume (float& leftVol,
  212574. float& rightVol)
  212575. {
  212576. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212577. DWORD n;
  212578. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212579. {
  212580. const unsigned short* const nn = (const unsigned short*) &n;
  212581. rightVol = nn[0] / (float) 0xffff;
  212582. leftVol = nn[1] / (float) 0xffff;
  212583. return true;
  212584. }
  212585. else
  212586. {
  212587. rightVol = leftVol = 1.0f;
  212588. return false;
  212589. }
  212590. }
  212591. void MidiOutput::setVolume (float leftVol,
  212592. float rightVol)
  212593. {
  212594. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212595. DWORD n;
  212596. unsigned short* const nn = (unsigned short*) &n;
  212597. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212598. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212599. midiOutSetVolume (handle->handle, n);
  212600. }
  212601. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212602. {
  212603. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212604. if (message.getRawDataSize() > 3
  212605. || message.isSysEx())
  212606. {
  212607. MIDIHDR h;
  212608. zerostruct (h);
  212609. h.lpData = (char*) message.getRawData();
  212610. h.dwBufferLength = message.getRawDataSize();
  212611. h.dwBytesRecorded = message.getRawDataSize();
  212612. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212613. {
  212614. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212615. if (res == MMSYSERR_NOERROR)
  212616. {
  212617. while ((h.dwFlags & MHDR_DONE) == 0)
  212618. Sleep (1);
  212619. int count = 500; // 1 sec timeout
  212620. while (--count >= 0)
  212621. {
  212622. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212623. if (res == MIDIERR_STILLPLAYING)
  212624. Sleep (2);
  212625. else
  212626. break;
  212627. }
  212628. }
  212629. }
  212630. }
  212631. else
  212632. {
  212633. midiOutShortMsg (handle->handle,
  212634. *(unsigned int*) message.getRawData());
  212635. }
  212636. }
  212637. #endif
  212638. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212639. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212640. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212641. // compiled on its own).
  212642. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212643. #undef WINDOWS
  212644. // #define ASIO_DEBUGGING
  212645. #ifdef ASIO_DEBUGGING
  212646. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212647. #else
  212648. #define log(a) {}
  212649. #endif
  212650. #ifdef ASIO_DEBUGGING
  212651. static void logError (const String& context, long error)
  212652. {
  212653. String err ("unknown error");
  212654. if (error == ASE_NotPresent)
  212655. err = "Not Present";
  212656. else if (error == ASE_HWMalfunction)
  212657. err = "Hardware Malfunction";
  212658. else if (error == ASE_InvalidParameter)
  212659. err = "Invalid Parameter";
  212660. else if (error == ASE_InvalidMode)
  212661. err = "Invalid Mode";
  212662. else if (error == ASE_SPNotAdvancing)
  212663. err = "Sample position not advancing";
  212664. else if (error == ASE_NoClock)
  212665. err = "No Clock";
  212666. else if (error == ASE_NoMemory)
  212667. err = "Out of memory";
  212668. log ("!!error: " + context + " - " + err);
  212669. }
  212670. #else
  212671. #define logError(a, b) {}
  212672. #endif
  212673. class ASIOAudioIODevice;
  212674. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212675. static const int maxASIOChannels = 160;
  212676. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212677. private Timer
  212678. {
  212679. public:
  212680. Component ourWindow;
  212681. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212682. const String& optionalDllForDirectLoading_)
  212683. : AudioIODevice (name_, "ASIO"),
  212684. asioObject (0),
  212685. classId (classId_),
  212686. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212687. currentBitDepth (16),
  212688. currentSampleRate (0),
  212689. isOpen_ (false),
  212690. isStarted (false),
  212691. postOutput (true),
  212692. insideControlPanelModalLoop (false),
  212693. shouldUsePreferredSize (false)
  212694. {
  212695. name = name_;
  212696. ourWindow.addToDesktop (0);
  212697. windowHandle = ourWindow.getWindowHandle();
  212698. jassert (currentASIODev [slotNumber] == 0);
  212699. currentASIODev [slotNumber] = this;
  212700. openDevice();
  212701. }
  212702. ~ASIOAudioIODevice()
  212703. {
  212704. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212705. if (currentASIODev[i] == this)
  212706. currentASIODev[i] = 0;
  212707. close();
  212708. log ("ASIO - exiting");
  212709. removeCurrentDriver();
  212710. }
  212711. void updateSampleRates()
  212712. {
  212713. // find a list of sample rates..
  212714. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212715. sampleRates.clear();
  212716. if (asioObject != 0)
  212717. {
  212718. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212719. {
  212720. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212721. if (err == 0)
  212722. {
  212723. sampleRates.add ((int) possibleSampleRates[index]);
  212724. log ("rate: " + String ((int) possibleSampleRates[index]));
  212725. }
  212726. else if (err != ASE_NoClock)
  212727. {
  212728. logError ("CanSampleRate", err);
  212729. }
  212730. }
  212731. if (sampleRates.size() == 0)
  212732. {
  212733. double cr = 0;
  212734. const long err = asioObject->getSampleRate (&cr);
  212735. log ("No sample rates supported - current rate: " + String ((int) cr));
  212736. if (err == 0)
  212737. sampleRates.add ((int) cr);
  212738. }
  212739. }
  212740. }
  212741. const StringArray getOutputChannelNames()
  212742. {
  212743. return outputChannelNames;
  212744. }
  212745. const StringArray getInputChannelNames()
  212746. {
  212747. return inputChannelNames;
  212748. }
  212749. int getNumSampleRates()
  212750. {
  212751. return sampleRates.size();
  212752. }
  212753. double getSampleRate (int index)
  212754. {
  212755. return sampleRates [index];
  212756. }
  212757. int getNumBufferSizesAvailable()
  212758. {
  212759. return bufferSizes.size();
  212760. }
  212761. int getBufferSizeSamples (int index)
  212762. {
  212763. return bufferSizes [index];
  212764. }
  212765. int getDefaultBufferSize()
  212766. {
  212767. return preferredSize;
  212768. }
  212769. const String open (const BigInteger& inputChannels,
  212770. const BigInteger& outputChannels,
  212771. double sr,
  212772. int bufferSizeSamples)
  212773. {
  212774. close();
  212775. currentCallback = 0;
  212776. if (bufferSizeSamples <= 0)
  212777. shouldUsePreferredSize = true;
  212778. if (asioObject == 0 || ! isASIOOpen)
  212779. {
  212780. log ("Warning: device not open");
  212781. const String err (openDevice());
  212782. if (asioObject == 0 || ! isASIOOpen)
  212783. return err;
  212784. }
  212785. isStarted = false;
  212786. bufferIndex = -1;
  212787. long err = 0;
  212788. long newPreferredSize = 0;
  212789. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212790. minSize = 0;
  212791. maxSize = 0;
  212792. newPreferredSize = 0;
  212793. granularity = 0;
  212794. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212795. {
  212796. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212797. shouldUsePreferredSize = true;
  212798. preferredSize = newPreferredSize;
  212799. }
  212800. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212801. // dynamic changes to the buffer size...
  212802. shouldUsePreferredSize = shouldUsePreferredSize
  212803. || getName().containsIgnoreCase ("Digidesign");
  212804. if (shouldUsePreferredSize)
  212805. {
  212806. log ("Using preferred size for buffer..");
  212807. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212808. {
  212809. bufferSizeSamples = preferredSize;
  212810. }
  212811. else
  212812. {
  212813. bufferSizeSamples = 1024;
  212814. logError ("GetBufferSize1", err);
  212815. }
  212816. shouldUsePreferredSize = false;
  212817. }
  212818. int sampleRate = roundDoubleToInt (sr);
  212819. currentSampleRate = sampleRate;
  212820. currentBlockSizeSamples = bufferSizeSamples;
  212821. currentChansOut.clear();
  212822. currentChansIn.clear();
  212823. zeromem (inBuffers, sizeof (inBuffers));
  212824. zeromem (outBuffers, sizeof (outBuffers));
  212825. updateSampleRates();
  212826. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212827. sampleRate = sampleRates[0];
  212828. jassert (sampleRate != 0);
  212829. if (sampleRate == 0)
  212830. sampleRate = 44100;
  212831. long numSources = 32;
  212832. ASIOClockSource clocks[32];
  212833. zeromem (clocks, sizeof (clocks));
  212834. asioObject->getClockSources (clocks, &numSources);
  212835. bool isSourceSet = false;
  212836. // careful not to remove this loop because it does more than just logging!
  212837. int i;
  212838. for (i = 0; i < numSources; ++i)
  212839. {
  212840. String s ("clock: ");
  212841. s += clocks[i].name;
  212842. if (clocks[i].isCurrentSource)
  212843. {
  212844. isSourceSet = true;
  212845. s << " (cur)";
  212846. }
  212847. log (s);
  212848. }
  212849. if (numSources > 1 && ! isSourceSet)
  212850. {
  212851. log ("setting clock source");
  212852. asioObject->setClockSource (clocks[0].index);
  212853. Thread::sleep (20);
  212854. }
  212855. else
  212856. {
  212857. if (numSources == 0)
  212858. {
  212859. log ("ASIO - no clock sources!");
  212860. }
  212861. }
  212862. double cr = 0;
  212863. err = asioObject->getSampleRate (&cr);
  212864. if (err == 0)
  212865. {
  212866. currentSampleRate = cr;
  212867. }
  212868. else
  212869. {
  212870. logError ("GetSampleRate", err);
  212871. currentSampleRate = 0;
  212872. }
  212873. error = String::empty;
  212874. needToReset = false;
  212875. isReSync = false;
  212876. err = 0;
  212877. bool buffersCreated = false;
  212878. if (currentSampleRate != sampleRate)
  212879. {
  212880. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212881. err = asioObject->setSampleRate (sampleRate);
  212882. if (err == ASE_NoClock && numSources > 0)
  212883. {
  212884. log ("trying to set a clock source..");
  212885. Thread::sleep (10);
  212886. err = asioObject->setClockSource (clocks[0].index);
  212887. if (err != 0)
  212888. {
  212889. logError ("SetClock", err);
  212890. }
  212891. Thread::sleep (10);
  212892. err = asioObject->setSampleRate (sampleRate);
  212893. }
  212894. }
  212895. if (err == 0)
  212896. {
  212897. currentSampleRate = sampleRate;
  212898. if (needToReset)
  212899. {
  212900. if (isReSync)
  212901. {
  212902. log ("Resync request");
  212903. }
  212904. log ("! Resetting ASIO after sample rate change");
  212905. removeCurrentDriver();
  212906. loadDriver();
  212907. const String error (initDriver());
  212908. if (error.isNotEmpty())
  212909. {
  212910. log ("ASIOInit: " + error);
  212911. }
  212912. needToReset = false;
  212913. isReSync = false;
  212914. }
  212915. numActiveInputChans = 0;
  212916. numActiveOutputChans = 0;
  212917. ASIOBufferInfo* info = bufferInfos;
  212918. int i;
  212919. for (i = 0; i < totalNumInputChans; ++i)
  212920. {
  212921. if (inputChannels[i])
  212922. {
  212923. currentChansIn.setBit (i);
  212924. info->isInput = 1;
  212925. info->channelNum = i;
  212926. info->buffers[0] = info->buffers[1] = 0;
  212927. ++info;
  212928. ++numActiveInputChans;
  212929. }
  212930. }
  212931. for (i = 0; i < totalNumOutputChans; ++i)
  212932. {
  212933. if (outputChannels[i])
  212934. {
  212935. currentChansOut.setBit (i);
  212936. info->isInput = 0;
  212937. info->channelNum = i;
  212938. info->buffers[0] = info->buffers[1] = 0;
  212939. ++info;
  212940. ++numActiveOutputChans;
  212941. }
  212942. }
  212943. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212944. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212945. if (currentASIODev[0] == this)
  212946. {
  212947. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212948. callbacks.asioMessage = &asioMessagesCallback0;
  212949. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212950. }
  212951. else if (currentASIODev[1] == this)
  212952. {
  212953. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212954. callbacks.asioMessage = &asioMessagesCallback1;
  212955. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212956. }
  212957. else if (currentASIODev[2] == this)
  212958. {
  212959. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212960. callbacks.asioMessage = &asioMessagesCallback2;
  212961. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212962. }
  212963. else
  212964. {
  212965. jassertfalse;
  212966. }
  212967. log ("disposing buffers");
  212968. err = asioObject->disposeBuffers();
  212969. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212970. err = asioObject->createBuffers (bufferInfos,
  212971. totalBuffers,
  212972. currentBlockSizeSamples,
  212973. &callbacks);
  212974. if (err != 0)
  212975. {
  212976. currentBlockSizeSamples = preferredSize;
  212977. logError ("create buffers 2", err);
  212978. asioObject->disposeBuffers();
  212979. err = asioObject->createBuffers (bufferInfos,
  212980. totalBuffers,
  212981. currentBlockSizeSamples,
  212982. &callbacks);
  212983. }
  212984. if (err == 0)
  212985. {
  212986. buffersCreated = true;
  212987. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212988. int n = 0;
  212989. Array <int> types;
  212990. currentBitDepth = 16;
  212991. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212992. {
  212993. if (inputChannels[i])
  212994. {
  212995. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212996. ASIOChannelInfo channelInfo;
  212997. zerostruct (channelInfo);
  212998. channelInfo.channel = i;
  212999. channelInfo.isInput = 1;
  213000. asioObject->getChannelInfo (&channelInfo);
  213001. types.addIfNotAlreadyThere (channelInfo.type);
  213002. typeToFormatParameters (channelInfo.type,
  213003. inputChannelBitDepths[n],
  213004. inputChannelBytesPerSample[n],
  213005. inputChannelIsFloat[n],
  213006. inputChannelLittleEndian[n]);
  213007. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213008. ++n;
  213009. }
  213010. }
  213011. jassert (numActiveInputChans == n);
  213012. n = 0;
  213013. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213014. {
  213015. if (outputChannels[i])
  213016. {
  213017. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213018. ASIOChannelInfo channelInfo;
  213019. zerostruct (channelInfo);
  213020. channelInfo.channel = i;
  213021. channelInfo.isInput = 0;
  213022. asioObject->getChannelInfo (&channelInfo);
  213023. types.addIfNotAlreadyThere (channelInfo.type);
  213024. typeToFormatParameters (channelInfo.type,
  213025. outputChannelBitDepths[n],
  213026. outputChannelBytesPerSample[n],
  213027. outputChannelIsFloat[n],
  213028. outputChannelLittleEndian[n]);
  213029. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213030. ++n;
  213031. }
  213032. }
  213033. jassert (numActiveOutputChans == n);
  213034. for (i = types.size(); --i >= 0;)
  213035. {
  213036. log ("channel format: " + String (types[i]));
  213037. }
  213038. jassert (n <= totalBuffers);
  213039. for (i = 0; i < numActiveOutputChans; ++i)
  213040. {
  213041. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213042. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213043. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213044. {
  213045. log ("!! Null buffers");
  213046. }
  213047. else
  213048. {
  213049. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213050. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213051. }
  213052. }
  213053. inputLatency = outputLatency = 0;
  213054. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213055. {
  213056. log ("ASIO - no latencies");
  213057. }
  213058. else
  213059. {
  213060. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213061. }
  213062. isOpen_ = true;
  213063. log ("starting ASIO");
  213064. calledback = false;
  213065. err = asioObject->start();
  213066. if (err != 0)
  213067. {
  213068. isOpen_ = false;
  213069. log ("ASIO - stop on failure");
  213070. Thread::sleep (10);
  213071. asioObject->stop();
  213072. error = "Can't start device";
  213073. Thread::sleep (10);
  213074. }
  213075. else
  213076. {
  213077. int count = 300;
  213078. while (--count > 0 && ! calledback)
  213079. Thread::sleep (10);
  213080. isStarted = true;
  213081. if (! calledback)
  213082. {
  213083. error = "Device didn't start correctly";
  213084. log ("ASIO didn't callback - stopping..");
  213085. asioObject->stop();
  213086. }
  213087. }
  213088. }
  213089. else
  213090. {
  213091. error = "Can't create i/o buffers";
  213092. }
  213093. }
  213094. else
  213095. {
  213096. error = "Can't set sample rate: ";
  213097. error << sampleRate;
  213098. }
  213099. if (error.isNotEmpty())
  213100. {
  213101. logError (error, err);
  213102. if (asioObject != 0 && buffersCreated)
  213103. asioObject->disposeBuffers();
  213104. Thread::sleep (20);
  213105. isStarted = false;
  213106. isOpen_ = false;
  213107. const String errorCopy (error);
  213108. close(); // (this resets the error string)
  213109. error = errorCopy;
  213110. }
  213111. needToReset = false;
  213112. isReSync = false;
  213113. return error;
  213114. }
  213115. void close()
  213116. {
  213117. error = String::empty;
  213118. stopTimer();
  213119. stop();
  213120. if (isASIOOpen && isOpen_)
  213121. {
  213122. const ScopedLock sl (callbackLock);
  213123. isOpen_ = false;
  213124. isStarted = false;
  213125. needToReset = false;
  213126. isReSync = false;
  213127. log ("ASIO - stopping");
  213128. if (asioObject != 0)
  213129. {
  213130. Thread::sleep (20);
  213131. asioObject->stop();
  213132. Thread::sleep (10);
  213133. asioObject->disposeBuffers();
  213134. }
  213135. Thread::sleep (10);
  213136. }
  213137. }
  213138. bool isOpen()
  213139. {
  213140. return isOpen_ || insideControlPanelModalLoop;
  213141. }
  213142. int getCurrentBufferSizeSamples()
  213143. {
  213144. return currentBlockSizeSamples;
  213145. }
  213146. double getCurrentSampleRate()
  213147. {
  213148. return currentSampleRate;
  213149. }
  213150. const BigInteger getActiveOutputChannels() const
  213151. {
  213152. return currentChansOut;
  213153. }
  213154. const BigInteger getActiveInputChannels() const
  213155. {
  213156. return currentChansIn;
  213157. }
  213158. int getCurrentBitDepth()
  213159. {
  213160. return currentBitDepth;
  213161. }
  213162. int getOutputLatencyInSamples()
  213163. {
  213164. return outputLatency + currentBlockSizeSamples / 4;
  213165. }
  213166. int getInputLatencyInSamples()
  213167. {
  213168. return inputLatency + currentBlockSizeSamples / 4;
  213169. }
  213170. void start (AudioIODeviceCallback* callback)
  213171. {
  213172. if (callback != 0)
  213173. {
  213174. callback->audioDeviceAboutToStart (this);
  213175. const ScopedLock sl (callbackLock);
  213176. currentCallback = callback;
  213177. }
  213178. }
  213179. void stop()
  213180. {
  213181. AudioIODeviceCallback* const lastCallback = currentCallback;
  213182. {
  213183. const ScopedLock sl (callbackLock);
  213184. currentCallback = 0;
  213185. }
  213186. if (lastCallback != 0)
  213187. lastCallback->audioDeviceStopped();
  213188. }
  213189. bool isPlaying()
  213190. {
  213191. return isASIOOpen && (currentCallback != 0);
  213192. }
  213193. const String getLastError()
  213194. {
  213195. return error;
  213196. }
  213197. bool hasControlPanel() const
  213198. {
  213199. return true;
  213200. }
  213201. bool showControlPanel()
  213202. {
  213203. log ("ASIO - showing control panel");
  213204. Component modalWindow (String::empty);
  213205. modalWindow.setOpaque (true);
  213206. modalWindow.addToDesktop (0);
  213207. modalWindow.enterModalState();
  213208. bool done = false;
  213209. JUCE_TRY
  213210. {
  213211. // are there are devices that need to be closed before showing their control panel?
  213212. // close();
  213213. insideControlPanelModalLoop = true;
  213214. const uint32 started = Time::getMillisecondCounter();
  213215. if (asioObject != 0)
  213216. {
  213217. asioObject->controlPanel();
  213218. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213219. log ("spent: " + String (spent));
  213220. if (spent > 300)
  213221. {
  213222. shouldUsePreferredSize = true;
  213223. done = true;
  213224. }
  213225. }
  213226. }
  213227. JUCE_CATCH_ALL
  213228. insideControlPanelModalLoop = false;
  213229. return done;
  213230. }
  213231. void resetRequest() throw()
  213232. {
  213233. needToReset = true;
  213234. }
  213235. void resyncRequest() throw()
  213236. {
  213237. needToReset = true;
  213238. isReSync = true;
  213239. }
  213240. void timerCallback()
  213241. {
  213242. if (! insideControlPanelModalLoop)
  213243. {
  213244. stopTimer();
  213245. // used to cause a reset
  213246. log ("! ASIO restart request!");
  213247. if (isOpen_)
  213248. {
  213249. AudioIODeviceCallback* const oldCallback = currentCallback;
  213250. close();
  213251. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213252. currentSampleRate, currentBlockSizeSamples);
  213253. if (oldCallback != 0)
  213254. start (oldCallback);
  213255. }
  213256. }
  213257. else
  213258. {
  213259. startTimer (100);
  213260. }
  213261. }
  213262. juce_UseDebuggingNewOperator
  213263. private:
  213264. IASIO* volatile asioObject;
  213265. ASIOCallbacks callbacks;
  213266. void* windowHandle;
  213267. CLSID classId;
  213268. const String optionalDllForDirectLoading;
  213269. String error;
  213270. long totalNumInputChans, totalNumOutputChans;
  213271. StringArray inputChannelNames, outputChannelNames;
  213272. Array<int> sampleRates, bufferSizes;
  213273. long inputLatency, outputLatency;
  213274. long minSize, maxSize, preferredSize, granularity;
  213275. int volatile currentBlockSizeSamples;
  213276. int volatile currentBitDepth;
  213277. double volatile currentSampleRate;
  213278. BigInteger currentChansOut, currentChansIn;
  213279. AudioIODeviceCallback* volatile currentCallback;
  213280. CriticalSection callbackLock;
  213281. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213282. float* inBuffers [maxASIOChannels];
  213283. float* outBuffers [maxASIOChannels];
  213284. int inputChannelBitDepths [maxASIOChannels];
  213285. int outputChannelBitDepths [maxASIOChannels];
  213286. int inputChannelBytesPerSample [maxASIOChannels];
  213287. int outputChannelBytesPerSample [maxASIOChannels];
  213288. bool inputChannelIsFloat [maxASIOChannels];
  213289. bool outputChannelIsFloat [maxASIOChannels];
  213290. bool inputChannelLittleEndian [maxASIOChannels];
  213291. bool outputChannelLittleEndian [maxASIOChannels];
  213292. WaitableEvent event1;
  213293. HeapBlock <float> tempBuffer;
  213294. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213295. bool isOpen_, isStarted;
  213296. bool volatile isASIOOpen;
  213297. bool volatile calledback;
  213298. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213299. bool volatile insideControlPanelModalLoop;
  213300. bool volatile shouldUsePreferredSize;
  213301. void removeCurrentDriver()
  213302. {
  213303. if (asioObject != 0)
  213304. {
  213305. asioObject->Release();
  213306. asioObject = 0;
  213307. }
  213308. }
  213309. bool loadDriver()
  213310. {
  213311. removeCurrentDriver();
  213312. JUCE_TRY
  213313. {
  213314. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213315. classId, (void**) &asioObject) == S_OK)
  213316. {
  213317. return true;
  213318. }
  213319. // If a class isn't registered but we have a path for it, we can fallback to
  213320. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213321. if (optionalDllForDirectLoading.isNotEmpty())
  213322. {
  213323. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213324. if (h != 0)
  213325. {
  213326. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213327. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213328. if (dllGetClassObject != 0)
  213329. {
  213330. IClassFactory* classFactory = 0;
  213331. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213332. if (classFactory != 0)
  213333. {
  213334. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213335. classFactory->Release();
  213336. }
  213337. return asioObject != 0;
  213338. }
  213339. }
  213340. }
  213341. }
  213342. JUCE_CATCH_ALL
  213343. asioObject = 0;
  213344. return false;
  213345. }
  213346. const String initDriver()
  213347. {
  213348. if (asioObject != 0)
  213349. {
  213350. char buffer [256];
  213351. zeromem (buffer, sizeof (buffer));
  213352. if (! asioObject->init (windowHandle))
  213353. {
  213354. asioObject->getErrorMessage (buffer);
  213355. return String (buffer, sizeof (buffer) - 1);
  213356. }
  213357. // just in case any daft drivers expect this to be called..
  213358. asioObject->getDriverName (buffer);
  213359. return String::empty;
  213360. }
  213361. return "No Driver";
  213362. }
  213363. const String openDevice()
  213364. {
  213365. // use this in case the driver starts opening dialog boxes..
  213366. Component modalWindow (String::empty);
  213367. modalWindow.setOpaque (true);
  213368. modalWindow.addToDesktop (0);
  213369. modalWindow.enterModalState();
  213370. // open the device and get its info..
  213371. log ("opening ASIO device: " + getName());
  213372. needToReset = false;
  213373. isReSync = false;
  213374. outputChannelNames.clear();
  213375. inputChannelNames.clear();
  213376. bufferSizes.clear();
  213377. sampleRates.clear();
  213378. isASIOOpen = false;
  213379. isOpen_ = false;
  213380. totalNumInputChans = 0;
  213381. totalNumOutputChans = 0;
  213382. numActiveInputChans = 0;
  213383. numActiveOutputChans = 0;
  213384. currentCallback = 0;
  213385. error = String::empty;
  213386. if (getName().isEmpty())
  213387. return error;
  213388. long err = 0;
  213389. if (loadDriver())
  213390. {
  213391. if ((error = initDriver()).isEmpty())
  213392. {
  213393. numActiveInputChans = 0;
  213394. numActiveOutputChans = 0;
  213395. totalNumInputChans = 0;
  213396. totalNumOutputChans = 0;
  213397. if (asioObject != 0
  213398. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213399. {
  213400. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213401. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213402. {
  213403. // find a list of buffer sizes..
  213404. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213405. if (granularity >= 0)
  213406. {
  213407. granularity = jmax (1, (int) granularity);
  213408. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213409. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213410. }
  213411. else if (granularity < 0)
  213412. {
  213413. for (int i = 0; i < 18; ++i)
  213414. {
  213415. const int s = (1 << i);
  213416. if (s >= minSize && s <= maxSize)
  213417. bufferSizes.add (s);
  213418. }
  213419. }
  213420. if (! bufferSizes.contains (preferredSize))
  213421. bufferSizes.insert (0, preferredSize);
  213422. double currentRate = 0;
  213423. asioObject->getSampleRate (&currentRate);
  213424. if (currentRate <= 0.0 || currentRate > 192001.0)
  213425. {
  213426. log ("setting sample rate");
  213427. err = asioObject->setSampleRate (44100.0);
  213428. if (err != 0)
  213429. {
  213430. logError ("setting sample rate", err);
  213431. }
  213432. asioObject->getSampleRate (&currentRate);
  213433. }
  213434. currentSampleRate = currentRate;
  213435. postOutput = (asioObject->outputReady() == 0);
  213436. if (postOutput)
  213437. {
  213438. log ("ASIO outputReady = ok");
  213439. }
  213440. updateSampleRates();
  213441. // ..because cubase does it at this point
  213442. inputLatency = outputLatency = 0;
  213443. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213444. {
  213445. log ("ASIO - no latencies");
  213446. }
  213447. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213448. // create some dummy buffers now.. because cubase does..
  213449. numActiveInputChans = 0;
  213450. numActiveOutputChans = 0;
  213451. ASIOBufferInfo* info = bufferInfos;
  213452. int i, numChans = 0;
  213453. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213454. {
  213455. info->isInput = 1;
  213456. info->channelNum = i;
  213457. info->buffers[0] = info->buffers[1] = 0;
  213458. ++info;
  213459. ++numChans;
  213460. }
  213461. const int outputBufferIndex = numChans;
  213462. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213463. {
  213464. info->isInput = 0;
  213465. info->channelNum = i;
  213466. info->buffers[0] = info->buffers[1] = 0;
  213467. ++info;
  213468. ++numChans;
  213469. }
  213470. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213471. if (currentASIODev[0] == this)
  213472. {
  213473. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213474. callbacks.asioMessage = &asioMessagesCallback0;
  213475. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213476. }
  213477. else if (currentASIODev[1] == this)
  213478. {
  213479. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213480. callbacks.asioMessage = &asioMessagesCallback1;
  213481. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213482. }
  213483. else if (currentASIODev[2] == this)
  213484. {
  213485. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213486. callbacks.asioMessage = &asioMessagesCallback2;
  213487. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213488. }
  213489. else
  213490. {
  213491. jassertfalse;
  213492. }
  213493. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213494. if (preferredSize > 0)
  213495. {
  213496. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213497. if (err != 0)
  213498. {
  213499. logError ("dummy buffers", err);
  213500. }
  213501. }
  213502. long newInps = 0, newOuts = 0;
  213503. asioObject->getChannels (&newInps, &newOuts);
  213504. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213505. {
  213506. totalNumInputChans = newInps;
  213507. totalNumOutputChans = newOuts;
  213508. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213509. }
  213510. updateSampleRates();
  213511. ASIOChannelInfo channelInfo;
  213512. channelInfo.type = 0;
  213513. for (i = 0; i < totalNumInputChans; ++i)
  213514. {
  213515. zerostruct (channelInfo);
  213516. channelInfo.channel = i;
  213517. channelInfo.isInput = 1;
  213518. asioObject->getChannelInfo (&channelInfo);
  213519. inputChannelNames.add (String (channelInfo.name));
  213520. }
  213521. for (i = 0; i < totalNumOutputChans; ++i)
  213522. {
  213523. zerostruct (channelInfo);
  213524. channelInfo.channel = i;
  213525. channelInfo.isInput = 0;
  213526. asioObject->getChannelInfo (&channelInfo);
  213527. outputChannelNames.add (String (channelInfo.name));
  213528. typeToFormatParameters (channelInfo.type,
  213529. outputChannelBitDepths[i],
  213530. outputChannelBytesPerSample[i],
  213531. outputChannelIsFloat[i],
  213532. outputChannelLittleEndian[i]);
  213533. if (i < 2)
  213534. {
  213535. // clear the channels that are used with the dummy stuff
  213536. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213537. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213538. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213539. }
  213540. }
  213541. outputChannelNames.trim();
  213542. inputChannelNames.trim();
  213543. outputChannelNames.appendNumbersToDuplicates (false, true);
  213544. inputChannelNames.appendNumbersToDuplicates (false, true);
  213545. // start and stop because cubase does it..
  213546. asioObject->getLatencies (&inputLatency, &outputLatency);
  213547. if ((err = asioObject->start()) != 0)
  213548. {
  213549. // ignore an error here, as it might start later after setting other stuff up
  213550. logError ("ASIO start", err);
  213551. }
  213552. Thread::sleep (100);
  213553. asioObject->stop();
  213554. }
  213555. else
  213556. {
  213557. error = "Can't detect buffer sizes";
  213558. }
  213559. }
  213560. else
  213561. {
  213562. error = "Can't detect asio channels";
  213563. }
  213564. }
  213565. }
  213566. else
  213567. {
  213568. error = "No such device";
  213569. }
  213570. if (error.isNotEmpty())
  213571. {
  213572. logError (error, err);
  213573. if (asioObject != 0)
  213574. asioObject->disposeBuffers();
  213575. removeCurrentDriver();
  213576. isASIOOpen = false;
  213577. }
  213578. else
  213579. {
  213580. isASIOOpen = true;
  213581. log ("ASIO device open");
  213582. }
  213583. isOpen_ = false;
  213584. needToReset = false;
  213585. isReSync = false;
  213586. return error;
  213587. }
  213588. void callback (const long index)
  213589. {
  213590. if (isStarted)
  213591. {
  213592. bufferIndex = index;
  213593. processBuffer();
  213594. }
  213595. else
  213596. {
  213597. if (postOutput && (asioObject != 0))
  213598. asioObject->outputReady();
  213599. }
  213600. calledback = true;
  213601. }
  213602. void processBuffer()
  213603. {
  213604. const ASIOBufferInfo* const infos = bufferInfos;
  213605. const int bi = bufferIndex;
  213606. const ScopedLock sl (callbackLock);
  213607. if (needToReset)
  213608. {
  213609. needToReset = false;
  213610. if (isReSync)
  213611. {
  213612. log ("! ASIO resync");
  213613. isReSync = false;
  213614. }
  213615. else
  213616. {
  213617. startTimer (20);
  213618. }
  213619. }
  213620. if (bi >= 0)
  213621. {
  213622. const int samps = currentBlockSizeSamples;
  213623. if (currentCallback != 0)
  213624. {
  213625. int i;
  213626. for (i = 0; i < numActiveInputChans; ++i)
  213627. {
  213628. float* const dst = inBuffers[i];
  213629. jassert (dst != 0);
  213630. const char* const src = (const char*) (infos[i].buffers[bi]);
  213631. if (inputChannelIsFloat[i])
  213632. {
  213633. memcpy (dst, src, samps * sizeof (float));
  213634. }
  213635. else
  213636. {
  213637. jassert (dst == tempBuffer + (samps * i));
  213638. switch (inputChannelBitDepths[i])
  213639. {
  213640. case 16:
  213641. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213642. samps, inputChannelLittleEndian[i]);
  213643. break;
  213644. case 24:
  213645. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213646. samps, inputChannelLittleEndian[i]);
  213647. break;
  213648. case 32:
  213649. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213650. samps, inputChannelLittleEndian[i]);
  213651. break;
  213652. case 64:
  213653. jassertfalse;
  213654. break;
  213655. }
  213656. }
  213657. }
  213658. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  213659. numActiveInputChans,
  213660. outBuffers,
  213661. numActiveOutputChans,
  213662. samps);
  213663. for (i = 0; i < numActiveOutputChans; ++i)
  213664. {
  213665. float* const src = outBuffers[i];
  213666. jassert (src != 0);
  213667. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213668. if (outputChannelIsFloat[i])
  213669. {
  213670. memcpy (dst, src, samps * sizeof (float));
  213671. }
  213672. else
  213673. {
  213674. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213675. switch (outputChannelBitDepths[i])
  213676. {
  213677. case 16:
  213678. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213679. samps, outputChannelLittleEndian[i]);
  213680. break;
  213681. case 24:
  213682. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213683. samps, outputChannelLittleEndian[i]);
  213684. break;
  213685. case 32:
  213686. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213687. samps, outputChannelLittleEndian[i]);
  213688. break;
  213689. case 64:
  213690. jassertfalse;
  213691. break;
  213692. }
  213693. }
  213694. }
  213695. }
  213696. else
  213697. {
  213698. for (int i = 0; i < numActiveOutputChans; ++i)
  213699. {
  213700. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213701. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213702. }
  213703. }
  213704. }
  213705. if (postOutput)
  213706. asioObject->outputReady();
  213707. }
  213708. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213709. {
  213710. if (currentASIODev[0] != 0)
  213711. currentASIODev[0]->callback (index);
  213712. return 0;
  213713. }
  213714. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213715. {
  213716. if (currentASIODev[1] != 0)
  213717. currentASIODev[1]->callback (index);
  213718. return 0;
  213719. }
  213720. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213721. {
  213722. if (currentASIODev[2] != 0)
  213723. currentASIODev[2]->callback (index);
  213724. return 0;
  213725. }
  213726. static void bufferSwitchCallback0 (long index, long)
  213727. {
  213728. if (currentASIODev[0] != 0)
  213729. currentASIODev[0]->callback (index);
  213730. }
  213731. static void bufferSwitchCallback1 (long index, long)
  213732. {
  213733. if (currentASIODev[1] != 0)
  213734. currentASIODev[1]->callback (index);
  213735. }
  213736. static void bufferSwitchCallback2 (long index, long)
  213737. {
  213738. if (currentASIODev[2] != 0)
  213739. currentASIODev[2]->callback (index);
  213740. }
  213741. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  213742. {
  213743. return asioMessagesCallback (selector, value, 0);
  213744. }
  213745. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  213746. {
  213747. return asioMessagesCallback (selector, value, 1);
  213748. }
  213749. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  213750. {
  213751. return asioMessagesCallback (selector, value, 2);
  213752. }
  213753. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  213754. {
  213755. switch (selector)
  213756. {
  213757. case kAsioSelectorSupported:
  213758. if (value == kAsioResetRequest
  213759. || value == kAsioEngineVersion
  213760. || value == kAsioResyncRequest
  213761. || value == kAsioLatenciesChanged
  213762. || value == kAsioSupportsInputMonitor)
  213763. return 1;
  213764. break;
  213765. case kAsioBufferSizeChange:
  213766. break;
  213767. case kAsioResetRequest:
  213768. if (currentASIODev[deviceIndex] != 0)
  213769. currentASIODev[deviceIndex]->resetRequest();
  213770. return 1;
  213771. case kAsioResyncRequest:
  213772. if (currentASIODev[deviceIndex] != 0)
  213773. currentASIODev[deviceIndex]->resyncRequest();
  213774. return 1;
  213775. case kAsioLatenciesChanged:
  213776. return 1;
  213777. case kAsioEngineVersion:
  213778. return 2;
  213779. case kAsioSupportsTimeInfo:
  213780. case kAsioSupportsTimeCode:
  213781. return 0;
  213782. }
  213783. return 0;
  213784. }
  213785. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  213786. {
  213787. }
  213788. static void convertInt16ToFloat (const char* src,
  213789. float* dest,
  213790. const int srcStrideBytes,
  213791. int numSamples,
  213792. const bool littleEndian) throw()
  213793. {
  213794. const double g = 1.0 / 32768.0;
  213795. if (littleEndian)
  213796. {
  213797. while (--numSamples >= 0)
  213798. {
  213799. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213800. src += srcStrideBytes;
  213801. }
  213802. }
  213803. else
  213804. {
  213805. while (--numSamples >= 0)
  213806. {
  213807. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213808. src += srcStrideBytes;
  213809. }
  213810. }
  213811. }
  213812. static void convertFloatToInt16 (const float* src,
  213813. char* dest,
  213814. const int dstStrideBytes,
  213815. int numSamples,
  213816. const bool littleEndian) throw()
  213817. {
  213818. const double maxVal = (double) 0x7fff;
  213819. if (littleEndian)
  213820. {
  213821. while (--numSamples >= 0)
  213822. {
  213823. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213824. dest += dstStrideBytes;
  213825. }
  213826. }
  213827. else
  213828. {
  213829. while (--numSamples >= 0)
  213830. {
  213831. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213832. dest += dstStrideBytes;
  213833. }
  213834. }
  213835. }
  213836. static void convertInt24ToFloat (const char* src,
  213837. float* dest,
  213838. const int srcStrideBytes,
  213839. int numSamples,
  213840. const bool littleEndian) throw()
  213841. {
  213842. const double g = 1.0 / 0x7fffff;
  213843. if (littleEndian)
  213844. {
  213845. while (--numSamples >= 0)
  213846. {
  213847. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213848. src += srcStrideBytes;
  213849. }
  213850. }
  213851. else
  213852. {
  213853. while (--numSamples >= 0)
  213854. {
  213855. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213856. src += srcStrideBytes;
  213857. }
  213858. }
  213859. }
  213860. static void convertFloatToInt24 (const float* src,
  213861. char* dest,
  213862. const int dstStrideBytes,
  213863. int numSamples,
  213864. const bool littleEndian) throw()
  213865. {
  213866. const double maxVal = (double) 0x7fffff;
  213867. if (littleEndian)
  213868. {
  213869. while (--numSamples >= 0)
  213870. {
  213871. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213872. dest += dstStrideBytes;
  213873. }
  213874. }
  213875. else
  213876. {
  213877. while (--numSamples >= 0)
  213878. {
  213879. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213880. dest += dstStrideBytes;
  213881. }
  213882. }
  213883. }
  213884. static void convertInt32ToFloat (const char* src,
  213885. float* dest,
  213886. const int srcStrideBytes,
  213887. int numSamples,
  213888. const bool littleEndian) throw()
  213889. {
  213890. const double g = 1.0 / 0x7fffffff;
  213891. if (littleEndian)
  213892. {
  213893. while (--numSamples >= 0)
  213894. {
  213895. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213896. src += srcStrideBytes;
  213897. }
  213898. }
  213899. else
  213900. {
  213901. while (--numSamples >= 0)
  213902. {
  213903. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213904. src += srcStrideBytes;
  213905. }
  213906. }
  213907. }
  213908. static void convertFloatToInt32 (const float* src,
  213909. char* dest,
  213910. const int dstStrideBytes,
  213911. int numSamples,
  213912. const bool littleEndian) throw()
  213913. {
  213914. const double maxVal = (double) 0x7fffffff;
  213915. if (littleEndian)
  213916. {
  213917. while (--numSamples >= 0)
  213918. {
  213919. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213920. dest += dstStrideBytes;
  213921. }
  213922. }
  213923. else
  213924. {
  213925. while (--numSamples >= 0)
  213926. {
  213927. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213928. dest += dstStrideBytes;
  213929. }
  213930. }
  213931. }
  213932. static void typeToFormatParameters (const long type,
  213933. int& bitDepth,
  213934. int& byteStride,
  213935. bool& formatIsFloat,
  213936. bool& littleEndian) throw()
  213937. {
  213938. bitDepth = 0;
  213939. littleEndian = false;
  213940. formatIsFloat = false;
  213941. switch (type)
  213942. {
  213943. case ASIOSTInt16MSB:
  213944. case ASIOSTInt16LSB:
  213945. case ASIOSTInt32MSB16:
  213946. case ASIOSTInt32LSB16:
  213947. bitDepth = 16; break;
  213948. case ASIOSTFloat32MSB:
  213949. case ASIOSTFloat32LSB:
  213950. formatIsFloat = true;
  213951. bitDepth = 32; break;
  213952. case ASIOSTInt32MSB:
  213953. case ASIOSTInt32LSB:
  213954. bitDepth = 32; break;
  213955. case ASIOSTInt24MSB:
  213956. case ASIOSTInt24LSB:
  213957. case ASIOSTInt32MSB24:
  213958. case ASIOSTInt32LSB24:
  213959. case ASIOSTInt32MSB18:
  213960. case ASIOSTInt32MSB20:
  213961. case ASIOSTInt32LSB18:
  213962. case ASIOSTInt32LSB20:
  213963. bitDepth = 24; break;
  213964. case ASIOSTFloat64MSB:
  213965. case ASIOSTFloat64LSB:
  213966. default:
  213967. bitDepth = 64;
  213968. break;
  213969. }
  213970. switch (type)
  213971. {
  213972. case ASIOSTInt16MSB:
  213973. case ASIOSTInt32MSB16:
  213974. case ASIOSTFloat32MSB:
  213975. case ASIOSTFloat64MSB:
  213976. case ASIOSTInt32MSB:
  213977. case ASIOSTInt32MSB18:
  213978. case ASIOSTInt32MSB20:
  213979. case ASIOSTInt32MSB24:
  213980. case ASIOSTInt24MSB:
  213981. littleEndian = false; break;
  213982. case ASIOSTInt16LSB:
  213983. case ASIOSTInt32LSB16:
  213984. case ASIOSTFloat32LSB:
  213985. case ASIOSTFloat64LSB:
  213986. case ASIOSTInt32LSB:
  213987. case ASIOSTInt32LSB18:
  213988. case ASIOSTInt32LSB20:
  213989. case ASIOSTInt32LSB24:
  213990. case ASIOSTInt24LSB:
  213991. littleEndian = true; break;
  213992. default:
  213993. break;
  213994. }
  213995. switch (type)
  213996. {
  213997. case ASIOSTInt16LSB:
  213998. case ASIOSTInt16MSB:
  213999. byteStride = 2; break;
  214000. case ASIOSTInt24LSB:
  214001. case ASIOSTInt24MSB:
  214002. byteStride = 3; break;
  214003. case ASIOSTInt32MSB16:
  214004. case ASIOSTInt32LSB16:
  214005. case ASIOSTInt32MSB:
  214006. case ASIOSTInt32MSB18:
  214007. case ASIOSTInt32MSB20:
  214008. case ASIOSTInt32MSB24:
  214009. case ASIOSTInt32LSB:
  214010. case ASIOSTInt32LSB18:
  214011. case ASIOSTInt32LSB20:
  214012. case ASIOSTInt32LSB24:
  214013. case ASIOSTFloat32LSB:
  214014. case ASIOSTFloat32MSB:
  214015. byteStride = 4; break;
  214016. case ASIOSTFloat64MSB:
  214017. case ASIOSTFloat64LSB:
  214018. byteStride = 8; break;
  214019. default:
  214020. break;
  214021. }
  214022. }
  214023. };
  214024. class ASIOAudioIODeviceType : public AudioIODeviceType
  214025. {
  214026. public:
  214027. ASIOAudioIODeviceType()
  214028. : AudioIODeviceType ("ASIO"),
  214029. hasScanned (false)
  214030. {
  214031. CoInitialize (0);
  214032. }
  214033. ~ASIOAudioIODeviceType()
  214034. {
  214035. }
  214036. void scanForDevices()
  214037. {
  214038. hasScanned = true;
  214039. deviceNames.clear();
  214040. classIds.clear();
  214041. HKEY hk = 0;
  214042. int index = 0;
  214043. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214044. {
  214045. for (;;)
  214046. {
  214047. char name [256];
  214048. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214049. {
  214050. addDriverInfo (name, hk);
  214051. }
  214052. else
  214053. {
  214054. break;
  214055. }
  214056. }
  214057. RegCloseKey (hk);
  214058. }
  214059. }
  214060. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214061. {
  214062. jassert (hasScanned); // need to call scanForDevices() before doing this
  214063. return deviceNames;
  214064. }
  214065. int getDefaultDeviceIndex (bool) const
  214066. {
  214067. jassert (hasScanned); // need to call scanForDevices() before doing this
  214068. for (int i = deviceNames.size(); --i >= 0;)
  214069. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214070. return i; // asio4all is a safe choice for a default..
  214071. #if JUCE_DEBUG
  214072. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214073. return 1; // (the digi m-box driver crashes the app when you run
  214074. // it in the debugger, which can be a bit annoying)
  214075. #endif
  214076. return 0;
  214077. }
  214078. static int findFreeSlot()
  214079. {
  214080. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214081. if (currentASIODev[i] == 0)
  214082. return i;
  214083. jassertfalse; // unfortunately you can only have a finite number
  214084. // of ASIO devices open at the same time..
  214085. return -1;
  214086. }
  214087. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214088. {
  214089. jassert (hasScanned); // need to call scanForDevices() before doing this
  214090. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214091. }
  214092. bool hasSeparateInputsAndOutputs() const { return false; }
  214093. AudioIODevice* createDevice (const String& outputDeviceName,
  214094. const String& inputDeviceName)
  214095. {
  214096. // ASIO can't open two different devices for input and output - they must be the same one.
  214097. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214098. jassert (hasScanned); // need to call scanForDevices() before doing this
  214099. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214100. : inputDeviceName);
  214101. if (index >= 0)
  214102. {
  214103. const int freeSlot = findFreeSlot();
  214104. if (freeSlot >= 0)
  214105. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214106. }
  214107. return 0;
  214108. }
  214109. juce_UseDebuggingNewOperator
  214110. private:
  214111. StringArray deviceNames;
  214112. OwnedArray <CLSID> classIds;
  214113. bool hasScanned;
  214114. static bool checkClassIsOk (const String& classId)
  214115. {
  214116. HKEY hk = 0;
  214117. bool ok = false;
  214118. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214119. {
  214120. int index = 0;
  214121. for (;;)
  214122. {
  214123. WCHAR buf [512];
  214124. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214125. {
  214126. if (classId.equalsIgnoreCase (buf))
  214127. {
  214128. HKEY subKey, pathKey;
  214129. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214130. {
  214131. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214132. {
  214133. WCHAR pathName [1024];
  214134. DWORD dtype = REG_SZ;
  214135. DWORD dsize = sizeof (pathName);
  214136. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214137. ok = File (pathName).exists();
  214138. RegCloseKey (pathKey);
  214139. }
  214140. RegCloseKey (subKey);
  214141. }
  214142. break;
  214143. }
  214144. }
  214145. else
  214146. {
  214147. break;
  214148. }
  214149. }
  214150. RegCloseKey (hk);
  214151. }
  214152. return ok;
  214153. }
  214154. void addDriverInfo (const String& keyName, HKEY hk)
  214155. {
  214156. HKEY subKey;
  214157. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214158. {
  214159. WCHAR buf [256];
  214160. zerostruct (buf);
  214161. DWORD dtype = REG_SZ;
  214162. DWORD dsize = sizeof (buf);
  214163. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214164. {
  214165. if (dsize > 0 && checkClassIsOk (buf))
  214166. {
  214167. CLSID classId;
  214168. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214169. {
  214170. dtype = REG_SZ;
  214171. dsize = sizeof (buf);
  214172. String deviceName;
  214173. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214174. deviceName = buf;
  214175. else
  214176. deviceName = keyName;
  214177. log ("found " + deviceName);
  214178. deviceNames.add (deviceName);
  214179. classIds.add (new CLSID (classId));
  214180. }
  214181. }
  214182. RegCloseKey (subKey);
  214183. }
  214184. }
  214185. }
  214186. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214187. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214188. };
  214189. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214190. {
  214191. return new ASIOAudioIODeviceType();
  214192. }
  214193. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214194. void* guid,
  214195. const String& optionalDllForDirectLoading)
  214196. {
  214197. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214198. if (freeSlot < 0)
  214199. return 0;
  214200. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214201. }
  214202. #undef log
  214203. #endif
  214204. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214205. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214206. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214207. // compiled on its own).
  214208. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214209. END_JUCE_NAMESPACE
  214210. extern "C"
  214211. {
  214212. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214213. typedef struct typeDSBUFFERDESC
  214214. {
  214215. DWORD dwSize;
  214216. DWORD dwFlags;
  214217. DWORD dwBufferBytes;
  214218. DWORD dwReserved;
  214219. LPWAVEFORMATEX lpwfxFormat;
  214220. GUID guid3DAlgorithm;
  214221. } DSBUFFERDESC;
  214222. struct IDirectSoundBuffer;
  214223. #undef INTERFACE
  214224. #define INTERFACE IDirectSound
  214225. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214226. {
  214227. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214228. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214229. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214230. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214231. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214232. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214233. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214234. STDMETHOD(Compact) (THIS) PURE;
  214235. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214236. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214237. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214238. };
  214239. #undef INTERFACE
  214240. #define INTERFACE IDirectSoundBuffer
  214241. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214242. {
  214243. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214244. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214245. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214246. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214247. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214248. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214249. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214250. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214251. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214252. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214253. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214254. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214255. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214256. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214257. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214258. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214259. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214260. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214261. STDMETHOD(Stop) (THIS) PURE;
  214262. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214263. STDMETHOD(Restore) (THIS) PURE;
  214264. };
  214265. typedef struct typeDSCBUFFERDESC
  214266. {
  214267. DWORD dwSize;
  214268. DWORD dwFlags;
  214269. DWORD dwBufferBytes;
  214270. DWORD dwReserved;
  214271. LPWAVEFORMATEX lpwfxFormat;
  214272. } DSCBUFFERDESC;
  214273. struct IDirectSoundCaptureBuffer;
  214274. #undef INTERFACE
  214275. #define INTERFACE IDirectSoundCapture
  214276. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214277. {
  214278. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214279. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214280. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214281. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214282. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214283. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214284. };
  214285. #undef INTERFACE
  214286. #define INTERFACE IDirectSoundCaptureBuffer
  214287. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214288. {
  214289. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214290. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214291. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214292. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214293. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214294. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214295. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214296. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214297. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214298. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214299. STDMETHOD(Stop) (THIS) PURE;
  214300. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214301. };
  214302. };
  214303. BEGIN_JUCE_NAMESPACE
  214304. static const String getDSErrorMessage (HRESULT hr)
  214305. {
  214306. const char* result = 0;
  214307. switch (hr)
  214308. {
  214309. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214310. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214311. case E_INVALIDARG: result = "Invalid parameter"; break;
  214312. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214313. case E_FAIL: result = "Generic error"; break;
  214314. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214315. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214316. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214317. case E_NOTIMPL: result = "Unsupported function"; break;
  214318. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214319. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214320. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214321. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214322. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214323. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214324. case E_NOINTERFACE: result = "No interface"; break;
  214325. case S_OK: result = "No error"; break;
  214326. default: return "Unknown error: " + String ((int) hr);
  214327. }
  214328. return result;
  214329. }
  214330. #define DS_DEBUGGING 1
  214331. #ifdef DS_DEBUGGING
  214332. #define CATCH JUCE_CATCH_EXCEPTION
  214333. #undef log
  214334. #define log(a) Logger::writeToLog(a);
  214335. #undef logError
  214336. #define logError(a) logDSError(a, __LINE__);
  214337. static void logDSError (HRESULT hr, int lineNum)
  214338. {
  214339. if (hr != S_OK)
  214340. {
  214341. String error ("DS error at line ");
  214342. error << lineNum << " - " << getDSErrorMessage (hr);
  214343. log (error);
  214344. }
  214345. }
  214346. #else
  214347. #define CATCH JUCE_CATCH_ALL
  214348. #define log(a)
  214349. #define logError(a)
  214350. #endif
  214351. #define DSOUND_FUNCTION(functionName, params) \
  214352. typedef HRESULT (WINAPI *type##functionName) params; \
  214353. static type##functionName ds##functionName = 0;
  214354. #define DSOUND_FUNCTION_LOAD(functionName) \
  214355. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214356. jassert (ds##functionName != 0);
  214357. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214358. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214359. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214360. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214361. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214362. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214363. static void initialiseDSoundFunctions()
  214364. {
  214365. if (dsDirectSoundCreate == 0)
  214366. {
  214367. HMODULE h = LoadLibraryA ("dsound.dll");
  214368. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214369. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214370. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214371. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214372. }
  214373. }
  214374. class DSoundInternalOutChannel
  214375. {
  214376. String name;
  214377. LPGUID guid;
  214378. int sampleRate, bufferSizeSamples;
  214379. float* leftBuffer;
  214380. float* rightBuffer;
  214381. IDirectSound* pDirectSound;
  214382. IDirectSoundBuffer* pOutputBuffer;
  214383. DWORD writeOffset;
  214384. int totalBytesPerBuffer;
  214385. int bytesPerBuffer;
  214386. unsigned int lastPlayCursor;
  214387. public:
  214388. int bitDepth;
  214389. bool doneFlag;
  214390. DSoundInternalOutChannel (const String& name_,
  214391. LPGUID guid_,
  214392. int rate,
  214393. int bufferSize,
  214394. float* left,
  214395. float* right)
  214396. : name (name_),
  214397. guid (guid_),
  214398. sampleRate (rate),
  214399. bufferSizeSamples (bufferSize),
  214400. leftBuffer (left),
  214401. rightBuffer (right),
  214402. pDirectSound (0),
  214403. pOutputBuffer (0),
  214404. bitDepth (16)
  214405. {
  214406. }
  214407. ~DSoundInternalOutChannel()
  214408. {
  214409. close();
  214410. }
  214411. void close()
  214412. {
  214413. HRESULT hr;
  214414. if (pOutputBuffer != 0)
  214415. {
  214416. JUCE_TRY
  214417. {
  214418. log ("closing dsound out: " + name);
  214419. hr = pOutputBuffer->Stop();
  214420. logError (hr);
  214421. }
  214422. CATCH
  214423. JUCE_TRY
  214424. {
  214425. hr = pOutputBuffer->Release();
  214426. logError (hr);
  214427. }
  214428. CATCH
  214429. pOutputBuffer = 0;
  214430. }
  214431. if (pDirectSound != 0)
  214432. {
  214433. JUCE_TRY
  214434. {
  214435. hr = pDirectSound->Release();
  214436. logError (hr);
  214437. }
  214438. CATCH
  214439. pDirectSound = 0;
  214440. }
  214441. }
  214442. const String open()
  214443. {
  214444. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214445. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214446. pDirectSound = 0;
  214447. pOutputBuffer = 0;
  214448. writeOffset = 0;
  214449. String error;
  214450. HRESULT hr = E_NOINTERFACE;
  214451. if (dsDirectSoundCreate != 0)
  214452. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214453. if (hr == S_OK)
  214454. {
  214455. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214456. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214457. const int numChannels = 2;
  214458. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214459. logError (hr);
  214460. if (hr == S_OK)
  214461. {
  214462. IDirectSoundBuffer* pPrimaryBuffer;
  214463. DSBUFFERDESC primaryDesc;
  214464. zerostruct (primaryDesc);
  214465. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214466. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214467. primaryDesc.dwBufferBytes = 0;
  214468. primaryDesc.lpwfxFormat = 0;
  214469. log ("opening dsound out step 2");
  214470. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214471. logError (hr);
  214472. if (hr == S_OK)
  214473. {
  214474. WAVEFORMATEX wfFormat;
  214475. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214476. wfFormat.nChannels = (unsigned short) numChannels;
  214477. wfFormat.nSamplesPerSec = sampleRate;
  214478. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214479. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214480. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214481. wfFormat.cbSize = 0;
  214482. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214483. logError (hr);
  214484. if (hr == S_OK)
  214485. {
  214486. DSBUFFERDESC secondaryDesc;
  214487. zerostruct (secondaryDesc);
  214488. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214489. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214490. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214491. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214492. secondaryDesc.lpwfxFormat = &wfFormat;
  214493. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214494. logError (hr);
  214495. if (hr == S_OK)
  214496. {
  214497. log ("opening dsound out step 3");
  214498. DWORD dwDataLen;
  214499. unsigned char* pDSBuffData;
  214500. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214501. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214502. logError (hr);
  214503. if (hr == S_OK)
  214504. {
  214505. zeromem (pDSBuffData, dwDataLen);
  214506. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214507. if (hr == S_OK)
  214508. {
  214509. hr = pOutputBuffer->SetCurrentPosition (0);
  214510. if (hr == S_OK)
  214511. {
  214512. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214513. if (hr == S_OK)
  214514. return String::empty;
  214515. }
  214516. }
  214517. }
  214518. }
  214519. }
  214520. }
  214521. }
  214522. }
  214523. error = getDSErrorMessage (hr);
  214524. close();
  214525. return error;
  214526. }
  214527. void synchronisePosition()
  214528. {
  214529. if (pOutputBuffer != 0)
  214530. {
  214531. DWORD playCursor;
  214532. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214533. }
  214534. }
  214535. bool service()
  214536. {
  214537. if (pOutputBuffer == 0)
  214538. return true;
  214539. DWORD playCursor, writeCursor;
  214540. for (;;)
  214541. {
  214542. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214543. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214544. {
  214545. pOutputBuffer->Restore();
  214546. continue;
  214547. }
  214548. if (hr == S_OK)
  214549. break;
  214550. logError (hr);
  214551. jassertfalse;
  214552. return true;
  214553. }
  214554. int playWriteGap = writeCursor - playCursor;
  214555. if (playWriteGap < 0)
  214556. playWriteGap += totalBytesPerBuffer;
  214557. int bytesEmpty = playCursor - writeOffset;
  214558. if (bytesEmpty < 0)
  214559. bytesEmpty += totalBytesPerBuffer;
  214560. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214561. {
  214562. writeOffset = writeCursor;
  214563. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214564. }
  214565. if (bytesEmpty >= bytesPerBuffer)
  214566. {
  214567. LPBYTE lpbuf1 = 0;
  214568. LPBYTE lpbuf2 = 0;
  214569. DWORD dwSize1 = 0;
  214570. DWORD dwSize2 = 0;
  214571. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214572. bytesPerBuffer,
  214573. (void**) &lpbuf1, &dwSize1,
  214574. (void**) &lpbuf2, &dwSize2, 0);
  214575. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214576. {
  214577. pOutputBuffer->Restore();
  214578. hr = pOutputBuffer->Lock (writeOffset,
  214579. bytesPerBuffer,
  214580. (void**) &lpbuf1, &dwSize1,
  214581. (void**) &lpbuf2, &dwSize2, 0);
  214582. }
  214583. if (hr == S_OK)
  214584. {
  214585. if (bitDepth == 16)
  214586. {
  214587. const float gainL = 32767.0f;
  214588. const float gainR = 32767.0f;
  214589. int* dest = (int*)lpbuf1;
  214590. const float* left = leftBuffer;
  214591. const float* right = rightBuffer;
  214592. int samples1 = dwSize1 >> 2;
  214593. int samples2 = dwSize2 >> 2;
  214594. if (left == 0)
  214595. {
  214596. while (--samples1 >= 0)
  214597. {
  214598. int r = roundToInt (gainR * *right++);
  214599. if (r < -32768)
  214600. r = -32768;
  214601. else if (r > 32767)
  214602. r = 32767;
  214603. *dest++ = (r << 16);
  214604. }
  214605. dest = (int*)lpbuf2;
  214606. while (--samples2 >= 0)
  214607. {
  214608. int r = roundToInt (gainR * *right++);
  214609. if (r < -32768)
  214610. r = -32768;
  214611. else if (r > 32767)
  214612. r = 32767;
  214613. *dest++ = (r << 16);
  214614. }
  214615. }
  214616. else if (right == 0)
  214617. {
  214618. while (--samples1 >= 0)
  214619. {
  214620. int l = roundToInt (gainL * *left++);
  214621. if (l < -32768)
  214622. l = -32768;
  214623. else if (l > 32767)
  214624. l = 32767;
  214625. l &= 0xffff;
  214626. *dest++ = l;
  214627. }
  214628. dest = (int*)lpbuf2;
  214629. while (--samples2 >= 0)
  214630. {
  214631. int l = roundToInt (gainL * *left++);
  214632. if (l < -32768)
  214633. l = -32768;
  214634. else if (l > 32767)
  214635. l = 32767;
  214636. l &= 0xffff;
  214637. *dest++ = l;
  214638. }
  214639. }
  214640. else
  214641. {
  214642. while (--samples1 >= 0)
  214643. {
  214644. int l = roundToInt (gainL * *left++);
  214645. if (l < -32768)
  214646. l = -32768;
  214647. else if (l > 32767)
  214648. l = 32767;
  214649. l &= 0xffff;
  214650. int r = roundToInt (gainR * *right++);
  214651. if (r < -32768)
  214652. r = -32768;
  214653. else if (r > 32767)
  214654. r = 32767;
  214655. *dest++ = (r << 16) | l;
  214656. }
  214657. dest = (int*)lpbuf2;
  214658. while (--samples2 >= 0)
  214659. {
  214660. int l = roundToInt (gainL * *left++);
  214661. if (l < -32768)
  214662. l = -32768;
  214663. else if (l > 32767)
  214664. l = 32767;
  214665. l &= 0xffff;
  214666. int r = roundToInt (gainR * *right++);
  214667. if (r < -32768)
  214668. r = -32768;
  214669. else if (r > 32767)
  214670. r = 32767;
  214671. *dest++ = (r << 16) | l;
  214672. }
  214673. }
  214674. }
  214675. else
  214676. {
  214677. jassertfalse;
  214678. }
  214679. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214680. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214681. }
  214682. else
  214683. {
  214684. jassertfalse;
  214685. logError (hr);
  214686. }
  214687. bytesEmpty -= bytesPerBuffer;
  214688. return true;
  214689. }
  214690. else
  214691. {
  214692. return false;
  214693. }
  214694. }
  214695. };
  214696. struct DSoundInternalInChannel
  214697. {
  214698. String name;
  214699. LPGUID guid;
  214700. int sampleRate, bufferSizeSamples;
  214701. float* leftBuffer;
  214702. float* rightBuffer;
  214703. IDirectSound* pDirectSound;
  214704. IDirectSoundCapture* pDirectSoundCapture;
  214705. IDirectSoundCaptureBuffer* pInputBuffer;
  214706. public:
  214707. unsigned int readOffset;
  214708. int bytesPerBuffer, totalBytesPerBuffer;
  214709. int bitDepth;
  214710. bool doneFlag;
  214711. DSoundInternalInChannel (const String& name_,
  214712. LPGUID guid_,
  214713. int rate,
  214714. int bufferSize,
  214715. float* left,
  214716. float* right)
  214717. : name (name_),
  214718. guid (guid_),
  214719. sampleRate (rate),
  214720. bufferSizeSamples (bufferSize),
  214721. leftBuffer (left),
  214722. rightBuffer (right),
  214723. pDirectSound (0),
  214724. pDirectSoundCapture (0),
  214725. pInputBuffer (0),
  214726. bitDepth (16)
  214727. {
  214728. }
  214729. ~DSoundInternalInChannel()
  214730. {
  214731. close();
  214732. }
  214733. void close()
  214734. {
  214735. HRESULT hr;
  214736. if (pInputBuffer != 0)
  214737. {
  214738. JUCE_TRY
  214739. {
  214740. log ("closing dsound in: " + name);
  214741. hr = pInputBuffer->Stop();
  214742. logError (hr);
  214743. }
  214744. CATCH
  214745. JUCE_TRY
  214746. {
  214747. hr = pInputBuffer->Release();
  214748. logError (hr);
  214749. }
  214750. CATCH
  214751. pInputBuffer = 0;
  214752. }
  214753. if (pDirectSoundCapture != 0)
  214754. {
  214755. JUCE_TRY
  214756. {
  214757. hr = pDirectSoundCapture->Release();
  214758. logError (hr);
  214759. }
  214760. CATCH
  214761. pDirectSoundCapture = 0;
  214762. }
  214763. if (pDirectSound != 0)
  214764. {
  214765. JUCE_TRY
  214766. {
  214767. hr = pDirectSound->Release();
  214768. logError (hr);
  214769. }
  214770. CATCH
  214771. pDirectSound = 0;
  214772. }
  214773. }
  214774. const String open()
  214775. {
  214776. log ("opening dsound in device: " + name
  214777. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214778. pDirectSound = 0;
  214779. pDirectSoundCapture = 0;
  214780. pInputBuffer = 0;
  214781. readOffset = 0;
  214782. totalBytesPerBuffer = 0;
  214783. String error;
  214784. HRESULT hr = E_NOINTERFACE;
  214785. if (dsDirectSoundCaptureCreate != 0)
  214786. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214787. logError (hr);
  214788. if (hr == S_OK)
  214789. {
  214790. const int numChannels = 2;
  214791. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214792. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214793. WAVEFORMATEX wfFormat;
  214794. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214795. wfFormat.nChannels = (unsigned short)numChannels;
  214796. wfFormat.nSamplesPerSec = sampleRate;
  214797. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214798. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214799. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214800. wfFormat.cbSize = 0;
  214801. DSCBUFFERDESC captureDesc;
  214802. zerostruct (captureDesc);
  214803. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214804. captureDesc.dwFlags = 0;
  214805. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214806. captureDesc.lpwfxFormat = &wfFormat;
  214807. log ("opening dsound in step 2");
  214808. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214809. logError (hr);
  214810. if (hr == S_OK)
  214811. {
  214812. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214813. logError (hr);
  214814. if (hr == S_OK)
  214815. return String::empty;
  214816. }
  214817. }
  214818. error = getDSErrorMessage (hr);
  214819. close();
  214820. return error;
  214821. }
  214822. void synchronisePosition()
  214823. {
  214824. if (pInputBuffer != 0)
  214825. {
  214826. DWORD capturePos;
  214827. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214828. }
  214829. }
  214830. bool service()
  214831. {
  214832. if (pInputBuffer == 0)
  214833. return true;
  214834. DWORD capturePos, readPos;
  214835. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214836. logError (hr);
  214837. if (hr != S_OK)
  214838. return true;
  214839. int bytesFilled = readPos - readOffset;
  214840. if (bytesFilled < 0)
  214841. bytesFilled += totalBytesPerBuffer;
  214842. if (bytesFilled >= bytesPerBuffer)
  214843. {
  214844. LPBYTE lpbuf1 = 0;
  214845. LPBYTE lpbuf2 = 0;
  214846. DWORD dwsize1 = 0;
  214847. DWORD dwsize2 = 0;
  214848. HRESULT hr = pInputBuffer->Lock (readOffset,
  214849. bytesPerBuffer,
  214850. (void**) &lpbuf1, &dwsize1,
  214851. (void**) &lpbuf2, &dwsize2, 0);
  214852. if (hr == S_OK)
  214853. {
  214854. if (bitDepth == 16)
  214855. {
  214856. const float g = 1.0f / 32768.0f;
  214857. float* destL = leftBuffer;
  214858. float* destR = rightBuffer;
  214859. int samples1 = dwsize1 >> 2;
  214860. int samples2 = dwsize2 >> 2;
  214861. const short* src = (const short*)lpbuf1;
  214862. if (destL == 0)
  214863. {
  214864. while (--samples1 >= 0)
  214865. {
  214866. ++src;
  214867. *destR++ = *src++ * g;
  214868. }
  214869. src = (const short*)lpbuf2;
  214870. while (--samples2 >= 0)
  214871. {
  214872. ++src;
  214873. *destR++ = *src++ * g;
  214874. }
  214875. }
  214876. else if (destR == 0)
  214877. {
  214878. while (--samples1 >= 0)
  214879. {
  214880. *destL++ = *src++ * g;
  214881. ++src;
  214882. }
  214883. src = (const short*)lpbuf2;
  214884. while (--samples2 >= 0)
  214885. {
  214886. *destL++ = *src++ * g;
  214887. ++src;
  214888. }
  214889. }
  214890. else
  214891. {
  214892. while (--samples1 >= 0)
  214893. {
  214894. *destL++ = *src++ * g;
  214895. *destR++ = *src++ * g;
  214896. }
  214897. src = (const short*)lpbuf2;
  214898. while (--samples2 >= 0)
  214899. {
  214900. *destL++ = *src++ * g;
  214901. *destR++ = *src++ * g;
  214902. }
  214903. }
  214904. }
  214905. else
  214906. {
  214907. jassertfalse;
  214908. }
  214909. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214910. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214911. }
  214912. else
  214913. {
  214914. logError (hr);
  214915. jassertfalse;
  214916. }
  214917. bytesFilled -= bytesPerBuffer;
  214918. return true;
  214919. }
  214920. else
  214921. {
  214922. return false;
  214923. }
  214924. }
  214925. };
  214926. class DSoundAudioIODevice : public AudioIODevice,
  214927. public Thread
  214928. {
  214929. public:
  214930. DSoundAudioIODevice (const String& deviceName,
  214931. const int outputDeviceIndex_,
  214932. const int inputDeviceIndex_)
  214933. : AudioIODevice (deviceName, "DirectSound"),
  214934. Thread ("Juce DSound"),
  214935. isOpen_ (false),
  214936. isStarted (false),
  214937. outputDeviceIndex (outputDeviceIndex_),
  214938. inputDeviceIndex (inputDeviceIndex_),
  214939. totalSamplesOut (0),
  214940. sampleRate (0.0),
  214941. inputBuffers (1, 1),
  214942. outputBuffers (1, 1),
  214943. callback (0),
  214944. bufferSizeSamples (0)
  214945. {
  214946. if (outputDeviceIndex_ >= 0)
  214947. {
  214948. outChannels.add (TRANS("Left"));
  214949. outChannels.add (TRANS("Right"));
  214950. }
  214951. if (inputDeviceIndex_ >= 0)
  214952. {
  214953. inChannels.add (TRANS("Left"));
  214954. inChannels.add (TRANS("Right"));
  214955. }
  214956. }
  214957. ~DSoundAudioIODevice()
  214958. {
  214959. close();
  214960. }
  214961. const StringArray getOutputChannelNames()
  214962. {
  214963. return outChannels;
  214964. }
  214965. const StringArray getInputChannelNames()
  214966. {
  214967. return inChannels;
  214968. }
  214969. int getNumSampleRates()
  214970. {
  214971. return 4;
  214972. }
  214973. double getSampleRate (int index)
  214974. {
  214975. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214976. return samps [jlimit (0, 3, index)];
  214977. }
  214978. int getNumBufferSizesAvailable()
  214979. {
  214980. return 50;
  214981. }
  214982. int getBufferSizeSamples (int index)
  214983. {
  214984. int n = 64;
  214985. for (int i = 0; i < index; ++i)
  214986. n += (n < 512) ? 32
  214987. : ((n < 1024) ? 64
  214988. : ((n < 2048) ? 128 : 256));
  214989. return n;
  214990. }
  214991. int getDefaultBufferSize()
  214992. {
  214993. return 2560;
  214994. }
  214995. const String open (const BigInteger& inputChannels,
  214996. const BigInteger& outputChannels,
  214997. double sampleRate,
  214998. int bufferSizeSamples)
  214999. {
  215000. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215001. isOpen_ = lastError.isEmpty();
  215002. return lastError;
  215003. }
  215004. void close()
  215005. {
  215006. stop();
  215007. if (isOpen_)
  215008. {
  215009. closeDevice();
  215010. isOpen_ = false;
  215011. }
  215012. }
  215013. bool isOpen()
  215014. {
  215015. return isOpen_ && isThreadRunning();
  215016. }
  215017. int getCurrentBufferSizeSamples()
  215018. {
  215019. return bufferSizeSamples;
  215020. }
  215021. double getCurrentSampleRate()
  215022. {
  215023. return sampleRate;
  215024. }
  215025. int getCurrentBitDepth()
  215026. {
  215027. int i, bits = 256;
  215028. for (i = inChans.size(); --i >= 0;)
  215029. bits = jmin (bits, inChans[i]->bitDepth);
  215030. for (i = outChans.size(); --i >= 0;)
  215031. bits = jmin (bits, outChans[i]->bitDepth);
  215032. if (bits > 32)
  215033. bits = 16;
  215034. return bits;
  215035. }
  215036. const BigInteger getActiveOutputChannels() const
  215037. {
  215038. return enabledOutputs;
  215039. }
  215040. const BigInteger getActiveInputChannels() const
  215041. {
  215042. return enabledInputs;
  215043. }
  215044. int getOutputLatencyInSamples()
  215045. {
  215046. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215047. }
  215048. int getInputLatencyInSamples()
  215049. {
  215050. return getOutputLatencyInSamples();
  215051. }
  215052. void start (AudioIODeviceCallback* call)
  215053. {
  215054. if (isOpen_ && call != 0 && ! isStarted)
  215055. {
  215056. if (! isThreadRunning())
  215057. {
  215058. // something gone wrong and the thread's stopped..
  215059. isOpen_ = false;
  215060. return;
  215061. }
  215062. call->audioDeviceAboutToStart (this);
  215063. const ScopedLock sl (startStopLock);
  215064. callback = call;
  215065. isStarted = true;
  215066. }
  215067. }
  215068. void stop()
  215069. {
  215070. if (isStarted)
  215071. {
  215072. AudioIODeviceCallback* const callbackLocal = callback;
  215073. {
  215074. const ScopedLock sl (startStopLock);
  215075. isStarted = false;
  215076. }
  215077. if (callbackLocal != 0)
  215078. callbackLocal->audioDeviceStopped();
  215079. }
  215080. }
  215081. bool isPlaying()
  215082. {
  215083. return isStarted && isOpen_ && isThreadRunning();
  215084. }
  215085. const String getLastError()
  215086. {
  215087. return lastError;
  215088. }
  215089. juce_UseDebuggingNewOperator
  215090. StringArray inChannels, outChannels;
  215091. int outputDeviceIndex, inputDeviceIndex;
  215092. private:
  215093. bool isOpen_;
  215094. bool isStarted;
  215095. String lastError;
  215096. OwnedArray <DSoundInternalInChannel> inChans;
  215097. OwnedArray <DSoundInternalOutChannel> outChans;
  215098. WaitableEvent startEvent;
  215099. int bufferSizeSamples;
  215100. int volatile totalSamplesOut;
  215101. int64 volatile lastBlockTime;
  215102. double sampleRate;
  215103. BigInteger enabledInputs, enabledOutputs;
  215104. AudioSampleBuffer inputBuffers, outputBuffers;
  215105. AudioIODeviceCallback* callback;
  215106. CriticalSection startStopLock;
  215107. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215108. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215109. const String openDevice (const BigInteger& inputChannels,
  215110. const BigInteger& outputChannels,
  215111. double sampleRate_,
  215112. int bufferSizeSamples_);
  215113. void closeDevice()
  215114. {
  215115. isStarted = false;
  215116. stopThread (5000);
  215117. inChans.clear();
  215118. outChans.clear();
  215119. inputBuffers.setSize (1, 1);
  215120. outputBuffers.setSize (1, 1);
  215121. }
  215122. void resync()
  215123. {
  215124. if (! threadShouldExit())
  215125. {
  215126. sleep (5);
  215127. int i;
  215128. for (i = 0; i < outChans.size(); ++i)
  215129. outChans.getUnchecked(i)->synchronisePosition();
  215130. for (i = 0; i < inChans.size(); ++i)
  215131. inChans.getUnchecked(i)->synchronisePosition();
  215132. }
  215133. }
  215134. public:
  215135. void run()
  215136. {
  215137. while (! threadShouldExit())
  215138. {
  215139. if (wait (100))
  215140. break;
  215141. }
  215142. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215143. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215144. while (! threadShouldExit())
  215145. {
  215146. int numToDo = 0;
  215147. uint32 startTime = Time::getMillisecondCounter();
  215148. int i;
  215149. for (i = inChans.size(); --i >= 0;)
  215150. {
  215151. inChans.getUnchecked(i)->doneFlag = false;
  215152. ++numToDo;
  215153. }
  215154. for (i = outChans.size(); --i >= 0;)
  215155. {
  215156. outChans.getUnchecked(i)->doneFlag = false;
  215157. ++numToDo;
  215158. }
  215159. if (numToDo > 0)
  215160. {
  215161. const int maxCount = 3;
  215162. int count = maxCount;
  215163. for (;;)
  215164. {
  215165. for (i = inChans.size(); --i >= 0;)
  215166. {
  215167. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215168. if ((! in->doneFlag) && in->service())
  215169. {
  215170. in->doneFlag = true;
  215171. --numToDo;
  215172. }
  215173. }
  215174. for (i = outChans.size(); --i >= 0;)
  215175. {
  215176. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215177. if ((! out->doneFlag) && out->service())
  215178. {
  215179. out->doneFlag = true;
  215180. --numToDo;
  215181. }
  215182. }
  215183. if (numToDo <= 0)
  215184. break;
  215185. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215186. {
  215187. resync();
  215188. break;
  215189. }
  215190. if (--count <= 0)
  215191. {
  215192. Sleep (1);
  215193. count = maxCount;
  215194. }
  215195. if (threadShouldExit())
  215196. return;
  215197. }
  215198. }
  215199. else
  215200. {
  215201. sleep (1);
  215202. }
  215203. const ScopedLock sl (startStopLock);
  215204. if (isStarted)
  215205. {
  215206. JUCE_TRY
  215207. {
  215208. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215209. inputBuffers.getNumChannels(),
  215210. outputBuffers.getArrayOfChannels(),
  215211. outputBuffers.getNumChannels(),
  215212. bufferSizeSamples);
  215213. }
  215214. JUCE_CATCH_EXCEPTION
  215215. totalSamplesOut += bufferSizeSamples;
  215216. }
  215217. else
  215218. {
  215219. outputBuffers.clear();
  215220. totalSamplesOut = 0;
  215221. sleep (1);
  215222. }
  215223. }
  215224. }
  215225. };
  215226. class DSoundAudioIODeviceType : public AudioIODeviceType
  215227. {
  215228. public:
  215229. DSoundAudioIODeviceType()
  215230. : AudioIODeviceType ("DirectSound"),
  215231. hasScanned (false)
  215232. {
  215233. initialiseDSoundFunctions();
  215234. }
  215235. ~DSoundAudioIODeviceType()
  215236. {
  215237. }
  215238. void scanForDevices()
  215239. {
  215240. hasScanned = true;
  215241. outputDeviceNames.clear();
  215242. outputGuids.clear();
  215243. inputDeviceNames.clear();
  215244. inputGuids.clear();
  215245. if (dsDirectSoundEnumerateW != 0)
  215246. {
  215247. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215248. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215249. }
  215250. }
  215251. const StringArray getDeviceNames (bool wantInputNames) const
  215252. {
  215253. jassert (hasScanned); // need to call scanForDevices() before doing this
  215254. return wantInputNames ? inputDeviceNames
  215255. : outputDeviceNames;
  215256. }
  215257. int getDefaultDeviceIndex (bool /*forInput*/) const
  215258. {
  215259. jassert (hasScanned); // need to call scanForDevices() before doing this
  215260. return 0;
  215261. }
  215262. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215263. {
  215264. jassert (hasScanned); // need to call scanForDevices() before doing this
  215265. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215266. if (d == 0)
  215267. return -1;
  215268. return asInput ? d->inputDeviceIndex
  215269. : d->outputDeviceIndex;
  215270. }
  215271. bool hasSeparateInputsAndOutputs() const { return true; }
  215272. AudioIODevice* createDevice (const String& outputDeviceName,
  215273. const String& inputDeviceName)
  215274. {
  215275. jassert (hasScanned); // need to call scanForDevices() before doing this
  215276. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215277. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215278. if (outputIndex >= 0 || inputIndex >= 0)
  215279. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215280. : inputDeviceName,
  215281. outputIndex, inputIndex);
  215282. return 0;
  215283. }
  215284. juce_UseDebuggingNewOperator
  215285. StringArray outputDeviceNames;
  215286. OwnedArray <GUID> outputGuids;
  215287. StringArray inputDeviceNames;
  215288. OwnedArray <GUID> inputGuids;
  215289. private:
  215290. bool hasScanned;
  215291. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215292. {
  215293. desc = desc.trim();
  215294. if (desc.isNotEmpty())
  215295. {
  215296. const String origDesc (desc);
  215297. int n = 2;
  215298. while (outputDeviceNames.contains (desc))
  215299. desc = origDesc + " (" + String (n++) + ")";
  215300. outputDeviceNames.add (desc);
  215301. if (lpGUID != 0)
  215302. outputGuids.add (new GUID (*lpGUID));
  215303. else
  215304. outputGuids.add (0);
  215305. }
  215306. return TRUE;
  215307. }
  215308. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215309. {
  215310. return ((DSoundAudioIODeviceType*) object)
  215311. ->outputEnumProc (lpGUID, String (description));
  215312. }
  215313. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215314. {
  215315. return ((DSoundAudioIODeviceType*) object)
  215316. ->outputEnumProc (lpGUID, String (description));
  215317. }
  215318. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215319. {
  215320. desc = desc.trim();
  215321. if (desc.isNotEmpty())
  215322. {
  215323. const String origDesc (desc);
  215324. int n = 2;
  215325. while (inputDeviceNames.contains (desc))
  215326. desc = origDesc + " (" + String (n++) + ")";
  215327. inputDeviceNames.add (desc);
  215328. if (lpGUID != 0)
  215329. inputGuids.add (new GUID (*lpGUID));
  215330. else
  215331. inputGuids.add (0);
  215332. }
  215333. return TRUE;
  215334. }
  215335. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215336. {
  215337. return ((DSoundAudioIODeviceType*) object)
  215338. ->inputEnumProc (lpGUID, String (description));
  215339. }
  215340. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215341. {
  215342. return ((DSoundAudioIODeviceType*) object)
  215343. ->inputEnumProc (lpGUID, String (description));
  215344. }
  215345. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215346. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215347. };
  215348. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215349. const BigInteger& outputChannels,
  215350. double sampleRate_,
  215351. int bufferSizeSamples_)
  215352. {
  215353. closeDevice();
  215354. totalSamplesOut = 0;
  215355. sampleRate = sampleRate_;
  215356. if (bufferSizeSamples_ <= 0)
  215357. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215358. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215359. DSoundAudioIODeviceType dlh;
  215360. dlh.scanForDevices();
  215361. enabledInputs = inputChannels;
  215362. enabledInputs.setRange (inChannels.size(),
  215363. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215364. false);
  215365. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215366. inputBuffers.clear();
  215367. int i, numIns = 0;
  215368. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215369. {
  215370. float* left = 0;
  215371. if (enabledInputs[i])
  215372. left = inputBuffers.getSampleData (numIns++);
  215373. float* right = 0;
  215374. if (enabledInputs[i + 1])
  215375. right = inputBuffers.getSampleData (numIns++);
  215376. if (left != 0 || right != 0)
  215377. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215378. dlh.inputGuids [inputDeviceIndex],
  215379. (int) sampleRate, bufferSizeSamples,
  215380. left, right));
  215381. }
  215382. enabledOutputs = outputChannels;
  215383. enabledOutputs.setRange (outChannels.size(),
  215384. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215385. false);
  215386. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215387. outputBuffers.clear();
  215388. int numOuts = 0;
  215389. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215390. {
  215391. float* left = 0;
  215392. if (enabledOutputs[i])
  215393. left = outputBuffers.getSampleData (numOuts++);
  215394. float* right = 0;
  215395. if (enabledOutputs[i + 1])
  215396. right = outputBuffers.getSampleData (numOuts++);
  215397. if (left != 0 || right != 0)
  215398. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215399. dlh.outputGuids [outputDeviceIndex],
  215400. (int) sampleRate, bufferSizeSamples,
  215401. left, right));
  215402. }
  215403. String error;
  215404. // boost our priority while opening the devices to try to get better sync between them
  215405. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215406. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215407. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215408. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215409. for (i = 0; i < outChans.size(); ++i)
  215410. {
  215411. error = outChans[i]->open();
  215412. if (error.isNotEmpty())
  215413. {
  215414. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215415. break;
  215416. }
  215417. }
  215418. if (error.isEmpty())
  215419. {
  215420. for (i = 0; i < inChans.size(); ++i)
  215421. {
  215422. error = inChans[i]->open();
  215423. if (error.isNotEmpty())
  215424. {
  215425. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215426. break;
  215427. }
  215428. }
  215429. }
  215430. if (error.isEmpty())
  215431. {
  215432. totalSamplesOut = 0;
  215433. for (i = 0; i < outChans.size(); ++i)
  215434. outChans.getUnchecked(i)->synchronisePosition();
  215435. for (i = 0; i < inChans.size(); ++i)
  215436. inChans.getUnchecked(i)->synchronisePosition();
  215437. startThread (9);
  215438. sleep (10);
  215439. notify();
  215440. }
  215441. else
  215442. {
  215443. log (error);
  215444. }
  215445. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215446. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215447. return error;
  215448. }
  215449. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215450. {
  215451. return new DSoundAudioIODeviceType();
  215452. }
  215453. #undef log
  215454. #endif
  215455. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215456. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215457. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215458. // compiled on its own).
  215459. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215460. #if 1
  215461. const String getAudioErrorDesc (HRESULT hr)
  215462. {
  215463. const char* e = 0;
  215464. switch (hr)
  215465. {
  215466. case E_POINTER: e = "E_POINTER"; break;
  215467. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  215468. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  215469. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215470. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215471. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215472. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  215473. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215474. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  215475. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215476. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  215477. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  215478. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215479. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215480. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215481. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215482. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215483. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215484. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215485. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215486. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215487. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215488. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215489. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  215490. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215491. default: return String::toHexString ((int) hr);
  215492. }
  215493. return e;
  215494. }
  215495. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  215496. #define OK(a) wasapi_checkResult(a)
  215497. static bool wasapi_checkResult (HRESULT hr)
  215498. {
  215499. logFailure (hr);
  215500. return SUCCEEDED (hr);
  215501. }
  215502. #else
  215503. #define logFailure(hr) {}
  215504. #define OK(a) SUCCEEDED(a)
  215505. #endif
  215506. static const String wasapi_getDeviceID (IMMDevice* const device)
  215507. {
  215508. String s;
  215509. WCHAR* deviceId = 0;
  215510. if (OK (device->GetId (&deviceId)))
  215511. {
  215512. s = String (deviceId);
  215513. CoTaskMemFree (deviceId);
  215514. }
  215515. return s;
  215516. }
  215517. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  215518. {
  215519. EDataFlow flow = eRender;
  215520. ComSmartPtr <IMMEndpoint> endPoint;
  215521. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  215522. (void) OK (endPoint->GetDataFlow (&flow));
  215523. return flow;
  215524. }
  215525. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215526. {
  215527. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215528. }
  215529. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215530. {
  215531. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215532. : sizeof (WAVEFORMATEX));
  215533. }
  215534. class WASAPIDeviceBase
  215535. {
  215536. public:
  215537. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215538. : device (device_),
  215539. sampleRate (0),
  215540. numChannels (0),
  215541. actualNumChannels (0),
  215542. defaultSampleRate (0),
  215543. minBufferSize (0),
  215544. defaultBufferSize (0),
  215545. latencySamples (0),
  215546. useExclusiveMode (useExclusiveMode_)
  215547. {
  215548. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215549. ComSmartPtr <IAudioClient> tempClient (createClient());
  215550. if (tempClient == 0)
  215551. return;
  215552. REFERENCE_TIME defaultPeriod, minPeriod;
  215553. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215554. return;
  215555. WAVEFORMATEX* mixFormat = 0;
  215556. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  215557. return;
  215558. WAVEFORMATEXTENSIBLE format;
  215559. wasapi_copyWavFormat (format, mixFormat);
  215560. CoTaskMemFree (mixFormat);
  215561. actualNumChannels = numChannels = format.Format.nChannels;
  215562. defaultSampleRate = format.Format.nSamplesPerSec;
  215563. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  215564. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  215565. rates.addUsingDefaultSort (defaultSampleRate);
  215566. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215567. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215568. {
  215569. if (ratesToTest[i] == defaultSampleRate)
  215570. continue;
  215571. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215572. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215573. (WAVEFORMATEX*) &format, 0)))
  215574. if (! rates.contains (ratesToTest[i]))
  215575. rates.addUsingDefaultSort (ratesToTest[i]);
  215576. }
  215577. }
  215578. ~WASAPIDeviceBase()
  215579. {
  215580. device = 0;
  215581. CloseHandle (clientEvent);
  215582. }
  215583. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215584. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215585. {
  215586. sampleRate = newSampleRate;
  215587. channels = newChannels;
  215588. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215589. numChannels = channels.getHighestBit() + 1;
  215590. if (numChannels == 0)
  215591. return true;
  215592. client = createClient();
  215593. if (client != 0
  215594. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215595. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215596. {
  215597. channelMaps.clear();
  215598. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215599. if (channels[i])
  215600. channelMaps.add (i);
  215601. REFERENCE_TIME latency;
  215602. if (OK (client->GetStreamLatency (&latency)))
  215603. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  215604. (void) OK (client->GetBufferSize (&actualBufferSize));
  215605. return OK (client->SetEventHandle (clientEvent));
  215606. }
  215607. return false;
  215608. }
  215609. void closeClient()
  215610. {
  215611. if (client != 0)
  215612. client->Stop();
  215613. client = 0;
  215614. ResetEvent (clientEvent);
  215615. }
  215616. ComSmartPtr <IMMDevice> device;
  215617. ComSmartPtr <IAudioClient> client;
  215618. double sampleRate, defaultSampleRate;
  215619. int numChannels, actualNumChannels;
  215620. int minBufferSize, defaultBufferSize, latencySamples;
  215621. const bool useExclusiveMode;
  215622. Array <double> rates;
  215623. HANDLE clientEvent;
  215624. BigInteger channels;
  215625. AudioDataConverters::DataFormat dataFormat;
  215626. Array <int> channelMaps;
  215627. UINT32 actualBufferSize;
  215628. int bytesPerSample;
  215629. private:
  215630. const ComSmartPtr <IAudioClient> createClient()
  215631. {
  215632. ComSmartPtr <IAudioClient> client;
  215633. if (device != 0)
  215634. {
  215635. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  215636. logFailure (hr);
  215637. }
  215638. return client;
  215639. }
  215640. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215641. {
  215642. WAVEFORMATEXTENSIBLE format;
  215643. zerostruct (format);
  215644. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215645. {
  215646. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215647. }
  215648. else
  215649. {
  215650. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215651. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215652. }
  215653. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215654. format.Format.nChannels = (WORD) numChannels;
  215655. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215656. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215657. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215658. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215659. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215660. switch (numChannels)
  215661. {
  215662. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215663. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215664. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215665. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215666. case 8: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER; break;
  215667. default: break;
  215668. }
  215669. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215670. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215671. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215672. logFailure (hr);
  215673. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215674. {
  215675. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215676. hr = S_OK;
  215677. }
  215678. CoTaskMemFree (nearestFormat);
  215679. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215680. if (useExclusiveMode)
  215681. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215682. GUID session;
  215683. if (hr == S_OK
  215684. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215685. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215686. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215687. {
  215688. actualNumChannels = format.Format.nChannels;
  215689. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215690. bytesPerSample = format.Format.wBitsPerSample / 8;
  215691. dataFormat = isFloat ? AudioDataConverters::float32LE
  215692. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  215693. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  215694. : AudioDataConverters::int16LE)));
  215695. return true;
  215696. }
  215697. return false;
  215698. }
  215699. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215700. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215701. };
  215702. class WASAPIInputDevice : public WASAPIDeviceBase
  215703. {
  215704. public:
  215705. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215706. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215707. reservoir (1, 1)
  215708. {
  215709. }
  215710. ~WASAPIInputDevice()
  215711. {
  215712. close();
  215713. }
  215714. bool open (const double newSampleRate, const BigInteger& newChannels)
  215715. {
  215716. reservoirSize = 0;
  215717. reservoirCapacity = 16384;
  215718. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215719. return openClient (newSampleRate, newChannels)
  215720. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  215721. }
  215722. void close()
  215723. {
  215724. closeClient();
  215725. captureClient = 0;
  215726. reservoir.setSize (0);
  215727. }
  215728. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215729. {
  215730. if (numChannels <= 0)
  215731. return;
  215732. int offset = 0;
  215733. while (bufferSize > 0)
  215734. {
  215735. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215736. {
  215737. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215738. for (int i = 0; i < numDestBuffers; ++i)
  215739. {
  215740. float* const dest = destBuffers[i] + offset;
  215741. const int srcChan = channelMaps.getUnchecked(i);
  215742. switch (dataFormat)
  215743. {
  215744. case AudioDataConverters::float32LE:
  215745. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215746. break;
  215747. case AudioDataConverters::int32LE:
  215748. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215749. break;
  215750. case AudioDataConverters::int24LE:
  215751. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  215752. break;
  215753. case AudioDataConverters::int16LE:
  215754. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  215755. break;
  215756. default: jassertfalse; break;
  215757. }
  215758. }
  215759. bufferSize -= samplesToDo;
  215760. offset += samplesToDo;
  215761. reservoirSize -= samplesToDo;
  215762. }
  215763. else
  215764. {
  215765. UINT32 packetLength = 0;
  215766. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  215767. break;
  215768. if (packetLength == 0)
  215769. {
  215770. if (thread.threadShouldExit())
  215771. break;
  215772. Thread::sleep (1);
  215773. continue;
  215774. }
  215775. uint8* inputData = 0;
  215776. UINT32 numSamplesAvailable;
  215777. DWORD flags;
  215778. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215779. {
  215780. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215781. for (int i = 0; i < numDestBuffers; ++i)
  215782. {
  215783. float* const dest = destBuffers[i] + offset;
  215784. const int srcChan = channelMaps.getUnchecked(i);
  215785. switch (dataFormat)
  215786. {
  215787. case AudioDataConverters::float32LE:
  215788. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215789. break;
  215790. case AudioDataConverters::int32LE:
  215791. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  215792. break;
  215793. case AudioDataConverters::int24LE:
  215794. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  215795. break;
  215796. case AudioDataConverters::int16LE:
  215797. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  215798. break;
  215799. default: jassertfalse; break;
  215800. }
  215801. }
  215802. bufferSize -= samplesToDo;
  215803. offset += samplesToDo;
  215804. if (samplesToDo < (int) numSamplesAvailable)
  215805. {
  215806. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215807. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215808. bytesPerSample * actualNumChannels * reservoirSize);
  215809. }
  215810. captureClient->ReleaseBuffer (numSamplesAvailable);
  215811. }
  215812. }
  215813. }
  215814. }
  215815. ComSmartPtr <IAudioCaptureClient> captureClient;
  215816. MemoryBlock reservoir;
  215817. int reservoirSize, reservoirCapacity;
  215818. private:
  215819. WASAPIInputDevice (const WASAPIInputDevice&);
  215820. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  215821. };
  215822. class WASAPIOutputDevice : public WASAPIDeviceBase
  215823. {
  215824. public:
  215825. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215826. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215827. {
  215828. }
  215829. ~WASAPIOutputDevice()
  215830. {
  215831. close();
  215832. }
  215833. bool open (const double newSampleRate, const BigInteger& newChannels)
  215834. {
  215835. return openClient (newSampleRate, newChannels)
  215836. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  215837. }
  215838. void close()
  215839. {
  215840. closeClient();
  215841. renderClient = 0;
  215842. }
  215843. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215844. {
  215845. if (numChannels <= 0)
  215846. return;
  215847. int offset = 0;
  215848. while (bufferSize > 0)
  215849. {
  215850. UINT32 padding = 0;
  215851. if (! OK (client->GetCurrentPadding (&padding)))
  215852. return;
  215853. int samplesToDo = useExclusiveMode ? bufferSize
  215854. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215855. if (samplesToDo <= 0)
  215856. {
  215857. if (thread.threadShouldExit())
  215858. break;
  215859. Thread::sleep (0);
  215860. continue;
  215861. }
  215862. uint8* outputData = 0;
  215863. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  215864. {
  215865. for (int i = 0; i < numSrcBuffers; ++i)
  215866. {
  215867. const float* const source = srcBuffers[i] + offset;
  215868. const int destChan = channelMaps.getUnchecked(i);
  215869. switch (dataFormat)
  215870. {
  215871. case AudioDataConverters::float32LE:
  215872. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  215873. break;
  215874. case AudioDataConverters::int32LE:
  215875. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  215876. break;
  215877. case AudioDataConverters::int24LE:
  215878. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  215879. break;
  215880. case AudioDataConverters::int16LE:
  215881. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  215882. break;
  215883. default: jassertfalse; break;
  215884. }
  215885. }
  215886. renderClient->ReleaseBuffer (samplesToDo, 0);
  215887. offset += samplesToDo;
  215888. bufferSize -= samplesToDo;
  215889. }
  215890. }
  215891. }
  215892. ComSmartPtr <IAudioRenderClient> renderClient;
  215893. private:
  215894. WASAPIOutputDevice (const WASAPIOutputDevice&);
  215895. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  215896. };
  215897. class WASAPIAudioIODevice : public AudioIODevice,
  215898. public Thread
  215899. {
  215900. public:
  215901. WASAPIAudioIODevice (const String& deviceName,
  215902. const String& outputDeviceId_,
  215903. const String& inputDeviceId_,
  215904. const bool useExclusiveMode_)
  215905. : AudioIODevice (deviceName, "Windows Audio"),
  215906. Thread ("Juce WASAPI"),
  215907. isOpen_ (false),
  215908. isStarted (false),
  215909. outputDeviceId (outputDeviceId_),
  215910. inputDeviceId (inputDeviceId_),
  215911. useExclusiveMode (useExclusiveMode_),
  215912. currentBufferSizeSamples (0),
  215913. currentSampleRate (0),
  215914. callback (0)
  215915. {
  215916. }
  215917. ~WASAPIAudioIODevice()
  215918. {
  215919. close();
  215920. }
  215921. bool initialise()
  215922. {
  215923. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215924. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215925. latencyIn = latencyOut = 0;
  215926. Array <double> ratesIn, ratesOut;
  215927. if (createDevices())
  215928. {
  215929. jassert (inputDevice != 0 || outputDevice != 0);
  215930. if (inputDevice != 0 && outputDevice != 0)
  215931. {
  215932. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215933. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215934. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215935. sampleRates = inputDevice->rates;
  215936. sampleRates.removeValuesNotIn (outputDevice->rates);
  215937. }
  215938. else
  215939. {
  215940. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215941. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215942. defaultSampleRate = d->defaultSampleRate;
  215943. minBufferSize = d->minBufferSize;
  215944. defaultBufferSize = d->defaultBufferSize;
  215945. sampleRates = d->rates;
  215946. }
  215947. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215948. if (minBufferSize != defaultBufferSize)
  215949. bufferSizes.addUsingDefaultSort (minBufferSize);
  215950. int n = 64;
  215951. for (int i = 0; i < 40; ++i)
  215952. {
  215953. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215954. bufferSizes.addUsingDefaultSort (n);
  215955. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215956. }
  215957. return true;
  215958. }
  215959. return false;
  215960. }
  215961. const StringArray getOutputChannelNames()
  215962. {
  215963. StringArray outChannels;
  215964. if (outputDevice != 0)
  215965. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215966. outChannels.add ("Output channel " + String (i));
  215967. return outChannels;
  215968. }
  215969. const StringArray getInputChannelNames()
  215970. {
  215971. StringArray inChannels;
  215972. if (inputDevice != 0)
  215973. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215974. inChannels.add ("Input channel " + String (i));
  215975. return inChannels;
  215976. }
  215977. int getNumSampleRates() { return sampleRates.size(); }
  215978. double getSampleRate (int index) { return sampleRates [index]; }
  215979. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215980. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215981. int getDefaultBufferSize() { return defaultBufferSize; }
  215982. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215983. double getCurrentSampleRate() { return currentSampleRate; }
  215984. int getCurrentBitDepth() { return 32; }
  215985. int getOutputLatencyInSamples() { return latencyOut; }
  215986. int getInputLatencyInSamples() { return latencyIn; }
  215987. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215988. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215989. const String getLastError() { return lastError; }
  215990. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215991. double sampleRate, int bufferSizeSamples)
  215992. {
  215993. close();
  215994. lastError = String::empty;
  215995. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215996. {
  215997. lastError = "The input and output devices don't share a common sample rate!";
  215998. return lastError;
  215999. }
  216000. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216001. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216002. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216003. {
  216004. lastError = "Couldn't open the input device!";
  216005. return lastError;
  216006. }
  216007. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216008. {
  216009. close();
  216010. lastError = "Couldn't open the output device!";
  216011. return lastError;
  216012. }
  216013. if (inputDevice != 0)
  216014. ResetEvent (inputDevice->clientEvent);
  216015. if (outputDevice != 0)
  216016. ResetEvent (outputDevice->clientEvent);
  216017. startThread (8);
  216018. Thread::sleep (5);
  216019. if (inputDevice != 0 && inputDevice->client != 0)
  216020. {
  216021. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216022. HRESULT hr = inputDevice->client->Start();
  216023. logFailure (hr); //xxx handle this
  216024. }
  216025. if (outputDevice != 0 && outputDevice->client != 0)
  216026. {
  216027. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216028. HRESULT hr = outputDevice->client->Start();
  216029. logFailure (hr); //xxx handle this
  216030. }
  216031. isOpen_ = true;
  216032. return lastError;
  216033. }
  216034. void close()
  216035. {
  216036. stop();
  216037. if (inputDevice != 0)
  216038. SetEvent (inputDevice->clientEvent);
  216039. if (outputDevice != 0)
  216040. SetEvent (outputDevice->clientEvent);
  216041. stopThread (5000);
  216042. if (inputDevice != 0)
  216043. inputDevice->close();
  216044. if (outputDevice != 0)
  216045. outputDevice->close();
  216046. isOpen_ = false;
  216047. }
  216048. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216049. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216050. void start (AudioIODeviceCallback* call)
  216051. {
  216052. if (isOpen_ && call != 0 && ! isStarted)
  216053. {
  216054. if (! isThreadRunning())
  216055. {
  216056. // something's gone wrong and the thread's stopped..
  216057. isOpen_ = false;
  216058. return;
  216059. }
  216060. call->audioDeviceAboutToStart (this);
  216061. const ScopedLock sl (startStopLock);
  216062. callback = call;
  216063. isStarted = true;
  216064. }
  216065. }
  216066. void stop()
  216067. {
  216068. if (isStarted)
  216069. {
  216070. AudioIODeviceCallback* const callbackLocal = callback;
  216071. {
  216072. const ScopedLock sl (startStopLock);
  216073. isStarted = false;
  216074. }
  216075. if (callbackLocal != 0)
  216076. callbackLocal->audioDeviceStopped();
  216077. }
  216078. }
  216079. void setMMThreadPriority()
  216080. {
  216081. DynamicLibraryLoader dll ("avrt.dll");
  216082. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216083. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216084. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216085. {
  216086. DWORD dummy = 0;
  216087. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216088. if (h != 0)
  216089. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216090. }
  216091. }
  216092. void run()
  216093. {
  216094. setMMThreadPriority();
  216095. const int bufferSize = currentBufferSizeSamples;
  216096. HANDLE events[2];
  216097. int numEvents = 0;
  216098. if (inputDevice != 0)
  216099. events [numEvents++] = inputDevice->clientEvent;
  216100. if (outputDevice != 0)
  216101. events [numEvents++] = outputDevice->clientEvent;
  216102. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216103. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216104. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216105. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216106. float** const inputBuffers = ins.getArrayOfChannels();
  216107. float** const outputBuffers = outs.getArrayOfChannels();
  216108. ins.clear();
  216109. while (! threadShouldExit())
  216110. {
  216111. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216112. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216113. if (result == WAIT_TIMEOUT)
  216114. continue;
  216115. if (threadShouldExit())
  216116. break;
  216117. if (inputDevice != 0)
  216118. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216119. // Make the callback..
  216120. {
  216121. const ScopedLock sl (startStopLock);
  216122. if (isStarted)
  216123. {
  216124. JUCE_TRY
  216125. {
  216126. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216127. numInputBuffers,
  216128. outputBuffers,
  216129. numOutputBuffers,
  216130. bufferSize);
  216131. }
  216132. JUCE_CATCH_EXCEPTION
  216133. }
  216134. else
  216135. {
  216136. outs.clear();
  216137. }
  216138. }
  216139. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216140. continue;
  216141. if (outputDevice != 0)
  216142. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216143. }
  216144. }
  216145. juce_UseDebuggingNewOperator
  216146. String outputDeviceId, inputDeviceId;
  216147. String lastError;
  216148. private:
  216149. // Device stats...
  216150. ScopedPointer<WASAPIInputDevice> inputDevice;
  216151. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216152. const bool useExclusiveMode;
  216153. double defaultSampleRate;
  216154. int minBufferSize, defaultBufferSize;
  216155. int latencyIn, latencyOut;
  216156. Array <double> sampleRates;
  216157. Array <int> bufferSizes;
  216158. // Active state...
  216159. bool isOpen_, isStarted;
  216160. int currentBufferSizeSamples;
  216161. double currentSampleRate;
  216162. AudioIODeviceCallback* callback;
  216163. CriticalSection startStopLock;
  216164. bool createDevices()
  216165. {
  216166. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216167. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216168. return false;
  216169. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216170. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  216171. return false;
  216172. UINT32 numDevices = 0;
  216173. if (! OK (deviceCollection->GetCount (&numDevices)))
  216174. return false;
  216175. for (UINT32 i = 0; i < numDevices; ++i)
  216176. {
  216177. ComSmartPtr <IMMDevice> device;
  216178. if (! OK (deviceCollection->Item (i, &device)))
  216179. continue;
  216180. const String deviceId (wasapi_getDeviceID (device));
  216181. if (deviceId.isEmpty())
  216182. continue;
  216183. const EDataFlow flow = wasapi_getDataFlow (device);
  216184. if (deviceId == inputDeviceId && flow == eCapture)
  216185. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216186. else if (deviceId == outputDeviceId && flow == eRender)
  216187. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216188. }
  216189. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216190. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216191. }
  216192. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216193. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216194. };
  216195. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216196. {
  216197. public:
  216198. WASAPIAudioIODeviceType()
  216199. : AudioIODeviceType ("Windows Audio"),
  216200. hasScanned (false)
  216201. {
  216202. }
  216203. ~WASAPIAudioIODeviceType()
  216204. {
  216205. }
  216206. void scanForDevices()
  216207. {
  216208. hasScanned = true;
  216209. outputDeviceNames.clear();
  216210. inputDeviceNames.clear();
  216211. outputDeviceIds.clear();
  216212. inputDeviceIds.clear();
  216213. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216214. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216215. return;
  216216. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216217. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216218. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216219. UINT32 numDevices = 0;
  216220. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  216221. && OK (deviceCollection->GetCount (&numDevices))))
  216222. return;
  216223. for (UINT32 i = 0; i < numDevices; ++i)
  216224. {
  216225. ComSmartPtr <IMMDevice> device;
  216226. if (! OK (deviceCollection->Item (i, &device)))
  216227. continue;
  216228. const String deviceId (wasapi_getDeviceID (device));
  216229. DWORD state = 0;
  216230. if (! OK (device->GetState (&state)))
  216231. continue;
  216232. if (state != DEVICE_STATE_ACTIVE)
  216233. continue;
  216234. String name;
  216235. {
  216236. ComSmartPtr <IPropertyStore> properties;
  216237. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  216238. continue;
  216239. PROPVARIANT value;
  216240. PropVariantInit (&value);
  216241. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216242. name = value.pwszVal;
  216243. PropVariantClear (&value);
  216244. }
  216245. const EDataFlow flow = wasapi_getDataFlow (device);
  216246. if (flow == eRender)
  216247. {
  216248. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216249. outputDeviceIds.insert (index, deviceId);
  216250. outputDeviceNames.insert (index, name);
  216251. }
  216252. else if (flow == eCapture)
  216253. {
  216254. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216255. inputDeviceIds.insert (index, deviceId);
  216256. inputDeviceNames.insert (index, name);
  216257. }
  216258. }
  216259. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216260. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216261. }
  216262. const StringArray getDeviceNames (bool wantInputNames) const
  216263. {
  216264. jassert (hasScanned); // need to call scanForDevices() before doing this
  216265. return wantInputNames ? inputDeviceNames
  216266. : outputDeviceNames;
  216267. }
  216268. int getDefaultDeviceIndex (bool /*forInput*/) const
  216269. {
  216270. jassert (hasScanned); // need to call scanForDevices() before doing this
  216271. return 0;
  216272. }
  216273. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216274. {
  216275. jassert (hasScanned); // need to call scanForDevices() before doing this
  216276. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216277. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216278. : outputDeviceIds.indexOf (d->outputDeviceId));
  216279. }
  216280. bool hasSeparateInputsAndOutputs() const { return true; }
  216281. AudioIODevice* createDevice (const String& outputDeviceName,
  216282. const String& inputDeviceName)
  216283. {
  216284. jassert (hasScanned); // need to call scanForDevices() before doing this
  216285. const bool useExclusiveMode = false;
  216286. ScopedPointer<WASAPIAudioIODevice> device;
  216287. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216288. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216289. if (outputIndex >= 0 || inputIndex >= 0)
  216290. {
  216291. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216292. : inputDeviceName,
  216293. outputDeviceIds [outputIndex],
  216294. inputDeviceIds [inputIndex],
  216295. useExclusiveMode);
  216296. if (! device->initialise())
  216297. device = 0;
  216298. }
  216299. return device.release();
  216300. }
  216301. juce_UseDebuggingNewOperator
  216302. StringArray outputDeviceNames, outputDeviceIds;
  216303. StringArray inputDeviceNames, inputDeviceIds;
  216304. private:
  216305. bool hasScanned;
  216306. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216307. {
  216308. String s;
  216309. IMMDevice* dev = 0;
  216310. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216311. eMultimedia, &dev)))
  216312. {
  216313. WCHAR* deviceId = 0;
  216314. if (OK (dev->GetId (&deviceId)))
  216315. {
  216316. s = String (deviceId);
  216317. CoTaskMemFree (deviceId);
  216318. }
  216319. dev->Release();
  216320. }
  216321. return s;
  216322. }
  216323. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216324. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216325. };
  216326. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216327. {
  216328. return new WASAPIAudioIODeviceType();
  216329. }
  216330. #undef logFailure
  216331. #undef OK
  216332. #endif
  216333. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216334. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216335. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216336. // compiled on its own).
  216337. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216338. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216339. {
  216340. public:
  216341. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216342. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216343. const ComSmartPtr <IBaseFilter>& filter_,
  216344. int minWidth, int minHeight,
  216345. int maxWidth, int maxHeight)
  216346. : owner (owner_),
  216347. captureGraphBuilder (captureGraphBuilder_),
  216348. filter (filter_),
  216349. ok (false),
  216350. imageNeedsFlipping (false),
  216351. width (0),
  216352. height (0),
  216353. activeUsers (0),
  216354. recordNextFrameTime (false)
  216355. {
  216356. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216357. if (FAILED (hr))
  216358. return;
  216359. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216360. if (FAILED (hr))
  216361. return;
  216362. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  216363. if (FAILED (hr))
  216364. return;
  216365. {
  216366. ComSmartPtr <IAMStreamConfig> streamConfig;
  216367. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216368. IID_IAMStreamConfig, (void**) &streamConfig);
  216369. if (streamConfig != 0)
  216370. {
  216371. getVideoSizes (streamConfig);
  216372. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216373. return;
  216374. }
  216375. }
  216376. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216377. if (FAILED (hr))
  216378. return;
  216379. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216380. if (FAILED (hr))
  216381. return;
  216382. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216383. if (FAILED (hr))
  216384. return;
  216385. if (! connectFilters (filter, smartTee))
  216386. return;
  216387. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216388. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216389. if (FAILED (hr))
  216390. return;
  216391. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  216392. if (FAILED (hr))
  216393. return;
  216394. AM_MEDIA_TYPE mt;
  216395. zerostruct (mt);
  216396. mt.majortype = MEDIATYPE_Video;
  216397. mt.subtype = MEDIASUBTYPE_RGB24;
  216398. mt.formattype = FORMAT_VideoInfo;
  216399. sampleGrabber->SetMediaType (&mt);
  216400. callback = new GrabberCallback (*this);
  216401. sampleGrabber->SetCallback (callback, 1);
  216402. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216403. if (FAILED (hr))
  216404. return;
  216405. ComSmartPtr <IPin> grabberInputPin;
  216406. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  216407. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  216408. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  216409. return;
  216410. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216411. if (FAILED (hr))
  216412. return;
  216413. zerostruct (mt);
  216414. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216415. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216416. width = pVih->bmiHeader.biWidth;
  216417. height = pVih->bmiHeader.biHeight;
  216418. ComSmartPtr <IBaseFilter> nullFilter;
  216419. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216420. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216421. if (connectFilters (sampleGrabberBase, nullFilter)
  216422. && addGraphToRot())
  216423. {
  216424. activeImage = Image (Image::RGB, width, height, true);
  216425. loadingImage = Image (Image::RGB, width, height, true);
  216426. ok = true;
  216427. }
  216428. }
  216429. ~DShowCameraDeviceInteral()
  216430. {
  216431. if (mediaControl != 0)
  216432. mediaControl->Stop();
  216433. removeGraphFromRot();
  216434. for (int i = viewerComps.size(); --i >= 0;)
  216435. viewerComps.getUnchecked(i)->ownerDeleted();
  216436. callback = 0;
  216437. graphBuilder = 0;
  216438. sampleGrabber = 0;
  216439. mediaControl = 0;
  216440. filter = 0;
  216441. captureGraphBuilder = 0;
  216442. smartTee = 0;
  216443. smartTeePreviewOutputPin = 0;
  216444. smartTeeCaptureOutputPin = 0;
  216445. asfWriter = 0;
  216446. }
  216447. void addUser()
  216448. {
  216449. if (ok && activeUsers++ == 0)
  216450. mediaControl->Run();
  216451. }
  216452. void removeUser()
  216453. {
  216454. if (ok && --activeUsers == 0)
  216455. mediaControl->Stop();
  216456. }
  216457. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216458. {
  216459. if (recordNextFrameTime)
  216460. {
  216461. const double defaultCameraLatency = 0.1;
  216462. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216463. recordNextFrameTime = false;
  216464. ComSmartPtr <IPin> pin;
  216465. if (getPin (filter, PINDIR_OUTPUT, &pin))
  216466. {
  216467. ComSmartPtr <IAMPushSource> pushSource;
  216468. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  216469. if (pushSource != 0)
  216470. {
  216471. REFERENCE_TIME latency = 0;
  216472. hr = pushSource->GetLatency (&latency);
  216473. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216474. }
  216475. }
  216476. }
  216477. {
  216478. const int lineStride = width * 3;
  216479. const ScopedLock sl (imageSwapLock);
  216480. {
  216481. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216482. for (int i = 0; i < height; ++i)
  216483. memcpy (destData.getLinePointer ((height - 1) - i),
  216484. buffer + lineStride * i,
  216485. lineStride);
  216486. }
  216487. imageNeedsFlipping = true;
  216488. }
  216489. if (listeners.size() > 0)
  216490. callListeners (loadingImage);
  216491. sendChangeMessage (this);
  216492. }
  216493. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216494. {
  216495. if (imageNeedsFlipping)
  216496. {
  216497. const ScopedLock sl (imageSwapLock);
  216498. swapVariables (loadingImage, activeImage);
  216499. imageNeedsFlipping = false;
  216500. }
  216501. RectanglePlacement rp (RectanglePlacement::centred);
  216502. double dx = 0, dy = 0, dw = width, dh = height;
  216503. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216504. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216505. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216506. g.saveState();
  216507. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216508. g.fillAll (Colours::black);
  216509. g.restoreState();
  216510. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216511. }
  216512. bool createFileCaptureFilter (const File& file)
  216513. {
  216514. removeFileCaptureFilter();
  216515. file.deleteFile();
  216516. mediaControl->Stop();
  216517. firstRecordedTime = Time();
  216518. recordNextFrameTime = true;
  216519. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216520. if (SUCCEEDED (hr))
  216521. {
  216522. ComSmartPtr <IFileSinkFilter> fileSink;
  216523. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  216524. if (SUCCEEDED (hr))
  216525. {
  216526. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216527. if (SUCCEEDED (hr))
  216528. {
  216529. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216530. if (SUCCEEDED (hr))
  216531. {
  216532. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216533. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  216534. asfConfig->SetIndexMode (true);
  216535. ComSmartPtr <IWMProfileManager> profileManager;
  216536. hr = WMCreateProfileManager (&profileManager);
  216537. // This gibberish is the DirectShow profile for a video-only wmv file.
  216538. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  216539. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216540. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216541. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  216542. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  216543. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216544. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  216545. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  216546. prof = prof.replace ("$WIDTH", String (width))
  216547. .replace ("$HEIGHT", String (height));
  216548. ComSmartPtr <IWMProfile> currentProfile;
  216549. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  216550. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216551. if (SUCCEEDED (hr))
  216552. {
  216553. ComSmartPtr <IPin> asfWriterInputPin;
  216554. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  216555. {
  216556. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216557. if (SUCCEEDED (hr)
  216558. && ok && activeUsers > 0
  216559. && SUCCEEDED (mediaControl->Run()))
  216560. {
  216561. return true;
  216562. }
  216563. }
  216564. }
  216565. }
  216566. }
  216567. }
  216568. }
  216569. removeFileCaptureFilter();
  216570. if (ok && activeUsers > 0)
  216571. mediaControl->Run();
  216572. return false;
  216573. }
  216574. void removeFileCaptureFilter()
  216575. {
  216576. mediaControl->Stop();
  216577. if (asfWriter != 0)
  216578. {
  216579. graphBuilder->RemoveFilter (asfWriter);
  216580. asfWriter = 0;
  216581. }
  216582. if (ok && activeUsers > 0)
  216583. mediaControl->Run();
  216584. }
  216585. void addListener (CameraDevice::Listener* listenerToAdd)
  216586. {
  216587. const ScopedLock sl (listenerLock);
  216588. if (listeners.size() == 0)
  216589. addUser();
  216590. listeners.addIfNotAlreadyThere (listenerToAdd);
  216591. }
  216592. void removeListener (CameraDevice::Listener* listenerToRemove)
  216593. {
  216594. const ScopedLock sl (listenerLock);
  216595. listeners.removeValue (listenerToRemove);
  216596. if (listeners.size() == 0)
  216597. removeUser();
  216598. }
  216599. void callListeners (const Image& image)
  216600. {
  216601. const ScopedLock sl (listenerLock);
  216602. for (int i = listeners.size(); --i >= 0;)
  216603. {
  216604. CameraDevice::Listener* const l = listeners[i];
  216605. if (l != 0)
  216606. l->imageReceived (image);
  216607. }
  216608. }
  216609. class DShowCaptureViewerComp : public Component,
  216610. public ChangeListener
  216611. {
  216612. public:
  216613. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216614. : owner (owner_)
  216615. {
  216616. setOpaque (true);
  216617. owner->addChangeListener (this);
  216618. owner->addUser();
  216619. owner->viewerComps.add (this);
  216620. setSize (owner_->width, owner_->height);
  216621. }
  216622. ~DShowCaptureViewerComp()
  216623. {
  216624. if (owner != 0)
  216625. {
  216626. owner->viewerComps.removeValue (this);
  216627. owner->removeUser();
  216628. owner->removeChangeListener (this);
  216629. }
  216630. }
  216631. void ownerDeleted()
  216632. {
  216633. owner = 0;
  216634. }
  216635. void paint (Graphics& g)
  216636. {
  216637. g.setColour (Colours::black);
  216638. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216639. if (owner != 0)
  216640. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216641. else
  216642. g.fillAll (Colours::black);
  216643. }
  216644. void changeListenerCallback (void*)
  216645. {
  216646. repaint();
  216647. }
  216648. private:
  216649. DShowCameraDeviceInteral* owner;
  216650. };
  216651. bool ok;
  216652. int width, height;
  216653. Time firstRecordedTime;
  216654. Array <DShowCaptureViewerComp*> viewerComps;
  216655. private:
  216656. CameraDevice* const owner;
  216657. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216658. ComSmartPtr <IBaseFilter> filter;
  216659. ComSmartPtr <IBaseFilter> smartTee;
  216660. ComSmartPtr <IGraphBuilder> graphBuilder;
  216661. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216662. ComSmartPtr <IMediaControl> mediaControl;
  216663. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216664. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216665. ComSmartPtr <IBaseFilter> asfWriter;
  216666. int activeUsers;
  216667. Array <int> widths, heights;
  216668. DWORD graphRegistrationID;
  216669. CriticalSection imageSwapLock;
  216670. bool imageNeedsFlipping;
  216671. Image loadingImage;
  216672. Image activeImage;
  216673. bool recordNextFrameTime;
  216674. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216675. {
  216676. widths.clear();
  216677. heights.clear();
  216678. int count = 0, size = 0;
  216679. streamConfig->GetNumberOfCapabilities (&count, &size);
  216680. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216681. {
  216682. for (int i = 0; i < count; ++i)
  216683. {
  216684. VIDEO_STREAM_CONFIG_CAPS scc;
  216685. AM_MEDIA_TYPE* config;
  216686. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216687. if (SUCCEEDED (hr))
  216688. {
  216689. const int w = scc.InputSize.cx;
  216690. const int h = scc.InputSize.cy;
  216691. bool duplicate = false;
  216692. for (int j = widths.size(); --j >= 0;)
  216693. {
  216694. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216695. {
  216696. duplicate = true;
  216697. break;
  216698. }
  216699. }
  216700. if (! duplicate)
  216701. {
  216702. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216703. widths.add (w);
  216704. heights.add (h);
  216705. }
  216706. deleteMediaType (config);
  216707. }
  216708. }
  216709. }
  216710. }
  216711. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216712. const int minWidth, const int minHeight,
  216713. const int maxWidth, const int maxHeight)
  216714. {
  216715. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216716. streamConfig->GetNumberOfCapabilities (&count, &size);
  216717. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216718. {
  216719. AM_MEDIA_TYPE* config;
  216720. VIDEO_STREAM_CONFIG_CAPS scc;
  216721. for (int i = 0; i < count; ++i)
  216722. {
  216723. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216724. if (SUCCEEDED (hr))
  216725. {
  216726. if (scc.InputSize.cx >= minWidth
  216727. && scc.InputSize.cy >= minHeight
  216728. && scc.InputSize.cx <= maxWidth
  216729. && scc.InputSize.cy <= maxHeight)
  216730. {
  216731. int area = scc.InputSize.cx * scc.InputSize.cy;
  216732. if (area > bestArea)
  216733. {
  216734. bestIndex = i;
  216735. bestArea = area;
  216736. }
  216737. }
  216738. deleteMediaType (config);
  216739. }
  216740. }
  216741. if (bestIndex >= 0)
  216742. {
  216743. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216744. hr = streamConfig->SetFormat (config);
  216745. deleteMediaType (config);
  216746. return SUCCEEDED (hr);
  216747. }
  216748. }
  216749. return false;
  216750. }
  216751. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  216752. {
  216753. ComSmartPtr <IEnumPins> enumerator;
  216754. ComSmartPtr <IPin> pin;
  216755. filter->EnumPins (&enumerator);
  216756. while (enumerator->Next (1, &pin, 0) == S_OK)
  216757. {
  216758. PIN_DIRECTION dir;
  216759. pin->QueryDirection (&dir);
  216760. if (wantedDirection == dir)
  216761. {
  216762. PIN_INFO info;
  216763. zerostruct (info);
  216764. pin->QueryPinInfo (&info);
  216765. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216766. {
  216767. pin->AddRef();
  216768. *result = pin;
  216769. return true;
  216770. }
  216771. }
  216772. }
  216773. return false;
  216774. }
  216775. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216776. {
  216777. ComSmartPtr <IPin> in, out;
  216778. return getPin (first, PINDIR_OUTPUT, &out)
  216779. && getPin (second, PINDIR_INPUT, &in)
  216780. && SUCCEEDED (graphBuilder->Connect (out, in));
  216781. }
  216782. bool addGraphToRot()
  216783. {
  216784. ComSmartPtr <IRunningObjectTable> rot;
  216785. if (FAILED (GetRunningObjectTable (0, &rot)))
  216786. return false;
  216787. ComSmartPtr <IMoniker> moniker;
  216788. WCHAR buffer[128];
  216789. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  216790. if (FAILED (hr))
  216791. return false;
  216792. graphRegistrationID = 0;
  216793. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216794. }
  216795. void removeGraphFromRot()
  216796. {
  216797. ComSmartPtr <IRunningObjectTable> rot;
  216798. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  216799. rot->Revoke (graphRegistrationID);
  216800. }
  216801. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216802. {
  216803. if (pmt->cbFormat != 0)
  216804. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216805. if (pmt->pUnk != 0)
  216806. pmt->pUnk->Release();
  216807. CoTaskMemFree (pmt);
  216808. }
  216809. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216810. {
  216811. public:
  216812. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216813. : owner (owner_)
  216814. {
  216815. }
  216816. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216817. {
  216818. return E_FAIL;
  216819. }
  216820. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216821. {
  216822. owner.handleFrame (time, buffer, bufferSize);
  216823. return S_OK;
  216824. }
  216825. private:
  216826. DShowCameraDeviceInteral& owner;
  216827. GrabberCallback (const GrabberCallback&);
  216828. GrabberCallback& operator= (const GrabberCallback&);
  216829. };
  216830. ComSmartPtr <GrabberCallback> callback;
  216831. Array <CameraDevice::Listener*> listeners;
  216832. CriticalSection listenerLock;
  216833. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  216834. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  216835. };
  216836. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216837. : name (name_)
  216838. {
  216839. isRecording = false;
  216840. }
  216841. CameraDevice::~CameraDevice()
  216842. {
  216843. stopRecording();
  216844. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216845. internal = 0;
  216846. }
  216847. Component* CameraDevice::createViewerComponent()
  216848. {
  216849. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216850. }
  216851. const String CameraDevice::getFileExtension()
  216852. {
  216853. return ".wmv";
  216854. }
  216855. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216856. {
  216857. stopRecording();
  216858. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216859. d->addUser();
  216860. isRecording = d->createFileCaptureFilter (file);
  216861. }
  216862. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216863. {
  216864. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216865. return d->firstRecordedTime;
  216866. }
  216867. void CameraDevice::stopRecording()
  216868. {
  216869. if (isRecording)
  216870. {
  216871. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216872. d->removeFileCaptureFilter();
  216873. d->removeUser();
  216874. isRecording = false;
  216875. }
  216876. }
  216877. void CameraDevice::addListener (Listener* listenerToAdd)
  216878. {
  216879. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216880. if (listenerToAdd != 0)
  216881. d->addListener (listenerToAdd);
  216882. }
  216883. void CameraDevice::removeListener (Listener* listenerToRemove)
  216884. {
  216885. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216886. if (listenerToRemove != 0)
  216887. d->removeListener (listenerToRemove);
  216888. }
  216889. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216890. const int deviceIndexToOpen,
  216891. String& name)
  216892. {
  216893. int index = 0;
  216894. ComSmartPtr <IBaseFilter> result;
  216895. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216896. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216897. if (SUCCEEDED (hr))
  216898. {
  216899. ComSmartPtr <IEnumMoniker> enumerator;
  216900. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  216901. if (SUCCEEDED (hr) && enumerator != 0)
  216902. {
  216903. ComSmartPtr <IBaseFilter> captureFilter;
  216904. ComSmartPtr <IMoniker> moniker;
  216905. ULONG fetched;
  216906. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  216907. {
  216908. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  216909. if (SUCCEEDED (hr))
  216910. {
  216911. ComSmartPtr <IPropertyBag> propertyBag;
  216912. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  216913. if (SUCCEEDED (hr))
  216914. {
  216915. VARIANT var;
  216916. var.vt = VT_BSTR;
  216917. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216918. propertyBag = 0;
  216919. if (SUCCEEDED (hr))
  216920. {
  216921. if (names != 0)
  216922. names->add (var.bstrVal);
  216923. if (index == deviceIndexToOpen)
  216924. {
  216925. name = var.bstrVal;
  216926. result = captureFilter;
  216927. captureFilter = 0;
  216928. break;
  216929. }
  216930. ++index;
  216931. }
  216932. moniker = 0;
  216933. }
  216934. captureFilter = 0;
  216935. }
  216936. }
  216937. }
  216938. }
  216939. return result;
  216940. }
  216941. const StringArray CameraDevice::getAvailableDevices()
  216942. {
  216943. StringArray devs;
  216944. String dummy;
  216945. enumerateCameras (&devs, -1, dummy);
  216946. return devs;
  216947. }
  216948. CameraDevice* CameraDevice::openDevice (int index,
  216949. int minWidth, int minHeight,
  216950. int maxWidth, int maxHeight)
  216951. {
  216952. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216953. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216954. if (SUCCEEDED (hr))
  216955. {
  216956. String name;
  216957. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216958. if (filter != 0)
  216959. {
  216960. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216961. DShowCameraDeviceInteral* const intern
  216962. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216963. minWidth, minHeight, maxWidth, maxHeight);
  216964. cam->internal = intern;
  216965. if (intern->ok)
  216966. return cam.release();
  216967. }
  216968. }
  216969. return 0;
  216970. }
  216971. #endif
  216972. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216973. #endif
  216974. // Auto-link the other win32 libs that are needed by library calls..
  216975. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216976. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216977. // Auto-links to various win32 libs that are needed by library calls..
  216978. #pragma comment(lib, "kernel32.lib")
  216979. #pragma comment(lib, "user32.lib")
  216980. #pragma comment(lib, "shell32.lib")
  216981. #pragma comment(lib, "gdi32.lib")
  216982. #pragma comment(lib, "vfw32.lib")
  216983. #pragma comment(lib, "comdlg32.lib")
  216984. #pragma comment(lib, "winmm.lib")
  216985. #pragma comment(lib, "wininet.lib")
  216986. #pragma comment(lib, "ole32.lib")
  216987. #pragma comment(lib, "oleaut32.lib")
  216988. #pragma comment(lib, "advapi32.lib")
  216989. #pragma comment(lib, "ws2_32.lib")
  216990. #pragma comment(lib, "comsupp.lib")
  216991. #pragma comment(lib, "version.lib")
  216992. #if JUCE_OPENGL
  216993. #pragma comment(lib, "OpenGL32.Lib")
  216994. #pragma comment(lib, "GlU32.Lib")
  216995. #endif
  216996. #if JUCE_QUICKTIME
  216997. #pragma comment (lib, "QTMLClient.lib")
  216998. #endif
  216999. #if JUCE_USE_CAMERA
  217000. #pragma comment (lib, "Strmiids.lib")
  217001. #pragma comment (lib, "wmvcore.lib")
  217002. #endif
  217003. #if JUCE_DIRECT2D
  217004. #pragma comment (lib, "Dwrite.lib")
  217005. #pragma comment (lib, "D2d1.lib")
  217006. #endif
  217007. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217008. #endif
  217009. END_JUCE_NAMESPACE
  217010. #endif
  217011. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217012. #endif
  217013. #if JUCE_LINUX
  217014. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217015. /*
  217016. This file wraps together all the mac-specific code, so that
  217017. we can include all the native headers just once, and compile all our
  217018. platform-specific stuff in one big lump, keeping it out of the way of
  217019. the rest of the codebase.
  217020. */
  217021. #if JUCE_LINUX
  217022. BEGIN_JUCE_NAMESPACE
  217023. #define JUCE_INCLUDED_FILE 1
  217024. // Now include the actual code files..
  217025. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217026. /*
  217027. This file contains posix routines that are common to both the Linux and Mac builds.
  217028. It gets included directly in the cpp files for these platforms.
  217029. */
  217030. CriticalSection::CriticalSection() throw()
  217031. {
  217032. pthread_mutexattr_t atts;
  217033. pthread_mutexattr_init (&atts);
  217034. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217035. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217036. pthread_mutex_init (&internal, &atts);
  217037. }
  217038. CriticalSection::~CriticalSection() throw()
  217039. {
  217040. pthread_mutex_destroy (&internal);
  217041. }
  217042. void CriticalSection::enter() const throw()
  217043. {
  217044. pthread_mutex_lock (&internal);
  217045. }
  217046. bool CriticalSection::tryEnter() const throw()
  217047. {
  217048. return pthread_mutex_trylock (&internal) == 0;
  217049. }
  217050. void CriticalSection::exit() const throw()
  217051. {
  217052. pthread_mutex_unlock (&internal);
  217053. }
  217054. class WaitableEventImpl
  217055. {
  217056. public:
  217057. WaitableEventImpl (const bool manualReset_)
  217058. : triggered (false),
  217059. manualReset (manualReset_)
  217060. {
  217061. pthread_cond_init (&condition, 0);
  217062. pthread_mutexattr_t atts;
  217063. pthread_mutexattr_init (&atts);
  217064. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217065. pthread_mutex_init (&mutex, &atts);
  217066. }
  217067. ~WaitableEventImpl()
  217068. {
  217069. pthread_cond_destroy (&condition);
  217070. pthread_mutex_destroy (&mutex);
  217071. }
  217072. bool wait (const int timeOutMillisecs) throw()
  217073. {
  217074. pthread_mutex_lock (&mutex);
  217075. if (! triggered)
  217076. {
  217077. if (timeOutMillisecs < 0)
  217078. {
  217079. do
  217080. {
  217081. pthread_cond_wait (&condition, &mutex);
  217082. }
  217083. while (! triggered);
  217084. }
  217085. else
  217086. {
  217087. struct timeval now;
  217088. gettimeofday (&now, 0);
  217089. struct timespec time;
  217090. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217091. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217092. if (time.tv_nsec >= 1000000000)
  217093. {
  217094. time.tv_nsec -= 1000000000;
  217095. time.tv_sec++;
  217096. }
  217097. do
  217098. {
  217099. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217100. {
  217101. pthread_mutex_unlock (&mutex);
  217102. return false;
  217103. }
  217104. }
  217105. while (! triggered);
  217106. }
  217107. }
  217108. if (! manualReset)
  217109. triggered = false;
  217110. pthread_mutex_unlock (&mutex);
  217111. return true;
  217112. }
  217113. void signal() throw()
  217114. {
  217115. pthread_mutex_lock (&mutex);
  217116. triggered = true;
  217117. pthread_cond_broadcast (&condition);
  217118. pthread_mutex_unlock (&mutex);
  217119. }
  217120. void reset() throw()
  217121. {
  217122. pthread_mutex_lock (&mutex);
  217123. triggered = false;
  217124. pthread_mutex_unlock (&mutex);
  217125. }
  217126. private:
  217127. pthread_cond_t condition;
  217128. pthread_mutex_t mutex;
  217129. bool triggered;
  217130. const bool manualReset;
  217131. WaitableEventImpl (const WaitableEventImpl&);
  217132. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217133. };
  217134. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217135. : internal (new WaitableEventImpl (manualReset))
  217136. {
  217137. }
  217138. WaitableEvent::~WaitableEvent() throw()
  217139. {
  217140. delete static_cast <WaitableEventImpl*> (internal);
  217141. }
  217142. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217143. {
  217144. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217145. }
  217146. void WaitableEvent::signal() const throw()
  217147. {
  217148. static_cast <WaitableEventImpl*> (internal)->signal();
  217149. }
  217150. void WaitableEvent::reset() const throw()
  217151. {
  217152. static_cast <WaitableEventImpl*> (internal)->reset();
  217153. }
  217154. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217155. {
  217156. struct timespec time;
  217157. time.tv_sec = millisecs / 1000;
  217158. time.tv_nsec = (millisecs % 1000) * 1000000;
  217159. nanosleep (&time, 0);
  217160. }
  217161. const juce_wchar File::separator = '/';
  217162. const String File::separatorString ("/");
  217163. const File File::getCurrentWorkingDirectory()
  217164. {
  217165. HeapBlock<char> heapBuffer;
  217166. char localBuffer [1024];
  217167. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217168. int bufferSize = 4096;
  217169. while (cwd == 0 && errno == ERANGE)
  217170. {
  217171. heapBuffer.malloc (bufferSize);
  217172. cwd = getcwd (heapBuffer, bufferSize - 1);
  217173. bufferSize += 1024;
  217174. }
  217175. return File (String::fromUTF8 (cwd));
  217176. }
  217177. bool File::setAsCurrentWorkingDirectory() const
  217178. {
  217179. return chdir (getFullPathName().toUTF8()) == 0;
  217180. }
  217181. static bool juce_stat (const String& fileName, struct stat& info)
  217182. {
  217183. return fileName.isNotEmpty()
  217184. && (stat (fileName.toUTF8(), &info) == 0);
  217185. }
  217186. bool File::isDirectory() const
  217187. {
  217188. struct stat info;
  217189. return fullPath.isEmpty()
  217190. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217191. }
  217192. bool File::exists() const
  217193. {
  217194. return fullPath.isNotEmpty()
  217195. && access (fullPath.toUTF8(), F_OK) == 0;
  217196. }
  217197. bool File::existsAsFile() const
  217198. {
  217199. return exists() && ! isDirectory();
  217200. }
  217201. int64 File::getSize() const
  217202. {
  217203. struct stat info;
  217204. return juce_stat (fullPath, info) ? info.st_size : 0;
  217205. }
  217206. bool File::hasWriteAccess() const
  217207. {
  217208. if (exists())
  217209. return access (fullPath.toUTF8(), W_OK) == 0;
  217210. if ((! isDirectory()) && fullPath.containsChar (separator))
  217211. return getParentDirectory().hasWriteAccess();
  217212. return false;
  217213. }
  217214. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217215. {
  217216. struct stat info;
  217217. const int res = stat (fullPath.toUTF8(), &info);
  217218. if (res != 0)
  217219. return false;
  217220. info.st_mode &= 0777; // Just permissions
  217221. if (shouldBeReadOnly)
  217222. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217223. else
  217224. // Give everybody write permission?
  217225. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217226. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217227. }
  217228. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217229. {
  217230. modificationTime = 0;
  217231. accessTime = 0;
  217232. creationTime = 0;
  217233. struct stat info;
  217234. const int res = stat (fullPath.toUTF8(), &info);
  217235. if (res == 0)
  217236. {
  217237. modificationTime = (int64) info.st_mtime * 1000;
  217238. accessTime = (int64) info.st_atime * 1000;
  217239. creationTime = (int64) info.st_ctime * 1000;
  217240. }
  217241. }
  217242. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217243. {
  217244. struct utimbuf times;
  217245. times.actime = (time_t) (accessTime / 1000);
  217246. times.modtime = (time_t) (modificationTime / 1000);
  217247. return utime (fullPath.toUTF8(), &times) == 0;
  217248. }
  217249. bool File::deleteFile() const
  217250. {
  217251. if (! exists())
  217252. return true;
  217253. else if (isDirectory())
  217254. return rmdir (fullPath.toUTF8()) == 0;
  217255. else
  217256. return remove (fullPath.toUTF8()) == 0;
  217257. }
  217258. bool File::moveInternal (const File& dest) const
  217259. {
  217260. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217261. return true;
  217262. if (hasWriteAccess() && copyInternal (dest))
  217263. {
  217264. if (deleteFile())
  217265. return true;
  217266. dest.deleteFile();
  217267. }
  217268. return false;
  217269. }
  217270. void File::createDirectoryInternal (const String& fileName) const
  217271. {
  217272. mkdir (fileName.toUTF8(), 0777);
  217273. }
  217274. int64 juce_fileSetPosition (void* handle, int64 pos)
  217275. {
  217276. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217277. return pos;
  217278. return -1;
  217279. }
  217280. void FileInputStream::openHandle()
  217281. {
  217282. totalSize = file.getSize();
  217283. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217284. if (f != -1)
  217285. fileHandle = (void*) f;
  217286. }
  217287. void FileInputStream::closeHandle()
  217288. {
  217289. if (fileHandle != 0)
  217290. {
  217291. close ((int) (pointer_sized_int) fileHandle);
  217292. fileHandle = 0;
  217293. }
  217294. }
  217295. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217296. {
  217297. if (fileHandle != 0)
  217298. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217299. return 0;
  217300. }
  217301. void FileOutputStream::openHandle()
  217302. {
  217303. if (file.exists())
  217304. {
  217305. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217306. if (f != -1)
  217307. {
  217308. currentPosition = lseek (f, 0, SEEK_END);
  217309. if (currentPosition >= 0)
  217310. fileHandle = (void*) f;
  217311. else
  217312. close (f);
  217313. }
  217314. }
  217315. else
  217316. {
  217317. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217318. if (f != -1)
  217319. fileHandle = (void*) f;
  217320. }
  217321. }
  217322. void FileOutputStream::closeHandle()
  217323. {
  217324. if (fileHandle != 0)
  217325. {
  217326. close ((int) (pointer_sized_int) fileHandle);
  217327. fileHandle = 0;
  217328. }
  217329. }
  217330. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217331. {
  217332. if (fileHandle != 0)
  217333. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217334. return 0;
  217335. }
  217336. void FileOutputStream::flushInternal()
  217337. {
  217338. if (fileHandle != 0)
  217339. fsync ((int) (pointer_sized_int) fileHandle);
  217340. }
  217341. const File juce_getExecutableFile()
  217342. {
  217343. Dl_info exeInfo;
  217344. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217345. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217346. }
  217347. // if this file doesn't exist, find a parent of it that does..
  217348. static bool juce_doStatFS (File f, struct statfs& result)
  217349. {
  217350. for (int i = 5; --i >= 0;)
  217351. {
  217352. if (f.exists())
  217353. break;
  217354. f = f.getParentDirectory();
  217355. }
  217356. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217357. }
  217358. int64 File::getBytesFreeOnVolume() const
  217359. {
  217360. struct statfs buf;
  217361. if (juce_doStatFS (*this, buf))
  217362. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217363. return 0;
  217364. }
  217365. int64 File::getVolumeTotalSize() const
  217366. {
  217367. struct statfs buf;
  217368. if (juce_doStatFS (*this, buf))
  217369. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217370. return 0;
  217371. }
  217372. const String File::getVolumeLabel() const
  217373. {
  217374. #if JUCE_MAC
  217375. struct VolAttrBuf
  217376. {
  217377. u_int32_t length;
  217378. attrreference_t mountPointRef;
  217379. char mountPointSpace [MAXPATHLEN];
  217380. } attrBuf;
  217381. struct attrlist attrList;
  217382. zerostruct (attrList);
  217383. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217384. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217385. File f (*this);
  217386. for (;;)
  217387. {
  217388. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217389. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217390. (int) attrBuf.mountPointRef.attr_length);
  217391. const File parent (f.getParentDirectory());
  217392. if (f == parent)
  217393. break;
  217394. f = parent;
  217395. }
  217396. #endif
  217397. return String::empty;
  217398. }
  217399. int File::getVolumeSerialNumber() const
  217400. {
  217401. return 0; // xxx
  217402. }
  217403. void juce_runSystemCommand (const String& command)
  217404. {
  217405. int result = system (command.toUTF8());
  217406. (void) result;
  217407. }
  217408. const String juce_getOutputFromCommand (const String& command)
  217409. {
  217410. // slight bodge here, as we just pipe the output into a temp file and read it...
  217411. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217412. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217413. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217414. String result (tempFile.loadFileAsString());
  217415. tempFile.deleteFile();
  217416. return result;
  217417. }
  217418. class InterProcessLock::Pimpl
  217419. {
  217420. public:
  217421. Pimpl (const String& name, const int timeOutMillisecs)
  217422. : handle (0), refCount (1)
  217423. {
  217424. #if JUCE_MAC
  217425. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217426. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217427. #else
  217428. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217429. #endif
  217430. temp.create();
  217431. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217432. if (handle != 0)
  217433. {
  217434. struct flock fl;
  217435. zerostruct (fl);
  217436. fl.l_whence = SEEK_SET;
  217437. fl.l_type = F_WRLCK;
  217438. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217439. for (;;)
  217440. {
  217441. const int result = fcntl (handle, F_SETLK, &fl);
  217442. if (result >= 0)
  217443. return;
  217444. if (errno != EINTR)
  217445. {
  217446. if (timeOutMillisecs == 0
  217447. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217448. break;
  217449. Thread::sleep (10);
  217450. }
  217451. }
  217452. }
  217453. closeFile();
  217454. }
  217455. ~Pimpl()
  217456. {
  217457. closeFile();
  217458. }
  217459. void closeFile()
  217460. {
  217461. if (handle != 0)
  217462. {
  217463. struct flock fl;
  217464. zerostruct (fl);
  217465. fl.l_whence = SEEK_SET;
  217466. fl.l_type = F_UNLCK;
  217467. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217468. {}
  217469. close (handle);
  217470. handle = 0;
  217471. }
  217472. }
  217473. int handle, refCount;
  217474. };
  217475. InterProcessLock::InterProcessLock (const String& name_)
  217476. : name (name_)
  217477. {
  217478. }
  217479. InterProcessLock::~InterProcessLock()
  217480. {
  217481. }
  217482. bool InterProcessLock::enter (const int timeOutMillisecs)
  217483. {
  217484. const ScopedLock sl (lock);
  217485. if (pimpl == 0)
  217486. {
  217487. pimpl = new Pimpl (name, timeOutMillisecs);
  217488. if (pimpl->handle == 0)
  217489. pimpl = 0;
  217490. }
  217491. else
  217492. {
  217493. pimpl->refCount++;
  217494. }
  217495. return pimpl != 0;
  217496. }
  217497. void InterProcessLock::exit()
  217498. {
  217499. const ScopedLock sl (lock);
  217500. // Trying to release the lock too many times!
  217501. jassert (pimpl != 0);
  217502. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217503. pimpl = 0;
  217504. }
  217505. void JUCE_API juce_threadEntryPoint (void*);
  217506. void* threadEntryProc (void* userData)
  217507. {
  217508. JUCE_AUTORELEASEPOOL
  217509. juce_threadEntryPoint (userData);
  217510. return 0;
  217511. }
  217512. void* juce_createThread (void* userData)
  217513. {
  217514. pthread_t handle = 0;
  217515. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217516. {
  217517. pthread_detach (handle);
  217518. return (void*) handle;
  217519. }
  217520. return 0;
  217521. }
  217522. void juce_killThread (void* handle)
  217523. {
  217524. if (handle != 0)
  217525. pthread_cancel ((pthread_t) handle);
  217526. }
  217527. void juce_setCurrentThreadName (const String& /*name*/)
  217528. {
  217529. }
  217530. bool juce_setThreadPriority (void* handle, int priority)
  217531. {
  217532. struct sched_param param;
  217533. int policy;
  217534. priority = jlimit (0, 10, priority);
  217535. if (handle == 0)
  217536. handle = (void*) pthread_self();
  217537. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217538. return false;
  217539. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217540. const int minPriority = sched_get_priority_min (policy);
  217541. const int maxPriority = sched_get_priority_max (policy);
  217542. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217543. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217544. }
  217545. Thread::ThreadID Thread::getCurrentThreadId()
  217546. {
  217547. return (ThreadID) pthread_self();
  217548. }
  217549. void Thread::yield()
  217550. {
  217551. sched_yield();
  217552. }
  217553. /* Remove this macro if you're having problems compiling the cpu affinity
  217554. calls (the API for these has changed about quite a bit in various Linux
  217555. versions, and a lot of distros seem to ship with obsolete versions)
  217556. */
  217557. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217558. #define SUPPORT_AFFINITIES 1
  217559. #endif
  217560. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217561. {
  217562. #if SUPPORT_AFFINITIES
  217563. cpu_set_t affinity;
  217564. CPU_ZERO (&affinity);
  217565. for (int i = 0; i < 32; ++i)
  217566. if ((affinityMask & (1 << i)) != 0)
  217567. CPU_SET (i, &affinity);
  217568. /*
  217569. N.B. If this line causes a compile error, then you've probably not got the latest
  217570. version of glibc installed.
  217571. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217572. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217573. */
  217574. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217575. sched_yield();
  217576. #else
  217577. /* affinities aren't supported because either the appropriate header files weren't found,
  217578. or the SUPPORT_AFFINITIES macro was turned off
  217579. */
  217580. jassertfalse;
  217581. #endif
  217582. }
  217583. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217584. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217585. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217586. // compiled on its own).
  217587. #if JUCE_INCLUDED_FILE
  217588. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  217589. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  217590. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  217591. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  217592. bool File::copyInternal (const File& dest) const
  217593. {
  217594. FileInputStream in (*this);
  217595. if (dest.deleteFile())
  217596. {
  217597. {
  217598. FileOutputStream out (dest);
  217599. if (out.failedToOpen())
  217600. return false;
  217601. if (out.writeFromInputStream (in, -1) == getSize())
  217602. return true;
  217603. }
  217604. dest.deleteFile();
  217605. }
  217606. return false;
  217607. }
  217608. void File::findFileSystemRoots (Array<File>& destArray)
  217609. {
  217610. destArray.add (File ("/"));
  217611. }
  217612. bool File::isOnCDRomDrive() const
  217613. {
  217614. struct statfs buf;
  217615. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217616. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  217617. }
  217618. bool File::isOnHardDisk() const
  217619. {
  217620. struct statfs buf;
  217621. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217622. {
  217623. switch (buf.f_type)
  217624. {
  217625. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217626. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217627. case U_NFS_SUPER_MAGIC: // Network NFS
  217628. case U_SMB_SUPER_MAGIC: // Network Samba
  217629. return false;
  217630. default:
  217631. // Assume anything else is a hard-disk (but note it could
  217632. // be a RAM disk. There isn't a good way of determining
  217633. // this for sure)
  217634. return true;
  217635. }
  217636. }
  217637. // Assume so if this fails for some reason
  217638. return true;
  217639. }
  217640. bool File::isOnRemovableDrive() const
  217641. {
  217642. jassertfalse; // xxx not implemented for linux!
  217643. return false;
  217644. }
  217645. bool File::isHidden() const
  217646. {
  217647. return getFileName().startsWithChar ('.');
  217648. }
  217649. static const File juce_readlink (const char* const utf8, const File& defaultFile)
  217650. {
  217651. const int size = 8192;
  217652. HeapBlock<char> buffer;
  217653. buffer.malloc (size + 4);
  217654. const size_t numBytes = readlink (utf8, buffer, size);
  217655. if (numBytes > 0 && numBytes <= size)
  217656. return File (String::fromUTF8 (buffer, (int) numBytes));
  217657. return defaultFile;
  217658. }
  217659. const File File::getLinkedTarget() const
  217660. {
  217661. return juce_readlink (getFullPathName().toUTF8(), *this);
  217662. }
  217663. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217664. const File File::getSpecialLocation (const SpecialLocationType type)
  217665. {
  217666. switch (type)
  217667. {
  217668. case userHomeDirectory:
  217669. {
  217670. const char* homeDir = getenv ("HOME");
  217671. if (homeDir == 0)
  217672. {
  217673. struct passwd* const pw = getpwuid (getuid());
  217674. if (pw != 0)
  217675. homeDir = pw->pw_dir;
  217676. }
  217677. return File (String::fromUTF8 (homeDir));
  217678. }
  217679. case userDocumentsDirectory:
  217680. case userMusicDirectory:
  217681. case userMoviesDirectory:
  217682. case userApplicationDataDirectory:
  217683. return File ("~");
  217684. case userDesktopDirectory:
  217685. return File ("~/Desktop");
  217686. case commonApplicationDataDirectory:
  217687. return File ("/var");
  217688. case globalApplicationsDirectory:
  217689. return File ("/usr");
  217690. case tempDirectory:
  217691. {
  217692. File tmp ("/var/tmp");
  217693. if (! tmp.isDirectory())
  217694. {
  217695. tmp = "/tmp";
  217696. if (! tmp.isDirectory())
  217697. tmp = File::getCurrentWorkingDirectory();
  217698. }
  217699. return tmp;
  217700. }
  217701. case invokedExecutableFile:
  217702. if (juce_Argv0 != 0)
  217703. return File (String::fromUTF8 (juce_Argv0));
  217704. // deliberate fall-through...
  217705. case currentExecutableFile:
  217706. case currentApplicationFile:
  217707. return juce_getExecutableFile();
  217708. case hostApplicationPath:
  217709. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217710. default:
  217711. jassertfalse; // unknown type?
  217712. break;
  217713. }
  217714. return File::nonexistent;
  217715. }
  217716. const String File::getVersion() const
  217717. {
  217718. return String::empty; // xxx not yet implemented
  217719. }
  217720. bool File::moveToTrash() const
  217721. {
  217722. if (! exists())
  217723. return true;
  217724. File trashCan ("~/.Trash");
  217725. if (! trashCan.isDirectory())
  217726. trashCan = "~/.local/share/Trash/files";
  217727. if (! trashCan.isDirectory())
  217728. return false;
  217729. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217730. getFileExtension()));
  217731. }
  217732. class DirectoryIterator::NativeIterator::Pimpl
  217733. {
  217734. public:
  217735. Pimpl (const File& directory, const String& wildCard_)
  217736. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217737. wildCard (wildCard_),
  217738. dir (opendir (directory.getFullPathName().toUTF8()))
  217739. {
  217740. if (wildCard == "*.*")
  217741. wildCard = "*";
  217742. wildcardUTF8 = wildCard.toUTF8();
  217743. }
  217744. ~Pimpl()
  217745. {
  217746. if (dir != 0)
  217747. closedir (dir);
  217748. }
  217749. bool next (String& filenameFound,
  217750. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217751. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217752. {
  217753. if (dir == 0)
  217754. return false;
  217755. for (;;)
  217756. {
  217757. struct dirent* const de = readdir (dir);
  217758. if (de == 0)
  217759. return false;
  217760. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217761. {
  217762. filenameFound = String::fromUTF8 (de->d_name);
  217763. const String path (parentDir + filenameFound);
  217764. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217765. {
  217766. struct stat info;
  217767. const bool statOk = juce_stat (path, info);
  217768. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217769. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217770. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217771. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217772. }
  217773. if (isHidden != 0)
  217774. *isHidden = filenameFound.startsWithChar ('.');
  217775. if (isReadOnly != 0)
  217776. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217777. return true;
  217778. }
  217779. }
  217780. }
  217781. private:
  217782. String parentDir, wildCard;
  217783. const char* wildcardUTF8;
  217784. DIR* dir;
  217785. Pimpl (const Pimpl&);
  217786. Pimpl& operator= (const Pimpl&);
  217787. };
  217788. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217789. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217790. {
  217791. }
  217792. DirectoryIterator::NativeIterator::~NativeIterator()
  217793. {
  217794. }
  217795. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217796. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217797. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217798. {
  217799. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217800. }
  217801. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217802. {
  217803. String cmdString (fileName.replace (" ", "\\ ",false));
  217804. cmdString << " " << parameters;
  217805. if (URL::isProbablyAWebsiteURL (fileName)
  217806. || cmdString.startsWithIgnoreCase ("file:")
  217807. || URL::isProbablyAnEmailAddress (fileName))
  217808. {
  217809. // create a command that tries to launch a bunch of likely browsers
  217810. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217811. StringArray cmdLines;
  217812. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217813. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217814. cmdString = cmdLines.joinIntoString (" || ");
  217815. }
  217816. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217817. const int cpid = fork();
  217818. if (cpid == 0)
  217819. {
  217820. setsid();
  217821. // Child process
  217822. execve (argv[0], (char**) argv, environ);
  217823. exit (0);
  217824. }
  217825. return cpid >= 0;
  217826. }
  217827. void File::revealToUser() const
  217828. {
  217829. if (isDirectory())
  217830. startAsProcess();
  217831. else if (getParentDirectory().exists())
  217832. getParentDirectory().startAsProcess();
  217833. }
  217834. #endif
  217835. /*** End of inlined file: juce_linux_Files.cpp ***/
  217836. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217837. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217838. // compiled on its own).
  217839. #if JUCE_INCLUDED_FILE
  217840. struct NamedPipeInternal
  217841. {
  217842. String pipeInName, pipeOutName;
  217843. int pipeIn, pipeOut;
  217844. bool volatile createdPipe, blocked, stopReadOperation;
  217845. static void signalHandler (int) {}
  217846. };
  217847. void NamedPipe::cancelPendingReads()
  217848. {
  217849. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217850. {
  217851. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217852. intern->stopReadOperation = true;
  217853. char buffer [1] = { 0 };
  217854. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217855. (void) bytesWritten;
  217856. int timeout = 2000;
  217857. while (intern->blocked && --timeout >= 0)
  217858. Thread::sleep (2);
  217859. intern->stopReadOperation = false;
  217860. }
  217861. }
  217862. void NamedPipe::close()
  217863. {
  217864. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217865. if (intern != 0)
  217866. {
  217867. internal = 0;
  217868. if (intern->pipeIn != -1)
  217869. ::close (intern->pipeIn);
  217870. if (intern->pipeOut != -1)
  217871. ::close (intern->pipeOut);
  217872. if (intern->createdPipe)
  217873. {
  217874. unlink (intern->pipeInName.toUTF8());
  217875. unlink (intern->pipeOutName.toUTF8());
  217876. }
  217877. delete intern;
  217878. }
  217879. }
  217880. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217881. {
  217882. close();
  217883. NamedPipeInternal* const intern = new NamedPipeInternal();
  217884. internal = intern;
  217885. intern->createdPipe = createPipe;
  217886. intern->blocked = false;
  217887. intern->stopReadOperation = false;
  217888. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217889. siginterrupt (SIGPIPE, 1);
  217890. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217891. intern->pipeInName = pipePath + "_in";
  217892. intern->pipeOutName = pipePath + "_out";
  217893. intern->pipeIn = -1;
  217894. intern->pipeOut = -1;
  217895. if (createPipe)
  217896. {
  217897. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217898. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217899. {
  217900. delete intern;
  217901. internal = 0;
  217902. return false;
  217903. }
  217904. }
  217905. return true;
  217906. }
  217907. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217908. {
  217909. int bytesRead = -1;
  217910. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217911. if (intern != 0)
  217912. {
  217913. intern->blocked = true;
  217914. if (intern->pipeIn == -1)
  217915. {
  217916. if (intern->createdPipe)
  217917. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217918. else
  217919. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217920. if (intern->pipeIn == -1)
  217921. {
  217922. intern->blocked = false;
  217923. return -1;
  217924. }
  217925. }
  217926. bytesRead = 0;
  217927. char* p = (char*) destBuffer;
  217928. while (bytesRead < maxBytesToRead)
  217929. {
  217930. const int bytesThisTime = maxBytesToRead - bytesRead;
  217931. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217932. if (numRead <= 0 || intern->stopReadOperation)
  217933. {
  217934. bytesRead = -1;
  217935. break;
  217936. }
  217937. bytesRead += numRead;
  217938. p += bytesRead;
  217939. }
  217940. intern->blocked = false;
  217941. }
  217942. return bytesRead;
  217943. }
  217944. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217945. {
  217946. int bytesWritten = -1;
  217947. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217948. if (intern != 0)
  217949. {
  217950. if (intern->pipeOut == -1)
  217951. {
  217952. if (intern->createdPipe)
  217953. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217954. else
  217955. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217956. if (intern->pipeOut == -1)
  217957. {
  217958. return -1;
  217959. }
  217960. }
  217961. const char* p = (const char*) sourceBuffer;
  217962. bytesWritten = 0;
  217963. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217964. while (bytesWritten < numBytesToWrite
  217965. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217966. {
  217967. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217968. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217969. if (numWritten <= 0)
  217970. {
  217971. bytesWritten = -1;
  217972. break;
  217973. }
  217974. bytesWritten += numWritten;
  217975. p += bytesWritten;
  217976. }
  217977. }
  217978. return bytesWritten;
  217979. }
  217980. #endif
  217981. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217982. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217983. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217984. // compiled on its own).
  217985. #if JUCE_INCLUDED_FILE
  217986. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  217987. {
  217988. int numResults = 0;
  217989. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217990. if (s != -1)
  217991. {
  217992. char buf [1024];
  217993. struct ifconf ifc;
  217994. ifc.ifc_len = sizeof (buf);
  217995. ifc.ifc_buf = buf;
  217996. ioctl (s, SIOCGIFCONF, &ifc);
  217997. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217998. {
  217999. struct ifreq ifr;
  218000. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218001. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218002. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218003. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  218004. && numResults < maxNum)
  218005. {
  218006. int64 a = 0;
  218007. for (int j = 6; --j >= 0;)
  218008. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  218009. *addresses++ = a;
  218010. ++numResults;
  218011. }
  218012. }
  218013. close (s);
  218014. }
  218015. return numResults;
  218016. }
  218017. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218018. const String& emailSubject,
  218019. const String& bodyText,
  218020. const StringArray& filesToAttach)
  218021. {
  218022. jassertfalse; // xxx todo
  218023. return false;
  218024. }
  218025. /** A HTTP input stream that uses sockets.
  218026. */
  218027. class JUCE_HTTPSocketStream
  218028. {
  218029. public:
  218030. JUCE_HTTPSocketStream()
  218031. : readPosition (0),
  218032. socketHandle (-1),
  218033. levelsOfRedirection (0),
  218034. timeoutSeconds (15)
  218035. {
  218036. }
  218037. ~JUCE_HTTPSocketStream()
  218038. {
  218039. closeSocket();
  218040. }
  218041. bool open (const String& url,
  218042. const String& headers,
  218043. const MemoryBlock& postData,
  218044. const bool isPost,
  218045. URL::OpenStreamProgressCallback* callback,
  218046. void* callbackContext,
  218047. int timeOutMs)
  218048. {
  218049. closeSocket();
  218050. uint32 timeOutTime = Time::getMillisecondCounter();
  218051. if (timeOutMs == 0)
  218052. timeOutTime += 60000;
  218053. else if (timeOutMs < 0)
  218054. timeOutTime = 0xffffffff;
  218055. else
  218056. timeOutTime += timeOutMs;
  218057. String hostName, hostPath;
  218058. int hostPort;
  218059. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218060. return false;
  218061. const struct hostent* host = 0;
  218062. int port = 0;
  218063. String proxyName, proxyPath;
  218064. int proxyPort = 0;
  218065. String proxyURL (getenv ("http_proxy"));
  218066. if (proxyURL.startsWithIgnoreCase ("http://"))
  218067. {
  218068. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218069. return false;
  218070. host = gethostbyname (proxyName.toUTF8());
  218071. port = proxyPort;
  218072. }
  218073. else
  218074. {
  218075. host = gethostbyname (hostName.toUTF8());
  218076. port = hostPort;
  218077. }
  218078. if (host == 0)
  218079. return false;
  218080. struct sockaddr_in address;
  218081. zerostruct (address);
  218082. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218083. address.sin_family = host->h_addrtype;
  218084. address.sin_port = htons (port);
  218085. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218086. if (socketHandle == -1)
  218087. return false;
  218088. int receiveBufferSize = 16384;
  218089. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218090. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218091. #if JUCE_MAC
  218092. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218093. #endif
  218094. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218095. {
  218096. closeSocket();
  218097. return false;
  218098. }
  218099. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218100. proxyName, proxyPort,
  218101. hostPath, url,
  218102. headers, postData,
  218103. isPost));
  218104. size_t totalHeaderSent = 0;
  218105. while (totalHeaderSent < requestHeader.getSize())
  218106. {
  218107. if (Time::getMillisecondCounter() > timeOutTime)
  218108. {
  218109. closeSocket();
  218110. return false;
  218111. }
  218112. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218113. if (send (socketHandle,
  218114. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218115. numToSend, 0)
  218116. != numToSend)
  218117. {
  218118. closeSocket();
  218119. return false;
  218120. }
  218121. totalHeaderSent += numToSend;
  218122. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218123. {
  218124. closeSocket();
  218125. return false;
  218126. }
  218127. }
  218128. const String responseHeader (readResponse (timeOutTime));
  218129. if (responseHeader.isNotEmpty())
  218130. {
  218131. //DBG (responseHeader);
  218132. headerLines.clear();
  218133. headerLines.addLines (responseHeader);
  218134. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218135. .substring (0, 3).getIntValue();
  218136. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218137. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218138. String location (findHeaderItem (headerLines, "Location:"));
  218139. if (statusCode >= 300 && statusCode < 400
  218140. && location.isNotEmpty())
  218141. {
  218142. if (! location.startsWithIgnoreCase ("http://"))
  218143. location = "http://" + location;
  218144. if (levelsOfRedirection++ < 3)
  218145. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218146. }
  218147. else
  218148. {
  218149. levelsOfRedirection = 0;
  218150. return true;
  218151. }
  218152. }
  218153. closeSocket();
  218154. return false;
  218155. }
  218156. int read (void* buffer, int bytesToRead)
  218157. {
  218158. fd_set readbits;
  218159. FD_ZERO (&readbits);
  218160. FD_SET (socketHandle, &readbits);
  218161. struct timeval tv;
  218162. tv.tv_sec = timeoutSeconds;
  218163. tv.tv_usec = 0;
  218164. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218165. return 0; // (timeout)
  218166. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218167. readPosition += bytesRead;
  218168. return bytesRead;
  218169. }
  218170. int readPosition;
  218171. StringArray headerLines;
  218172. juce_UseDebuggingNewOperator
  218173. private:
  218174. int socketHandle, levelsOfRedirection;
  218175. const int timeoutSeconds;
  218176. void closeSocket()
  218177. {
  218178. if (socketHandle >= 0)
  218179. close (socketHandle);
  218180. socketHandle = -1;
  218181. }
  218182. const MemoryBlock createRequestHeader (const String& hostName,
  218183. const int hostPort,
  218184. const String& proxyName,
  218185. const int proxyPort,
  218186. const String& hostPath,
  218187. const String& originalURL,
  218188. const String& headers,
  218189. const MemoryBlock& postData,
  218190. const bool isPost)
  218191. {
  218192. String header (isPost ? "POST " : "GET ");
  218193. if (proxyName.isEmpty())
  218194. {
  218195. header << hostPath << " HTTP/1.0\r\nHost: "
  218196. << hostName << ':' << hostPort;
  218197. }
  218198. else
  218199. {
  218200. header << originalURL << " HTTP/1.0\r\nHost: "
  218201. << proxyName << ':' << proxyPort;
  218202. }
  218203. header << "\r\nUser-Agent: JUCE/"
  218204. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218205. << "\r\nConnection: Close\r\nContent-Length: "
  218206. << postData.getSize() << "\r\n"
  218207. << headers << "\r\n";
  218208. MemoryBlock mb;
  218209. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218210. mb.append (postData.getData(), postData.getSize());
  218211. return mb;
  218212. }
  218213. const String readResponse (const uint32 timeOutTime)
  218214. {
  218215. int bytesRead = 0, numConsecutiveLFs = 0;
  218216. MemoryBlock buffer (1024, true);
  218217. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218218. && Time::getMillisecondCounter() <= timeOutTime)
  218219. {
  218220. fd_set readbits;
  218221. FD_ZERO (&readbits);
  218222. FD_SET (socketHandle, &readbits);
  218223. struct timeval tv;
  218224. tv.tv_sec = timeoutSeconds;
  218225. tv.tv_usec = 0;
  218226. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218227. return String::empty; // (timeout)
  218228. buffer.ensureSize (bytesRead + 8, true);
  218229. char* const dest = (char*) buffer.getData() + bytesRead;
  218230. if (recv (socketHandle, dest, 1, 0) == -1)
  218231. return String::empty;
  218232. const char lastByte = *dest;
  218233. ++bytesRead;
  218234. if (lastByte == '\n')
  218235. ++numConsecutiveLFs;
  218236. else if (lastByte != '\r')
  218237. numConsecutiveLFs = 0;
  218238. }
  218239. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218240. if (header.startsWithIgnoreCase ("HTTP/"))
  218241. return header.trimEnd();
  218242. return String::empty;
  218243. }
  218244. static bool decomposeURL (const String& url,
  218245. String& host, String& path, int& port)
  218246. {
  218247. if (! url.startsWithIgnoreCase ("http://"))
  218248. return false;
  218249. const int nextSlash = url.indexOfChar (7, '/');
  218250. int nextColon = url.indexOfChar (7, ':');
  218251. if (nextColon > nextSlash && nextSlash > 0)
  218252. nextColon = -1;
  218253. if (nextColon >= 0)
  218254. {
  218255. host = url.substring (7, nextColon);
  218256. if (nextSlash >= 0)
  218257. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218258. else
  218259. port = url.substring (nextColon + 1).getIntValue();
  218260. }
  218261. else
  218262. {
  218263. port = 80;
  218264. if (nextSlash >= 0)
  218265. host = url.substring (7, nextSlash);
  218266. else
  218267. host = url.substring (7);
  218268. }
  218269. if (nextSlash >= 0)
  218270. path = url.substring (nextSlash);
  218271. else
  218272. path = "/";
  218273. return true;
  218274. }
  218275. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218276. {
  218277. for (int i = 0; i < lines.size(); ++i)
  218278. if (lines[i].startsWithIgnoreCase (itemName))
  218279. return lines[i].substring (itemName.length()).trim();
  218280. return String::empty;
  218281. }
  218282. };
  218283. void* juce_openInternetFile (const String& url,
  218284. const String& headers,
  218285. const MemoryBlock& postData,
  218286. const bool isPost,
  218287. URL::OpenStreamProgressCallback* callback,
  218288. void* callbackContext,
  218289. int timeOutMs)
  218290. {
  218291. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218292. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218293. return s.release();
  218294. return 0;
  218295. }
  218296. void juce_closeInternetFile (void* handle)
  218297. {
  218298. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218299. }
  218300. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218301. {
  218302. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218303. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218304. }
  218305. int64 juce_getInternetFileContentLength (void* handle)
  218306. {
  218307. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218308. if (s != 0)
  218309. {
  218310. //xxx todo
  218311. jassertfalse
  218312. }
  218313. return -1;
  218314. }
  218315. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218316. {
  218317. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218318. if (s != 0)
  218319. {
  218320. for (int i = 0; i < s->headerLines.size(); ++i)
  218321. {
  218322. const String& headersEntry = s->headerLines[i];
  218323. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218324. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218325. const String previousValue (headers [key]);
  218326. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218327. }
  218328. }
  218329. }
  218330. int juce_seekInInternetFile (void* handle, int newPosition)
  218331. {
  218332. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218333. return s != 0 ? s->readPosition : 0;
  218334. }
  218335. #endif
  218336. /*** End of inlined file: juce_linux_Network.cpp ***/
  218337. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218338. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218339. // compiled on its own).
  218340. #if JUCE_INCLUDED_FILE
  218341. void Logger::outputDebugString (const String& text)
  218342. {
  218343. std::cerr << text << std::endl;
  218344. }
  218345. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218346. {
  218347. return Linux;
  218348. }
  218349. const String SystemStats::getOperatingSystemName()
  218350. {
  218351. return "Linux";
  218352. }
  218353. bool SystemStats::isOperatingSystem64Bit()
  218354. {
  218355. #if JUCE_64BIT
  218356. return true;
  218357. #else
  218358. //xxx not sure how to find this out?..
  218359. return false;
  218360. #endif
  218361. }
  218362. static const String juce_getCpuInfo (const char* const key)
  218363. {
  218364. StringArray lines;
  218365. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218366. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218367. if (lines[i].startsWithIgnoreCase (key))
  218368. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218369. return String::empty;
  218370. }
  218371. const String SystemStats::getCpuVendor()
  218372. {
  218373. return juce_getCpuInfo ("vendor_id");
  218374. }
  218375. int SystemStats::getCpuSpeedInMegaherz()
  218376. {
  218377. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  218378. }
  218379. int SystemStats::getMemorySizeInMegabytes()
  218380. {
  218381. struct sysinfo sysi;
  218382. if (sysinfo (&sysi) == 0)
  218383. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218384. return 0;
  218385. }
  218386. int SystemStats::getPageSize()
  218387. {
  218388. return sysconf (_SC_PAGESIZE);
  218389. }
  218390. const String SystemStats::getLogonName()
  218391. {
  218392. const char* user = getenv ("USER");
  218393. if (user == 0)
  218394. {
  218395. struct passwd* const pw = getpwuid (getuid());
  218396. if (pw != 0)
  218397. user = pw->pw_name;
  218398. }
  218399. return String::fromUTF8 (user);
  218400. }
  218401. const String SystemStats::getFullUserName()
  218402. {
  218403. return getLogonName();
  218404. }
  218405. void SystemStats::initialiseStats()
  218406. {
  218407. const String flags (juce_getCpuInfo ("flags"));
  218408. cpuFlags.hasMMX = flags.contains ("mmx");
  218409. cpuFlags.hasSSE = flags.contains ("sse");
  218410. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218411. cpuFlags.has3DNow = flags.contains ("3dnow");
  218412. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  218413. }
  218414. void PlatformUtilities::fpuReset()
  218415. {
  218416. }
  218417. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  218418. {
  218419. if (gettimeofday (t, 0) != 0)
  218420. return false;
  218421. static unsigned int calibrate = 0;
  218422. static bool calibrated = false;
  218423. if (! calibrated)
  218424. {
  218425. calibrated = true;
  218426. struct sysinfo sysi;
  218427. if (sysinfo (&sysi) == 0)
  218428. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218429. }
  218430. t->tv_sec -= calibrate;
  218431. return true;
  218432. }
  218433. uint32 juce_millisecondsSinceStartup() throw()
  218434. {
  218435. timeval t;
  218436. if (juce_getTimeSinceStartup (&t))
  218437. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218438. return 0;
  218439. }
  218440. int64 Time::getHighResolutionTicks() throw()
  218441. {
  218442. timeval t;
  218443. if (juce_getTimeSinceStartup (&t))
  218444. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218445. return 0;
  218446. }
  218447. int64 Time::getHighResolutionTicksPerSecond() throw()
  218448. {
  218449. return 1000000; // (microseconds)
  218450. }
  218451. double Time::getMillisecondCounterHiRes() throw()
  218452. {
  218453. return getHighResolutionTicks() * 0.001;
  218454. }
  218455. bool Time::setSystemTimeToThisTime() const
  218456. {
  218457. timeval t;
  218458. t.tv_sec = millisSinceEpoch % 1000000;
  218459. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218460. return settimeofday (&t, 0) ? false : true;
  218461. }
  218462. #endif
  218463. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218464. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218465. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218466. // compiled on its own).
  218467. #if JUCE_INCLUDED_FILE
  218468. /*
  218469. Note that a lot of methods that you'd expect to find in this file actually
  218470. live in juce_posix_SharedCode.h!
  218471. */
  218472. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218473. void Process::setPriority (ProcessPriority prior)
  218474. {
  218475. struct sched_param param;
  218476. int policy, maxp, minp;
  218477. const int p = (int) prior;
  218478. if (p <= 1)
  218479. policy = SCHED_OTHER;
  218480. else
  218481. policy = SCHED_RR;
  218482. minp = sched_get_priority_min (policy);
  218483. maxp = sched_get_priority_max (policy);
  218484. if (p < 2)
  218485. param.sched_priority = 0;
  218486. else if (p == 2 )
  218487. // Set to middle of lower realtime priority range
  218488. param.sched_priority = minp + (maxp - minp) / 4;
  218489. else
  218490. // Set to middle of higher realtime priority range
  218491. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218492. pthread_setschedparam (pthread_self(), policy, &param);
  218493. }
  218494. void Process::terminate()
  218495. {
  218496. exit (0);
  218497. }
  218498. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  218499. {
  218500. static char testResult = 0;
  218501. if (testResult == 0)
  218502. {
  218503. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218504. if (testResult >= 0)
  218505. {
  218506. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218507. testResult = 1;
  218508. }
  218509. }
  218510. return testResult < 0;
  218511. }
  218512. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218513. {
  218514. return juce_isRunningUnderDebugger();
  218515. }
  218516. void Process::raisePrivilege()
  218517. {
  218518. // If running suid root, change effective user
  218519. // to root
  218520. if (geteuid() != 0 && getuid() == 0)
  218521. {
  218522. setreuid (geteuid(), getuid());
  218523. setregid (getegid(), getgid());
  218524. }
  218525. }
  218526. void Process::lowerPrivilege()
  218527. {
  218528. // If runing suid root, change effective user
  218529. // back to real user
  218530. if (geteuid() == 0 && getuid() != 0)
  218531. {
  218532. setreuid (geteuid(), getuid());
  218533. setregid (getegid(), getgid());
  218534. }
  218535. }
  218536. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218537. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218538. {
  218539. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218540. }
  218541. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218542. {
  218543. dlclose(handle);
  218544. }
  218545. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218546. {
  218547. return dlsym (libraryHandle, procedureName.toCString());
  218548. }
  218549. #endif
  218550. #endif
  218551. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218552. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218553. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218554. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218555. // compiled on its own).
  218556. #if JUCE_INCLUDED_FILE
  218557. extern Display* display;
  218558. extern Window juce_messageWindowHandle;
  218559. namespace ClipboardHelpers
  218560. {
  218561. static String localClipboardContent;
  218562. static Atom atom_UTF8_STRING;
  218563. static Atom atom_CLIPBOARD;
  218564. static Atom atom_TARGETS;
  218565. static void initSelectionAtoms()
  218566. {
  218567. static bool isInitialised = false;
  218568. if (! isInitialised)
  218569. {
  218570. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218571. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218572. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218573. }
  218574. }
  218575. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218576. // works only for strings shorter than 1000000 bytes
  218577. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218578. {
  218579. String returnData;
  218580. char* clipData;
  218581. Atom actualType;
  218582. int actualFormat;
  218583. unsigned long numItems, bytesLeft;
  218584. if (XGetWindowProperty (display, window, prop,
  218585. 0L /* offset */, 1000000 /* length (max) */, False,
  218586. AnyPropertyType /* format */,
  218587. &actualType, &actualFormat, &numItems, &bytesLeft,
  218588. (unsigned char**) &clipData) == Success)
  218589. {
  218590. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218591. returnData = String::fromUTF8 (clipData, numItems);
  218592. else if (actualType == XA_STRING && actualFormat == 8)
  218593. returnData = String (clipData, numItems);
  218594. if (clipData != 0)
  218595. XFree (clipData);
  218596. jassert (bytesLeft == 0 || numItems == 1000000);
  218597. }
  218598. XDeleteProperty (display, window, prop);
  218599. return returnData;
  218600. }
  218601. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218602. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218603. {
  218604. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218605. // The selection owner will be asked to set the JUCE_SEL property on the
  218606. // juce_messageWindowHandle with the selection content
  218607. XConvertSelection (display, selection, requestedFormat, property_name,
  218608. juce_messageWindowHandle, CurrentTime);
  218609. int count = 50; // will wait at most for 200 ms
  218610. while (--count >= 0)
  218611. {
  218612. XEvent event;
  218613. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218614. {
  218615. if (event.xselection.property == property_name)
  218616. {
  218617. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218618. selectionContent = readWindowProperty (event.xselection.requestor,
  218619. event.xselection.property,
  218620. requestedFormat);
  218621. return true;
  218622. }
  218623. else
  218624. {
  218625. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218626. }
  218627. }
  218628. // not very elegant.. we could do a select() or something like that...
  218629. // however clipboard content requesting is inherently slow on x11, it
  218630. // often takes 50ms or more so...
  218631. Thread::sleep (4);
  218632. }
  218633. return false;
  218634. }
  218635. }
  218636. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218637. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218638. {
  218639. ClipboardHelpers::initSelectionAtoms();
  218640. // the selection content is sent to the target window as a window property
  218641. XSelectionEvent reply;
  218642. reply.type = SelectionNotify;
  218643. reply.display = evt.display;
  218644. reply.requestor = evt.requestor;
  218645. reply.selection = evt.selection;
  218646. reply.target = evt.target;
  218647. reply.property = None; // == "fail"
  218648. reply.time = evt.time;
  218649. HeapBlock <char> data;
  218650. int propertyFormat = 0, numDataItems = 0;
  218651. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218652. {
  218653. if (evt.target == XA_STRING)
  218654. {
  218655. // format data according to system locale
  218656. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218657. data.calloc (numDataItems + 1);
  218658. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218659. propertyFormat = 8; // bits/item
  218660. }
  218661. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218662. {
  218663. // translate to utf8
  218664. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218665. data.calloc (numDataItems + 1);
  218666. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218667. propertyFormat = 8; // bits/item
  218668. }
  218669. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218670. {
  218671. // another application wants to know what we are able to send
  218672. numDataItems = 2;
  218673. propertyFormat = 32; // atoms are 32-bit
  218674. data.calloc (numDataItems * 4);
  218675. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218676. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218677. atoms[1] = XA_STRING;
  218678. }
  218679. }
  218680. else
  218681. {
  218682. DBG ("requested unsupported clipboard");
  218683. }
  218684. if (data != 0)
  218685. {
  218686. const int maxReasonableSelectionSize = 1000000;
  218687. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218688. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218689. {
  218690. XChangeProperty (evt.display, evt.requestor,
  218691. evt.property, evt.target,
  218692. propertyFormat /* 8 or 32 */, PropModeReplace,
  218693. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218694. reply.property = evt.property; // " == success"
  218695. }
  218696. }
  218697. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218698. }
  218699. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218700. {
  218701. ClipboardHelpers::initSelectionAtoms();
  218702. ClipboardHelpers::localClipboardContent = clipText;
  218703. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218704. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218705. }
  218706. const String SystemClipboard::getTextFromClipboard()
  218707. {
  218708. ClipboardHelpers::initSelectionAtoms();
  218709. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218710. level" clipboard that is supposed to be filled by ctrl-C
  218711. etc). When a clipboard manager is running, the content of this
  218712. selection is preserved even when the original selection owner
  218713. exits.
  218714. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218715. filled by good old x11 apps such as xterm)
  218716. */
  218717. String content;
  218718. Atom selection = XA_PRIMARY;
  218719. Window selectionOwner = None;
  218720. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218721. {
  218722. selection = ClipboardHelpers::atom_CLIPBOARD;
  218723. selectionOwner = XGetSelectionOwner (display, selection);
  218724. }
  218725. if (selectionOwner != None)
  218726. {
  218727. if (selectionOwner == juce_messageWindowHandle)
  218728. {
  218729. content = ClipboardHelpers::localClipboardContent;
  218730. }
  218731. else
  218732. {
  218733. // first try: we want an utf8 string
  218734. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218735. if (! ok)
  218736. {
  218737. // second chance, ask for a good old locale-dependent string ..
  218738. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218739. }
  218740. }
  218741. }
  218742. return content;
  218743. }
  218744. #endif
  218745. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218746. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218747. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218748. // compiled on its own).
  218749. #if JUCE_INCLUDED_FILE
  218750. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218751. #define JUCE_DEBUG_XERRORS 1
  218752. #endif
  218753. Display* display = 0;
  218754. Window juce_messageWindowHandle = None;
  218755. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218756. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218757. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218758. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218759. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218760. class InternalMessageQueue
  218761. {
  218762. public:
  218763. InternalMessageQueue()
  218764. : bytesInSocket (0),
  218765. totalEventCount (0)
  218766. {
  218767. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218768. (void) ret; jassert (ret == 0);
  218769. //setNonBlocking (fd[0]);
  218770. //setNonBlocking (fd[1]);
  218771. }
  218772. ~InternalMessageQueue()
  218773. {
  218774. close (fd[0]);
  218775. close (fd[1]);
  218776. clearSingletonInstance();
  218777. }
  218778. void postMessage (Message* msg)
  218779. {
  218780. const int maxBytesInSocketQueue = 128;
  218781. ScopedLock sl (lock);
  218782. queue.add (msg);
  218783. if (bytesInSocket < maxBytesInSocketQueue)
  218784. {
  218785. ++bytesInSocket;
  218786. ScopedUnlock ul (lock);
  218787. const unsigned char x = 0xff;
  218788. size_t bytesWritten = write (fd[0], &x, 1);
  218789. (void) bytesWritten;
  218790. }
  218791. }
  218792. bool isEmpty() const
  218793. {
  218794. ScopedLock sl (lock);
  218795. return queue.size() == 0;
  218796. }
  218797. bool dispatchNextEvent()
  218798. {
  218799. // This alternates between giving priority to XEvents or internal messages,
  218800. // to keep everything running smoothly..
  218801. if ((++totalEventCount & 1) != 0)
  218802. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218803. else
  218804. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218805. }
  218806. // Wait for an event (either XEvent, or an internal Message)
  218807. bool sleepUntilEvent (const int timeoutMs)
  218808. {
  218809. if (! isEmpty())
  218810. return true;
  218811. if (display != 0)
  218812. {
  218813. ScopedXLock xlock;
  218814. if (XPending (display))
  218815. return true;
  218816. }
  218817. struct timeval tv;
  218818. tv.tv_sec = 0;
  218819. tv.tv_usec = timeoutMs * 1000;
  218820. int fd0 = getWaitHandle();
  218821. int fdmax = fd0;
  218822. fd_set readset;
  218823. FD_ZERO (&readset);
  218824. FD_SET (fd0, &readset);
  218825. if (display != 0)
  218826. {
  218827. ScopedXLock xlock;
  218828. int fd1 = XConnectionNumber (display);
  218829. FD_SET (fd1, &readset);
  218830. fdmax = jmax (fd0, fd1);
  218831. }
  218832. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218833. return (ret > 0); // ret <= 0 if error or timeout
  218834. }
  218835. struct MessageThreadFuncCall
  218836. {
  218837. enum { uniqueID = 0x73774623 };
  218838. MessageCallbackFunction* func;
  218839. void* parameter;
  218840. void* result;
  218841. CriticalSection lock;
  218842. WaitableEvent event;
  218843. };
  218844. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218845. private:
  218846. CriticalSection lock;
  218847. OwnedArray <Message> queue;
  218848. int fd[2];
  218849. int bytesInSocket;
  218850. int totalEventCount;
  218851. int getWaitHandle() const throw() { return fd[1]; }
  218852. static bool setNonBlocking (int handle)
  218853. {
  218854. int socketFlags = fcntl (handle, F_GETFL, 0);
  218855. if (socketFlags == -1)
  218856. return false;
  218857. socketFlags |= O_NONBLOCK;
  218858. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218859. }
  218860. static bool dispatchNextXEvent()
  218861. {
  218862. if (display == 0)
  218863. return false;
  218864. XEvent evt;
  218865. {
  218866. ScopedXLock xlock;
  218867. if (! XPending (display))
  218868. return false;
  218869. XNextEvent (display, &evt);
  218870. }
  218871. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218872. juce_handleSelectionRequest (evt.xselectionrequest);
  218873. else if (evt.xany.window != juce_messageWindowHandle)
  218874. juce_windowMessageReceive (&evt);
  218875. return true;
  218876. }
  218877. Message* popNextMessage()
  218878. {
  218879. ScopedLock sl (lock);
  218880. if (bytesInSocket > 0)
  218881. {
  218882. --bytesInSocket;
  218883. ScopedUnlock ul (lock);
  218884. unsigned char x;
  218885. size_t numBytes = read (fd[1], &x, 1);
  218886. (void) numBytes;
  218887. }
  218888. return queue.removeAndReturn (0);
  218889. }
  218890. bool dispatchNextInternalMessage()
  218891. {
  218892. ScopedPointer <Message> msg (popNextMessage());
  218893. if (msg == 0)
  218894. return false;
  218895. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218896. {
  218897. // Handle callback message
  218898. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218899. call->result = (*(call->func)) (call->parameter);
  218900. call->event.signal();
  218901. }
  218902. else
  218903. {
  218904. // Handle "normal" messages
  218905. MessageManager::getInstance()->deliverMessage (msg.release());
  218906. }
  218907. return true;
  218908. }
  218909. };
  218910. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218911. namespace LinuxErrorHandling
  218912. {
  218913. static bool errorOccurred = false;
  218914. static bool keyboardBreakOccurred = false;
  218915. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218916. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218917. // Usually happens when client-server connection is broken
  218918. static int ioErrorHandler (Display* display)
  218919. {
  218920. DBG ("ERROR: connection to X server broken.. terminating.");
  218921. if (JUCEApplication::isStandaloneApp())
  218922. MessageManager::getInstance()->stopDispatchLoop();
  218923. errorOccurred = true;
  218924. return 0;
  218925. }
  218926. // A protocol error has occurred
  218927. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218928. {
  218929. #if JUCE_DEBUG_XERRORS
  218930. char errorStr[64] = { 0 };
  218931. char requestStr[64] = { 0 };
  218932. XGetErrorText (display, event->error_code, errorStr, 64);
  218933. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218934. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218935. #endif
  218936. return 0;
  218937. }
  218938. static void installXErrorHandlers()
  218939. {
  218940. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218941. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218942. }
  218943. static void removeXErrorHandlers()
  218944. {
  218945. XSetIOErrorHandler (oldIOErrorHandler);
  218946. oldIOErrorHandler = 0;
  218947. XSetErrorHandler (oldErrorHandler);
  218948. oldErrorHandler = 0;
  218949. }
  218950. static void keyboardBreakSignalHandler (int sig)
  218951. {
  218952. if (sig == SIGINT)
  218953. keyboardBreakOccurred = true;
  218954. }
  218955. static void installKeyboardBreakHandler()
  218956. {
  218957. struct sigaction saction;
  218958. sigset_t maskSet;
  218959. sigemptyset (&maskSet);
  218960. saction.sa_handler = keyboardBreakSignalHandler;
  218961. saction.sa_mask = maskSet;
  218962. saction.sa_flags = 0;
  218963. sigaction (SIGINT, &saction, 0);
  218964. }
  218965. }
  218966. void MessageManager::doPlatformSpecificInitialisation()
  218967. {
  218968. // Initialise xlib for multiple thread support
  218969. static bool initThreadCalled = false;
  218970. if (! initThreadCalled)
  218971. {
  218972. if (! XInitThreads())
  218973. {
  218974. // This is fatal! Print error and closedown
  218975. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218976. if (JUCEApplication::isStandaloneApp())
  218977. Process::terminate();
  218978. return;
  218979. }
  218980. initThreadCalled = true;
  218981. }
  218982. LinuxErrorHandling::installXErrorHandlers();
  218983. LinuxErrorHandling::installKeyboardBreakHandler();
  218984. // Create the internal message queue
  218985. InternalMessageQueue::getInstance();
  218986. // Try to connect to a display
  218987. String displayName (getenv ("DISPLAY"));
  218988. if (displayName.isEmpty())
  218989. displayName = ":0.0";
  218990. display = XOpenDisplay (displayName.toCString());
  218991. if (display != 0) // This is not fatal! we can run headless.
  218992. {
  218993. // Create a context to store user data associated with Windows we create in WindowDriver
  218994. windowHandleXContext = XUniqueContext();
  218995. // We're only interested in client messages for this window, which are always sent
  218996. XSetWindowAttributes swa;
  218997. swa.event_mask = NoEventMask;
  218998. // Create our message window (this will never be mapped)
  218999. const int screen = DefaultScreen (display);
  219000. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219001. 0, 0, 1, 1, 0, 0, InputOnly,
  219002. DefaultVisual (display, screen),
  219003. CWEventMask, &swa);
  219004. }
  219005. }
  219006. void MessageManager::doPlatformSpecificShutdown()
  219007. {
  219008. InternalMessageQueue::deleteInstance();
  219009. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219010. {
  219011. XDestroyWindow (display, juce_messageWindowHandle);
  219012. XCloseDisplay (display);
  219013. juce_messageWindowHandle = 0;
  219014. display = 0;
  219015. LinuxErrorHandling::removeXErrorHandlers();
  219016. }
  219017. }
  219018. bool juce_postMessageToSystemQueue (Message* message)
  219019. {
  219020. if (LinuxErrorHandling::errorOccurred)
  219021. return false;
  219022. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219023. return true;
  219024. }
  219025. void MessageManager::broadcastMessage (const String& value) throw()
  219026. {
  219027. /* TODO */
  219028. }
  219029. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  219030. void* parameter)
  219031. {
  219032. if (LinuxErrorHandling::errorOccurred)
  219033. return 0;
  219034. if (isThisTheMessageThread())
  219035. return func (parameter);
  219036. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219037. messageCallContext.func = func;
  219038. messageCallContext.parameter = parameter;
  219039. InternalMessageQueue::getInstanceWithoutCreating()
  219040. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219041. 0, 0, &messageCallContext));
  219042. // Wait for it to complete before continuing
  219043. messageCallContext.event.wait();
  219044. return messageCallContext.result;
  219045. }
  219046. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219047. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219048. {
  219049. while (! LinuxErrorHandling::errorOccurred)
  219050. {
  219051. if (LinuxErrorHandling::keyboardBreakOccurred)
  219052. {
  219053. LinuxErrorHandling::errorOccurred = true;
  219054. if (JUCEApplication::isStandaloneApp())
  219055. Process::terminate();
  219056. break;
  219057. }
  219058. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219059. return true;
  219060. if (returnIfNoPendingMessages)
  219061. break;
  219062. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219063. }
  219064. return false;
  219065. }
  219066. #endif
  219067. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219068. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219069. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219070. // compiled on its own).
  219071. #if JUCE_INCLUDED_FILE
  219072. class FreeTypeFontFace
  219073. {
  219074. public:
  219075. enum FontStyle
  219076. {
  219077. Plain = 0,
  219078. Bold = 1,
  219079. Italic = 2
  219080. };
  219081. FreeTypeFontFace (const String& familyName)
  219082. : hasSerif (false),
  219083. monospaced (false)
  219084. {
  219085. family = familyName;
  219086. }
  219087. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219088. {
  219089. if (names [(int) style].fileName.isEmpty())
  219090. {
  219091. names [(int) style].fileName = name;
  219092. names [(int) style].faceIndex = faceIndex;
  219093. }
  219094. }
  219095. const String& getFamilyName() const throw() { return family; }
  219096. const String& getFileName (const int style, int& faceIndex) const throw()
  219097. {
  219098. faceIndex = names[style].faceIndex;
  219099. return names[style].fileName;
  219100. }
  219101. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219102. bool getMonospaced() const throw() { return monospaced; }
  219103. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219104. bool getSerif() const throw() { return hasSerif; }
  219105. private:
  219106. String family;
  219107. struct FontNameIndex
  219108. {
  219109. String fileName;
  219110. int faceIndex;
  219111. };
  219112. FontNameIndex names[4];
  219113. bool hasSerif, monospaced;
  219114. };
  219115. class FreeTypeInterface : public DeletedAtShutdown
  219116. {
  219117. public:
  219118. FreeTypeInterface()
  219119. : ftLib (0),
  219120. lastFace (0),
  219121. lastBold (false),
  219122. lastItalic (false)
  219123. {
  219124. if (FT_Init_FreeType (&ftLib) != 0)
  219125. {
  219126. ftLib = 0;
  219127. DBG ("Failed to initialize FreeType");
  219128. }
  219129. StringArray fontDirs;
  219130. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219131. fontDirs.removeEmptyStrings (true);
  219132. if (fontDirs.size() == 0)
  219133. {
  219134. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219135. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219136. if (fontsInfo != 0)
  219137. {
  219138. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219139. {
  219140. fontDirs.add (e->getAllSubText().trim());
  219141. }
  219142. }
  219143. }
  219144. if (fontDirs.size() == 0)
  219145. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219146. for (int i = 0; i < fontDirs.size(); ++i)
  219147. enumerateFaces (fontDirs[i]);
  219148. }
  219149. ~FreeTypeInterface()
  219150. {
  219151. if (lastFace != 0)
  219152. FT_Done_Face (lastFace);
  219153. if (ftLib != 0)
  219154. FT_Done_FreeType (ftLib);
  219155. clearSingletonInstance();
  219156. }
  219157. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219158. {
  219159. for (int i = 0; i < faces.size(); i++)
  219160. if (faces[i]->getFamilyName() == familyName)
  219161. return faces[i];
  219162. if (! create)
  219163. return 0;
  219164. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219165. faces.add (newFace);
  219166. return newFace;
  219167. }
  219168. // Enumerate all font faces available in a given directory
  219169. void enumerateFaces (const String& path)
  219170. {
  219171. File dirPath (path);
  219172. if (path.isEmpty() || ! dirPath.isDirectory())
  219173. return;
  219174. DirectoryIterator di (dirPath, true);
  219175. while (di.next())
  219176. {
  219177. File possible (di.getFile());
  219178. if (possible.hasFileExtension ("ttf")
  219179. || possible.hasFileExtension ("pfb")
  219180. || possible.hasFileExtension ("pcf"))
  219181. {
  219182. FT_Face face;
  219183. int faceIndex = 0;
  219184. int numFaces = 0;
  219185. do
  219186. {
  219187. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219188. faceIndex, &face) == 0)
  219189. {
  219190. if (faceIndex == 0)
  219191. numFaces = face->num_faces;
  219192. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219193. {
  219194. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219195. int style = (int) FreeTypeFontFace::Plain;
  219196. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219197. style |= (int) FreeTypeFontFace::Bold;
  219198. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219199. style |= (int) FreeTypeFontFace::Italic;
  219200. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219201. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219202. // Surely there must be a better way to do this?
  219203. const String name (face->family_name);
  219204. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219205. || name.containsIgnoreCase ("Verdana")
  219206. || name.containsIgnoreCase ("Arial")));
  219207. }
  219208. FT_Done_Face (face);
  219209. }
  219210. ++faceIndex;
  219211. }
  219212. while (faceIndex < numFaces);
  219213. }
  219214. }
  219215. }
  219216. // Create a FreeType face object for a given font
  219217. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219218. {
  219219. FT_Face face = 0;
  219220. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219221. {
  219222. face = lastFace;
  219223. }
  219224. else
  219225. {
  219226. if (lastFace != 0)
  219227. {
  219228. FT_Done_Face (lastFace);
  219229. lastFace = 0;
  219230. }
  219231. lastFontName = fontName;
  219232. lastBold = bold;
  219233. lastItalic = italic;
  219234. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219235. if (ftFace != 0)
  219236. {
  219237. int style = (int) FreeTypeFontFace::Plain;
  219238. if (bold)
  219239. style |= (int) FreeTypeFontFace::Bold;
  219240. if (italic)
  219241. style |= (int) FreeTypeFontFace::Italic;
  219242. int faceIndex;
  219243. String fileName (ftFace->getFileName (style, faceIndex));
  219244. if (fileName.isEmpty())
  219245. {
  219246. style ^= (int) FreeTypeFontFace::Bold;
  219247. fileName = ftFace->getFileName (style, faceIndex);
  219248. if (fileName.isEmpty())
  219249. {
  219250. style ^= (int) FreeTypeFontFace::Bold;
  219251. style ^= (int) FreeTypeFontFace::Italic;
  219252. fileName = ftFace->getFileName (style, faceIndex);
  219253. if (! fileName.length())
  219254. {
  219255. style ^= (int) FreeTypeFontFace::Bold;
  219256. fileName = ftFace->getFileName (style, faceIndex);
  219257. }
  219258. }
  219259. }
  219260. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219261. {
  219262. face = lastFace;
  219263. // If there isn't a unicode charmap then select the first one.
  219264. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219265. FT_Set_Charmap (face, face->charmaps[0]);
  219266. }
  219267. }
  219268. }
  219269. return face;
  219270. }
  219271. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219272. {
  219273. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219274. const float height = (float) (face->ascender - face->descender);
  219275. const float scaleX = 1.0f / height;
  219276. const float scaleY = -1.0f / height;
  219277. Path destShape;
  219278. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219279. || face->glyph->format != ft_glyph_format_outline)
  219280. {
  219281. return false;
  219282. }
  219283. const FT_Outline* const outline = &face->glyph->outline;
  219284. const short* const contours = outline->contours;
  219285. const char* const tags = outline->tags;
  219286. FT_Vector* const points = outline->points;
  219287. for (int c = 0; c < outline->n_contours; c++)
  219288. {
  219289. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219290. const int endPoint = contours[c];
  219291. for (int p = startPoint; p <= endPoint; p++)
  219292. {
  219293. const float x = scaleX * points[p].x;
  219294. const float y = scaleY * points[p].y;
  219295. if (p == startPoint)
  219296. {
  219297. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219298. {
  219299. float x2 = scaleX * points [endPoint].x;
  219300. float y2 = scaleY * points [endPoint].y;
  219301. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219302. {
  219303. x2 = (x + x2) * 0.5f;
  219304. y2 = (y + y2) * 0.5f;
  219305. }
  219306. destShape.startNewSubPath (x2, y2);
  219307. }
  219308. else
  219309. {
  219310. destShape.startNewSubPath (x, y);
  219311. }
  219312. }
  219313. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219314. {
  219315. if (p != startPoint)
  219316. destShape.lineTo (x, y);
  219317. }
  219318. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219319. {
  219320. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219321. float x2 = scaleX * points [nextIndex].x;
  219322. float y2 = scaleY * points [nextIndex].y;
  219323. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219324. {
  219325. x2 = (x + x2) * 0.5f;
  219326. y2 = (y + y2) * 0.5f;
  219327. }
  219328. else
  219329. {
  219330. ++p;
  219331. }
  219332. destShape.quadraticTo (x, y, x2, y2);
  219333. }
  219334. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219335. {
  219336. if (p >= endPoint)
  219337. return false;
  219338. const int next1 = p + 1;
  219339. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219340. const float x2 = scaleX * points [next1].x;
  219341. const float y2 = scaleY * points [next1].y;
  219342. const float x3 = scaleX * points [next2].x;
  219343. const float y3 = scaleY * points [next2].y;
  219344. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219345. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219346. return false;
  219347. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219348. p += 2;
  219349. }
  219350. }
  219351. destShape.closeSubPath();
  219352. }
  219353. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219354. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219355. addKerning (face, dest, character, glyphIndex);
  219356. return true;
  219357. }
  219358. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219359. {
  219360. const float height = (float) (face->ascender - face->descender);
  219361. uint32 rightGlyphIndex;
  219362. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219363. while (rightGlyphIndex != 0)
  219364. {
  219365. FT_Vector kerning;
  219366. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219367. {
  219368. if (kerning.x != 0)
  219369. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219370. }
  219371. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219372. }
  219373. }
  219374. // Add a glyph to a font
  219375. bool addGlyphToFont (const uint32 character, const String& fontName,
  219376. bool bold, bool italic, CustomTypeface& dest)
  219377. {
  219378. FT_Face face = createFT_Face (fontName, bold, italic);
  219379. return face != 0 && addGlyph (face, dest, character);
  219380. }
  219381. void getFamilyNames (StringArray& familyNames) const
  219382. {
  219383. for (int i = 0; i < faces.size(); i++)
  219384. familyNames.add (faces[i]->getFamilyName());
  219385. }
  219386. void getMonospacedNames (StringArray& monoSpaced) const
  219387. {
  219388. for (int i = 0; i < faces.size(); i++)
  219389. if (faces[i]->getMonospaced())
  219390. monoSpaced.add (faces[i]->getFamilyName());
  219391. }
  219392. void getSerifNames (StringArray& serif) const
  219393. {
  219394. for (int i = 0; i < faces.size(); i++)
  219395. if (faces[i]->getSerif())
  219396. serif.add (faces[i]->getFamilyName());
  219397. }
  219398. void getSansSerifNames (StringArray& sansSerif) const
  219399. {
  219400. for (int i = 0; i < faces.size(); i++)
  219401. if (! faces[i]->getSerif())
  219402. sansSerif.add (faces[i]->getFamilyName());
  219403. }
  219404. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219405. private:
  219406. FT_Library ftLib;
  219407. FT_Face lastFace;
  219408. String lastFontName;
  219409. bool lastBold, lastItalic;
  219410. OwnedArray<FreeTypeFontFace> faces;
  219411. };
  219412. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219413. class FreetypeTypeface : public CustomTypeface
  219414. {
  219415. public:
  219416. FreetypeTypeface (const Font& font)
  219417. {
  219418. FT_Face face = FreeTypeInterface::getInstance()
  219419. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219420. if (face == 0)
  219421. {
  219422. #if JUCE_DEBUG
  219423. String msg ("Failed to create typeface: ");
  219424. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219425. DBG (msg);
  219426. #endif
  219427. }
  219428. else
  219429. {
  219430. setCharacteristics (font.getTypefaceName(),
  219431. face->ascender / (float) (face->ascender - face->descender),
  219432. font.isBold(), font.isItalic(),
  219433. L' ');
  219434. }
  219435. }
  219436. bool loadGlyphIfPossible (juce_wchar character)
  219437. {
  219438. return FreeTypeInterface::getInstance()
  219439. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219440. }
  219441. };
  219442. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219443. {
  219444. return new FreetypeTypeface (font);
  219445. }
  219446. const StringArray Font::findAllTypefaceNames()
  219447. {
  219448. StringArray s;
  219449. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219450. s.sort (true);
  219451. return s;
  219452. }
  219453. static const String pickBestFont (const StringArray& names,
  219454. const char* const choicesString)
  219455. {
  219456. StringArray choices;
  219457. choices.addTokens (String (choicesString), ",", String::empty);
  219458. choices.trim();
  219459. choices.removeEmptyStrings();
  219460. int i, j;
  219461. for (j = 0; j < choices.size(); ++j)
  219462. if (names.contains (choices[j], true))
  219463. return choices[j];
  219464. for (j = 0; j < choices.size(); ++j)
  219465. for (i = 0; i < names.size(); i++)
  219466. if (names[i].startsWithIgnoreCase (choices[j]))
  219467. return names[i];
  219468. for (j = 0; j < choices.size(); ++j)
  219469. for (i = 0; i < names.size(); i++)
  219470. if (names[i].containsIgnoreCase (choices[j]))
  219471. return names[i];
  219472. return names[0];
  219473. }
  219474. static const String linux_getDefaultSansSerifFontName()
  219475. {
  219476. StringArray allFonts;
  219477. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219478. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219479. }
  219480. static const String linux_getDefaultSerifFontName()
  219481. {
  219482. StringArray allFonts;
  219483. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219484. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219485. }
  219486. static const String linux_getDefaultMonospacedFontName()
  219487. {
  219488. StringArray allFonts;
  219489. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219490. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219491. }
  219492. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219493. {
  219494. defaultSans = linux_getDefaultSansSerifFontName();
  219495. defaultSerif = linux_getDefaultSerifFontName();
  219496. defaultFixed = linux_getDefaultMonospacedFontName();
  219497. }
  219498. #endif
  219499. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219500. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219501. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219502. // compiled on its own).
  219503. #if JUCE_INCLUDED_FILE
  219504. // These are defined in juce_linux_Messaging.cpp
  219505. extern Display* display;
  219506. extern XContext windowHandleXContext;
  219507. namespace Atoms
  219508. {
  219509. enum ProtocolItems
  219510. {
  219511. TAKE_FOCUS = 0,
  219512. DELETE_WINDOW = 1,
  219513. PING = 2
  219514. };
  219515. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219516. ActiveWin, Pid, WindowType, WindowState,
  219517. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219518. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219519. XdndActionDescription, XdndActionCopy,
  219520. allowedActions[5],
  219521. allowedMimeTypes[2];
  219522. const unsigned long DndVersion = 3;
  219523. static void initialiseAtoms()
  219524. {
  219525. static bool atomsInitialised = false;
  219526. if (! atomsInitialised)
  219527. {
  219528. atomsInitialised = true;
  219529. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219530. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219531. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219532. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219533. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219534. State = XInternAtom (display, "WM_STATE", True);
  219535. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219536. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219537. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219538. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219539. XdndAware = XInternAtom (display, "XdndAware", False);
  219540. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219541. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219542. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219543. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219544. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219545. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219546. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219547. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219548. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219549. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219550. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219551. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219552. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219553. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219554. allowedActions[1] = XdndActionCopy;
  219555. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219556. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219557. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219558. }
  219559. }
  219560. }
  219561. namespace Keys
  219562. {
  219563. enum MouseButtons
  219564. {
  219565. NoButton = 0,
  219566. LeftButton = 1,
  219567. MiddleButton = 2,
  219568. RightButton = 3,
  219569. WheelUp = 4,
  219570. WheelDown = 5
  219571. };
  219572. static int AltMask = 0;
  219573. static int NumLockMask = 0;
  219574. static bool numLock = false;
  219575. static bool capsLock = false;
  219576. static char keyStates [32];
  219577. static const int extendedKeyModifier = 0x10000000;
  219578. }
  219579. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219580. {
  219581. int keysym;
  219582. if (keyCode & Keys::extendedKeyModifier)
  219583. {
  219584. keysym = 0xff00 | (keyCode & 0xff);
  219585. }
  219586. else
  219587. {
  219588. keysym = keyCode;
  219589. if (keysym == (XK_Tab & 0xff)
  219590. || keysym == (XK_Return & 0xff)
  219591. || keysym == (XK_Escape & 0xff)
  219592. || keysym == (XK_BackSpace & 0xff))
  219593. {
  219594. keysym |= 0xff00;
  219595. }
  219596. }
  219597. ScopedXLock xlock;
  219598. const int keycode = XKeysymToKeycode (display, keysym);
  219599. const int keybyte = keycode >> 3;
  219600. const int keybit = (1 << (keycode & 7));
  219601. return (Keys::keyStates [keybyte] & keybit) != 0;
  219602. }
  219603. #if JUCE_USE_XSHM
  219604. namespace XSHMHelpers
  219605. {
  219606. static int trappedErrorCode = 0;
  219607. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219608. {
  219609. trappedErrorCode = err->error_code;
  219610. return 0;
  219611. }
  219612. static bool isShmAvailable() throw()
  219613. {
  219614. static bool isChecked = false;
  219615. static bool isAvailable = false;
  219616. if (! isChecked)
  219617. {
  219618. isChecked = true;
  219619. int major, minor;
  219620. Bool pixmaps;
  219621. ScopedXLock xlock;
  219622. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219623. {
  219624. trappedErrorCode = 0;
  219625. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219626. XShmSegmentInfo segmentInfo;
  219627. zerostruct (segmentInfo);
  219628. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219629. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219630. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219631. xImage->bytes_per_line * xImage->height,
  219632. IPC_CREAT | 0777)) >= 0)
  219633. {
  219634. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219635. if (segmentInfo.shmaddr != (void*) -1)
  219636. {
  219637. segmentInfo.readOnly = False;
  219638. xImage->data = segmentInfo.shmaddr;
  219639. XSync (display, False);
  219640. if (XShmAttach (display, &segmentInfo) != 0)
  219641. {
  219642. XSync (display, False);
  219643. XShmDetach (display, &segmentInfo);
  219644. isAvailable = true;
  219645. }
  219646. }
  219647. XFlush (display);
  219648. XDestroyImage (xImage);
  219649. shmdt (segmentInfo.shmaddr);
  219650. }
  219651. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219652. XSetErrorHandler (oldHandler);
  219653. if (trappedErrorCode != 0)
  219654. isAvailable = false;
  219655. }
  219656. }
  219657. return isAvailable;
  219658. }
  219659. }
  219660. #endif
  219661. #if JUCE_USE_XRENDER
  219662. namespace XRender
  219663. {
  219664. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219665. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219666. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219667. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219668. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219669. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219670. static tXRenderFindFormat xRenderFindFormat = 0;
  219671. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219672. static bool isAvailable()
  219673. {
  219674. static bool hasLoaded = false;
  219675. if (! hasLoaded)
  219676. {
  219677. ScopedXLock xlock;
  219678. hasLoaded = true;
  219679. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219680. if (h != 0)
  219681. {
  219682. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219683. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219684. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219685. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219686. }
  219687. if (xRenderQueryVersion != 0
  219688. && xRenderFindStandardFormat != 0
  219689. && xRenderFindFormat != 0
  219690. && xRenderFindVisualFormat != 0)
  219691. {
  219692. int major, minor;
  219693. if (xRenderQueryVersion (display, &major, &minor))
  219694. return true;
  219695. }
  219696. xRenderQueryVersion = 0;
  219697. }
  219698. return xRenderQueryVersion != 0;
  219699. }
  219700. static XRenderPictFormat* findPictureFormat()
  219701. {
  219702. ScopedXLock xlock;
  219703. XRenderPictFormat* pictFormat = 0;
  219704. if (isAvailable())
  219705. {
  219706. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219707. if (pictFormat == 0)
  219708. {
  219709. XRenderPictFormat desiredFormat;
  219710. desiredFormat.type = PictTypeDirect;
  219711. desiredFormat.depth = 32;
  219712. desiredFormat.direct.alphaMask = 0xff;
  219713. desiredFormat.direct.redMask = 0xff;
  219714. desiredFormat.direct.greenMask = 0xff;
  219715. desiredFormat.direct.blueMask = 0xff;
  219716. desiredFormat.direct.alpha = 24;
  219717. desiredFormat.direct.red = 16;
  219718. desiredFormat.direct.green = 8;
  219719. desiredFormat.direct.blue = 0;
  219720. pictFormat = xRenderFindFormat (display,
  219721. PictFormatType | PictFormatDepth
  219722. | PictFormatRedMask | PictFormatRed
  219723. | PictFormatGreenMask | PictFormatGreen
  219724. | PictFormatBlueMask | PictFormatBlue
  219725. | PictFormatAlphaMask | PictFormatAlpha,
  219726. &desiredFormat,
  219727. 0);
  219728. }
  219729. }
  219730. return pictFormat;
  219731. }
  219732. }
  219733. #endif
  219734. namespace Visuals
  219735. {
  219736. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219737. {
  219738. ScopedXLock xlock;
  219739. Visual* visual = 0;
  219740. int numVisuals = 0;
  219741. long desiredMask = VisualNoMask;
  219742. XVisualInfo desiredVisual;
  219743. desiredVisual.screen = DefaultScreen (display);
  219744. desiredVisual.depth = desiredDepth;
  219745. desiredMask = VisualScreenMask | VisualDepthMask;
  219746. if (desiredDepth == 32)
  219747. {
  219748. desiredVisual.c_class = TrueColor;
  219749. desiredVisual.red_mask = 0x00FF0000;
  219750. desiredVisual.green_mask = 0x0000FF00;
  219751. desiredVisual.blue_mask = 0x000000FF;
  219752. desiredVisual.bits_per_rgb = 8;
  219753. desiredMask |= VisualClassMask;
  219754. desiredMask |= VisualRedMaskMask;
  219755. desiredMask |= VisualGreenMaskMask;
  219756. desiredMask |= VisualBlueMaskMask;
  219757. desiredMask |= VisualBitsPerRGBMask;
  219758. }
  219759. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219760. desiredMask,
  219761. &desiredVisual,
  219762. &numVisuals);
  219763. if (xvinfos != 0)
  219764. {
  219765. for (int i = 0; i < numVisuals; i++)
  219766. {
  219767. if (xvinfos[i].depth == desiredDepth)
  219768. {
  219769. visual = xvinfos[i].visual;
  219770. break;
  219771. }
  219772. }
  219773. XFree (xvinfos);
  219774. }
  219775. return visual;
  219776. }
  219777. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219778. {
  219779. Visual* visual = 0;
  219780. if (desiredDepth == 32)
  219781. {
  219782. #if JUCE_USE_XSHM
  219783. if (XSHMHelpers::isShmAvailable())
  219784. {
  219785. #if JUCE_USE_XRENDER
  219786. if (XRender::isAvailable())
  219787. {
  219788. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219789. if (pictFormat != 0)
  219790. {
  219791. int numVisuals = 0;
  219792. XVisualInfo desiredVisual;
  219793. desiredVisual.screen = DefaultScreen (display);
  219794. desiredVisual.depth = 32;
  219795. desiredVisual.bits_per_rgb = 8;
  219796. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219797. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219798. &desiredVisual, &numVisuals);
  219799. if (xvinfos != 0)
  219800. {
  219801. for (int i = 0; i < numVisuals; ++i)
  219802. {
  219803. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219804. if (pictVisualFormat != 0
  219805. && pictVisualFormat->type == PictTypeDirect
  219806. && pictVisualFormat->direct.alphaMask)
  219807. {
  219808. visual = xvinfos[i].visual;
  219809. matchedDepth = 32;
  219810. break;
  219811. }
  219812. }
  219813. XFree (xvinfos);
  219814. }
  219815. }
  219816. }
  219817. #endif
  219818. if (visual == 0)
  219819. {
  219820. visual = findVisualWithDepth (32);
  219821. if (visual != 0)
  219822. matchedDepth = 32;
  219823. }
  219824. }
  219825. #endif
  219826. }
  219827. if (visual == 0 && desiredDepth >= 24)
  219828. {
  219829. visual = findVisualWithDepth (24);
  219830. if (visual != 0)
  219831. matchedDepth = 24;
  219832. }
  219833. if (visual == 0 && desiredDepth >= 16)
  219834. {
  219835. visual = findVisualWithDepth (16);
  219836. if (visual != 0)
  219837. matchedDepth = 16;
  219838. }
  219839. return visual;
  219840. }
  219841. }
  219842. class XBitmapImage : public Image::SharedImage
  219843. {
  219844. public:
  219845. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219846. const bool clearImage, const int imageDepth_, Visual* visual)
  219847. : Image::SharedImage (format_, w, h),
  219848. imageDepth (imageDepth_),
  219849. gc (None)
  219850. {
  219851. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219852. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219853. lineStride = ((w * pixelStride + 3) & ~3);
  219854. ScopedXLock xlock;
  219855. #if JUCE_USE_XSHM
  219856. usingXShm = false;
  219857. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219858. {
  219859. zerostruct (segmentInfo);
  219860. segmentInfo.shmid = -1;
  219861. segmentInfo.shmaddr = (char *) -1;
  219862. segmentInfo.readOnly = False;
  219863. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219864. if (xImage != 0)
  219865. {
  219866. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219867. xImage->bytes_per_line * xImage->height,
  219868. IPC_CREAT | 0777)) >= 0)
  219869. {
  219870. if (segmentInfo.shmid != -1)
  219871. {
  219872. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219873. if (segmentInfo.shmaddr != (void*) -1)
  219874. {
  219875. segmentInfo.readOnly = False;
  219876. xImage->data = segmentInfo.shmaddr;
  219877. imageData = (uint8*) segmentInfo.shmaddr;
  219878. if (XShmAttach (display, &segmentInfo) != 0)
  219879. usingXShm = true;
  219880. else
  219881. jassertfalse;
  219882. }
  219883. else
  219884. {
  219885. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219886. }
  219887. }
  219888. }
  219889. }
  219890. }
  219891. if (! usingXShm)
  219892. #endif
  219893. {
  219894. imageDataAllocated.malloc (lineStride * h);
  219895. imageData = imageDataAllocated;
  219896. if (format_ == Image::ARGB && clearImage)
  219897. zeromem (imageData, h * lineStride);
  219898. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219899. xImage->width = w;
  219900. xImage->height = h;
  219901. xImage->xoffset = 0;
  219902. xImage->format = ZPixmap;
  219903. xImage->data = (char*) imageData;
  219904. xImage->byte_order = ImageByteOrder (display);
  219905. xImage->bitmap_unit = BitmapUnit (display);
  219906. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219907. xImage->bitmap_pad = 32;
  219908. xImage->depth = pixelStride * 8;
  219909. xImage->bytes_per_line = lineStride;
  219910. xImage->bits_per_pixel = pixelStride * 8;
  219911. xImage->red_mask = 0x00FF0000;
  219912. xImage->green_mask = 0x0000FF00;
  219913. xImage->blue_mask = 0x000000FF;
  219914. if (imageDepth == 16)
  219915. {
  219916. const int pixelStride = 2;
  219917. const int lineStride = ((w * pixelStride + 3) & ~3);
  219918. imageData16Bit.malloc (lineStride * h);
  219919. xImage->data = imageData16Bit;
  219920. xImage->bitmap_pad = 16;
  219921. xImage->depth = pixelStride * 8;
  219922. xImage->bytes_per_line = lineStride;
  219923. xImage->bits_per_pixel = pixelStride * 8;
  219924. xImage->red_mask = visual->red_mask;
  219925. xImage->green_mask = visual->green_mask;
  219926. xImage->blue_mask = visual->blue_mask;
  219927. }
  219928. if (! XInitImage (xImage))
  219929. jassertfalse;
  219930. }
  219931. }
  219932. ~XBitmapImage()
  219933. {
  219934. ScopedXLock xlock;
  219935. if (gc != None)
  219936. XFreeGC (display, gc);
  219937. #if JUCE_USE_XSHM
  219938. if (usingXShm)
  219939. {
  219940. XShmDetach (display, &segmentInfo);
  219941. XFlush (display);
  219942. XDestroyImage (xImage);
  219943. shmdt (segmentInfo.shmaddr);
  219944. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219945. }
  219946. else
  219947. #endif
  219948. {
  219949. xImage->data = 0;
  219950. XDestroyImage (xImage);
  219951. }
  219952. }
  219953. Image::ImageType getType() const { return Image::NativeImage; }
  219954. LowLevelGraphicsContext* createLowLevelContext()
  219955. {
  219956. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219957. }
  219958. SharedImage* clone()
  219959. {
  219960. jassertfalse;
  219961. return 0;
  219962. }
  219963. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219964. {
  219965. ScopedXLock xlock;
  219966. if (gc == None)
  219967. {
  219968. XGCValues gcvalues;
  219969. gcvalues.foreground = None;
  219970. gcvalues.background = None;
  219971. gcvalues.function = GXcopy;
  219972. gcvalues.plane_mask = AllPlanes;
  219973. gcvalues.clip_mask = None;
  219974. gcvalues.graphics_exposures = False;
  219975. gc = XCreateGC (display, window,
  219976. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219977. &gcvalues);
  219978. }
  219979. if (imageDepth == 16)
  219980. {
  219981. const uint32 rMask = xImage->red_mask;
  219982. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219983. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219984. const uint32 gMask = xImage->green_mask;
  219985. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219986. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219987. const uint32 bMask = xImage->blue_mask;
  219988. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219989. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219990. const Image::BitmapData srcData (Image (this), false);
  219991. for (int y = sy; y < sy + dh; ++y)
  219992. {
  219993. const uint8* p = srcData.getPixelPointer (sx, y);
  219994. for (int x = sx; x < sx + dw; ++x)
  219995. {
  219996. const PixelRGB* const pixel = (const PixelRGB*) p;
  219997. p += srcData.pixelStride;
  219998. XPutPixel (xImage, x, y,
  219999. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220000. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220001. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220002. }
  220003. }
  220004. }
  220005. // blit results to screen.
  220006. #if JUCE_USE_XSHM
  220007. if (usingXShm)
  220008. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220009. else
  220010. #endif
  220011. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220012. }
  220013. juce_UseDebuggingNewOperator
  220014. private:
  220015. XImage* xImage;
  220016. const int imageDepth;
  220017. HeapBlock <uint8> imageDataAllocated;
  220018. HeapBlock <char> imageData16Bit;
  220019. GC gc;
  220020. #if JUCE_USE_XSHM
  220021. XShmSegmentInfo segmentInfo;
  220022. bool usingXShm;
  220023. #endif
  220024. static int getShiftNeeded (const uint32 mask) throw()
  220025. {
  220026. for (int i = 32; --i >= 0;)
  220027. if (((mask >> i) & 1) != 0)
  220028. return i - 7;
  220029. jassertfalse;
  220030. return 0;
  220031. }
  220032. };
  220033. class LinuxComponentPeer : public ComponentPeer
  220034. {
  220035. public:
  220036. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220037. : ComponentPeer (component, windowStyleFlags),
  220038. windowH (0),
  220039. parentWindow (0),
  220040. wx (0),
  220041. wy (0),
  220042. ww (0),
  220043. wh (0),
  220044. fullScreen (false),
  220045. mapped (false),
  220046. visual (0),
  220047. depth (0)
  220048. {
  220049. // it's dangerous to create a window on a thread other than the message thread..
  220050. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220051. repainter = new LinuxRepaintManager (this);
  220052. createWindow();
  220053. setTitle (component->getName());
  220054. }
  220055. ~LinuxComponentPeer()
  220056. {
  220057. // it's dangerous to delete a window on a thread other than the message thread..
  220058. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220059. deleteIconPixmaps();
  220060. destroyWindow();
  220061. windowH = 0;
  220062. }
  220063. void* getNativeHandle() const
  220064. {
  220065. return (void*) windowH;
  220066. }
  220067. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220068. {
  220069. XPointer peer = 0;
  220070. ScopedXLock xlock;
  220071. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220072. {
  220073. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220074. peer = 0;
  220075. }
  220076. return (LinuxComponentPeer*) peer;
  220077. }
  220078. void setVisible (bool shouldBeVisible)
  220079. {
  220080. ScopedXLock xlock;
  220081. if (shouldBeVisible)
  220082. XMapWindow (display, windowH);
  220083. else
  220084. XUnmapWindow (display, windowH);
  220085. }
  220086. void setTitle (const String& title)
  220087. {
  220088. setWindowTitle (windowH, title);
  220089. }
  220090. void setPosition (int x, int y)
  220091. {
  220092. setBounds (x, y, ww, wh, false);
  220093. }
  220094. void setSize (int w, int h)
  220095. {
  220096. setBounds (wx, wy, w, h, false);
  220097. }
  220098. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220099. {
  220100. fullScreen = isNowFullScreen;
  220101. if (windowH != 0)
  220102. {
  220103. Component::SafePointer<Component> deletionChecker (component);
  220104. wx = x;
  220105. wy = y;
  220106. ww = jmax (1, w);
  220107. wh = jmax (1, h);
  220108. ScopedXLock xlock;
  220109. // Make sure the Window manager does what we want
  220110. XSizeHints* hints = XAllocSizeHints();
  220111. hints->flags = USSize | USPosition;
  220112. hints->width = ww;
  220113. hints->height = wh;
  220114. hints->x = wx;
  220115. hints->y = wy;
  220116. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220117. {
  220118. hints->min_width = hints->max_width = hints->width;
  220119. hints->min_height = hints->max_height = hints->height;
  220120. hints->flags |= PMinSize | PMaxSize;
  220121. }
  220122. XSetWMNormalHints (display, windowH, hints);
  220123. XFree (hints);
  220124. XMoveResizeWindow (display, windowH,
  220125. wx - windowBorder.getLeft(),
  220126. wy - windowBorder.getTop(), ww, wh);
  220127. if (deletionChecker != 0)
  220128. {
  220129. updateBorderSize();
  220130. handleMovedOrResized();
  220131. }
  220132. }
  220133. }
  220134. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220135. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220136. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220137. {
  220138. return relativePosition + getScreenPosition();
  220139. }
  220140. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220141. {
  220142. return screenPosition - getScreenPosition();
  220143. }
  220144. void setMinimised (bool shouldBeMinimised)
  220145. {
  220146. if (shouldBeMinimised)
  220147. {
  220148. Window root = RootWindow (display, DefaultScreen (display));
  220149. XClientMessageEvent clientMsg;
  220150. clientMsg.display = display;
  220151. clientMsg.window = windowH;
  220152. clientMsg.type = ClientMessage;
  220153. clientMsg.format = 32;
  220154. clientMsg.message_type = Atoms::ChangeState;
  220155. clientMsg.data.l[0] = IconicState;
  220156. ScopedXLock xlock;
  220157. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220158. }
  220159. else
  220160. {
  220161. setVisible (true);
  220162. }
  220163. }
  220164. bool isMinimised() const
  220165. {
  220166. bool minimised = false;
  220167. unsigned char* stateProp;
  220168. unsigned long nitems, bytesLeft;
  220169. Atom actualType;
  220170. int actualFormat;
  220171. ScopedXLock xlock;
  220172. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220173. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220174. &stateProp) == Success
  220175. && actualType == Atoms::State
  220176. && actualFormat == 32
  220177. && nitems > 0)
  220178. {
  220179. if (((unsigned long*) stateProp)[0] == IconicState)
  220180. minimised = true;
  220181. XFree (stateProp);
  220182. }
  220183. return minimised;
  220184. }
  220185. void setFullScreen (const bool shouldBeFullScreen)
  220186. {
  220187. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220188. setMinimised (false);
  220189. if (fullScreen != shouldBeFullScreen)
  220190. {
  220191. if (shouldBeFullScreen)
  220192. r = Desktop::getInstance().getMainMonitorArea();
  220193. if (! r.isEmpty())
  220194. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220195. getComponent()->repaint();
  220196. }
  220197. }
  220198. bool isFullScreen() const
  220199. {
  220200. return fullScreen;
  220201. }
  220202. bool isChildWindowOf (Window possibleParent) const
  220203. {
  220204. Window* windowList = 0;
  220205. uint32 windowListSize = 0;
  220206. Window parent, root;
  220207. ScopedXLock xlock;
  220208. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220209. {
  220210. if (windowList != 0)
  220211. XFree (windowList);
  220212. return parent == possibleParent;
  220213. }
  220214. return false;
  220215. }
  220216. bool isFrontWindow() const
  220217. {
  220218. Window* windowList = 0;
  220219. uint32 windowListSize = 0;
  220220. bool result = false;
  220221. ScopedXLock xlock;
  220222. Window parent, root = RootWindow (display, DefaultScreen (display));
  220223. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220224. {
  220225. for (int i = windowListSize; --i >= 0;)
  220226. {
  220227. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220228. if (peer != 0)
  220229. {
  220230. result = (peer == this);
  220231. break;
  220232. }
  220233. }
  220234. }
  220235. if (windowList != 0)
  220236. XFree (windowList);
  220237. return result;
  220238. }
  220239. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220240. {
  220241. int x = position.getX();
  220242. int y = position.getY();
  220243. if (((unsigned int) x) >= (unsigned int) ww
  220244. || ((unsigned int) y) >= (unsigned int) wh)
  220245. return false;
  220246. bool inFront = false;
  220247. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220248. {
  220249. Component* const c = Desktop::getInstance().getComponent (i);
  220250. if (inFront)
  220251. {
  220252. if (c->contains (x + wx - c->getScreenX(),
  220253. y + wy - c->getScreenY()))
  220254. {
  220255. return false;
  220256. }
  220257. }
  220258. else if (c == getComponent())
  220259. {
  220260. inFront = true;
  220261. }
  220262. }
  220263. if (trueIfInAChildWindow)
  220264. return true;
  220265. ::Window root, child;
  220266. unsigned int bw, depth;
  220267. int wx, wy, w, h;
  220268. ScopedXLock xlock;
  220269. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220270. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220271. &bw, &depth))
  220272. {
  220273. return false;
  220274. }
  220275. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220276. return false;
  220277. return child == None;
  220278. }
  220279. const BorderSize getFrameSize() const
  220280. {
  220281. return BorderSize();
  220282. }
  220283. bool setAlwaysOnTop (bool alwaysOnTop)
  220284. {
  220285. return false;
  220286. }
  220287. void toFront (bool makeActive)
  220288. {
  220289. if (makeActive)
  220290. {
  220291. setVisible (true);
  220292. grabFocus();
  220293. }
  220294. XEvent ev;
  220295. ev.xclient.type = ClientMessage;
  220296. ev.xclient.serial = 0;
  220297. ev.xclient.send_event = True;
  220298. ev.xclient.message_type = Atoms::ActiveWin;
  220299. ev.xclient.window = windowH;
  220300. ev.xclient.format = 32;
  220301. ev.xclient.data.l[0] = 2;
  220302. ev.xclient.data.l[1] = CurrentTime;
  220303. ev.xclient.data.l[2] = 0;
  220304. ev.xclient.data.l[3] = 0;
  220305. ev.xclient.data.l[4] = 0;
  220306. {
  220307. ScopedXLock xlock;
  220308. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220309. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220310. XWindowAttributes attr;
  220311. XGetWindowAttributes (display, windowH, &attr);
  220312. if (component->isAlwaysOnTop())
  220313. XRaiseWindow (display, windowH);
  220314. XSync (display, False);
  220315. }
  220316. handleBroughtToFront();
  220317. }
  220318. void toBehind (ComponentPeer* other)
  220319. {
  220320. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220321. jassert (otherPeer != 0); // wrong type of window?
  220322. if (otherPeer != 0)
  220323. {
  220324. setMinimised (false);
  220325. Window newStack[] = { otherPeer->windowH, windowH };
  220326. ScopedXLock xlock;
  220327. XRestackWindows (display, newStack, 2);
  220328. }
  220329. }
  220330. bool isFocused() const
  220331. {
  220332. int revert = 0;
  220333. Window focusedWindow = 0;
  220334. ScopedXLock xlock;
  220335. XGetInputFocus (display, &focusedWindow, &revert);
  220336. return focusedWindow == windowH;
  220337. }
  220338. void grabFocus()
  220339. {
  220340. XWindowAttributes atts;
  220341. ScopedXLock xlock;
  220342. if (windowH != 0
  220343. && XGetWindowAttributes (display, windowH, &atts)
  220344. && atts.map_state == IsViewable
  220345. && ! isFocused())
  220346. {
  220347. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220348. isActiveApplication = true;
  220349. }
  220350. }
  220351. void textInputRequired (const Point<int>&)
  220352. {
  220353. }
  220354. void repaint (const Rectangle<int>& area)
  220355. {
  220356. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220357. }
  220358. void performAnyPendingRepaintsNow()
  220359. {
  220360. repainter->performAnyPendingRepaintsNow();
  220361. }
  220362. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220363. {
  220364. ScopedXLock xlock;
  220365. const int width = image.getWidth();
  220366. const int height = image.getHeight();
  220367. HeapBlock <char> colour (width * height);
  220368. int index = 0;
  220369. for (int y = 0; y < height; ++y)
  220370. for (int x = 0; x < width; ++x)
  220371. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  220372. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220373. 0, colour.getData(),
  220374. width, height, 32, 0);
  220375. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220376. width, height, 24);
  220377. GC gc = XCreateGC (display, pixmap, 0, 0);
  220378. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220379. XFreeGC (display, gc);
  220380. return pixmap;
  220381. }
  220382. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220383. {
  220384. ScopedXLock xlock;
  220385. const int width = image.getWidth();
  220386. const int height = image.getHeight();
  220387. const int stride = (width + 7) >> 3;
  220388. HeapBlock <char> mask;
  220389. mask.calloc (stride * height);
  220390. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220391. for (int y = 0; y < height; ++y)
  220392. {
  220393. for (int x = 0; x < width; ++x)
  220394. {
  220395. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220396. const int offset = y * stride + (x >> 3);
  220397. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220398. mask[offset] |= bit;
  220399. }
  220400. }
  220401. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220402. mask.getData(), width, height, 1, 0, 1);
  220403. }
  220404. void setIcon (const Image& newIcon)
  220405. {
  220406. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220407. HeapBlock <unsigned long> data (dataSize);
  220408. int index = 0;
  220409. data[index++] = newIcon.getWidth();
  220410. data[index++] = newIcon.getHeight();
  220411. for (int y = 0; y < newIcon.getHeight(); ++y)
  220412. for (int x = 0; x < newIcon.getWidth(); ++x)
  220413. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220414. ScopedXLock xlock;
  220415. XChangeProperty (display, windowH,
  220416. XInternAtom (display, "_NET_WM_ICON", False),
  220417. XA_CARDINAL, 32, PropModeReplace,
  220418. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220419. deleteIconPixmaps();
  220420. XWMHints* wmHints = XGetWMHints (display, windowH);
  220421. if (wmHints == 0)
  220422. wmHints = XAllocWMHints();
  220423. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220424. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220425. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220426. XSetWMHints (display, windowH, wmHints);
  220427. XFree (wmHints);
  220428. XSync (display, False);
  220429. }
  220430. void deleteIconPixmaps()
  220431. {
  220432. ScopedXLock xlock;
  220433. XWMHints* wmHints = XGetWMHints (display, windowH);
  220434. if (wmHints != 0)
  220435. {
  220436. if ((wmHints->flags & IconPixmapHint) != 0)
  220437. {
  220438. wmHints->flags &= ~IconPixmapHint;
  220439. XFreePixmap (display, wmHints->icon_pixmap);
  220440. }
  220441. if ((wmHints->flags & IconMaskHint) != 0)
  220442. {
  220443. wmHints->flags &= ~IconMaskHint;
  220444. XFreePixmap (display, wmHints->icon_mask);
  220445. }
  220446. XSetWMHints (display, windowH, wmHints);
  220447. XFree (wmHints);
  220448. }
  220449. }
  220450. void handleWindowMessage (XEvent* event)
  220451. {
  220452. switch (event->xany.type)
  220453. {
  220454. case 2: // 'KeyPress'
  220455. {
  220456. ScopedXLock xlock;
  220457. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220458. updateKeyStates (keyEvent->keycode, true);
  220459. char utf8 [64];
  220460. zeromem (utf8, sizeof (utf8));
  220461. KeySym sym;
  220462. {
  220463. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220464. ::setlocale (LC_ALL, "");
  220465. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220466. ::setlocale (LC_ALL, oldLocale);
  220467. }
  220468. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220469. int keyCode = (int) unicodeChar;
  220470. if (keyCode < 0x20)
  220471. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220472. const ModifierKeys oldMods (currentModifiers);
  220473. bool keyPressed = false;
  220474. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220475. if ((sym & 0xff00) == 0xff00)
  220476. {
  220477. // Translate keypad
  220478. if (sym == XK_KP_Divide)
  220479. keyCode = XK_slash;
  220480. else if (sym == XK_KP_Multiply)
  220481. keyCode = XK_asterisk;
  220482. else if (sym == XK_KP_Subtract)
  220483. keyCode = XK_hyphen;
  220484. else if (sym == XK_KP_Add)
  220485. keyCode = XK_plus;
  220486. else if (sym == XK_KP_Enter)
  220487. keyCode = XK_Return;
  220488. else if (sym == XK_KP_Decimal)
  220489. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220490. else if (sym == XK_KP_0)
  220491. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220492. else if (sym == XK_KP_1)
  220493. keyCode = Keys::numLock ? XK_1 : XK_End;
  220494. else if (sym == XK_KP_2)
  220495. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220496. else if (sym == XK_KP_3)
  220497. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220498. else if (sym == XK_KP_4)
  220499. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220500. else if (sym == XK_KP_5)
  220501. keyCode = XK_5;
  220502. else if (sym == XK_KP_6)
  220503. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220504. else if (sym == XK_KP_7)
  220505. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220506. else if (sym == XK_KP_8)
  220507. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220508. else if (sym == XK_KP_9)
  220509. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220510. switch (sym)
  220511. {
  220512. case XK_Left:
  220513. case XK_Right:
  220514. case XK_Up:
  220515. case XK_Down:
  220516. case XK_Page_Up:
  220517. case XK_Page_Down:
  220518. case XK_End:
  220519. case XK_Home:
  220520. case XK_Delete:
  220521. case XK_Insert:
  220522. keyPressed = true;
  220523. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220524. break;
  220525. case XK_Tab:
  220526. case XK_Return:
  220527. case XK_Escape:
  220528. case XK_BackSpace:
  220529. keyPressed = true;
  220530. keyCode &= 0xff;
  220531. break;
  220532. default:
  220533. {
  220534. if (sym >= XK_F1 && sym <= XK_F16)
  220535. {
  220536. keyPressed = true;
  220537. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220538. }
  220539. break;
  220540. }
  220541. }
  220542. }
  220543. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220544. keyPressed = true;
  220545. if (oldMods != currentModifiers)
  220546. handleModifierKeysChange();
  220547. if (keyDownChange)
  220548. handleKeyUpOrDown (true);
  220549. if (keyPressed)
  220550. handleKeyPress (keyCode, unicodeChar);
  220551. break;
  220552. }
  220553. case KeyRelease:
  220554. {
  220555. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220556. updateKeyStates (keyEvent->keycode, false);
  220557. ScopedXLock xlock;
  220558. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220559. const ModifierKeys oldMods (currentModifiers);
  220560. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220561. if (oldMods != currentModifiers)
  220562. handleModifierKeysChange();
  220563. if (keyDownChange)
  220564. handleKeyUpOrDown (false);
  220565. break;
  220566. }
  220567. case ButtonPress:
  220568. {
  220569. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220570. updateKeyModifiers (buttonPressEvent->state);
  220571. bool buttonMsg = false;
  220572. const int map = pointerMap [buttonPressEvent->button - Button1];
  220573. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220574. {
  220575. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220576. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220577. }
  220578. if (map == Keys::LeftButton)
  220579. {
  220580. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220581. buttonMsg = true;
  220582. }
  220583. else if (map == Keys::RightButton)
  220584. {
  220585. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220586. buttonMsg = true;
  220587. }
  220588. else if (map == Keys::MiddleButton)
  220589. {
  220590. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220591. buttonMsg = true;
  220592. }
  220593. if (buttonMsg)
  220594. {
  220595. toFront (true);
  220596. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220597. getEventTime (buttonPressEvent->time));
  220598. }
  220599. clearLastMousePos();
  220600. break;
  220601. }
  220602. case ButtonRelease:
  220603. {
  220604. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220605. updateKeyModifiers (buttonRelEvent->state);
  220606. const int map = pointerMap [buttonRelEvent->button - Button1];
  220607. if (map == Keys::LeftButton)
  220608. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220609. else if (map == Keys::RightButton)
  220610. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220611. else if (map == Keys::MiddleButton)
  220612. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220613. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220614. getEventTime (buttonRelEvent->time));
  220615. clearLastMousePos();
  220616. break;
  220617. }
  220618. case MotionNotify:
  220619. {
  220620. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220621. updateKeyModifiers (movedEvent->state);
  220622. const Point<int> mousePos (Desktop::getMousePosition());
  220623. if (lastMousePos != mousePos)
  220624. {
  220625. lastMousePos = mousePos;
  220626. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220627. {
  220628. Window wRoot = 0, wParent = 0;
  220629. {
  220630. ScopedXLock xlock;
  220631. unsigned int numChildren;
  220632. Window* wChild = 0;
  220633. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220634. }
  220635. if (wParent != 0
  220636. && wParent != windowH
  220637. && wParent != wRoot)
  220638. {
  220639. parentWindow = wParent;
  220640. updateBounds();
  220641. }
  220642. else
  220643. {
  220644. parentWindow = 0;
  220645. }
  220646. }
  220647. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220648. }
  220649. break;
  220650. }
  220651. case EnterNotify:
  220652. {
  220653. clearLastMousePos();
  220654. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220655. if (! currentModifiers.isAnyMouseButtonDown())
  220656. {
  220657. updateKeyModifiers (enterEvent->state);
  220658. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220659. }
  220660. break;
  220661. }
  220662. case LeaveNotify:
  220663. {
  220664. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220665. // Suppress the normal leave if we've got a pointer grab, or if
  220666. // it's a bogus one caused by clicking a mouse button when running
  220667. // in a Window manager
  220668. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220669. || leaveEvent->mode == NotifyUngrab)
  220670. {
  220671. updateKeyModifiers (leaveEvent->state);
  220672. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220673. }
  220674. break;
  220675. }
  220676. case FocusIn:
  220677. {
  220678. isActiveApplication = true;
  220679. if (isFocused())
  220680. handleFocusGain();
  220681. break;
  220682. }
  220683. case FocusOut:
  220684. {
  220685. isActiveApplication = false;
  220686. if (! isFocused())
  220687. handleFocusLoss();
  220688. break;
  220689. }
  220690. case Expose:
  220691. {
  220692. // Batch together all pending expose events
  220693. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220694. XEvent nextEvent;
  220695. ScopedXLock xlock;
  220696. if (exposeEvent->window != windowH)
  220697. {
  220698. Window child;
  220699. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220700. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220701. &child);
  220702. }
  220703. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220704. exposeEvent->width, exposeEvent->height));
  220705. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220706. {
  220707. XPeekEvent (display, (XEvent*) &nextEvent);
  220708. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220709. break;
  220710. XNextEvent (display, (XEvent*) &nextEvent);
  220711. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220712. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220713. nextExposeEvent->width, nextExposeEvent->height));
  220714. }
  220715. break;
  220716. }
  220717. case CirculateNotify:
  220718. case CreateNotify:
  220719. case DestroyNotify:
  220720. // Think we can ignore these
  220721. break;
  220722. case ConfigureNotify:
  220723. {
  220724. updateBounds();
  220725. updateBorderSize();
  220726. handleMovedOrResized();
  220727. // if the native title bar is dragged, need to tell any active menus, etc.
  220728. if ((styleFlags & windowHasTitleBar) != 0
  220729. && component->isCurrentlyBlockedByAnotherModalComponent())
  220730. {
  220731. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220732. if (currentModalComp != 0)
  220733. currentModalComp->inputAttemptWhenModal();
  220734. }
  220735. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220736. if (confEvent->window == windowH
  220737. && confEvent->above != 0
  220738. && isFrontWindow())
  220739. {
  220740. handleBroughtToFront();
  220741. }
  220742. break;
  220743. }
  220744. case ReparentNotify:
  220745. {
  220746. parentWindow = 0;
  220747. Window wRoot = 0;
  220748. Window* wChild = 0;
  220749. unsigned int numChildren;
  220750. {
  220751. ScopedXLock xlock;
  220752. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220753. }
  220754. if (parentWindow == windowH || parentWindow == wRoot)
  220755. parentWindow = 0;
  220756. updateBounds();
  220757. updateBorderSize();
  220758. handleMovedOrResized();
  220759. break;
  220760. }
  220761. case GravityNotify:
  220762. {
  220763. updateBounds();
  220764. updateBorderSize();
  220765. handleMovedOrResized();
  220766. break;
  220767. }
  220768. case MapNotify:
  220769. mapped = true;
  220770. handleBroughtToFront();
  220771. break;
  220772. case UnmapNotify:
  220773. mapped = false;
  220774. break;
  220775. case MappingNotify:
  220776. {
  220777. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  220778. if (mappingEvent->request != MappingPointer)
  220779. {
  220780. // Deal with modifier/keyboard mapping
  220781. ScopedXLock xlock;
  220782. XRefreshKeyboardMapping (mappingEvent);
  220783. updateModifierMappings();
  220784. }
  220785. break;
  220786. }
  220787. case ClientMessage:
  220788. {
  220789. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  220790. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220791. {
  220792. const Atom atom = (Atom) clientMsg->data.l[0];
  220793. if (atom == Atoms::ProtocolList [Atoms::PING])
  220794. {
  220795. Window root = RootWindow (display, DefaultScreen (display));
  220796. event->xclient.window = root;
  220797. XSendEvent (display, root, False, NoEventMask, event);
  220798. XFlush (display);
  220799. }
  220800. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220801. {
  220802. XWindowAttributes atts;
  220803. ScopedXLock xlock;
  220804. if (clientMsg->window != 0
  220805. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220806. {
  220807. if (atts.map_state == IsViewable)
  220808. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220809. }
  220810. }
  220811. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220812. {
  220813. handleUserClosingWindow();
  220814. }
  220815. }
  220816. else if (clientMsg->message_type == Atoms::XdndEnter)
  220817. {
  220818. handleDragAndDropEnter (clientMsg);
  220819. }
  220820. else if (clientMsg->message_type == Atoms::XdndLeave)
  220821. {
  220822. resetDragAndDrop();
  220823. }
  220824. else if (clientMsg->message_type == Atoms::XdndPosition)
  220825. {
  220826. handleDragAndDropPosition (clientMsg);
  220827. }
  220828. else if (clientMsg->message_type == Atoms::XdndDrop)
  220829. {
  220830. handleDragAndDropDrop (clientMsg);
  220831. }
  220832. else if (clientMsg->message_type == Atoms::XdndStatus)
  220833. {
  220834. handleDragAndDropStatus (clientMsg);
  220835. }
  220836. else if (clientMsg->message_type == Atoms::XdndFinished)
  220837. {
  220838. resetDragAndDrop();
  220839. }
  220840. break;
  220841. }
  220842. case SelectionNotify:
  220843. handleDragAndDropSelection (event);
  220844. break;
  220845. case SelectionClear:
  220846. case SelectionRequest:
  220847. break;
  220848. default:
  220849. #if JUCE_USE_XSHM
  220850. {
  220851. ScopedXLock xlock;
  220852. if (event->xany.type == XShmGetEventBase (display))
  220853. repainter->notifyPaintCompleted();
  220854. }
  220855. #endif
  220856. break;
  220857. }
  220858. }
  220859. void showMouseCursor (Cursor cursor) throw()
  220860. {
  220861. ScopedXLock xlock;
  220862. XDefineCursor (display, windowH, cursor);
  220863. }
  220864. void setTaskBarIcon (const Image& image)
  220865. {
  220866. ScopedXLock xlock;
  220867. taskbarImage = image;
  220868. Screen* const screen = XDefaultScreenOfDisplay (display);
  220869. const int screenNumber = XScreenNumberOfScreen (screen);
  220870. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220871. screenAtom << screenNumber;
  220872. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220873. XGrabServer (display);
  220874. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220875. if (managerWin != None)
  220876. XSelectInput (display, managerWin, StructureNotifyMask);
  220877. XUngrabServer (display);
  220878. XFlush (display);
  220879. if (managerWin != None)
  220880. {
  220881. XEvent ev;
  220882. zerostruct (ev);
  220883. ev.xclient.type = ClientMessage;
  220884. ev.xclient.window = managerWin;
  220885. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220886. ev.xclient.format = 32;
  220887. ev.xclient.data.l[0] = CurrentTime;
  220888. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220889. ev.xclient.data.l[2] = windowH;
  220890. ev.xclient.data.l[3] = 0;
  220891. ev.xclient.data.l[4] = 0;
  220892. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220893. XSync (display, False);
  220894. }
  220895. // For older KDE's ...
  220896. long atomData = 1;
  220897. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220898. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220899. // For more recent KDE's...
  220900. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220901. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220902. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220903. XSizeHints* hints = XAllocSizeHints();
  220904. hints->flags = PMinSize;
  220905. hints->min_width = 22;
  220906. hints->min_height = 22;
  220907. XSetWMNormalHints (display, windowH, hints);
  220908. XFree (hints);
  220909. }
  220910. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220911. juce_UseDebuggingNewOperator
  220912. bool dontRepaint;
  220913. static ModifierKeys currentModifiers;
  220914. static bool isActiveApplication;
  220915. private:
  220916. class LinuxRepaintManager : public Timer
  220917. {
  220918. public:
  220919. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220920. : peer (peer_),
  220921. lastTimeImageUsed (0)
  220922. {
  220923. #if JUCE_USE_XSHM
  220924. shmCompletedDrawing = true;
  220925. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220926. if (useARGBImagesForRendering)
  220927. {
  220928. ScopedXLock xlock;
  220929. XShmSegmentInfo segmentinfo;
  220930. XImage* const testImage
  220931. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220932. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220933. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220934. XDestroyImage (testImage);
  220935. }
  220936. #endif
  220937. }
  220938. ~LinuxRepaintManager()
  220939. {
  220940. }
  220941. void timerCallback()
  220942. {
  220943. #if JUCE_USE_XSHM
  220944. if (! shmCompletedDrawing)
  220945. return;
  220946. #endif
  220947. if (! regionsNeedingRepaint.isEmpty())
  220948. {
  220949. stopTimer();
  220950. performAnyPendingRepaintsNow();
  220951. }
  220952. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220953. {
  220954. stopTimer();
  220955. image = Image::null;
  220956. }
  220957. }
  220958. void repaint (const Rectangle<int>& area)
  220959. {
  220960. if (! isTimerRunning())
  220961. startTimer (repaintTimerPeriod);
  220962. regionsNeedingRepaint.add (area);
  220963. }
  220964. void performAnyPendingRepaintsNow()
  220965. {
  220966. #if JUCE_USE_XSHM
  220967. if (! shmCompletedDrawing)
  220968. {
  220969. startTimer (repaintTimerPeriod);
  220970. return;
  220971. }
  220972. #endif
  220973. peer->clearMaskedRegion();
  220974. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220975. regionsNeedingRepaint.clear();
  220976. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220977. if (! totalArea.isEmpty())
  220978. {
  220979. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220980. || image.getHeight() < totalArea.getHeight())
  220981. {
  220982. #if JUCE_USE_XSHM
  220983. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220984. : Image::RGB,
  220985. #else
  220986. image = Image (new XBitmapImage (Image::RGB,
  220987. #endif
  220988. (totalArea.getWidth() + 31) & ~31,
  220989. (totalArea.getHeight() + 31) & ~31,
  220990. false, peer->depth, peer->visual));
  220991. }
  220992. startTimer (repaintTimerPeriod);
  220993. RectangleList adjustedList (originalRepaintRegion);
  220994. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220995. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220996. if (peer->depth == 32)
  220997. {
  220998. RectangleList::Iterator i (originalRepaintRegion);
  220999. while (i.next())
  221000. image.clear (*i.getRectangle() - totalArea.getPosition());
  221001. }
  221002. peer->handlePaint (context);
  221003. if (! peer->maskedRegion.isEmpty())
  221004. originalRepaintRegion.subtract (peer->maskedRegion);
  221005. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221006. {
  221007. #if JUCE_USE_XSHM
  221008. shmCompletedDrawing = false;
  221009. #endif
  221010. const Rectangle<int>& r = *i.getRectangle();
  221011. static_cast<XBitmapImage*> (image.getSharedImage())
  221012. ->blitToWindow (peer->windowH,
  221013. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221014. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221015. }
  221016. }
  221017. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221018. startTimer (repaintTimerPeriod);
  221019. }
  221020. #if JUCE_USE_XSHM
  221021. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221022. #endif
  221023. private:
  221024. enum { repaintTimerPeriod = 1000 / 100 };
  221025. LinuxComponentPeer* const peer;
  221026. Image image;
  221027. uint32 lastTimeImageUsed;
  221028. RectangleList regionsNeedingRepaint;
  221029. #if JUCE_USE_XSHM
  221030. bool useARGBImagesForRendering, shmCompletedDrawing;
  221031. #endif
  221032. LinuxRepaintManager (const LinuxRepaintManager&);
  221033. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221034. };
  221035. ScopedPointer <LinuxRepaintManager> repainter;
  221036. friend class LinuxRepaintManager;
  221037. Window windowH, parentWindow;
  221038. int wx, wy, ww, wh;
  221039. Image taskbarImage;
  221040. bool fullScreen, mapped;
  221041. Visual* visual;
  221042. int depth;
  221043. BorderSize windowBorder;
  221044. struct MotifWmHints
  221045. {
  221046. unsigned long flags;
  221047. unsigned long functions;
  221048. unsigned long decorations;
  221049. long input_mode;
  221050. unsigned long status;
  221051. };
  221052. static void updateKeyStates (const int keycode, const bool press) throw()
  221053. {
  221054. const int keybyte = keycode >> 3;
  221055. const int keybit = (1 << (keycode & 7));
  221056. if (press)
  221057. Keys::keyStates [keybyte] |= keybit;
  221058. else
  221059. Keys::keyStates [keybyte] &= ~keybit;
  221060. }
  221061. static void updateKeyModifiers (const int status) throw()
  221062. {
  221063. int keyMods = 0;
  221064. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221065. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221066. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221067. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221068. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221069. Keys::capsLock = ((status & LockMask) != 0);
  221070. }
  221071. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221072. {
  221073. int modifier = 0;
  221074. bool isModifier = true;
  221075. switch (sym)
  221076. {
  221077. case XK_Shift_L:
  221078. case XK_Shift_R:
  221079. modifier = ModifierKeys::shiftModifier;
  221080. break;
  221081. case XK_Control_L:
  221082. case XK_Control_R:
  221083. modifier = ModifierKeys::ctrlModifier;
  221084. break;
  221085. case XK_Alt_L:
  221086. case XK_Alt_R:
  221087. modifier = ModifierKeys::altModifier;
  221088. break;
  221089. case XK_Num_Lock:
  221090. if (press)
  221091. Keys::numLock = ! Keys::numLock;
  221092. break;
  221093. case XK_Caps_Lock:
  221094. if (press)
  221095. Keys::capsLock = ! Keys::capsLock;
  221096. break;
  221097. case XK_Scroll_Lock:
  221098. break;
  221099. default:
  221100. isModifier = false;
  221101. break;
  221102. }
  221103. if (modifier != 0)
  221104. {
  221105. if (press)
  221106. currentModifiers = currentModifiers.withFlags (modifier);
  221107. else
  221108. currentModifiers = currentModifiers.withoutFlags (modifier);
  221109. }
  221110. return isModifier;
  221111. }
  221112. // Alt and Num lock are not defined by standard X
  221113. // modifier constants: check what they're mapped to
  221114. static void updateModifierMappings() throw()
  221115. {
  221116. ScopedXLock xlock;
  221117. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221118. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221119. Keys::AltMask = 0;
  221120. Keys::NumLockMask = 0;
  221121. XModifierKeymap* mapping = XGetModifierMapping (display);
  221122. if (mapping)
  221123. {
  221124. for (int i = 0; i < 8; i++)
  221125. {
  221126. if (mapping->modifiermap [i << 1] == altLeftCode)
  221127. Keys::AltMask = 1 << i;
  221128. else if (mapping->modifiermap [i << 1] == numLockCode)
  221129. Keys::NumLockMask = 1 << i;
  221130. }
  221131. XFreeModifiermap (mapping);
  221132. }
  221133. }
  221134. void removeWindowDecorations (Window wndH)
  221135. {
  221136. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221137. if (hints != None)
  221138. {
  221139. MotifWmHints motifHints;
  221140. zerostruct (motifHints);
  221141. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221142. motifHints.decorations = 0;
  221143. ScopedXLock xlock;
  221144. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221145. (unsigned char*) &motifHints, 4);
  221146. }
  221147. hints = XInternAtom (display, "_WIN_HINTS", True);
  221148. if (hints != None)
  221149. {
  221150. long gnomeHints = 0;
  221151. ScopedXLock xlock;
  221152. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221153. (unsigned char*) &gnomeHints, 1);
  221154. }
  221155. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221156. if (hints != None)
  221157. {
  221158. long kwmHints = 2; /*KDE_tinyDecoration*/
  221159. ScopedXLock xlock;
  221160. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221161. (unsigned char*) &kwmHints, 1);
  221162. }
  221163. }
  221164. void addWindowButtons (Window wndH)
  221165. {
  221166. ScopedXLock xlock;
  221167. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221168. if (hints != None)
  221169. {
  221170. MotifWmHints motifHints;
  221171. zerostruct (motifHints);
  221172. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221173. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221174. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221175. if ((styleFlags & windowHasCloseButton) != 0)
  221176. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221177. if ((styleFlags & windowHasMinimiseButton) != 0)
  221178. {
  221179. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221180. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221181. }
  221182. if ((styleFlags & windowHasMaximiseButton) != 0)
  221183. {
  221184. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221185. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221186. }
  221187. if ((styleFlags & windowIsResizable) != 0)
  221188. {
  221189. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221190. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221191. }
  221192. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221193. }
  221194. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221195. if (hints != None)
  221196. {
  221197. int netHints [6];
  221198. int num = 0;
  221199. if ((styleFlags & windowIsResizable) != 0)
  221200. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221201. if ((styleFlags & windowHasMaximiseButton) != 0)
  221202. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221203. if ((styleFlags & windowHasMinimiseButton) != 0)
  221204. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221205. if ((styleFlags & windowHasCloseButton) != 0)
  221206. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221207. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221208. }
  221209. }
  221210. void setWindowType()
  221211. {
  221212. int netHints [2];
  221213. int numHints = 0;
  221214. if ((styleFlags & windowIsTemporary) != 0
  221215. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221216. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221217. else
  221218. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221219. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221220. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221221. (unsigned char*) &netHints, numHints);
  221222. numHints = 0;
  221223. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221224. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221225. if (component->isAlwaysOnTop())
  221226. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221227. if (numHints > 0)
  221228. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221229. (unsigned char*) &netHints, numHints);
  221230. }
  221231. void createWindow()
  221232. {
  221233. ScopedXLock xlock;
  221234. Atoms::initialiseAtoms();
  221235. resetDragAndDrop();
  221236. // Get defaults for various properties
  221237. const int screen = DefaultScreen (display);
  221238. Window root = RootWindow (display, screen);
  221239. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221240. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221241. if (visual == 0)
  221242. {
  221243. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221244. Process::terminate();
  221245. }
  221246. // Create and install a colormap suitable fr our visual
  221247. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221248. XInstallColormap (display, colormap);
  221249. // Set up the window attributes
  221250. XSetWindowAttributes swa;
  221251. swa.border_pixel = 0;
  221252. swa.background_pixmap = None;
  221253. swa.colormap = colormap;
  221254. swa.event_mask = getAllEventsMask();
  221255. windowH = XCreateWindow (display, root,
  221256. 0, 0, 1, 1,
  221257. 0, depth, InputOutput, visual,
  221258. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221259. &swa);
  221260. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221261. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221262. GrabModeAsync, GrabModeAsync, None, None);
  221263. // Set the window context to identify the window handle object
  221264. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221265. {
  221266. // Failed
  221267. jassertfalse;
  221268. Logger::outputDebugString ("Failed to create context information for window.\n");
  221269. XDestroyWindow (display, windowH);
  221270. windowH = 0;
  221271. return;
  221272. }
  221273. // Set window manager hints
  221274. XWMHints* wmHints = XAllocWMHints();
  221275. wmHints->flags = InputHint | StateHint;
  221276. wmHints->input = True; // Locally active input model
  221277. wmHints->initial_state = NormalState;
  221278. XSetWMHints (display, windowH, wmHints);
  221279. XFree (wmHints);
  221280. // Set the window type
  221281. setWindowType();
  221282. // Define decoration
  221283. if ((styleFlags & windowHasTitleBar) == 0)
  221284. removeWindowDecorations (windowH);
  221285. else
  221286. addWindowButtons (windowH);
  221287. // Set window name
  221288. setWindowTitle (windowH, getComponent()->getName());
  221289. // Associate the PID, allowing to be shut down when something goes wrong
  221290. unsigned long pid = getpid();
  221291. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221292. (unsigned char*) &pid, 1);
  221293. // Set window manager protocols
  221294. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221295. (unsigned char*) Atoms::ProtocolList, 2);
  221296. // Set drag and drop flags
  221297. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221298. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221299. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221300. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221301. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221302. (const unsigned char*) "", 0);
  221303. unsigned long dndVersion = Atoms::DndVersion;
  221304. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221305. (const unsigned char*) &dndVersion, 1);
  221306. // Initialise the pointer and keyboard mapping
  221307. // This is not the same as the logical pointer mapping the X server uses:
  221308. // we don't mess with this.
  221309. static bool mappingInitialised = false;
  221310. if (! mappingInitialised)
  221311. {
  221312. mappingInitialised = true;
  221313. const int numButtons = XGetPointerMapping (display, 0, 0);
  221314. if (numButtons == 2)
  221315. {
  221316. pointerMap[0] = Keys::LeftButton;
  221317. pointerMap[1] = Keys::RightButton;
  221318. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221319. }
  221320. else if (numButtons >= 3)
  221321. {
  221322. pointerMap[0] = Keys::LeftButton;
  221323. pointerMap[1] = Keys::MiddleButton;
  221324. pointerMap[2] = Keys::RightButton;
  221325. if (numButtons >= 5)
  221326. {
  221327. pointerMap[3] = Keys::WheelUp;
  221328. pointerMap[4] = Keys::WheelDown;
  221329. }
  221330. }
  221331. updateModifierMappings();
  221332. }
  221333. }
  221334. void destroyWindow()
  221335. {
  221336. ScopedXLock xlock;
  221337. XPointer handlePointer;
  221338. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221339. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221340. XDestroyWindow (display, windowH);
  221341. // Wait for it to complete and then remove any events for this
  221342. // window from the event queue.
  221343. XSync (display, false);
  221344. XEvent event;
  221345. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221346. {}
  221347. }
  221348. static int getAllEventsMask() throw()
  221349. {
  221350. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221351. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221352. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221353. }
  221354. static int64 getEventTime (::Time t)
  221355. {
  221356. static int64 eventTimeOffset = 0x12345678;
  221357. const int64 thisMessageTime = t;
  221358. if (eventTimeOffset == 0x12345678)
  221359. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221360. return eventTimeOffset + thisMessageTime;
  221361. }
  221362. static void setWindowTitle (Window xwin, const String& title)
  221363. {
  221364. XTextProperty nameProperty;
  221365. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221366. ScopedXLock xlock;
  221367. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221368. {
  221369. XSetWMName (display, xwin, &nameProperty);
  221370. XSetWMIconName (display, xwin, &nameProperty);
  221371. XFree (nameProperty.value);
  221372. }
  221373. }
  221374. void updateBorderSize()
  221375. {
  221376. if ((styleFlags & windowHasTitleBar) == 0)
  221377. {
  221378. windowBorder = BorderSize (0);
  221379. }
  221380. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221381. {
  221382. ScopedXLock xlock;
  221383. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221384. if (hints != None)
  221385. {
  221386. unsigned char* data = 0;
  221387. unsigned long nitems, bytesLeft;
  221388. Atom actualType;
  221389. int actualFormat;
  221390. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221391. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221392. &data) == Success)
  221393. {
  221394. const unsigned long* const sizes = (const unsigned long*) data;
  221395. if (actualFormat == 32)
  221396. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221397. (int) sizes[3], (int) sizes[1]);
  221398. XFree (data);
  221399. }
  221400. }
  221401. }
  221402. }
  221403. void updateBounds()
  221404. {
  221405. jassert (windowH != 0);
  221406. if (windowH != 0)
  221407. {
  221408. Window root, child;
  221409. unsigned int bw, depth;
  221410. ScopedXLock xlock;
  221411. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221412. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221413. &bw, &depth))
  221414. {
  221415. wx = wy = ww = wh = 0;
  221416. }
  221417. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221418. {
  221419. wx = wy = 0;
  221420. }
  221421. }
  221422. }
  221423. void resetDragAndDrop()
  221424. {
  221425. dragAndDropFiles.clear();
  221426. lastDropPos = Point<int> (-1, -1);
  221427. dragAndDropCurrentMimeType = 0;
  221428. dragAndDropSourceWindow = 0;
  221429. srcMimeTypeAtomList.clear();
  221430. }
  221431. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221432. {
  221433. msg.type = ClientMessage;
  221434. msg.display = display;
  221435. msg.window = dragAndDropSourceWindow;
  221436. msg.format = 32;
  221437. msg.data.l[0] = windowH;
  221438. ScopedXLock xlock;
  221439. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221440. }
  221441. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221442. {
  221443. XClientMessageEvent msg;
  221444. zerostruct (msg);
  221445. msg.message_type = Atoms::XdndStatus;
  221446. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221447. msg.data.l[4] = dropAction;
  221448. sendDragAndDropMessage (msg);
  221449. }
  221450. void sendDragAndDropLeave()
  221451. {
  221452. XClientMessageEvent msg;
  221453. zerostruct (msg);
  221454. msg.message_type = Atoms::XdndLeave;
  221455. sendDragAndDropMessage (msg);
  221456. }
  221457. void sendDragAndDropFinish()
  221458. {
  221459. XClientMessageEvent msg;
  221460. zerostruct (msg);
  221461. msg.message_type = Atoms::XdndFinished;
  221462. sendDragAndDropMessage (msg);
  221463. }
  221464. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221465. {
  221466. if ((clientMsg->data.l[1] & 1) == 0)
  221467. {
  221468. sendDragAndDropLeave();
  221469. if (dragAndDropFiles.size() > 0)
  221470. handleFileDragExit (dragAndDropFiles);
  221471. dragAndDropFiles.clear();
  221472. }
  221473. }
  221474. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221475. {
  221476. if (dragAndDropSourceWindow == 0)
  221477. return;
  221478. dragAndDropSourceWindow = clientMsg->data.l[0];
  221479. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221480. (int) clientMsg->data.l[2] & 0xffff);
  221481. dropPos -= getScreenPosition();
  221482. if (lastDropPos != dropPos)
  221483. {
  221484. lastDropPos = dropPos;
  221485. dragAndDropTimestamp = clientMsg->data.l[3];
  221486. Atom targetAction = Atoms::XdndActionCopy;
  221487. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221488. {
  221489. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221490. {
  221491. targetAction = Atoms::allowedActions[i];
  221492. break;
  221493. }
  221494. }
  221495. sendDragAndDropStatus (true, targetAction);
  221496. if (dragAndDropFiles.size() == 0)
  221497. updateDraggedFileList (clientMsg);
  221498. if (dragAndDropFiles.size() > 0)
  221499. handleFileDragMove (dragAndDropFiles, dropPos);
  221500. }
  221501. }
  221502. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221503. {
  221504. if (dragAndDropFiles.size() == 0)
  221505. updateDraggedFileList (clientMsg);
  221506. const StringArray files (dragAndDropFiles);
  221507. const Point<int> lastPos (lastDropPos);
  221508. sendDragAndDropFinish();
  221509. resetDragAndDrop();
  221510. if (files.size() > 0)
  221511. handleFileDragDrop (files, lastPos);
  221512. }
  221513. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221514. {
  221515. dragAndDropFiles.clear();
  221516. srcMimeTypeAtomList.clear();
  221517. dragAndDropCurrentMimeType = 0;
  221518. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221519. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221520. {
  221521. dragAndDropSourceWindow = 0;
  221522. return;
  221523. }
  221524. dragAndDropSourceWindow = clientMsg->data.l[0];
  221525. if ((clientMsg->data.l[1] & 1) != 0)
  221526. {
  221527. Atom actual;
  221528. int format;
  221529. unsigned long count = 0, remaining = 0;
  221530. unsigned char* data = 0;
  221531. ScopedXLock xlock;
  221532. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221533. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221534. &count, &remaining, &data);
  221535. if (data != 0)
  221536. {
  221537. if (actual == XA_ATOM && format == 32 && count != 0)
  221538. {
  221539. const unsigned long* const types = (const unsigned long*) data;
  221540. for (unsigned int i = 0; i < count; ++i)
  221541. if (types[i] != None)
  221542. srcMimeTypeAtomList.add (types[i]);
  221543. }
  221544. XFree (data);
  221545. }
  221546. }
  221547. if (srcMimeTypeAtomList.size() == 0)
  221548. {
  221549. for (int i = 2; i < 5; ++i)
  221550. if (clientMsg->data.l[i] != None)
  221551. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221552. if (srcMimeTypeAtomList.size() == 0)
  221553. {
  221554. dragAndDropSourceWindow = 0;
  221555. return;
  221556. }
  221557. }
  221558. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221559. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221560. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221561. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221562. handleDragAndDropPosition (clientMsg);
  221563. }
  221564. void handleDragAndDropSelection (const XEvent* const evt)
  221565. {
  221566. dragAndDropFiles.clear();
  221567. if (evt->xselection.property != 0)
  221568. {
  221569. StringArray lines;
  221570. {
  221571. MemoryBlock dropData;
  221572. for (;;)
  221573. {
  221574. Atom actual;
  221575. uint8* data = 0;
  221576. unsigned long count = 0, remaining = 0;
  221577. int format = 0;
  221578. ScopedXLock xlock;
  221579. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221580. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221581. &format, &count, &remaining, &data) == Success)
  221582. {
  221583. dropData.append (data, count * format / 8);
  221584. XFree (data);
  221585. if (remaining == 0)
  221586. break;
  221587. }
  221588. else
  221589. {
  221590. XFree (data);
  221591. break;
  221592. }
  221593. }
  221594. lines.addLines (dropData.toString());
  221595. }
  221596. for (int i = 0; i < lines.size(); ++i)
  221597. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221598. dragAndDropFiles.trim();
  221599. dragAndDropFiles.removeEmptyStrings();
  221600. }
  221601. }
  221602. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221603. {
  221604. dragAndDropFiles.clear();
  221605. if (dragAndDropSourceWindow != None
  221606. && dragAndDropCurrentMimeType != 0)
  221607. {
  221608. dragAndDropTimestamp = clientMsg->data.l[2];
  221609. ScopedXLock xlock;
  221610. XConvertSelection (display,
  221611. Atoms::XdndSelection,
  221612. dragAndDropCurrentMimeType,
  221613. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221614. windowH,
  221615. dragAndDropTimestamp);
  221616. }
  221617. }
  221618. StringArray dragAndDropFiles;
  221619. int dragAndDropTimestamp;
  221620. Point<int> lastDropPos;
  221621. Atom dragAndDropCurrentMimeType;
  221622. Window dragAndDropSourceWindow;
  221623. Array <Atom> srcMimeTypeAtomList;
  221624. static int pointerMap[5];
  221625. static Point<int> lastMousePos;
  221626. static void clearLastMousePos() throw()
  221627. {
  221628. lastMousePos = Point<int> (0x100000, 0x100000);
  221629. }
  221630. };
  221631. ModifierKeys LinuxComponentPeer::currentModifiers;
  221632. bool LinuxComponentPeer::isActiveApplication = false;
  221633. int LinuxComponentPeer::pointerMap[5];
  221634. Point<int> LinuxComponentPeer::lastMousePos;
  221635. bool Process::isForegroundProcess()
  221636. {
  221637. return LinuxComponentPeer::isActiveApplication;
  221638. }
  221639. void ModifierKeys::updateCurrentModifiers() throw()
  221640. {
  221641. currentModifiers = LinuxComponentPeer::currentModifiers;
  221642. }
  221643. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221644. {
  221645. Window root, child;
  221646. int x, y, winx, winy;
  221647. unsigned int mask;
  221648. int mouseMods = 0;
  221649. ScopedXLock xlock;
  221650. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221651. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221652. {
  221653. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221654. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221655. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221656. }
  221657. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221658. return LinuxComponentPeer::currentModifiers;
  221659. }
  221660. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221661. {
  221662. if (enableOrDisable)
  221663. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221664. }
  221665. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221666. {
  221667. return new LinuxComponentPeer (this, styleFlags);
  221668. }
  221669. // (this callback is hooked up in the messaging code)
  221670. void juce_windowMessageReceive (XEvent* event)
  221671. {
  221672. if (event->xany.window != None)
  221673. {
  221674. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221675. if (ComponentPeer::isValidPeer (peer))
  221676. peer->handleWindowMessage (event);
  221677. }
  221678. else
  221679. {
  221680. switch (event->xany.type)
  221681. {
  221682. case KeymapNotify:
  221683. {
  221684. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221685. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221686. break;
  221687. }
  221688. default:
  221689. break;
  221690. }
  221691. }
  221692. }
  221693. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221694. {
  221695. if (display == 0)
  221696. return;
  221697. #if JUCE_USE_XINERAMA
  221698. int major_opcode, first_event, first_error;
  221699. ScopedXLock xlock;
  221700. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221701. {
  221702. typedef Bool (*tXineramaIsActive) (Display*);
  221703. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221704. static tXineramaIsActive xXineramaIsActive = 0;
  221705. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221706. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221707. {
  221708. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221709. if (h == 0)
  221710. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221711. if (h != 0)
  221712. {
  221713. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221714. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221715. }
  221716. }
  221717. if (xXineramaIsActive != 0
  221718. && xXineramaQueryScreens != 0
  221719. && xXineramaIsActive (display))
  221720. {
  221721. int numMonitors = 0;
  221722. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221723. if (screens != 0)
  221724. {
  221725. for (int i = numMonitors; --i >= 0;)
  221726. {
  221727. int index = screens[i].screen_number;
  221728. if (index >= 0)
  221729. {
  221730. while (monitorCoords.size() < index)
  221731. monitorCoords.add (Rectangle<int>());
  221732. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221733. screens[i].y_org,
  221734. screens[i].width,
  221735. screens[i].height));
  221736. }
  221737. }
  221738. XFree (screens);
  221739. }
  221740. }
  221741. }
  221742. if (monitorCoords.size() == 0)
  221743. #endif
  221744. {
  221745. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221746. if (hints != None)
  221747. {
  221748. const int numMonitors = ScreenCount (display);
  221749. for (int i = 0; i < numMonitors; ++i)
  221750. {
  221751. Window root = RootWindow (display, i);
  221752. unsigned long nitems, bytesLeft;
  221753. Atom actualType;
  221754. int actualFormat;
  221755. unsigned char* data = 0;
  221756. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221757. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221758. &data) == Success)
  221759. {
  221760. const long* const position = (const long*) data;
  221761. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221762. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221763. position[2], position[3]));
  221764. XFree (data);
  221765. }
  221766. }
  221767. }
  221768. if (monitorCoords.size() == 0)
  221769. {
  221770. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221771. DisplayHeight (display, DefaultScreen (display))));
  221772. }
  221773. }
  221774. }
  221775. void Desktop::createMouseInputSources()
  221776. {
  221777. mouseSources.add (new MouseInputSource (0, true));
  221778. }
  221779. bool Desktop::canUseSemiTransparentWindows() throw()
  221780. {
  221781. int matchedDepth = 0;
  221782. const int desiredDepth = 32;
  221783. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221784. && (matchedDepth == desiredDepth);
  221785. }
  221786. const Point<int> Desktop::getMousePosition()
  221787. {
  221788. Window root, child;
  221789. int x, y, winx, winy;
  221790. unsigned int mask;
  221791. ScopedXLock xlock;
  221792. if (XQueryPointer (display,
  221793. RootWindow (display, DefaultScreen (display)),
  221794. &root, &child,
  221795. &x, &y, &winx, &winy, &mask) == False)
  221796. {
  221797. // Pointer not on the default screen
  221798. x = y = -1;
  221799. }
  221800. return Point<int> (x, y);
  221801. }
  221802. void Desktop::setMousePosition (const Point<int>& newPosition)
  221803. {
  221804. ScopedXLock xlock;
  221805. Window root = RootWindow (display, DefaultScreen (display));
  221806. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221807. }
  221808. static bool screenSaverAllowed = true;
  221809. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221810. {
  221811. if (screenSaverAllowed != isEnabled)
  221812. {
  221813. screenSaverAllowed = isEnabled;
  221814. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221815. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221816. if (xScreenSaverSuspend == 0)
  221817. {
  221818. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221819. if (h != 0)
  221820. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221821. }
  221822. ScopedXLock xlock;
  221823. if (xScreenSaverSuspend != 0)
  221824. xScreenSaverSuspend (display, ! isEnabled);
  221825. }
  221826. }
  221827. bool Desktop::isScreenSaverEnabled()
  221828. {
  221829. return screenSaverAllowed;
  221830. }
  221831. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221832. {
  221833. ScopedXLock xlock;
  221834. const unsigned int imageW = image.getWidth();
  221835. const unsigned int imageH = image.getHeight();
  221836. #if JUCE_USE_XCURSOR
  221837. {
  221838. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221839. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221840. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221841. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221842. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221843. static tXcursorImageCreate xXcursorImageCreate = 0;
  221844. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221845. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221846. static bool hasBeenLoaded = false;
  221847. if (! hasBeenLoaded)
  221848. {
  221849. hasBeenLoaded = true;
  221850. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221851. if (h != 0)
  221852. {
  221853. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221854. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221855. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221856. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221857. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221858. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221859. || ! xXcursorSupportsARGB (display))
  221860. xXcursorSupportsARGB = 0;
  221861. }
  221862. }
  221863. if (xXcursorSupportsARGB != 0)
  221864. {
  221865. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221866. if (xcImage != 0)
  221867. {
  221868. xcImage->xhot = hotspotX;
  221869. xcImage->yhot = hotspotY;
  221870. XcursorPixel* dest = xcImage->pixels;
  221871. for (int y = 0; y < (int) imageH; ++y)
  221872. for (int x = 0; x < (int) imageW; ++x)
  221873. *dest++ = image.getPixelAt (x, y).getARGB();
  221874. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221875. xXcursorImageDestroy (xcImage);
  221876. if (result != 0)
  221877. return result;
  221878. }
  221879. }
  221880. }
  221881. #endif
  221882. Window root = RootWindow (display, DefaultScreen (display));
  221883. unsigned int cursorW, cursorH;
  221884. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221885. return 0;
  221886. Image im (Image::ARGB, cursorW, cursorH, true);
  221887. {
  221888. Graphics g (im);
  221889. if (imageW > cursorW || imageH > cursorH)
  221890. {
  221891. hotspotX = (hotspotX * cursorW) / imageW;
  221892. hotspotY = (hotspotY * cursorH) / imageH;
  221893. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221894. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221895. false);
  221896. }
  221897. else
  221898. {
  221899. g.drawImageAt (image, 0, 0);
  221900. }
  221901. }
  221902. const int stride = (cursorW + 7) >> 3;
  221903. HeapBlock <char> maskPlane, sourcePlane;
  221904. maskPlane.calloc (stride * cursorH);
  221905. sourcePlane.calloc (stride * cursorH);
  221906. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221907. for (int y = cursorH; --y >= 0;)
  221908. {
  221909. for (int x = cursorW; --x >= 0;)
  221910. {
  221911. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221912. const int offset = y * stride + (x >> 3);
  221913. const Colour c (im.getPixelAt (x, y));
  221914. if (c.getAlpha() >= 128)
  221915. maskPlane[offset] |= mask;
  221916. if (c.getBrightness() >= 0.5f)
  221917. sourcePlane[offset] |= mask;
  221918. }
  221919. }
  221920. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221921. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221922. XColor white, black;
  221923. black.red = black.green = black.blue = 0;
  221924. white.red = white.green = white.blue = 0xffff;
  221925. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221926. XFreePixmap (display, sourcePixmap);
  221927. XFreePixmap (display, maskPixmap);
  221928. return result;
  221929. }
  221930. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221931. {
  221932. ScopedXLock xlock;
  221933. if (cursorHandle != 0)
  221934. XFreeCursor (display, (Cursor) cursorHandle);
  221935. }
  221936. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221937. {
  221938. unsigned int shape;
  221939. switch (type)
  221940. {
  221941. case NormalCursor: return None; // Use parent cursor
  221942. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221943. case WaitCursor: shape = XC_watch; break;
  221944. case IBeamCursor: shape = XC_xterm; break;
  221945. case PointingHandCursor: shape = XC_hand2; break;
  221946. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221947. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221948. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221949. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221950. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221951. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221952. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221953. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221954. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221955. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221956. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221957. case CrosshairCursor: shape = XC_crosshair; break;
  221958. case DraggingHandCursor:
  221959. {
  221960. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221961. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0, 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  221962. 132,117,151,116,132,146,248,60,209,138,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 };
  221963. const int dragHandDataSize = 99;
  221964. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221965. }
  221966. case CopyingCursor:
  221967. {
  221968. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221969. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0, 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  221970. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  221971. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221972. const int copyCursorSize = 119;
  221973. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221974. }
  221975. default:
  221976. jassertfalse;
  221977. return None;
  221978. }
  221979. ScopedXLock xlock;
  221980. return (void*) XCreateFontCursor (display, shape);
  221981. }
  221982. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221983. {
  221984. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221985. if (lp != 0)
  221986. lp->showMouseCursor ((Cursor) getHandle());
  221987. }
  221988. void MouseCursor::showInAllWindows() const
  221989. {
  221990. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221991. showInWindow (ComponentPeer::getPeer (i));
  221992. }
  221993. const Image juce_createIconForFile (const File& file)
  221994. {
  221995. return Image::null;
  221996. }
  221997. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221998. {
  221999. return createSoftwareImage (format, width, height, clearImage);
  222000. }
  222001. #if JUCE_OPENGL
  222002. class WindowedGLContext : public OpenGLContext
  222003. {
  222004. public:
  222005. WindowedGLContext (Component* const component,
  222006. const OpenGLPixelFormat& pixelFormat_,
  222007. GLXContext sharedContext)
  222008. : renderContext (0),
  222009. embeddedWindow (0),
  222010. pixelFormat (pixelFormat_),
  222011. swapInterval (0)
  222012. {
  222013. jassert (component != 0);
  222014. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222015. if (peer == 0)
  222016. return;
  222017. ScopedXLock xlock;
  222018. XSync (display, False);
  222019. GLint attribs [64];
  222020. int n = 0;
  222021. attribs[n++] = GLX_RGBA;
  222022. attribs[n++] = GLX_DOUBLEBUFFER;
  222023. attribs[n++] = GLX_RED_SIZE;
  222024. attribs[n++] = pixelFormat.redBits;
  222025. attribs[n++] = GLX_GREEN_SIZE;
  222026. attribs[n++] = pixelFormat.greenBits;
  222027. attribs[n++] = GLX_BLUE_SIZE;
  222028. attribs[n++] = pixelFormat.blueBits;
  222029. attribs[n++] = GLX_ALPHA_SIZE;
  222030. attribs[n++] = pixelFormat.alphaBits;
  222031. attribs[n++] = GLX_DEPTH_SIZE;
  222032. attribs[n++] = pixelFormat.depthBufferBits;
  222033. attribs[n++] = GLX_STENCIL_SIZE;
  222034. attribs[n++] = pixelFormat.stencilBufferBits;
  222035. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222036. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222037. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222038. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222039. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222040. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222041. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222042. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222043. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222044. attribs[n++] = None;
  222045. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222046. if (bestVisual == 0)
  222047. return;
  222048. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222049. Window windowH = (Window) peer->getNativeHandle();
  222050. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222051. XSetWindowAttributes swa;
  222052. swa.colormap = colourMap;
  222053. swa.border_pixel = 0;
  222054. swa.event_mask = ExposureMask | StructureNotifyMask;
  222055. embeddedWindow = XCreateWindow (display, windowH,
  222056. 0, 0, 1, 1, 0,
  222057. bestVisual->depth,
  222058. InputOutput,
  222059. bestVisual->visual,
  222060. CWBorderPixel | CWColormap | CWEventMask,
  222061. &swa);
  222062. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222063. XMapWindow (display, embeddedWindow);
  222064. XFreeColormap (display, colourMap);
  222065. XFree (bestVisual);
  222066. XSync (display, False);
  222067. }
  222068. ~WindowedGLContext()
  222069. {
  222070. ScopedXLock xlock;
  222071. deleteContext();
  222072. XUnmapWindow (display, embeddedWindow);
  222073. XDestroyWindow (display, embeddedWindow);
  222074. }
  222075. void deleteContext()
  222076. {
  222077. makeInactive();
  222078. if (renderContext != 0)
  222079. {
  222080. ScopedXLock xlock;
  222081. glXDestroyContext (display, renderContext);
  222082. renderContext = 0;
  222083. }
  222084. }
  222085. bool makeActive() const throw()
  222086. {
  222087. jassert (renderContext != 0);
  222088. ScopedXLock xlock;
  222089. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222090. && XSync (display, False);
  222091. }
  222092. bool makeInactive() const throw()
  222093. {
  222094. ScopedXLock xlock;
  222095. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222096. }
  222097. bool isActive() const throw()
  222098. {
  222099. ScopedXLock xlock;
  222100. return glXGetCurrentContext() == renderContext;
  222101. }
  222102. const OpenGLPixelFormat getPixelFormat() const
  222103. {
  222104. return pixelFormat;
  222105. }
  222106. void* getRawContext() const throw()
  222107. {
  222108. return renderContext;
  222109. }
  222110. void updateWindowPosition (int x, int y, int w, int h, int)
  222111. {
  222112. ScopedXLock xlock;
  222113. XMoveResizeWindow (display, embeddedWindow,
  222114. x, y, jmax (1, w), jmax (1, h));
  222115. }
  222116. void swapBuffers()
  222117. {
  222118. ScopedXLock xlock;
  222119. glXSwapBuffers (display, embeddedWindow);
  222120. }
  222121. bool setSwapInterval (const int numFramesPerSwap)
  222122. {
  222123. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222124. if (GLXSwapIntervalSGI != 0)
  222125. {
  222126. swapInterval = numFramesPerSwap;
  222127. GLXSwapIntervalSGI (numFramesPerSwap);
  222128. return true;
  222129. }
  222130. return false;
  222131. }
  222132. int getSwapInterval() const
  222133. {
  222134. return swapInterval;
  222135. }
  222136. void repaint()
  222137. {
  222138. }
  222139. juce_UseDebuggingNewOperator
  222140. GLXContext renderContext;
  222141. private:
  222142. Window embeddedWindow;
  222143. OpenGLPixelFormat pixelFormat;
  222144. int swapInterval;
  222145. WindowedGLContext (const WindowedGLContext&);
  222146. WindowedGLContext& operator= (const WindowedGLContext&);
  222147. };
  222148. OpenGLContext* OpenGLComponent::createContext()
  222149. {
  222150. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222151. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222152. return (c->renderContext != 0) ? c.release() : 0;
  222153. }
  222154. void juce_glViewport (const int w, const int h)
  222155. {
  222156. glViewport (0, 0, w, h);
  222157. }
  222158. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222159. OwnedArray <OpenGLPixelFormat>& results)
  222160. {
  222161. results.add (new OpenGLPixelFormat()); // xxx
  222162. }
  222163. #endif
  222164. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222165. {
  222166. jassertfalse; // not implemented!
  222167. return false;
  222168. }
  222169. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222170. {
  222171. jassertfalse; // not implemented!
  222172. return false;
  222173. }
  222174. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222175. {
  222176. if (! isOnDesktop ())
  222177. addToDesktop (0);
  222178. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222179. if (wp != 0)
  222180. {
  222181. wp->setTaskBarIcon (newImage);
  222182. setVisible (true);
  222183. toFront (false);
  222184. repaint();
  222185. }
  222186. }
  222187. void SystemTrayIconComponent::paint (Graphics& g)
  222188. {
  222189. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222190. if (wp != 0)
  222191. {
  222192. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222193. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222194. false);
  222195. }
  222196. }
  222197. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222198. {
  222199. // xxx not yet implemented!
  222200. }
  222201. void PlatformUtilities::beep()
  222202. {
  222203. std::cout << "\a" << std::flush;
  222204. }
  222205. bool AlertWindow::showNativeDialogBox (const String& title,
  222206. const String& bodyText,
  222207. bool isOkCancel)
  222208. {
  222209. // use a non-native one for the time being..
  222210. if (isOkCancel)
  222211. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222212. else
  222213. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222214. return true;
  222215. }
  222216. const int KeyPress::spaceKey = XK_space & 0xff;
  222217. const int KeyPress::returnKey = XK_Return & 0xff;
  222218. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222219. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222220. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222221. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222222. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222223. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222224. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222225. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222226. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222227. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222228. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222229. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222230. const int KeyPress::tabKey = XK_Tab & 0xff;
  222231. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222232. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222233. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222234. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222235. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222236. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222237. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222238. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222239. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222240. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222241. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222242. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222243. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222244. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222245. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222246. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222247. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222248. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222249. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222250. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222251. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222252. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222253. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222254. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222255. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222256. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222257. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222258. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222259. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222260. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222261. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222262. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222263. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222264. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222265. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222266. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222267. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222268. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222269. #endif
  222270. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222271. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222272. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222273. // compiled on its own).
  222274. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222275. static const int maxNumChans = 64;
  222276. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222277. {
  222278. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222279. snd_pcm_hw_params_t* hwParams;
  222280. snd_pcm_hw_params_alloca (&hwParams);
  222281. for (int i = 0; ratesToTry[i] != 0; ++i)
  222282. {
  222283. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222284. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222285. {
  222286. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222287. }
  222288. }
  222289. }
  222290. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222291. {
  222292. snd_pcm_hw_params_t *params;
  222293. snd_pcm_hw_params_alloca (&params);
  222294. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222295. {
  222296. snd_pcm_hw_params_get_channels_min (params, minChans);
  222297. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222298. }
  222299. }
  222300. static void getDeviceProperties (const String& deviceID,
  222301. unsigned int& minChansOut,
  222302. unsigned int& maxChansOut,
  222303. unsigned int& minChansIn,
  222304. unsigned int& maxChansIn,
  222305. Array <int>& rates)
  222306. {
  222307. if (deviceID.isEmpty())
  222308. return;
  222309. snd_ctl_t* handle;
  222310. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222311. {
  222312. snd_pcm_info_t* info;
  222313. snd_pcm_info_alloca (&info);
  222314. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222315. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222316. snd_pcm_info_set_subdevice (info, 0);
  222317. if (snd_ctl_pcm_info (handle, info) >= 0)
  222318. {
  222319. snd_pcm_t* pcmHandle;
  222320. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  222321. {
  222322. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222323. getDeviceSampleRates (pcmHandle, rates);
  222324. snd_pcm_close (pcmHandle);
  222325. }
  222326. }
  222327. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222328. if (snd_ctl_pcm_info (handle, info) >= 0)
  222329. {
  222330. snd_pcm_t* pcmHandle;
  222331. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  222332. {
  222333. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222334. if (rates.size() == 0)
  222335. getDeviceSampleRates (pcmHandle, rates);
  222336. snd_pcm_close (pcmHandle);
  222337. }
  222338. }
  222339. snd_ctl_close (handle);
  222340. }
  222341. }
  222342. class ALSADevice
  222343. {
  222344. public:
  222345. ALSADevice (const String& deviceID,
  222346. const bool forInput)
  222347. : handle (0),
  222348. bitDepth (16),
  222349. numChannelsRunning (0),
  222350. latency (0),
  222351. isInput (forInput),
  222352. sampleFormat (AudioDataConverters::int16LE)
  222353. {
  222354. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222355. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222356. SND_PCM_ASYNC));
  222357. }
  222358. ~ALSADevice()
  222359. {
  222360. if (handle != 0)
  222361. snd_pcm_close (handle);
  222362. }
  222363. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222364. {
  222365. if (handle == 0)
  222366. return false;
  222367. snd_pcm_hw_params_t* hwParams;
  222368. snd_pcm_hw_params_alloca (&hwParams);
  222369. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222370. return false;
  222371. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222372. isInterleaved = false;
  222373. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222374. isInterleaved = true;
  222375. else
  222376. {
  222377. jassertfalse;
  222378. return false;
  222379. }
  222380. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  222381. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  222382. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  222383. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  222384. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  222385. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  222386. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  222387. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  222388. bitDepth = 0;
  222389. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  222390. {
  222391. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222392. {
  222393. bitDepth = formatsToTry [i + 1];
  222394. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  222395. break;
  222396. }
  222397. }
  222398. if (bitDepth == 0)
  222399. {
  222400. error = "device doesn't support a compatible PCM format";
  222401. DBG ("ALSA error: " + error + "\n");
  222402. return false;
  222403. }
  222404. int dir = 0;
  222405. unsigned int periods = 4;
  222406. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222407. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222408. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222409. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222410. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222411. || failed (snd_pcm_hw_params (handle, hwParams)))
  222412. {
  222413. return false;
  222414. }
  222415. snd_pcm_uframes_t frames = 0;
  222416. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222417. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222418. latency = 0;
  222419. else
  222420. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222421. snd_pcm_sw_params_t* swParams;
  222422. snd_pcm_sw_params_alloca (&swParams);
  222423. snd_pcm_uframes_t boundary;
  222424. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222425. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222426. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222427. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222428. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222429. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222430. || failed (snd_pcm_sw_params (handle, swParams)))
  222431. {
  222432. return false;
  222433. }
  222434. /*
  222435. #if JUCE_DEBUG
  222436. // enable this to dump the config of the devices that get opened
  222437. snd_output_t* out;
  222438. snd_output_stdio_attach (&out, stderr, 0);
  222439. snd_pcm_hw_params_dump (hwParams, out);
  222440. snd_pcm_sw_params_dump (swParams, out);
  222441. #endif
  222442. */
  222443. numChannelsRunning = numChannels;
  222444. return true;
  222445. }
  222446. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222447. {
  222448. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222449. float** const data = outputChannelBuffer.getArrayOfChannels();
  222450. if (isInterleaved)
  222451. {
  222452. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222453. float* interleaved = static_cast <float*> (scratch.getData());
  222454. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  222455. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  222456. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  222457. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222458. return false;
  222459. }
  222460. else
  222461. {
  222462. for (int i = 0; i < numChannelsRunning; ++i)
  222463. if (data[i] != 0)
  222464. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  222465. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  222466. if (failed (num))
  222467. {
  222468. if (num == -EPIPE)
  222469. {
  222470. if (failed (snd_pcm_prepare (handle)))
  222471. return false;
  222472. }
  222473. else if (num != -ESTRPIPE)
  222474. return false;
  222475. }
  222476. }
  222477. return true;
  222478. }
  222479. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222480. {
  222481. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222482. float** const data = inputChannelBuffer.getArrayOfChannels();
  222483. if (isInterleaved)
  222484. {
  222485. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222486. float* interleaved = static_cast <float*> (scratch.getData());
  222487. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  222488. if (failed (num))
  222489. {
  222490. if (num == -EPIPE)
  222491. {
  222492. if (failed (snd_pcm_prepare (handle)))
  222493. return false;
  222494. }
  222495. else if (num != -ESTRPIPE)
  222496. return false;
  222497. }
  222498. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  222499. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  222500. }
  222501. else
  222502. {
  222503. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222504. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222505. return false;
  222506. for (int i = 0; i < numChannelsRunning; ++i)
  222507. if (data[i] != 0)
  222508. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  222509. }
  222510. return true;
  222511. }
  222512. juce_UseDebuggingNewOperator
  222513. snd_pcm_t* handle;
  222514. String error;
  222515. int bitDepth, numChannelsRunning, latency;
  222516. private:
  222517. const bool isInput;
  222518. bool isInterleaved;
  222519. MemoryBlock scratch;
  222520. AudioDataConverters::DataFormat sampleFormat;
  222521. bool failed (const int errorNum)
  222522. {
  222523. if (errorNum >= 0)
  222524. return false;
  222525. error = snd_strerror (errorNum);
  222526. DBG ("ALSA error: " + error + "\n");
  222527. return true;
  222528. }
  222529. };
  222530. class ALSAThread : public Thread
  222531. {
  222532. public:
  222533. ALSAThread (const String& inputId_,
  222534. const String& outputId_)
  222535. : Thread ("Juce ALSA"),
  222536. sampleRate (0),
  222537. bufferSize (0),
  222538. outputLatency (0),
  222539. inputLatency (0),
  222540. callback (0),
  222541. inputId (inputId_),
  222542. outputId (outputId_),
  222543. numCallbacks (0),
  222544. inputChannelBuffer (1, 1),
  222545. outputChannelBuffer (1, 1)
  222546. {
  222547. initialiseRatesAndChannels();
  222548. }
  222549. ~ALSAThread()
  222550. {
  222551. close();
  222552. }
  222553. void open (BigInteger inputChannels,
  222554. BigInteger outputChannels,
  222555. const double sampleRate_,
  222556. const int bufferSize_)
  222557. {
  222558. close();
  222559. error = String::empty;
  222560. sampleRate = sampleRate_;
  222561. bufferSize = bufferSize_;
  222562. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222563. inputChannelBuffer.clear();
  222564. inputChannelDataForCallback.clear();
  222565. currentInputChans.clear();
  222566. if (inputChannels.getHighestBit() >= 0)
  222567. {
  222568. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222569. {
  222570. if (inputChannels[i])
  222571. {
  222572. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222573. currentInputChans.setBit (i);
  222574. }
  222575. }
  222576. }
  222577. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222578. outputChannelBuffer.clear();
  222579. outputChannelDataForCallback.clear();
  222580. currentOutputChans.clear();
  222581. if (outputChannels.getHighestBit() >= 0)
  222582. {
  222583. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222584. {
  222585. if (outputChannels[i])
  222586. {
  222587. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222588. currentOutputChans.setBit (i);
  222589. }
  222590. }
  222591. }
  222592. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222593. {
  222594. outputDevice = new ALSADevice (outputId, false);
  222595. if (outputDevice->error.isNotEmpty())
  222596. {
  222597. error = outputDevice->error;
  222598. outputDevice = 0;
  222599. return;
  222600. }
  222601. currentOutputChans.setRange (0, minChansOut, true);
  222602. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222603. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222604. bufferSize))
  222605. {
  222606. error = outputDevice->error;
  222607. outputDevice = 0;
  222608. return;
  222609. }
  222610. outputLatency = outputDevice->latency;
  222611. }
  222612. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222613. {
  222614. inputDevice = new ALSADevice (inputId, true);
  222615. if (inputDevice->error.isNotEmpty())
  222616. {
  222617. error = inputDevice->error;
  222618. inputDevice = 0;
  222619. return;
  222620. }
  222621. currentInputChans.setRange (0, minChansIn, true);
  222622. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222623. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222624. bufferSize))
  222625. {
  222626. error = inputDevice->error;
  222627. inputDevice = 0;
  222628. return;
  222629. }
  222630. inputLatency = inputDevice->latency;
  222631. }
  222632. if (outputDevice == 0 && inputDevice == 0)
  222633. {
  222634. error = "no channels";
  222635. return;
  222636. }
  222637. if (outputDevice != 0 && inputDevice != 0)
  222638. {
  222639. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222640. }
  222641. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222642. return;
  222643. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222644. return;
  222645. startThread (9);
  222646. int count = 1000;
  222647. while (numCallbacks == 0)
  222648. {
  222649. sleep (5);
  222650. if (--count < 0 || ! isThreadRunning())
  222651. {
  222652. error = "device didn't start";
  222653. break;
  222654. }
  222655. }
  222656. }
  222657. void close()
  222658. {
  222659. stopThread (6000);
  222660. inputDevice = 0;
  222661. outputDevice = 0;
  222662. inputChannelBuffer.setSize (1, 1);
  222663. outputChannelBuffer.setSize (1, 1);
  222664. numCallbacks = 0;
  222665. }
  222666. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222667. {
  222668. const ScopedLock sl (callbackLock);
  222669. callback = newCallback;
  222670. }
  222671. void run()
  222672. {
  222673. while (! threadShouldExit())
  222674. {
  222675. if (inputDevice != 0)
  222676. {
  222677. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  222678. {
  222679. DBG ("ALSA: read failure");
  222680. break;
  222681. }
  222682. }
  222683. if (threadShouldExit())
  222684. break;
  222685. {
  222686. const ScopedLock sl (callbackLock);
  222687. ++numCallbacks;
  222688. if (callback != 0)
  222689. {
  222690. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222691. inputChannelDataForCallback.size(),
  222692. outputChannelDataForCallback.getRawDataPointer(),
  222693. outputChannelDataForCallback.size(),
  222694. bufferSize);
  222695. }
  222696. else
  222697. {
  222698. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222699. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222700. }
  222701. }
  222702. if (outputDevice != 0)
  222703. {
  222704. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222705. if (threadShouldExit())
  222706. break;
  222707. failed (snd_pcm_avail_update (outputDevice->handle));
  222708. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  222709. {
  222710. DBG ("ALSA: write failure");
  222711. break;
  222712. }
  222713. }
  222714. }
  222715. }
  222716. int getBitDepth() const throw()
  222717. {
  222718. if (outputDevice != 0)
  222719. return outputDevice->bitDepth;
  222720. if (inputDevice != 0)
  222721. return inputDevice->bitDepth;
  222722. return 16;
  222723. }
  222724. juce_UseDebuggingNewOperator
  222725. String error;
  222726. double sampleRate;
  222727. int bufferSize, outputLatency, inputLatency;
  222728. BigInteger currentInputChans, currentOutputChans;
  222729. Array <int> sampleRates;
  222730. StringArray channelNamesOut, channelNamesIn;
  222731. AudioIODeviceCallback* callback;
  222732. private:
  222733. const String inputId, outputId;
  222734. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222735. int numCallbacks;
  222736. CriticalSection callbackLock;
  222737. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222738. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222739. unsigned int minChansOut, maxChansOut;
  222740. unsigned int minChansIn, maxChansIn;
  222741. bool failed (const int errorNum)
  222742. {
  222743. if (errorNum >= 0)
  222744. return false;
  222745. error = snd_strerror (errorNum);
  222746. DBG ("ALSA error: " + error + "\n");
  222747. return true;
  222748. }
  222749. void initialiseRatesAndChannels()
  222750. {
  222751. sampleRates.clear();
  222752. channelNamesOut.clear();
  222753. channelNamesIn.clear();
  222754. minChansOut = 0;
  222755. maxChansOut = 0;
  222756. minChansIn = 0;
  222757. maxChansIn = 0;
  222758. unsigned int dummy = 0;
  222759. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222760. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222761. unsigned int i;
  222762. for (i = 0; i < maxChansOut; ++i)
  222763. channelNamesOut.add ("channel " + String ((int) i + 1));
  222764. for (i = 0; i < maxChansIn; ++i)
  222765. channelNamesIn.add ("channel " + String ((int) i + 1));
  222766. }
  222767. };
  222768. class ALSAAudioIODevice : public AudioIODevice
  222769. {
  222770. public:
  222771. ALSAAudioIODevice (const String& deviceName,
  222772. const String& inputId_,
  222773. const String& outputId_)
  222774. : AudioIODevice (deviceName, "ALSA"),
  222775. inputId (inputId_),
  222776. outputId (outputId_),
  222777. isOpen_ (false),
  222778. isStarted (false),
  222779. internal (inputId_, outputId_)
  222780. {
  222781. }
  222782. ~ALSAAudioIODevice()
  222783. {
  222784. }
  222785. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222786. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222787. int getNumSampleRates() { return internal.sampleRates.size(); }
  222788. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222789. int getDefaultBufferSize() { return 512; }
  222790. int getNumBufferSizesAvailable() { return 50; }
  222791. int getBufferSizeSamples (int index)
  222792. {
  222793. int n = 16;
  222794. for (int i = 0; i < index; ++i)
  222795. n += n < 64 ? 16
  222796. : (n < 512 ? 32
  222797. : (n < 1024 ? 64
  222798. : (n < 2048 ? 128 : 256)));
  222799. return n;
  222800. }
  222801. const String open (const BigInteger& inputChannels,
  222802. const BigInteger& outputChannels,
  222803. double sampleRate,
  222804. int bufferSizeSamples)
  222805. {
  222806. close();
  222807. if (bufferSizeSamples <= 0)
  222808. bufferSizeSamples = getDefaultBufferSize();
  222809. if (sampleRate <= 0)
  222810. {
  222811. for (int i = 0; i < getNumSampleRates(); ++i)
  222812. {
  222813. if (getSampleRate (i) >= 44100)
  222814. {
  222815. sampleRate = getSampleRate (i);
  222816. break;
  222817. }
  222818. }
  222819. }
  222820. internal.open (inputChannels, outputChannels,
  222821. sampleRate, bufferSizeSamples);
  222822. isOpen_ = internal.error.isEmpty();
  222823. return internal.error;
  222824. }
  222825. void close()
  222826. {
  222827. stop();
  222828. internal.close();
  222829. isOpen_ = false;
  222830. }
  222831. bool isOpen() { return isOpen_; }
  222832. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222833. const String getLastError() { return internal.error; }
  222834. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222835. double getCurrentSampleRate() { return internal.sampleRate; }
  222836. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222837. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222838. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222839. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222840. int getInputLatencyInSamples() { return internal.inputLatency; }
  222841. void start (AudioIODeviceCallback* callback)
  222842. {
  222843. if (! isOpen_)
  222844. callback = 0;
  222845. if (callback != 0)
  222846. callback->audioDeviceAboutToStart (this);
  222847. internal.setCallback (callback);
  222848. isStarted = (callback != 0);
  222849. }
  222850. void stop()
  222851. {
  222852. AudioIODeviceCallback* const oldCallback = internal.callback;
  222853. start (0);
  222854. if (oldCallback != 0)
  222855. oldCallback->audioDeviceStopped();
  222856. }
  222857. String inputId, outputId;
  222858. private:
  222859. bool isOpen_, isStarted;
  222860. ALSAThread internal;
  222861. };
  222862. class ALSAAudioIODeviceType : public AudioIODeviceType
  222863. {
  222864. public:
  222865. ALSAAudioIODeviceType()
  222866. : AudioIODeviceType ("ALSA"),
  222867. hasScanned (false)
  222868. {
  222869. }
  222870. ~ALSAAudioIODeviceType()
  222871. {
  222872. }
  222873. void scanForDevices()
  222874. {
  222875. if (hasScanned)
  222876. return;
  222877. hasScanned = true;
  222878. inputNames.clear();
  222879. inputIds.clear();
  222880. outputNames.clear();
  222881. outputIds.clear();
  222882. snd_ctl_t* handle = 0;
  222883. snd_ctl_card_info_t* info = 0;
  222884. snd_ctl_card_info_alloca (&info);
  222885. int cardNum = -1;
  222886. while (outputIds.size() + inputIds.size() <= 32)
  222887. {
  222888. snd_card_next (&cardNum);
  222889. if (cardNum < 0)
  222890. break;
  222891. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222892. {
  222893. if (snd_ctl_card_info (handle, info) >= 0)
  222894. {
  222895. String cardId (snd_ctl_card_info_get_id (info));
  222896. if (cardId.removeCharacters ("0123456789").isEmpty())
  222897. cardId = String (cardNum);
  222898. int device = -1;
  222899. for (;;)
  222900. {
  222901. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222902. break;
  222903. String id, name;
  222904. id << "hw:" << cardId << ',' << device;
  222905. bool isInput, isOutput;
  222906. if (testDevice (id, isInput, isOutput))
  222907. {
  222908. name << snd_ctl_card_info_get_name (info);
  222909. if (name.isEmpty())
  222910. name = id;
  222911. if (isInput)
  222912. {
  222913. inputNames.add (name);
  222914. inputIds.add (id);
  222915. }
  222916. if (isOutput)
  222917. {
  222918. outputNames.add (name);
  222919. outputIds.add (id);
  222920. }
  222921. }
  222922. }
  222923. }
  222924. snd_ctl_close (handle);
  222925. }
  222926. }
  222927. inputNames.appendNumbersToDuplicates (false, true);
  222928. outputNames.appendNumbersToDuplicates (false, true);
  222929. }
  222930. const StringArray getDeviceNames (bool wantInputNames) const
  222931. {
  222932. jassert (hasScanned); // need to call scanForDevices() before doing this
  222933. return wantInputNames ? inputNames : outputNames;
  222934. }
  222935. int getDefaultDeviceIndex (bool forInput) const
  222936. {
  222937. jassert (hasScanned); // need to call scanForDevices() before doing this
  222938. return 0;
  222939. }
  222940. bool hasSeparateInputsAndOutputs() const { return true; }
  222941. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222942. {
  222943. jassert (hasScanned); // need to call scanForDevices() before doing this
  222944. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222945. if (d == 0)
  222946. return -1;
  222947. return asInput ? inputIds.indexOf (d->inputId)
  222948. : outputIds.indexOf (d->outputId);
  222949. }
  222950. AudioIODevice* createDevice (const String& outputDeviceName,
  222951. const String& inputDeviceName)
  222952. {
  222953. jassert (hasScanned); // need to call scanForDevices() before doing this
  222954. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222955. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222956. String deviceName (outputIndex >= 0 ? outputDeviceName
  222957. : inputDeviceName);
  222958. if (inputIndex >= 0 || outputIndex >= 0)
  222959. return new ALSAAudioIODevice (deviceName,
  222960. inputIds [inputIndex],
  222961. outputIds [outputIndex]);
  222962. return 0;
  222963. }
  222964. juce_UseDebuggingNewOperator
  222965. private:
  222966. StringArray inputNames, outputNames, inputIds, outputIds;
  222967. bool hasScanned;
  222968. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222969. {
  222970. unsigned int minChansOut = 0, maxChansOut = 0;
  222971. unsigned int minChansIn = 0, maxChansIn = 0;
  222972. Array <int> rates;
  222973. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222974. DBG ("ALSA device: " + id
  222975. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222976. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222977. + " rates=" + String (rates.size()));
  222978. isInput = maxChansIn > 0;
  222979. isOutput = maxChansOut > 0;
  222980. return (isInput || isOutput) && rates.size() > 0;
  222981. }
  222982. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  222983. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  222984. };
  222985. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222986. {
  222987. return new ALSAAudioIODeviceType();
  222988. }
  222989. #endif
  222990. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222991. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222992. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222993. // compiled on its own).
  222994. #ifdef JUCE_INCLUDED_FILE
  222995. #if JUCE_JACK
  222996. static void* juce_libjack_handle = 0;
  222997. void* juce_load_jack_function (const char* const name)
  222998. {
  222999. if (juce_libjack_handle == 0)
  223000. return 0;
  223001. return dlsym (juce_libjack_handle, name);
  223002. }
  223003. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223004. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223005. return_type fn_name argument_types { \
  223006. static fn_name##_ptr_t fn = 0; \
  223007. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223008. if (fn) return (*fn)arguments; \
  223009. else return 0; \
  223010. }
  223011. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223012. typedef void (*fn_name##_ptr_t)argument_types; \
  223013. void fn_name argument_types { \
  223014. static fn_name##_ptr_t fn = 0; \
  223015. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223016. if (fn) (*fn)arguments; \
  223017. }
  223018. JUCE_DECL_JACK_FUNCTION (jack_client_t*, jack_client_open, (const char* client_name, jack_options_t options, jack_status_t* status), (client_name, options, status));
  223019. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223020. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223021. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223022. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223023. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223024. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223025. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223026. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223027. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_register, (jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size), (client, port_name, port_type, flags, buffer_size));
  223028. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223029. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223030. JUCE_DECL_JACK_FUNCTION (const char**, jack_get_ports, (jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags), (client, port_name_pattern, type_name_pattern, flags));
  223031. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223032. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223033. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223034. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223035. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223036. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223037. #if JUCE_DEBUG
  223038. #define JACK_LOGGING_ENABLED 1
  223039. #endif
  223040. #if JACK_LOGGING_ENABLED
  223041. static void jack_Log (const String& s)
  223042. {
  223043. std::cerr << s << std::endl;
  223044. }
  223045. static void dumpJackErrorMessage (const jack_status_t status)
  223046. {
  223047. if (status & JackServerFailed || status & JackServerError)
  223048. jack_Log ("Unable to connect to JACK server");
  223049. if (status & JackVersionError)
  223050. jack_Log ("Client's protocol version does not match");
  223051. if (status & JackInvalidOption)
  223052. jack_Log ("The operation contained an invalid or unsupported option");
  223053. if (status & JackNameNotUnique)
  223054. jack_Log ("The desired client name was not unique");
  223055. if (status & JackNoSuchClient)
  223056. jack_Log ("Requested client does not exist");
  223057. if (status & JackInitFailure)
  223058. jack_Log ("Unable to initialize client");
  223059. }
  223060. #else
  223061. #define dumpJackErrorMessage(a) {}
  223062. #define jack_Log(...) {}
  223063. #endif
  223064. #ifndef JUCE_JACK_CLIENT_NAME
  223065. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223066. #endif
  223067. class JackAudioIODevice : public AudioIODevice
  223068. {
  223069. public:
  223070. JackAudioIODevice (const String& deviceName,
  223071. const String& inputId_,
  223072. const String& outputId_)
  223073. : AudioIODevice (deviceName, "JACK"),
  223074. inputId (inputId_),
  223075. outputId (outputId_),
  223076. isOpen_ (false),
  223077. callback (0),
  223078. totalNumberOfInputChannels (0),
  223079. totalNumberOfOutputChannels (0)
  223080. {
  223081. jassert (deviceName.isNotEmpty());
  223082. jack_status_t status;
  223083. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223084. if (client == 0)
  223085. {
  223086. dumpJackErrorMessage (status);
  223087. }
  223088. else
  223089. {
  223090. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223091. // open input ports
  223092. const StringArray inputChannels (getInputChannelNames());
  223093. for (int i = 0; i < inputChannels.size(); i++)
  223094. {
  223095. String inputName;
  223096. inputName << "in_" << ++totalNumberOfInputChannels;
  223097. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223098. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223099. }
  223100. // open output ports
  223101. const StringArray outputChannels (getOutputChannelNames());
  223102. for (int i = 0; i < outputChannels.size (); i++)
  223103. {
  223104. String outputName;
  223105. outputName << "out_" << ++totalNumberOfOutputChannels;
  223106. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223107. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223108. }
  223109. inChans.calloc (totalNumberOfInputChannels + 2);
  223110. outChans.calloc (totalNumberOfOutputChannels + 2);
  223111. }
  223112. }
  223113. ~JackAudioIODevice()
  223114. {
  223115. close();
  223116. if (client != 0)
  223117. {
  223118. JUCE_NAMESPACE::jack_client_close (client);
  223119. client = 0;
  223120. }
  223121. }
  223122. const StringArray getChannelNames (bool forInput) const
  223123. {
  223124. StringArray names;
  223125. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223126. forInput ? JackPortIsInput : JackPortIsOutput);
  223127. if (ports != 0)
  223128. {
  223129. int j = 0;
  223130. while (ports[j] != 0)
  223131. {
  223132. const String portName (ports [j++]);
  223133. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223134. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223135. }
  223136. free (ports);
  223137. }
  223138. return names;
  223139. }
  223140. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223141. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223142. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223143. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223144. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223145. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223146. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223147. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223148. double sampleRate, int bufferSizeSamples)
  223149. {
  223150. if (client == 0)
  223151. {
  223152. lastError = "No JACK client running";
  223153. return lastError;
  223154. }
  223155. lastError = String::empty;
  223156. close();
  223157. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223158. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223159. JUCE_NAMESPACE::jack_activate (client);
  223160. isOpen_ = true;
  223161. if (! inputChannels.isZero())
  223162. {
  223163. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223164. if (ports != 0)
  223165. {
  223166. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223167. for (int i = 0; i < numInputChannels; ++i)
  223168. {
  223169. const String portName (ports[i]);
  223170. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223171. {
  223172. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223173. if (error != 0)
  223174. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223175. }
  223176. }
  223177. free (ports);
  223178. }
  223179. }
  223180. if (! outputChannels.isZero())
  223181. {
  223182. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223183. if (ports != 0)
  223184. {
  223185. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223186. for (int i = 0; i < numOutputChannels; ++i)
  223187. {
  223188. const String portName (ports[i]);
  223189. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223190. {
  223191. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223192. if (error != 0)
  223193. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223194. }
  223195. }
  223196. free (ports);
  223197. }
  223198. }
  223199. return lastError;
  223200. }
  223201. void close()
  223202. {
  223203. stop();
  223204. if (client != 0)
  223205. {
  223206. JUCE_NAMESPACE::jack_deactivate (client);
  223207. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223208. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223209. }
  223210. isOpen_ = false;
  223211. }
  223212. void start (AudioIODeviceCallback* newCallback)
  223213. {
  223214. if (isOpen_ && newCallback != callback)
  223215. {
  223216. if (newCallback != 0)
  223217. newCallback->audioDeviceAboutToStart (this);
  223218. AudioIODeviceCallback* const oldCallback = callback;
  223219. {
  223220. const ScopedLock sl (callbackLock);
  223221. callback = newCallback;
  223222. }
  223223. if (oldCallback != 0)
  223224. oldCallback->audioDeviceStopped();
  223225. }
  223226. }
  223227. void stop()
  223228. {
  223229. start (0);
  223230. }
  223231. bool isOpen() { return isOpen_; }
  223232. bool isPlaying() { return callback != 0; }
  223233. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223234. double getCurrentSampleRate() { return getSampleRate (0); }
  223235. int getCurrentBitDepth() { return 32; }
  223236. const String getLastError() { return lastError; }
  223237. const BigInteger getActiveOutputChannels() const
  223238. {
  223239. BigInteger outputBits;
  223240. for (int i = 0; i < outputPorts.size(); i++)
  223241. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223242. outputBits.setBit (i);
  223243. return outputBits;
  223244. }
  223245. const BigInteger getActiveInputChannels() const
  223246. {
  223247. BigInteger inputBits;
  223248. for (int i = 0; i < inputPorts.size(); i++)
  223249. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223250. inputBits.setBit (i);
  223251. return inputBits;
  223252. }
  223253. int getOutputLatencyInSamples()
  223254. {
  223255. int latency = 0;
  223256. for (int i = 0; i < outputPorts.size(); i++)
  223257. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223258. return latency;
  223259. }
  223260. int getInputLatencyInSamples()
  223261. {
  223262. int latency = 0;
  223263. for (int i = 0; i < inputPorts.size(); i++)
  223264. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223265. return latency;
  223266. }
  223267. String inputId, outputId;
  223268. private:
  223269. void process (const int numSamples)
  223270. {
  223271. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223272. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223273. {
  223274. jack_default_audio_sample_t* in
  223275. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223276. if (in != 0)
  223277. inChans [numActiveInChans++] = (float*) in;
  223278. }
  223279. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223280. {
  223281. jack_default_audio_sample_t* out
  223282. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223283. if (out != 0)
  223284. outChans [numActiveOutChans++] = (float*) out;
  223285. }
  223286. const ScopedLock sl (callbackLock);
  223287. if (callback != 0)
  223288. {
  223289. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223290. outChans, numActiveOutChans, numSamples);
  223291. }
  223292. else
  223293. {
  223294. for (i = 0; i < numActiveOutChans; ++i)
  223295. zeromem (outChans[i], sizeof (float) * numSamples);
  223296. }
  223297. }
  223298. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223299. {
  223300. if (callbackArgument != 0)
  223301. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223302. return 0;
  223303. }
  223304. static void threadInitCallback (void* callbackArgument)
  223305. {
  223306. jack_Log ("JackAudioIODevice::initialise");
  223307. }
  223308. static void shutdownCallback (void* callbackArgument)
  223309. {
  223310. jack_Log ("JackAudioIODevice::shutdown");
  223311. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223312. if (device != 0)
  223313. {
  223314. device->client = 0;
  223315. device->close();
  223316. }
  223317. }
  223318. static void errorCallback (const char* msg)
  223319. {
  223320. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223321. }
  223322. bool isOpen_;
  223323. jack_client_t* client;
  223324. String lastError;
  223325. AudioIODeviceCallback* callback;
  223326. CriticalSection callbackLock;
  223327. HeapBlock <float*> inChans, outChans;
  223328. int totalNumberOfInputChannels;
  223329. int totalNumberOfOutputChannels;
  223330. Array<void*> inputPorts, outputPorts;
  223331. };
  223332. class JackAudioIODeviceType : public AudioIODeviceType
  223333. {
  223334. public:
  223335. JackAudioIODeviceType()
  223336. : AudioIODeviceType ("JACK"),
  223337. hasScanned (false)
  223338. {
  223339. }
  223340. ~JackAudioIODeviceType()
  223341. {
  223342. }
  223343. void scanForDevices()
  223344. {
  223345. hasScanned = true;
  223346. inputNames.clear();
  223347. inputIds.clear();
  223348. outputNames.clear();
  223349. outputIds.clear();
  223350. if (juce_libjack_handle == 0)
  223351. {
  223352. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223353. if (juce_libjack_handle == 0)
  223354. return;
  223355. }
  223356. // open a dummy client
  223357. jack_status_t status;
  223358. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223359. if (client == 0)
  223360. {
  223361. dumpJackErrorMessage (status);
  223362. }
  223363. else
  223364. {
  223365. // scan for output devices
  223366. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223367. if (ports != 0)
  223368. {
  223369. int j = 0;
  223370. while (ports[j] != 0)
  223371. {
  223372. String clientName (ports[j]);
  223373. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223374. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223375. && ! inputNames.contains (clientName))
  223376. {
  223377. inputNames.add (clientName);
  223378. inputIds.add (ports [j]);
  223379. }
  223380. ++j;
  223381. }
  223382. free (ports);
  223383. }
  223384. // scan for input devices
  223385. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223386. if (ports != 0)
  223387. {
  223388. int j = 0;
  223389. while (ports[j] != 0)
  223390. {
  223391. String clientName (ports[j]);
  223392. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223393. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223394. && ! outputNames.contains (clientName))
  223395. {
  223396. outputNames.add (clientName);
  223397. outputIds.add (ports [j]);
  223398. }
  223399. ++j;
  223400. }
  223401. free (ports);
  223402. }
  223403. JUCE_NAMESPACE::jack_client_close (client);
  223404. }
  223405. }
  223406. const StringArray getDeviceNames (bool wantInputNames) const
  223407. {
  223408. jassert (hasScanned); // need to call scanForDevices() before doing this
  223409. return wantInputNames ? inputNames : outputNames;
  223410. }
  223411. int getDefaultDeviceIndex (bool forInput) const
  223412. {
  223413. jassert (hasScanned); // need to call scanForDevices() before doing this
  223414. return 0;
  223415. }
  223416. bool hasSeparateInputsAndOutputs() const { return true; }
  223417. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223418. {
  223419. jassert (hasScanned); // need to call scanForDevices() before doing this
  223420. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223421. if (d == 0)
  223422. return -1;
  223423. return asInput ? inputIds.indexOf (d->inputId)
  223424. : outputIds.indexOf (d->outputId);
  223425. }
  223426. AudioIODevice* createDevice (const String& outputDeviceName,
  223427. const String& inputDeviceName)
  223428. {
  223429. jassert (hasScanned); // need to call scanForDevices() before doing this
  223430. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223431. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223432. if (inputIndex >= 0 || outputIndex >= 0)
  223433. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223434. : inputDeviceName,
  223435. inputIds [inputIndex],
  223436. outputIds [outputIndex]);
  223437. return 0;
  223438. }
  223439. juce_UseDebuggingNewOperator
  223440. private:
  223441. StringArray inputNames, outputNames, inputIds, outputIds;
  223442. bool hasScanned;
  223443. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223444. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223445. };
  223446. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223447. {
  223448. return new JackAudioIODeviceType();
  223449. }
  223450. #else // if JACK is turned off..
  223451. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223452. #endif
  223453. #endif
  223454. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223455. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223456. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223457. // compiled on its own).
  223458. #if JUCE_INCLUDED_FILE
  223459. #if JUCE_ALSA
  223460. static snd_seq_t* iterateDevices (const bool forInput,
  223461. StringArray& deviceNamesFound,
  223462. const int deviceIndexToOpen)
  223463. {
  223464. snd_seq_t* returnedHandle = 0;
  223465. snd_seq_t* seqHandle;
  223466. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223467. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223468. {
  223469. snd_seq_system_info_t* systemInfo;
  223470. snd_seq_client_info_t* clientInfo;
  223471. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223472. {
  223473. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223474. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223475. {
  223476. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223477. while (--numClients >= 0 && returnedHandle == 0)
  223478. {
  223479. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223480. {
  223481. snd_seq_port_info_t* portInfo;
  223482. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223483. {
  223484. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223485. const int client = snd_seq_client_info_get_client (clientInfo);
  223486. snd_seq_port_info_set_client (portInfo, client);
  223487. snd_seq_port_info_set_port (portInfo, -1);
  223488. while (--numPorts >= 0)
  223489. {
  223490. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223491. && (snd_seq_port_info_get_capability (portInfo)
  223492. & (forInput ? SND_SEQ_PORT_CAP_READ
  223493. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223494. {
  223495. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223496. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223497. {
  223498. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223499. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223500. if (sourcePort != -1)
  223501. {
  223502. snd_seq_set_client_name (seqHandle,
  223503. forInput ? "Juce Midi Input"
  223504. : "Juce Midi Output");
  223505. const int portId
  223506. = snd_seq_create_simple_port (seqHandle,
  223507. forInput ? "Juce Midi In Port"
  223508. : "Juce Midi Out Port",
  223509. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223510. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223511. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223512. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223513. returnedHandle = seqHandle;
  223514. }
  223515. }
  223516. }
  223517. }
  223518. snd_seq_port_info_free (portInfo);
  223519. }
  223520. }
  223521. }
  223522. snd_seq_client_info_free (clientInfo);
  223523. }
  223524. snd_seq_system_info_free (systemInfo);
  223525. }
  223526. if (returnedHandle == 0)
  223527. snd_seq_close (seqHandle);
  223528. }
  223529. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223530. return returnedHandle;
  223531. }
  223532. static snd_seq_t* createDevice (const bool forInput,
  223533. const String& deviceNameToOpen)
  223534. {
  223535. snd_seq_t* seqHandle = 0;
  223536. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223537. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223538. {
  223539. snd_seq_set_client_name (seqHandle,
  223540. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223541. const int portId
  223542. = snd_seq_create_simple_port (seqHandle,
  223543. forInput ? "in"
  223544. : "out",
  223545. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223546. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223547. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223548. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223549. if (portId < 0)
  223550. {
  223551. snd_seq_close (seqHandle);
  223552. seqHandle = 0;
  223553. }
  223554. }
  223555. return seqHandle;
  223556. }
  223557. class MidiOutputDevice
  223558. {
  223559. public:
  223560. MidiOutputDevice (MidiOutput* const midiOutput_,
  223561. snd_seq_t* const seqHandle_)
  223562. :
  223563. midiOutput (midiOutput_),
  223564. seqHandle (seqHandle_),
  223565. maxEventSize (16 * 1024)
  223566. {
  223567. jassert (seqHandle != 0 && midiOutput != 0);
  223568. snd_midi_event_new (maxEventSize, &midiParser);
  223569. }
  223570. ~MidiOutputDevice()
  223571. {
  223572. snd_midi_event_free (midiParser);
  223573. snd_seq_close (seqHandle);
  223574. }
  223575. void sendMessageNow (const MidiMessage& message)
  223576. {
  223577. if (message.getRawDataSize() > maxEventSize)
  223578. {
  223579. maxEventSize = message.getRawDataSize();
  223580. snd_midi_event_free (midiParser);
  223581. snd_midi_event_new (maxEventSize, &midiParser);
  223582. }
  223583. snd_seq_event_t event;
  223584. snd_seq_ev_clear (&event);
  223585. snd_midi_event_encode (midiParser,
  223586. message.getRawData(),
  223587. message.getRawDataSize(),
  223588. &event);
  223589. snd_midi_event_reset_encode (midiParser);
  223590. snd_seq_ev_set_source (&event, 0);
  223591. snd_seq_ev_set_subs (&event);
  223592. snd_seq_ev_set_direct (&event);
  223593. snd_seq_event_output (seqHandle, &event);
  223594. snd_seq_drain_output (seqHandle);
  223595. }
  223596. juce_UseDebuggingNewOperator
  223597. private:
  223598. MidiOutput* const midiOutput;
  223599. snd_seq_t* const seqHandle;
  223600. snd_midi_event_t* midiParser;
  223601. int maxEventSize;
  223602. };
  223603. const StringArray MidiOutput::getDevices()
  223604. {
  223605. StringArray devices;
  223606. iterateDevices (false, devices, -1);
  223607. return devices;
  223608. }
  223609. int MidiOutput::getDefaultDeviceIndex()
  223610. {
  223611. return 0;
  223612. }
  223613. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223614. {
  223615. MidiOutput* newDevice = 0;
  223616. StringArray devices;
  223617. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  223618. if (handle != 0)
  223619. {
  223620. newDevice = new MidiOutput();
  223621. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223622. }
  223623. return newDevice;
  223624. }
  223625. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223626. {
  223627. MidiOutput* newDevice = 0;
  223628. snd_seq_t* const handle = createDevice (false, deviceName);
  223629. if (handle != 0)
  223630. {
  223631. newDevice = new MidiOutput();
  223632. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223633. }
  223634. return newDevice;
  223635. }
  223636. MidiOutput::~MidiOutput()
  223637. {
  223638. delete static_cast <MidiOutputDevice*> (internal);
  223639. }
  223640. void MidiOutput::reset()
  223641. {
  223642. }
  223643. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223644. {
  223645. return false;
  223646. }
  223647. void MidiOutput::setVolume (float leftVol, float rightVol)
  223648. {
  223649. }
  223650. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223651. {
  223652. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223653. }
  223654. class MidiInputThread : public Thread
  223655. {
  223656. public:
  223657. MidiInputThread (MidiInput* const midiInput_,
  223658. snd_seq_t* const seqHandle_,
  223659. MidiInputCallback* const callback_)
  223660. : Thread ("Juce MIDI Input"),
  223661. midiInput (midiInput_),
  223662. seqHandle (seqHandle_),
  223663. callback (callback_)
  223664. {
  223665. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223666. }
  223667. ~MidiInputThread()
  223668. {
  223669. snd_seq_close (seqHandle);
  223670. }
  223671. void run()
  223672. {
  223673. const int maxEventSize = 16 * 1024;
  223674. snd_midi_event_t* midiParser;
  223675. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223676. {
  223677. HeapBlock <uint8> buffer (maxEventSize);
  223678. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223679. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223680. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223681. while (! threadShouldExit())
  223682. {
  223683. if (poll (pfd, numPfds, 500) > 0)
  223684. {
  223685. snd_seq_event_t* inputEvent = 0;
  223686. snd_seq_nonblock (seqHandle, 1);
  223687. do
  223688. {
  223689. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223690. {
  223691. // xxx what about SYSEXes that are too big for the buffer?
  223692. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223693. snd_midi_event_reset_decode (midiParser);
  223694. if (numBytes > 0)
  223695. {
  223696. const MidiMessage message ((const uint8*) buffer,
  223697. numBytes,
  223698. Time::getMillisecondCounter() * 0.001);
  223699. callback->handleIncomingMidiMessage (midiInput, message);
  223700. }
  223701. snd_seq_free_event (inputEvent);
  223702. }
  223703. }
  223704. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223705. snd_seq_free_event (inputEvent);
  223706. }
  223707. }
  223708. snd_midi_event_free (midiParser);
  223709. }
  223710. };
  223711. juce_UseDebuggingNewOperator
  223712. private:
  223713. MidiInput* const midiInput;
  223714. snd_seq_t* const seqHandle;
  223715. MidiInputCallback* const callback;
  223716. };
  223717. MidiInput::MidiInput (const String& name_)
  223718. : name (name_),
  223719. internal (0)
  223720. {
  223721. }
  223722. MidiInput::~MidiInput()
  223723. {
  223724. stop();
  223725. delete static_cast <MidiInputThread*> (internal);
  223726. }
  223727. void MidiInput::start()
  223728. {
  223729. static_cast <MidiInputThread*> (internal)->startThread();
  223730. }
  223731. void MidiInput::stop()
  223732. {
  223733. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223734. }
  223735. int MidiInput::getDefaultDeviceIndex()
  223736. {
  223737. return 0;
  223738. }
  223739. const StringArray MidiInput::getDevices()
  223740. {
  223741. StringArray devices;
  223742. iterateDevices (true, devices, -1);
  223743. return devices;
  223744. }
  223745. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223746. {
  223747. MidiInput* newDevice = 0;
  223748. StringArray devices;
  223749. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  223750. if (handle != 0)
  223751. {
  223752. newDevice = new MidiInput (devices [deviceIndex]);
  223753. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223754. }
  223755. return newDevice;
  223756. }
  223757. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223758. {
  223759. MidiInput* newDevice = 0;
  223760. snd_seq_t* const handle = createDevice (true, deviceName);
  223761. if (handle != 0)
  223762. {
  223763. newDevice = new MidiInput (deviceName);
  223764. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223765. }
  223766. return newDevice;
  223767. }
  223768. #else
  223769. // (These are just stub functions if ALSA is unavailable...)
  223770. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223771. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223772. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223773. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223774. MidiOutput::~MidiOutput() {}
  223775. void MidiOutput::reset() {}
  223776. bool MidiOutput::getVolume (float&, float&) { return false; }
  223777. void MidiOutput::setVolume (float, float) {}
  223778. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223779. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223780. MidiInput::~MidiInput() {}
  223781. void MidiInput::start() {}
  223782. void MidiInput::stop() {}
  223783. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223784. const StringArray MidiInput::getDevices() { return StringArray(); }
  223785. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223786. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223787. #endif
  223788. #endif
  223789. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223790. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223791. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223792. // compiled on its own).
  223793. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223794. AudioCDReader::AudioCDReader()
  223795. : AudioFormatReader (0, "CD Audio")
  223796. {
  223797. }
  223798. const StringArray AudioCDReader::getAvailableCDNames()
  223799. {
  223800. StringArray names;
  223801. return names;
  223802. }
  223803. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223804. {
  223805. return 0;
  223806. }
  223807. AudioCDReader::~AudioCDReader()
  223808. {
  223809. }
  223810. void AudioCDReader::refreshTrackLengths()
  223811. {
  223812. }
  223813. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223814. int64 startSampleInFile, int numSamples)
  223815. {
  223816. return false;
  223817. }
  223818. bool AudioCDReader::isCDStillPresent() const
  223819. {
  223820. return false;
  223821. }
  223822. bool AudioCDReader::isTrackAudio (int trackNum) const
  223823. {
  223824. return false;
  223825. }
  223826. void AudioCDReader::enableIndexScanning (bool b)
  223827. {
  223828. }
  223829. int AudioCDReader::getLastIndex() const
  223830. {
  223831. return 0;
  223832. }
  223833. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223834. {
  223835. return Array<int>();
  223836. }
  223837. #endif
  223838. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223839. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223840. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223841. // compiled on its own).
  223842. #if JUCE_INCLUDED_FILE
  223843. void FileChooser::showPlatformDialog (Array<File>& results,
  223844. const String& title,
  223845. const File& file,
  223846. const String& filters,
  223847. bool isDirectory,
  223848. bool selectsFiles,
  223849. bool isSave,
  223850. bool warnAboutOverwritingExistingFiles,
  223851. bool selectMultipleFiles,
  223852. FilePreviewComponent* previewComponent)
  223853. {
  223854. const String separator (":");
  223855. String command ("zenity --file-selection");
  223856. if (title.isNotEmpty())
  223857. command << " --title=\"" << title << "\"";
  223858. if (file != File::nonexistent)
  223859. command << " --filename=\"" << file.getFullPathName () << "\"";
  223860. if (isDirectory)
  223861. command << " --directory";
  223862. if (isSave)
  223863. command << " --save";
  223864. if (selectMultipleFiles)
  223865. command << " --multiple --separator=\"" << separator << "\"";
  223866. command << " 2>&1";
  223867. MemoryOutputStream result;
  223868. int status = -1;
  223869. FILE* stream = popen (command.toUTF8(), "r");
  223870. if (stream != 0)
  223871. {
  223872. for (;;)
  223873. {
  223874. char buffer [1024];
  223875. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223876. if (bytesRead <= 0)
  223877. break;
  223878. result.write (buffer, bytesRead);
  223879. }
  223880. status = pclose (stream);
  223881. }
  223882. if (status == 0)
  223883. {
  223884. StringArray tokens;
  223885. if (selectMultipleFiles)
  223886. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223887. else
  223888. tokens.add (result.toUTF8());
  223889. for (int i = 0; i < tokens.size(); i++)
  223890. results.add (File (tokens[i]));
  223891. return;
  223892. }
  223893. //xxx ain't got one!
  223894. jassertfalse;
  223895. }
  223896. #endif
  223897. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223898. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223899. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223900. // compiled on its own).
  223901. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223902. /*
  223903. Sorry.. This class isn't implemented on Linux!
  223904. */
  223905. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223906. : browser (0),
  223907. blankPageShown (false),
  223908. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223909. {
  223910. setOpaque (true);
  223911. }
  223912. WebBrowserComponent::~WebBrowserComponent()
  223913. {
  223914. }
  223915. void WebBrowserComponent::goToURL (const String& url,
  223916. const StringArray* headers,
  223917. const MemoryBlock* postData)
  223918. {
  223919. lastURL = url;
  223920. lastHeaders.clear();
  223921. if (headers != 0)
  223922. lastHeaders = *headers;
  223923. lastPostData.setSize (0);
  223924. if (postData != 0)
  223925. lastPostData = *postData;
  223926. blankPageShown = false;
  223927. }
  223928. void WebBrowserComponent::stop()
  223929. {
  223930. }
  223931. void WebBrowserComponent::goBack()
  223932. {
  223933. lastURL = String::empty;
  223934. blankPageShown = false;
  223935. }
  223936. void WebBrowserComponent::goForward()
  223937. {
  223938. lastURL = String::empty;
  223939. }
  223940. void WebBrowserComponent::refresh()
  223941. {
  223942. }
  223943. void WebBrowserComponent::paint (Graphics& g)
  223944. {
  223945. g.fillAll (Colours::white);
  223946. }
  223947. void WebBrowserComponent::checkWindowAssociation()
  223948. {
  223949. }
  223950. void WebBrowserComponent::reloadLastURL()
  223951. {
  223952. if (lastURL.isNotEmpty())
  223953. {
  223954. goToURL (lastURL, &lastHeaders, &lastPostData);
  223955. lastURL = String::empty;
  223956. }
  223957. }
  223958. void WebBrowserComponent::parentHierarchyChanged()
  223959. {
  223960. checkWindowAssociation();
  223961. }
  223962. void WebBrowserComponent::resized()
  223963. {
  223964. }
  223965. void WebBrowserComponent::visibilityChanged()
  223966. {
  223967. checkWindowAssociation();
  223968. }
  223969. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223970. {
  223971. return true;
  223972. }
  223973. #endif
  223974. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223975. #endif
  223976. END_JUCE_NAMESPACE
  223977. #endif
  223978. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223979. #endif
  223980. #if JUCE_MAC || JUCE_IPHONE
  223981. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223982. /*
  223983. This file wraps together all the mac-specific code, so that
  223984. we can include all the native headers just once, and compile all our
  223985. platform-specific stuff in one big lump, keeping it out of the way of
  223986. the rest of the codebase.
  223987. */
  223988. #if JUCE_MAC || JUCE_IOS
  223989. BEGIN_JUCE_NAMESPACE
  223990. #undef Point
  223991. #define JUCE_INCLUDED_FILE 1
  223992. // Now include the actual code files..
  223993. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223994. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223995. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223996. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223997. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223998. actually calling into a similarly named class in the other module's address space.
  223999. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224000. have unique names, and should avoid this problem.
  224001. If you're using the amalgamated version, you can just set this macro to something unique before
  224002. you include juce_amalgamated.cpp.
  224003. */
  224004. #ifndef JUCE_ObjCExtraSuffix
  224005. #define JUCE_ObjCExtraSuffix 3
  224006. #endif
  224007. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224008. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224009. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224010. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224011. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224012. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224013. // compiled on its own).
  224014. #if JUCE_INCLUDED_FILE
  224015. static const String nsStringToJuce (NSString* s)
  224016. {
  224017. return String::fromUTF8 ([s UTF8String]);
  224018. }
  224019. static NSString* juceStringToNS (const String& s)
  224020. {
  224021. return [NSString stringWithUTF8String: s.toUTF8()];
  224022. }
  224023. static const String convertUTF16ToString (const UniChar* utf16)
  224024. {
  224025. String s;
  224026. while (*utf16 != 0)
  224027. s += (juce_wchar) *utf16++;
  224028. return s;
  224029. }
  224030. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224031. {
  224032. String result;
  224033. if (cfString != 0)
  224034. {
  224035. CFRange range = { 0, CFStringGetLength (cfString) };
  224036. HeapBlock <UniChar> u (range.length + 1);
  224037. CFStringGetCharacters (cfString, range, u);
  224038. u[range.length] = 0;
  224039. result = convertUTF16ToString (u);
  224040. }
  224041. return result;
  224042. }
  224043. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224044. {
  224045. const int len = s.length();
  224046. HeapBlock <UniChar> temp (len + 2);
  224047. for (int i = 0; i <= len; ++i)
  224048. temp[i] = s[i];
  224049. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224050. }
  224051. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224052. {
  224053. #if JUCE_IOS
  224054. const ScopedAutoReleasePool pool;
  224055. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224056. #else
  224057. UnicodeMapping map;
  224058. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224059. kUnicodeNoSubset,
  224060. kTextEncodingDefaultFormat);
  224061. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224062. kUnicodeCanonicalCompVariant,
  224063. kTextEncodingDefaultFormat);
  224064. map.mappingVersion = kUnicodeUseLatestMapping;
  224065. UnicodeToTextInfo conversionInfo = 0;
  224066. String result;
  224067. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224068. {
  224069. const int len = s.length();
  224070. HeapBlock <UniChar> tempIn, tempOut;
  224071. tempIn.calloc (len + 2);
  224072. tempOut.calloc (len + 2);
  224073. for (int i = 0; i <= len; ++i)
  224074. tempIn[i] = s[i];
  224075. ByteCount bytesRead = 0;
  224076. ByteCount outputBufferSize = 0;
  224077. if (ConvertFromUnicodeToText (conversionInfo,
  224078. len * sizeof (UniChar), tempIn,
  224079. kUnicodeDefaultDirectionMask,
  224080. 0, 0, 0, 0,
  224081. len * sizeof (UniChar), &bytesRead,
  224082. &outputBufferSize, tempOut) == noErr)
  224083. {
  224084. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224085. juce_wchar* t = result;
  224086. unsigned int i;
  224087. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224088. t[i] = (juce_wchar) tempOut[i];
  224089. t[i] = 0;
  224090. }
  224091. DisposeUnicodeToTextInfo (&conversionInfo);
  224092. }
  224093. return result;
  224094. #endif
  224095. }
  224096. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224097. void SystemClipboard::copyTextToClipboard (const String& text)
  224098. {
  224099. #if JUCE_IOS
  224100. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224101. forPasteboardType: @"public.text"];
  224102. #else
  224103. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224104. owner: nil];
  224105. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224106. forType: NSStringPboardType];
  224107. #endif
  224108. }
  224109. const String SystemClipboard::getTextFromClipboard()
  224110. {
  224111. #if JUCE_IOS
  224112. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224113. #else
  224114. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224115. #endif
  224116. return text == 0 ? String::empty
  224117. : nsStringToJuce (text);
  224118. }
  224119. #endif
  224120. #endif
  224121. /*** End of inlined file: juce_mac_Strings.mm ***/
  224122. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224123. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224124. // compiled on its own).
  224125. #if JUCE_INCLUDED_FILE
  224126. namespace SystemStatsHelpers
  224127. {
  224128. static int64 highResTimerFrequency = 0;
  224129. static double highResTimerToMillisecRatio = 0;
  224130. #if JUCE_INTEL
  224131. static void juce_getCpuVendor (char* const v) throw()
  224132. {
  224133. int vendor[4];
  224134. zerostruct (vendor);
  224135. int dummy = 0;
  224136. asm ("mov %%ebx, %%esi \n\t"
  224137. "cpuid \n\t"
  224138. "xchg %%esi, %%ebx"
  224139. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224140. memcpy (v, vendor, 16);
  224141. }
  224142. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224143. {
  224144. unsigned int cpu = 0;
  224145. unsigned int ext = 0;
  224146. unsigned int family = 0;
  224147. unsigned int dummy = 0;
  224148. asm ("mov %%ebx, %%esi \n\t"
  224149. "cpuid \n\t"
  224150. "xchg %%esi, %%ebx"
  224151. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224152. familyModel = family;
  224153. extFeatures = ext;
  224154. return cpu;
  224155. }
  224156. #endif
  224157. }
  224158. void SystemStats::initialiseStats()
  224159. {
  224160. using namespace SystemStatsHelpers;
  224161. static bool initialised = false;
  224162. if (! initialised)
  224163. {
  224164. initialised = true;
  224165. #if JUCE_MAC
  224166. [NSApplication sharedApplication];
  224167. #endif
  224168. #if JUCE_INTEL
  224169. unsigned int familyModel, extFeatures;
  224170. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224171. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224172. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224173. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224174. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224175. #else
  224176. cpuFlags.hasMMX = false;
  224177. cpuFlags.hasSSE = false;
  224178. cpuFlags.hasSSE2 = false;
  224179. cpuFlags.has3DNow = false;
  224180. #endif
  224181. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224182. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224183. #else
  224184. cpuFlags.numCpus = (int) MPProcessors();
  224185. #endif
  224186. mach_timebase_info_data_t timebase;
  224187. (void) mach_timebase_info (&timebase);
  224188. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224189. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224190. String s (SystemStats::getJUCEVersion());
  224191. rlimit lim;
  224192. getrlimit (RLIMIT_NOFILE, &lim);
  224193. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224194. setrlimit (RLIMIT_NOFILE, &lim);
  224195. }
  224196. }
  224197. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224198. {
  224199. return MacOSX;
  224200. }
  224201. const String SystemStats::getOperatingSystemName()
  224202. {
  224203. return "Mac OS X";
  224204. }
  224205. #if ! JUCE_IOS
  224206. int PlatformUtilities::getOSXMinorVersionNumber()
  224207. {
  224208. SInt32 versionMinor = 0;
  224209. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224210. (void) err;
  224211. jassert (err == noErr);
  224212. return (int) versionMinor;
  224213. }
  224214. #endif
  224215. bool SystemStats::isOperatingSystem64Bit()
  224216. {
  224217. #if JUCE_IOS
  224218. return false;
  224219. #elif JUCE_64BIT
  224220. return true;
  224221. #else
  224222. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224223. #endif
  224224. }
  224225. int SystemStats::getMemorySizeInMegabytes()
  224226. {
  224227. uint64 mem = 0;
  224228. size_t memSize = sizeof (mem);
  224229. int mib[] = { CTL_HW, HW_MEMSIZE };
  224230. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224231. return (int) (mem / (1024 * 1024));
  224232. }
  224233. const String SystemStats::getCpuVendor()
  224234. {
  224235. #if JUCE_INTEL
  224236. char v [16];
  224237. SystemStatsHelpers::juce_getCpuVendor (v);
  224238. return String (v, 16);
  224239. #else
  224240. return String::empty;
  224241. #endif
  224242. }
  224243. int SystemStats::getCpuSpeedInMegaherz()
  224244. {
  224245. uint64 speedHz = 0;
  224246. size_t speedSize = sizeof (speedHz);
  224247. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224248. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224249. #if JUCE_BIG_ENDIAN
  224250. if (speedSize == 4)
  224251. speedHz >>= 32;
  224252. #endif
  224253. return (int) (speedHz / 1000000);
  224254. }
  224255. const String SystemStats::getLogonName()
  224256. {
  224257. return nsStringToJuce (NSUserName());
  224258. }
  224259. const String SystemStats::getFullUserName()
  224260. {
  224261. return nsStringToJuce (NSFullUserName());
  224262. }
  224263. uint32 juce_millisecondsSinceStartup() throw()
  224264. {
  224265. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224266. }
  224267. double Time::getMillisecondCounterHiRes() throw()
  224268. {
  224269. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224270. }
  224271. int64 Time::getHighResolutionTicks() throw()
  224272. {
  224273. return (int64) mach_absolute_time();
  224274. }
  224275. int64 Time::getHighResolutionTicksPerSecond() throw()
  224276. {
  224277. return SystemStatsHelpers::highResTimerFrequency;
  224278. }
  224279. bool Time::setSystemTimeToThisTime() const
  224280. {
  224281. jassertfalse;
  224282. return false;
  224283. }
  224284. int SystemStats::getPageSize()
  224285. {
  224286. return (int) NSPageSize();
  224287. }
  224288. void PlatformUtilities::fpuReset()
  224289. {
  224290. }
  224291. #endif
  224292. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224293. /*** Start of inlined file: juce_mac_Network.mm ***/
  224294. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224295. // compiled on its own).
  224296. #if JUCE_INCLUDED_FILE
  224297. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224298. {
  224299. #ifndef IFT_ETHER
  224300. #define IFT_ETHER 6
  224301. #endif
  224302. ifaddrs* addrs = 0;
  224303. int numResults = 0;
  224304. if (getifaddrs (&addrs) == 0)
  224305. {
  224306. const ifaddrs* cursor = addrs;
  224307. while (cursor != 0 && numResults < maxNum)
  224308. {
  224309. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224310. if (sto->ss_family == AF_LINK)
  224311. {
  224312. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224313. if (sadd->sdl_type == IFT_ETHER)
  224314. {
  224315. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224316. uint64 a = 0;
  224317. for (int i = 6; --i >= 0;)
  224318. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224319. *addresses++ = (int64) a;
  224320. ++numResults;
  224321. }
  224322. }
  224323. cursor = cursor->ifa_next;
  224324. }
  224325. freeifaddrs (addrs);
  224326. }
  224327. return numResults;
  224328. }
  224329. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224330. const String& emailSubject,
  224331. const String& bodyText,
  224332. const StringArray& filesToAttach)
  224333. {
  224334. #if JUCE_IOS
  224335. //xxx probably need to use MFMailComposeViewController
  224336. jassertfalse;
  224337. return false;
  224338. #else
  224339. const ScopedAutoReleasePool pool;
  224340. String script;
  224341. script << "tell application \"Mail\"\r\n"
  224342. "set newMessage to make new outgoing message with properties {subject:\""
  224343. << emailSubject.replace ("\"", "\\\"")
  224344. << "\", content:\""
  224345. << bodyText.replace ("\"", "\\\"")
  224346. << "\" & return & return}\r\n"
  224347. "tell newMessage\r\n"
  224348. "set visible to true\r\n"
  224349. "set sender to \"sdfsdfsdfewf\"\r\n"
  224350. "make new to recipient at end of to recipients with properties {address:\""
  224351. << targetEmailAddress
  224352. << "\"}\r\n";
  224353. for (int i = 0; i < filesToAttach.size(); ++i)
  224354. {
  224355. script << "tell content\r\n"
  224356. "make new attachment with properties {file name:\""
  224357. << filesToAttach[i].replace ("\"", "\\\"")
  224358. << "\"} at after the last paragraph\r\n"
  224359. "end tell\r\n";
  224360. }
  224361. script << "end tell\r\n"
  224362. "end tell\r\n";
  224363. NSAppleScript* s = [[NSAppleScript alloc]
  224364. initWithSource: juceStringToNS (script)];
  224365. NSDictionary* error = 0;
  224366. const bool ok = [s executeAndReturnError: &error] != nil;
  224367. [s release];
  224368. return ok;
  224369. #endif
  224370. }
  224371. END_JUCE_NAMESPACE
  224372. using namespace JUCE_NAMESPACE;
  224373. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224374. @interface JuceURLConnection : NSObject
  224375. {
  224376. @public
  224377. NSURLRequest* request;
  224378. NSURLConnection* connection;
  224379. NSMutableData* data;
  224380. Thread* runLoopThread;
  224381. bool initialised, hasFailed, hasFinished;
  224382. int position;
  224383. int64 contentLength;
  224384. NSDictionary* headers;
  224385. NSLock* dataLock;
  224386. }
  224387. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224388. - (void) dealloc;
  224389. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224390. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224391. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224392. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224393. - (BOOL) isOpen;
  224394. - (int) read: (char*) dest numBytes: (int) num;
  224395. - (int) readPosition;
  224396. - (void) stop;
  224397. - (void) createConnection;
  224398. @end
  224399. class JuceURLConnectionMessageThread : public Thread
  224400. {
  224401. JuceURLConnection* owner;
  224402. public:
  224403. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224404. : Thread ("http connection"),
  224405. owner (owner_)
  224406. {
  224407. }
  224408. ~JuceURLConnectionMessageThread()
  224409. {
  224410. stopThread (10000);
  224411. }
  224412. void run()
  224413. {
  224414. [owner createConnection];
  224415. while (! threadShouldExit())
  224416. {
  224417. const ScopedAutoReleasePool pool;
  224418. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224419. }
  224420. }
  224421. };
  224422. @implementation JuceURLConnection
  224423. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224424. withCallback: (URL::OpenStreamProgressCallback*) callback
  224425. withContext: (void*) context;
  224426. {
  224427. [super init];
  224428. request = req;
  224429. [request retain];
  224430. data = [[NSMutableData data] retain];
  224431. dataLock = [[NSLock alloc] init];
  224432. connection = 0;
  224433. initialised = false;
  224434. hasFailed = false;
  224435. hasFinished = false;
  224436. contentLength = -1;
  224437. headers = 0;
  224438. runLoopThread = new JuceURLConnectionMessageThread (self);
  224439. runLoopThread->startThread();
  224440. while (runLoopThread->isThreadRunning() && ! initialised)
  224441. {
  224442. if (callback != 0)
  224443. callback (context, -1, (int) [[request HTTPBody] length]);
  224444. Thread::sleep (1);
  224445. }
  224446. return self;
  224447. }
  224448. - (void) dealloc
  224449. {
  224450. [self stop];
  224451. deleteAndZero (runLoopThread);
  224452. [connection release];
  224453. [data release];
  224454. [dataLock release];
  224455. [request release];
  224456. [headers release];
  224457. [super dealloc];
  224458. }
  224459. - (void) createConnection
  224460. {
  224461. NSUInteger oldRetainCount = [self retainCount];
  224462. connection = [[NSURLConnection alloc] initWithRequest: request
  224463. delegate: self];
  224464. if (oldRetainCount == [self retainCount])
  224465. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224466. if (connection == nil)
  224467. runLoopThread->signalThreadShouldExit();
  224468. }
  224469. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224470. {
  224471. (void) conn;
  224472. [dataLock lock];
  224473. [data setLength: 0];
  224474. [dataLock unlock];
  224475. initialised = true;
  224476. contentLength = [response expectedContentLength];
  224477. [headers release];
  224478. headers = 0;
  224479. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224480. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224481. }
  224482. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224483. {
  224484. (void) conn;
  224485. DBG (nsStringToJuce ([error description]));
  224486. hasFailed = true;
  224487. initialised = true;
  224488. if (runLoopThread != 0)
  224489. runLoopThread->signalThreadShouldExit();
  224490. }
  224491. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224492. {
  224493. (void) conn;
  224494. [dataLock lock];
  224495. [data appendData: newData];
  224496. [dataLock unlock];
  224497. initialised = true;
  224498. }
  224499. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224500. {
  224501. (void) conn;
  224502. hasFinished = true;
  224503. initialised = true;
  224504. if (runLoopThread != 0)
  224505. runLoopThread->signalThreadShouldExit();
  224506. }
  224507. - (BOOL) isOpen
  224508. {
  224509. return connection != 0 && ! hasFailed;
  224510. }
  224511. - (int) readPosition
  224512. {
  224513. return position;
  224514. }
  224515. - (int) read: (char*) dest numBytes: (int) numNeeded
  224516. {
  224517. int numDone = 0;
  224518. while (numNeeded > 0)
  224519. {
  224520. int available = jmin (numNeeded, (int) [data length]);
  224521. if (available > 0)
  224522. {
  224523. [dataLock lock];
  224524. [data getBytes: dest length: available];
  224525. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224526. [dataLock unlock];
  224527. numDone += available;
  224528. numNeeded -= available;
  224529. dest += available;
  224530. }
  224531. else
  224532. {
  224533. if (hasFailed || hasFinished)
  224534. break;
  224535. Thread::sleep (1);
  224536. }
  224537. }
  224538. position += numDone;
  224539. return numDone;
  224540. }
  224541. - (void) stop
  224542. {
  224543. [connection cancel];
  224544. if (runLoopThread != 0)
  224545. runLoopThread->stopThread (10000);
  224546. }
  224547. @end
  224548. BEGIN_JUCE_NAMESPACE
  224549. void* juce_openInternetFile (const String& url,
  224550. const String& headers,
  224551. const MemoryBlock& postData,
  224552. const bool isPost,
  224553. URL::OpenStreamProgressCallback* callback,
  224554. void* callbackContext,
  224555. int timeOutMs)
  224556. {
  224557. const ScopedAutoReleasePool pool;
  224558. NSMutableURLRequest* req = [NSMutableURLRequest
  224559. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224560. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224561. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224562. if (req == nil)
  224563. return 0;
  224564. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224565. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224566. StringArray headerLines;
  224567. headerLines.addLines (headers);
  224568. headerLines.removeEmptyStrings (true);
  224569. for (int i = 0; i < headerLines.size(); ++i)
  224570. {
  224571. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224572. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224573. if (key.isNotEmpty() && value.isNotEmpty())
  224574. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224575. }
  224576. if (isPost && postData.getSize() > 0)
  224577. {
  224578. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224579. length: postData.getSize()]];
  224580. }
  224581. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224582. withCallback: callback
  224583. withContext: callbackContext];
  224584. if ([s isOpen])
  224585. return s;
  224586. [s release];
  224587. return 0;
  224588. }
  224589. void juce_closeInternetFile (void* handle)
  224590. {
  224591. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224592. if (s != 0)
  224593. {
  224594. const ScopedAutoReleasePool pool;
  224595. [s stop];
  224596. [s release];
  224597. }
  224598. }
  224599. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224600. {
  224601. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224602. if (s != 0)
  224603. {
  224604. const ScopedAutoReleasePool pool;
  224605. return [s read: (char*) buffer numBytes: bytesToRead];
  224606. }
  224607. return 0;
  224608. }
  224609. int64 juce_getInternetFileContentLength (void* handle)
  224610. {
  224611. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224612. if (s != 0)
  224613. return s->contentLength;
  224614. return -1;
  224615. }
  224616. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224617. {
  224618. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224619. if (s != 0 && s->headers != 0)
  224620. {
  224621. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224622. NSString* key;
  224623. while ((key = [enumerator nextObject]) != nil)
  224624. headers.set (nsStringToJuce (key),
  224625. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224626. }
  224627. }
  224628. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224629. {
  224630. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224631. if (s != 0)
  224632. return [s readPosition];
  224633. return 0;
  224634. }
  224635. #endif
  224636. /*** End of inlined file: juce_mac_Network.mm ***/
  224637. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224638. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224639. // compiled on its own).
  224640. #if JUCE_INCLUDED_FILE
  224641. struct NamedPipeInternal
  224642. {
  224643. String pipeInName, pipeOutName;
  224644. int pipeIn, pipeOut;
  224645. bool volatile createdPipe, blocked, stopReadOperation;
  224646. static void signalHandler (int) {}
  224647. };
  224648. void NamedPipe::cancelPendingReads()
  224649. {
  224650. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224651. {
  224652. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224653. intern->stopReadOperation = true;
  224654. char buffer [1] = { 0 };
  224655. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224656. (void) bytesWritten;
  224657. int timeout = 2000;
  224658. while (intern->blocked && --timeout >= 0)
  224659. Thread::sleep (2);
  224660. intern->stopReadOperation = false;
  224661. }
  224662. }
  224663. void NamedPipe::close()
  224664. {
  224665. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224666. if (intern != 0)
  224667. {
  224668. internal = 0;
  224669. if (intern->pipeIn != -1)
  224670. ::close (intern->pipeIn);
  224671. if (intern->pipeOut != -1)
  224672. ::close (intern->pipeOut);
  224673. if (intern->createdPipe)
  224674. {
  224675. unlink (intern->pipeInName.toUTF8());
  224676. unlink (intern->pipeOutName.toUTF8());
  224677. }
  224678. delete intern;
  224679. }
  224680. }
  224681. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224682. {
  224683. close();
  224684. NamedPipeInternal* const intern = new NamedPipeInternal();
  224685. internal = intern;
  224686. intern->createdPipe = createPipe;
  224687. intern->blocked = false;
  224688. intern->stopReadOperation = false;
  224689. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224690. siginterrupt (SIGPIPE, 1);
  224691. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224692. intern->pipeInName = pipePath + "_in";
  224693. intern->pipeOutName = pipePath + "_out";
  224694. intern->pipeIn = -1;
  224695. intern->pipeOut = -1;
  224696. if (createPipe)
  224697. {
  224698. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224699. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224700. {
  224701. delete intern;
  224702. internal = 0;
  224703. return false;
  224704. }
  224705. }
  224706. return true;
  224707. }
  224708. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224709. {
  224710. int bytesRead = -1;
  224711. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224712. if (intern != 0)
  224713. {
  224714. intern->blocked = true;
  224715. if (intern->pipeIn == -1)
  224716. {
  224717. if (intern->createdPipe)
  224718. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224719. else
  224720. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224721. if (intern->pipeIn == -1)
  224722. {
  224723. intern->blocked = false;
  224724. return -1;
  224725. }
  224726. }
  224727. bytesRead = 0;
  224728. char* p = (char*) destBuffer;
  224729. while (bytesRead < maxBytesToRead)
  224730. {
  224731. const int bytesThisTime = maxBytesToRead - bytesRead;
  224732. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224733. if (numRead <= 0 || intern->stopReadOperation)
  224734. {
  224735. bytesRead = -1;
  224736. break;
  224737. }
  224738. bytesRead += numRead;
  224739. p += bytesRead;
  224740. }
  224741. intern->blocked = false;
  224742. }
  224743. return bytesRead;
  224744. }
  224745. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224746. {
  224747. int bytesWritten = -1;
  224748. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224749. if (intern != 0)
  224750. {
  224751. if (intern->pipeOut == -1)
  224752. {
  224753. if (intern->createdPipe)
  224754. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224755. else
  224756. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224757. if (intern->pipeOut == -1)
  224758. {
  224759. return -1;
  224760. }
  224761. }
  224762. const char* p = (const char*) sourceBuffer;
  224763. bytesWritten = 0;
  224764. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224765. while (bytesWritten < numBytesToWrite
  224766. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224767. {
  224768. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224769. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224770. if (numWritten <= 0)
  224771. {
  224772. bytesWritten = -1;
  224773. break;
  224774. }
  224775. bytesWritten += numWritten;
  224776. p += bytesWritten;
  224777. }
  224778. }
  224779. return bytesWritten;
  224780. }
  224781. #endif
  224782. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224783. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224784. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224785. // compiled on its own).
  224786. #if JUCE_INCLUDED_FILE
  224787. /*
  224788. Note that a lot of methods that you'd expect to find in this file actually
  224789. live in juce_posix_SharedCode.h!
  224790. */
  224791. bool Process::isForegroundProcess()
  224792. {
  224793. #if JUCE_MAC
  224794. return [NSApp isActive];
  224795. #else
  224796. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224797. #endif
  224798. }
  224799. void Process::raisePrivilege()
  224800. {
  224801. jassertfalse;
  224802. }
  224803. void Process::lowerPrivilege()
  224804. {
  224805. jassertfalse;
  224806. }
  224807. void Process::terminate()
  224808. {
  224809. exit (0);
  224810. }
  224811. void Process::setPriority (ProcessPriority)
  224812. {
  224813. // xxx
  224814. }
  224815. #endif
  224816. /*** End of inlined file: juce_mac_Threads.mm ***/
  224817. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224818. /*
  224819. This file contains posix routines that are common to both the Linux and Mac builds.
  224820. It gets included directly in the cpp files for these platforms.
  224821. */
  224822. CriticalSection::CriticalSection() throw()
  224823. {
  224824. pthread_mutexattr_t atts;
  224825. pthread_mutexattr_init (&atts);
  224826. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224827. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224828. pthread_mutex_init (&internal, &atts);
  224829. }
  224830. CriticalSection::~CriticalSection() throw()
  224831. {
  224832. pthread_mutex_destroy (&internal);
  224833. }
  224834. void CriticalSection::enter() const throw()
  224835. {
  224836. pthread_mutex_lock (&internal);
  224837. }
  224838. bool CriticalSection::tryEnter() const throw()
  224839. {
  224840. return pthread_mutex_trylock (&internal) == 0;
  224841. }
  224842. void CriticalSection::exit() const throw()
  224843. {
  224844. pthread_mutex_unlock (&internal);
  224845. }
  224846. class WaitableEventImpl
  224847. {
  224848. public:
  224849. WaitableEventImpl (const bool manualReset_)
  224850. : triggered (false),
  224851. manualReset (manualReset_)
  224852. {
  224853. pthread_cond_init (&condition, 0);
  224854. pthread_mutexattr_t atts;
  224855. pthread_mutexattr_init (&atts);
  224856. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224857. pthread_mutex_init (&mutex, &atts);
  224858. }
  224859. ~WaitableEventImpl()
  224860. {
  224861. pthread_cond_destroy (&condition);
  224862. pthread_mutex_destroy (&mutex);
  224863. }
  224864. bool wait (const int timeOutMillisecs) throw()
  224865. {
  224866. pthread_mutex_lock (&mutex);
  224867. if (! triggered)
  224868. {
  224869. if (timeOutMillisecs < 0)
  224870. {
  224871. do
  224872. {
  224873. pthread_cond_wait (&condition, &mutex);
  224874. }
  224875. while (! triggered);
  224876. }
  224877. else
  224878. {
  224879. struct timeval now;
  224880. gettimeofday (&now, 0);
  224881. struct timespec time;
  224882. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224883. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224884. if (time.tv_nsec >= 1000000000)
  224885. {
  224886. time.tv_nsec -= 1000000000;
  224887. time.tv_sec++;
  224888. }
  224889. do
  224890. {
  224891. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224892. {
  224893. pthread_mutex_unlock (&mutex);
  224894. return false;
  224895. }
  224896. }
  224897. while (! triggered);
  224898. }
  224899. }
  224900. if (! manualReset)
  224901. triggered = false;
  224902. pthread_mutex_unlock (&mutex);
  224903. return true;
  224904. }
  224905. void signal() throw()
  224906. {
  224907. pthread_mutex_lock (&mutex);
  224908. triggered = true;
  224909. pthread_cond_broadcast (&condition);
  224910. pthread_mutex_unlock (&mutex);
  224911. }
  224912. void reset() throw()
  224913. {
  224914. pthread_mutex_lock (&mutex);
  224915. triggered = false;
  224916. pthread_mutex_unlock (&mutex);
  224917. }
  224918. private:
  224919. pthread_cond_t condition;
  224920. pthread_mutex_t mutex;
  224921. bool triggered;
  224922. const bool manualReset;
  224923. WaitableEventImpl (const WaitableEventImpl&);
  224924. WaitableEventImpl& operator= (const WaitableEventImpl&);
  224925. };
  224926. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224927. : internal (new WaitableEventImpl (manualReset))
  224928. {
  224929. }
  224930. WaitableEvent::~WaitableEvent() throw()
  224931. {
  224932. delete static_cast <WaitableEventImpl*> (internal);
  224933. }
  224934. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224935. {
  224936. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224937. }
  224938. void WaitableEvent::signal() const throw()
  224939. {
  224940. static_cast <WaitableEventImpl*> (internal)->signal();
  224941. }
  224942. void WaitableEvent::reset() const throw()
  224943. {
  224944. static_cast <WaitableEventImpl*> (internal)->reset();
  224945. }
  224946. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224947. {
  224948. struct timespec time;
  224949. time.tv_sec = millisecs / 1000;
  224950. time.tv_nsec = (millisecs % 1000) * 1000000;
  224951. nanosleep (&time, 0);
  224952. }
  224953. const juce_wchar File::separator = '/';
  224954. const String File::separatorString ("/");
  224955. const File File::getCurrentWorkingDirectory()
  224956. {
  224957. HeapBlock<char> heapBuffer;
  224958. char localBuffer [1024];
  224959. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224960. int bufferSize = 4096;
  224961. while (cwd == 0 && errno == ERANGE)
  224962. {
  224963. heapBuffer.malloc (bufferSize);
  224964. cwd = getcwd (heapBuffer, bufferSize - 1);
  224965. bufferSize += 1024;
  224966. }
  224967. return File (String::fromUTF8 (cwd));
  224968. }
  224969. bool File::setAsCurrentWorkingDirectory() const
  224970. {
  224971. return chdir (getFullPathName().toUTF8()) == 0;
  224972. }
  224973. static bool juce_stat (const String& fileName, struct stat& info)
  224974. {
  224975. return fileName.isNotEmpty()
  224976. && (stat (fileName.toUTF8(), &info) == 0);
  224977. }
  224978. bool File::isDirectory() const
  224979. {
  224980. struct stat info;
  224981. return fullPath.isEmpty()
  224982. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224983. }
  224984. bool File::exists() const
  224985. {
  224986. return fullPath.isNotEmpty()
  224987. && access (fullPath.toUTF8(), F_OK) == 0;
  224988. }
  224989. bool File::existsAsFile() const
  224990. {
  224991. return exists() && ! isDirectory();
  224992. }
  224993. int64 File::getSize() const
  224994. {
  224995. struct stat info;
  224996. return juce_stat (fullPath, info) ? info.st_size : 0;
  224997. }
  224998. bool File::hasWriteAccess() const
  224999. {
  225000. if (exists())
  225001. return access (fullPath.toUTF8(), W_OK) == 0;
  225002. if ((! isDirectory()) && fullPath.containsChar (separator))
  225003. return getParentDirectory().hasWriteAccess();
  225004. return false;
  225005. }
  225006. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225007. {
  225008. struct stat info;
  225009. const int res = stat (fullPath.toUTF8(), &info);
  225010. if (res != 0)
  225011. return false;
  225012. info.st_mode &= 0777; // Just permissions
  225013. if (shouldBeReadOnly)
  225014. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225015. else
  225016. // Give everybody write permission?
  225017. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225018. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225019. }
  225020. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225021. {
  225022. modificationTime = 0;
  225023. accessTime = 0;
  225024. creationTime = 0;
  225025. struct stat info;
  225026. const int res = stat (fullPath.toUTF8(), &info);
  225027. if (res == 0)
  225028. {
  225029. modificationTime = (int64) info.st_mtime * 1000;
  225030. accessTime = (int64) info.st_atime * 1000;
  225031. creationTime = (int64) info.st_ctime * 1000;
  225032. }
  225033. }
  225034. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225035. {
  225036. struct utimbuf times;
  225037. times.actime = (time_t) (accessTime / 1000);
  225038. times.modtime = (time_t) (modificationTime / 1000);
  225039. return utime (fullPath.toUTF8(), &times) == 0;
  225040. }
  225041. bool File::deleteFile() const
  225042. {
  225043. if (! exists())
  225044. return true;
  225045. else if (isDirectory())
  225046. return rmdir (fullPath.toUTF8()) == 0;
  225047. else
  225048. return remove (fullPath.toUTF8()) == 0;
  225049. }
  225050. bool File::moveInternal (const File& dest) const
  225051. {
  225052. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225053. return true;
  225054. if (hasWriteAccess() && copyInternal (dest))
  225055. {
  225056. if (deleteFile())
  225057. return true;
  225058. dest.deleteFile();
  225059. }
  225060. return false;
  225061. }
  225062. void File::createDirectoryInternal (const String& fileName) const
  225063. {
  225064. mkdir (fileName.toUTF8(), 0777);
  225065. }
  225066. int64 juce_fileSetPosition (void* handle, int64 pos)
  225067. {
  225068. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225069. return pos;
  225070. return -1;
  225071. }
  225072. void FileInputStream::openHandle()
  225073. {
  225074. totalSize = file.getSize();
  225075. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225076. if (f != -1)
  225077. fileHandle = (void*) f;
  225078. }
  225079. void FileInputStream::closeHandle()
  225080. {
  225081. if (fileHandle != 0)
  225082. {
  225083. close ((int) (pointer_sized_int) fileHandle);
  225084. fileHandle = 0;
  225085. }
  225086. }
  225087. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225088. {
  225089. if (fileHandle != 0)
  225090. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225091. return 0;
  225092. }
  225093. void FileOutputStream::openHandle()
  225094. {
  225095. if (file.exists())
  225096. {
  225097. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225098. if (f != -1)
  225099. {
  225100. currentPosition = lseek (f, 0, SEEK_END);
  225101. if (currentPosition >= 0)
  225102. fileHandle = (void*) f;
  225103. else
  225104. close (f);
  225105. }
  225106. }
  225107. else
  225108. {
  225109. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225110. if (f != -1)
  225111. fileHandle = (void*) f;
  225112. }
  225113. }
  225114. void FileOutputStream::closeHandle()
  225115. {
  225116. if (fileHandle != 0)
  225117. {
  225118. close ((int) (pointer_sized_int) fileHandle);
  225119. fileHandle = 0;
  225120. }
  225121. }
  225122. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225123. {
  225124. if (fileHandle != 0)
  225125. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225126. return 0;
  225127. }
  225128. void FileOutputStream::flushInternal()
  225129. {
  225130. if (fileHandle != 0)
  225131. fsync ((int) (pointer_sized_int) fileHandle);
  225132. }
  225133. const File juce_getExecutableFile()
  225134. {
  225135. Dl_info exeInfo;
  225136. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225137. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225138. }
  225139. // if this file doesn't exist, find a parent of it that does..
  225140. static bool juce_doStatFS (File f, struct statfs& result)
  225141. {
  225142. for (int i = 5; --i >= 0;)
  225143. {
  225144. if (f.exists())
  225145. break;
  225146. f = f.getParentDirectory();
  225147. }
  225148. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225149. }
  225150. int64 File::getBytesFreeOnVolume() const
  225151. {
  225152. struct statfs buf;
  225153. if (juce_doStatFS (*this, buf))
  225154. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225155. return 0;
  225156. }
  225157. int64 File::getVolumeTotalSize() const
  225158. {
  225159. struct statfs buf;
  225160. if (juce_doStatFS (*this, buf))
  225161. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225162. return 0;
  225163. }
  225164. const String File::getVolumeLabel() const
  225165. {
  225166. #if JUCE_MAC
  225167. struct VolAttrBuf
  225168. {
  225169. u_int32_t length;
  225170. attrreference_t mountPointRef;
  225171. char mountPointSpace [MAXPATHLEN];
  225172. } attrBuf;
  225173. struct attrlist attrList;
  225174. zerostruct (attrList);
  225175. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225176. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225177. File f (*this);
  225178. for (;;)
  225179. {
  225180. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225181. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225182. (int) attrBuf.mountPointRef.attr_length);
  225183. const File parent (f.getParentDirectory());
  225184. if (f == parent)
  225185. break;
  225186. f = parent;
  225187. }
  225188. #endif
  225189. return String::empty;
  225190. }
  225191. int File::getVolumeSerialNumber() const
  225192. {
  225193. return 0; // xxx
  225194. }
  225195. void juce_runSystemCommand (const String& command)
  225196. {
  225197. int result = system (command.toUTF8());
  225198. (void) result;
  225199. }
  225200. const String juce_getOutputFromCommand (const String& command)
  225201. {
  225202. // slight bodge here, as we just pipe the output into a temp file and read it...
  225203. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225204. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225205. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225206. String result (tempFile.loadFileAsString());
  225207. tempFile.deleteFile();
  225208. return result;
  225209. }
  225210. class InterProcessLock::Pimpl
  225211. {
  225212. public:
  225213. Pimpl (const String& name, const int timeOutMillisecs)
  225214. : handle (0), refCount (1)
  225215. {
  225216. #if JUCE_MAC
  225217. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225218. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225219. #else
  225220. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225221. #endif
  225222. temp.create();
  225223. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225224. if (handle != 0)
  225225. {
  225226. struct flock fl;
  225227. zerostruct (fl);
  225228. fl.l_whence = SEEK_SET;
  225229. fl.l_type = F_WRLCK;
  225230. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225231. for (;;)
  225232. {
  225233. const int result = fcntl (handle, F_SETLK, &fl);
  225234. if (result >= 0)
  225235. return;
  225236. if (errno != EINTR)
  225237. {
  225238. if (timeOutMillisecs == 0
  225239. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225240. break;
  225241. Thread::sleep (10);
  225242. }
  225243. }
  225244. }
  225245. closeFile();
  225246. }
  225247. ~Pimpl()
  225248. {
  225249. closeFile();
  225250. }
  225251. void closeFile()
  225252. {
  225253. if (handle != 0)
  225254. {
  225255. struct flock fl;
  225256. zerostruct (fl);
  225257. fl.l_whence = SEEK_SET;
  225258. fl.l_type = F_UNLCK;
  225259. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225260. {}
  225261. close (handle);
  225262. handle = 0;
  225263. }
  225264. }
  225265. int handle, refCount;
  225266. };
  225267. InterProcessLock::InterProcessLock (const String& name_)
  225268. : name (name_)
  225269. {
  225270. }
  225271. InterProcessLock::~InterProcessLock()
  225272. {
  225273. }
  225274. bool InterProcessLock::enter (const int timeOutMillisecs)
  225275. {
  225276. const ScopedLock sl (lock);
  225277. if (pimpl == 0)
  225278. {
  225279. pimpl = new Pimpl (name, timeOutMillisecs);
  225280. if (pimpl->handle == 0)
  225281. pimpl = 0;
  225282. }
  225283. else
  225284. {
  225285. pimpl->refCount++;
  225286. }
  225287. return pimpl != 0;
  225288. }
  225289. void InterProcessLock::exit()
  225290. {
  225291. const ScopedLock sl (lock);
  225292. // Trying to release the lock too many times!
  225293. jassert (pimpl != 0);
  225294. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225295. pimpl = 0;
  225296. }
  225297. void JUCE_API juce_threadEntryPoint (void*);
  225298. void* threadEntryProc (void* userData)
  225299. {
  225300. JUCE_AUTORELEASEPOOL
  225301. juce_threadEntryPoint (userData);
  225302. return 0;
  225303. }
  225304. void* juce_createThread (void* userData)
  225305. {
  225306. pthread_t handle = 0;
  225307. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225308. {
  225309. pthread_detach (handle);
  225310. return (void*) handle;
  225311. }
  225312. return 0;
  225313. }
  225314. void juce_killThread (void* handle)
  225315. {
  225316. if (handle != 0)
  225317. pthread_cancel ((pthread_t) handle);
  225318. }
  225319. void juce_setCurrentThreadName (const String& /*name*/)
  225320. {
  225321. }
  225322. bool juce_setThreadPriority (void* handle, int priority)
  225323. {
  225324. struct sched_param param;
  225325. int policy;
  225326. priority = jlimit (0, 10, priority);
  225327. if (handle == 0)
  225328. handle = (void*) pthread_self();
  225329. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225330. return false;
  225331. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225332. const int minPriority = sched_get_priority_min (policy);
  225333. const int maxPriority = sched_get_priority_max (policy);
  225334. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225335. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225336. }
  225337. Thread::ThreadID Thread::getCurrentThreadId()
  225338. {
  225339. return (ThreadID) pthread_self();
  225340. }
  225341. void Thread::yield()
  225342. {
  225343. sched_yield();
  225344. }
  225345. /* Remove this macro if you're having problems compiling the cpu affinity
  225346. calls (the API for these has changed about quite a bit in various Linux
  225347. versions, and a lot of distros seem to ship with obsolete versions)
  225348. */
  225349. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225350. #define SUPPORT_AFFINITIES 1
  225351. #endif
  225352. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225353. {
  225354. #if SUPPORT_AFFINITIES
  225355. cpu_set_t affinity;
  225356. CPU_ZERO (&affinity);
  225357. for (int i = 0; i < 32; ++i)
  225358. if ((affinityMask & (1 << i)) != 0)
  225359. CPU_SET (i, &affinity);
  225360. /*
  225361. N.B. If this line causes a compile error, then you've probably not got the latest
  225362. version of glibc installed.
  225363. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225364. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225365. */
  225366. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225367. sched_yield();
  225368. #else
  225369. /* affinities aren't supported because either the appropriate header files weren't found,
  225370. or the SUPPORT_AFFINITIES macro was turned off
  225371. */
  225372. jassertfalse;
  225373. #endif
  225374. }
  225375. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225376. /*** Start of inlined file: juce_mac_Files.mm ***/
  225377. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225378. // compiled on its own).
  225379. #if JUCE_INCLUDED_FILE
  225380. /*
  225381. Note that a lot of methods that you'd expect to find in this file actually
  225382. live in juce_posix_SharedCode.h!
  225383. */
  225384. bool File::copyInternal (const File& dest) const
  225385. {
  225386. const ScopedAutoReleasePool pool;
  225387. NSFileManager* fm = [NSFileManager defaultManager];
  225388. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225389. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225390. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225391. toPath: juceStringToNS (dest.getFullPathName())
  225392. error: nil];
  225393. #else
  225394. && [fm copyPath: juceStringToNS (fullPath)
  225395. toPath: juceStringToNS (dest.getFullPathName())
  225396. handler: nil];
  225397. #endif
  225398. }
  225399. void File::findFileSystemRoots (Array<File>& destArray)
  225400. {
  225401. destArray.add (File ("/"));
  225402. }
  225403. static bool isFileOnDriveType (const File& f, const char* const* types)
  225404. {
  225405. struct statfs buf;
  225406. if (juce_doStatFS (f, buf))
  225407. {
  225408. const String type (buf.f_fstypename);
  225409. while (*types != 0)
  225410. if (type.equalsIgnoreCase (*types++))
  225411. return true;
  225412. }
  225413. return false;
  225414. }
  225415. bool File::isOnCDRomDrive() const
  225416. {
  225417. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225418. return isFileOnDriveType (*this, cdTypes);
  225419. }
  225420. bool File::isOnHardDisk() const
  225421. {
  225422. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225423. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225424. }
  225425. bool File::isOnRemovableDrive() const
  225426. {
  225427. #if JUCE_IOS
  225428. return false; // xxx is this possible?
  225429. #else
  225430. const ScopedAutoReleasePool pool;
  225431. BOOL removable = false;
  225432. [[NSWorkspace sharedWorkspace]
  225433. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225434. isRemovable: &removable
  225435. isWritable: nil
  225436. isUnmountable: nil
  225437. description: nil
  225438. type: nil];
  225439. return removable;
  225440. #endif
  225441. }
  225442. static bool juce_isHiddenFile (const String& path)
  225443. {
  225444. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225445. const ScopedAutoReleasePool pool;
  225446. NSNumber* hidden = nil;
  225447. NSError* err = nil;
  225448. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225449. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225450. && [hidden boolValue];
  225451. #else
  225452. #if JUCE_IOS
  225453. return File (path).getFileName().startsWithChar ('.');
  225454. #else
  225455. FSRef ref;
  225456. LSItemInfoRecord info;
  225457. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225458. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225459. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225460. #endif
  225461. #endif
  225462. }
  225463. bool File::isHidden() const
  225464. {
  225465. return juce_isHiddenFile (getFullPathName());
  225466. }
  225467. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225468. const File File::getSpecialLocation (const SpecialLocationType type)
  225469. {
  225470. const ScopedAutoReleasePool pool;
  225471. String resultPath;
  225472. switch (type)
  225473. {
  225474. case userHomeDirectory:
  225475. resultPath = nsStringToJuce (NSHomeDirectory());
  225476. break;
  225477. case userDocumentsDirectory:
  225478. resultPath = "~/Documents";
  225479. break;
  225480. case userDesktopDirectory:
  225481. resultPath = "~/Desktop";
  225482. break;
  225483. case userApplicationDataDirectory:
  225484. resultPath = "~/Library";
  225485. break;
  225486. case commonApplicationDataDirectory:
  225487. resultPath = "/Library";
  225488. break;
  225489. case globalApplicationsDirectory:
  225490. resultPath = "/Applications";
  225491. break;
  225492. case userMusicDirectory:
  225493. resultPath = "~/Music";
  225494. break;
  225495. case userMoviesDirectory:
  225496. resultPath = "~/Movies";
  225497. break;
  225498. case tempDirectory:
  225499. {
  225500. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225501. tmp.createDirectory();
  225502. return tmp.getFullPathName();
  225503. }
  225504. case invokedExecutableFile:
  225505. if (juce_Argv0 != 0)
  225506. return File (String::fromUTF8 (juce_Argv0));
  225507. // deliberate fall-through...
  225508. case currentExecutableFile:
  225509. return juce_getExecutableFile();
  225510. case currentApplicationFile:
  225511. {
  225512. const File exe (juce_getExecutableFile());
  225513. const File parent (exe.getParentDirectory());
  225514. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225515. ? parent.getParentDirectory().getParentDirectory()
  225516. : exe;
  225517. }
  225518. case hostApplicationPath:
  225519. {
  225520. unsigned int size = 8192;
  225521. HeapBlock<char> buffer;
  225522. buffer.calloc (size + 8);
  225523. _NSGetExecutablePath (buffer.getData(), &size);
  225524. return String::fromUTF8 (buffer, size);
  225525. }
  225526. default:
  225527. jassertfalse; // unknown type?
  225528. break;
  225529. }
  225530. if (resultPath.isNotEmpty())
  225531. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225532. return File::nonexistent;
  225533. }
  225534. const String File::getVersion() const
  225535. {
  225536. const ScopedAutoReleasePool pool;
  225537. String result;
  225538. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225539. if (bundle != 0)
  225540. {
  225541. NSDictionary* info = [bundle infoDictionary];
  225542. if (info != 0)
  225543. {
  225544. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225545. if (name != nil)
  225546. result = nsStringToJuce (name);
  225547. }
  225548. }
  225549. return result;
  225550. }
  225551. const File File::getLinkedTarget() const
  225552. {
  225553. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225554. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225555. #else
  225556. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225557. #endif
  225558. if (dest != nil)
  225559. return File (nsStringToJuce (dest));
  225560. return *this;
  225561. }
  225562. bool File::moveToTrash() const
  225563. {
  225564. if (! exists())
  225565. return true;
  225566. #if JUCE_IOS
  225567. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225568. #else
  225569. const ScopedAutoReleasePool pool;
  225570. NSString* p = juceStringToNS (getFullPathName());
  225571. return [[NSWorkspace sharedWorkspace]
  225572. performFileOperation: NSWorkspaceRecycleOperation
  225573. source: [p stringByDeletingLastPathComponent]
  225574. destination: @""
  225575. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225576. tag: nil ];
  225577. #endif
  225578. }
  225579. class DirectoryIterator::NativeIterator::Pimpl
  225580. {
  225581. public:
  225582. Pimpl (const File& directory, const String& wildCard_)
  225583. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225584. wildCard (wildCard_),
  225585. enumerator (0)
  225586. {
  225587. const ScopedAutoReleasePool pool;
  225588. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225589. wildcardUTF8 = wildCard.toUTF8();
  225590. }
  225591. ~Pimpl()
  225592. {
  225593. [enumerator release];
  225594. }
  225595. bool next (String& filenameFound,
  225596. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225597. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225598. {
  225599. const ScopedAutoReleasePool pool;
  225600. for (;;)
  225601. {
  225602. NSString* file;
  225603. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225604. return false;
  225605. [enumerator skipDescendents];
  225606. filenameFound = nsStringToJuce (file);
  225607. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225608. continue;
  225609. const String path (parentDir + filenameFound);
  225610. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225611. {
  225612. struct stat info;
  225613. const bool statOk = juce_stat (path, info);
  225614. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225615. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225616. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225617. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225618. }
  225619. if (isHidden != 0)
  225620. *isHidden = juce_isHiddenFile (path);
  225621. if (isReadOnly != 0)
  225622. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225623. return true;
  225624. }
  225625. }
  225626. private:
  225627. String parentDir, wildCard;
  225628. const char* wildcardUTF8;
  225629. NSDirectoryEnumerator* enumerator;
  225630. Pimpl (const Pimpl&);
  225631. Pimpl& operator= (const Pimpl&);
  225632. };
  225633. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225634. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225635. {
  225636. }
  225637. DirectoryIterator::NativeIterator::~NativeIterator()
  225638. {
  225639. }
  225640. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225641. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225642. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225643. {
  225644. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225645. }
  225646. bool juce_launchExecutable (const String& pathAndArguments)
  225647. {
  225648. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225649. const int cpid = fork();
  225650. if (cpid == 0)
  225651. {
  225652. // Child process
  225653. if (execve (argv[0], (char**) argv, 0) < 0)
  225654. exit (0);
  225655. }
  225656. else
  225657. {
  225658. if (cpid < 0)
  225659. return false;
  225660. }
  225661. return true;
  225662. }
  225663. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225664. {
  225665. #if JUCE_IOS
  225666. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225667. #else
  225668. const ScopedAutoReleasePool pool;
  225669. if (parameters.isEmpty())
  225670. {
  225671. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225672. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225673. }
  225674. bool ok = false;
  225675. if (PlatformUtilities::isBundle (fileName))
  225676. {
  225677. NSMutableArray* urls = [NSMutableArray array];
  225678. StringArray docs;
  225679. docs.addTokens (parameters, true);
  225680. for (int i = 0; i < docs.size(); ++i)
  225681. [urls addObject: juceStringToNS (docs[i])];
  225682. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225683. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225684. options: 0
  225685. additionalEventParamDescriptor: nil
  225686. launchIdentifiers: nil];
  225687. }
  225688. else if (File (fileName).exists())
  225689. {
  225690. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  225691. }
  225692. return ok;
  225693. #endif
  225694. }
  225695. void File::revealToUser() const
  225696. {
  225697. #if ! JUCE_IOS
  225698. if (exists())
  225699. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225700. else if (getParentDirectory().exists())
  225701. getParentDirectory().revealToUser();
  225702. #endif
  225703. }
  225704. #if ! JUCE_IOS
  225705. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225706. {
  225707. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225708. }
  225709. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225710. {
  225711. char path [2048];
  225712. zerostruct (path);
  225713. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225714. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225715. return String::empty;
  225716. }
  225717. #endif
  225718. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225719. {
  225720. const ScopedAutoReleasePool pool;
  225721. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225722. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225723. #else
  225724. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225725. #endif
  225726. return [fileDict fileHFSTypeCode];
  225727. }
  225728. bool PlatformUtilities::isBundle (const String& filename)
  225729. {
  225730. #if JUCE_IOS
  225731. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225732. #else
  225733. const ScopedAutoReleasePool pool;
  225734. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225735. #endif
  225736. }
  225737. #endif
  225738. /*** End of inlined file: juce_mac_Files.mm ***/
  225739. #if JUCE_IOS
  225740. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225741. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225742. // compiled on its own).
  225743. #if JUCE_INCLUDED_FILE
  225744. END_JUCE_NAMESPACE
  225745. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225746. {
  225747. }
  225748. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225749. - (void) applicationWillTerminate: (UIApplication*) application;
  225750. @end
  225751. @implementation JuceAppStartupDelegate
  225752. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225753. {
  225754. initialiseJuce_GUI();
  225755. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225756. exit (0);
  225757. }
  225758. - (void) applicationWillTerminate: (UIApplication*) application
  225759. {
  225760. jassert (JUCEApplication::getInstance() != 0);
  225761. JUCEApplication::getInstance()->shutdownApp();
  225762. delete JUCEApplication::getInstance();
  225763. shutdownJuce_GUI();
  225764. }
  225765. @end
  225766. BEGIN_JUCE_NAMESPACE
  225767. int juce_iOSMain (int argc, const char* argv[])
  225768. {
  225769. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225770. }
  225771. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225772. {
  225773. pool = [[NSAutoreleasePool alloc] init];
  225774. }
  225775. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225776. {
  225777. [((NSAutoreleasePool*) pool) release];
  225778. }
  225779. void PlatformUtilities::beep()
  225780. {
  225781. //xxx
  225782. //AudioServicesPlaySystemSound ();
  225783. }
  225784. void PlatformUtilities::addItemToDock (const File& file)
  225785. {
  225786. }
  225787. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225788. END_JUCE_NAMESPACE
  225789. @interface JuceAlertBoxDelegate : NSObject
  225790. {
  225791. @public
  225792. bool clickedOk;
  225793. }
  225794. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225795. @end
  225796. @implementation JuceAlertBoxDelegate
  225797. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225798. {
  225799. clickedOk = (buttonIndex == 0);
  225800. alertView.hidden = true;
  225801. }
  225802. @end
  225803. BEGIN_JUCE_NAMESPACE
  225804. // (This function is used directly by other bits of code)
  225805. bool juce_iPhoneShowModalAlert (const String& title,
  225806. const String& bodyText,
  225807. NSString* okButtonText,
  225808. NSString* cancelButtonText)
  225809. {
  225810. const ScopedAutoReleasePool pool;
  225811. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225812. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225813. message: juceStringToNS (bodyText)
  225814. delegate: callback
  225815. cancelButtonTitle: okButtonText
  225816. otherButtonTitles: cancelButtonText, nil];
  225817. [alert retain];
  225818. [alert show];
  225819. while (! alert.hidden && alert.superview != nil)
  225820. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225821. const bool result = callback->clickedOk;
  225822. [alert release];
  225823. [callback release];
  225824. return result;
  225825. }
  225826. bool AlertWindow::showNativeDialogBox (const String& title,
  225827. const String& bodyText,
  225828. bool isOkCancel)
  225829. {
  225830. return juce_iPhoneShowModalAlert (title, bodyText,
  225831. @"OK",
  225832. isOkCancel ? @"Cancel" : nil);
  225833. }
  225834. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225835. {
  225836. jassertfalse; // no such thing on the iphone!
  225837. return false;
  225838. }
  225839. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225840. {
  225841. jassertfalse; // no such thing on the iphone!
  225842. return false;
  225843. }
  225844. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225845. {
  225846. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225847. }
  225848. bool Desktop::isScreenSaverEnabled()
  225849. {
  225850. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225851. }
  225852. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  225853. {
  225854. const ScopedAutoReleasePool pool;
  225855. monitorCoords.clear();
  225856. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  225857. : [[UIScreen mainScreen] bounds];
  225858. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  225859. (int) r.origin.y,
  225860. (int) r.size.width,
  225861. (int) r.size.height));
  225862. }
  225863. #endif
  225864. #endif
  225865. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225866. #else
  225867. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225868. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225869. // compiled on its own).
  225870. #if JUCE_INCLUDED_FILE
  225871. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225872. {
  225873. pool = [[NSAutoreleasePool alloc] init];
  225874. }
  225875. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225876. {
  225877. [((NSAutoreleasePool*) pool) release];
  225878. }
  225879. void PlatformUtilities::beep()
  225880. {
  225881. NSBeep();
  225882. }
  225883. void PlatformUtilities::addItemToDock (const File& file)
  225884. {
  225885. // check that it's not already there...
  225886. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225887. .containsIgnoreCase (file.getFullPathName()))
  225888. {
  225889. juce_runSystemCommand ("defaults write com.apple.dock persistent-apps -array-add \"<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>"
  225890. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225891. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225892. }
  225893. }
  225894. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225895. bool AlertWindow::showNativeDialogBox (const String& title,
  225896. const String& bodyText,
  225897. bool isOkCancel)
  225898. {
  225899. const ScopedAutoReleasePool pool;
  225900. return NSRunAlertPanel (juceStringToNS (title),
  225901. juceStringToNS (bodyText),
  225902. @"Ok",
  225903. isOkCancel ? @"Cancel" : nil,
  225904. nil) == NSAlertDefaultReturn;
  225905. }
  225906. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225907. {
  225908. if (files.size() == 0)
  225909. return false;
  225910. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225911. if (draggingSource == 0)
  225912. {
  225913. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225914. return false;
  225915. }
  225916. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225917. if (sourceComp == 0)
  225918. {
  225919. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225920. return false;
  225921. }
  225922. const ScopedAutoReleasePool pool;
  225923. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225924. if (view == 0)
  225925. return false;
  225926. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225927. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225928. owner: nil];
  225929. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225930. for (int i = 0; i < files.size(); ++i)
  225931. [filesArray addObject: juceStringToNS (files[i])];
  225932. [pboard setPropertyList: filesArray
  225933. forType: NSFilenamesPboardType];
  225934. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225935. fromView: nil];
  225936. dragPosition.x -= 16;
  225937. dragPosition.y -= 16;
  225938. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225939. at: dragPosition
  225940. offset: NSMakeSize (0, 0)
  225941. event: [[view window] currentEvent]
  225942. pasteboard: pboard
  225943. source: view
  225944. slideBack: YES];
  225945. return true;
  225946. }
  225947. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225948. {
  225949. jassertfalse; // not implemented!
  225950. return false;
  225951. }
  225952. bool Desktop::canUseSemiTransparentWindows() throw()
  225953. {
  225954. return true;
  225955. }
  225956. const Point<int> Desktop::getMousePosition()
  225957. {
  225958. const ScopedAutoReleasePool pool;
  225959. const NSPoint p ([NSEvent mouseLocation]);
  225960. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225961. }
  225962. void Desktop::setMousePosition (const Point<int>& newPosition)
  225963. {
  225964. // this rubbish needs to be done around the warp call, to avoid causing a
  225965. // bizarre glitch..
  225966. CGAssociateMouseAndMouseCursorPosition (false);
  225967. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225968. CGAssociateMouseAndMouseCursorPosition (true);
  225969. }
  225970. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225971. class ScreenSaverDefeater : public Timer,
  225972. public DeletedAtShutdown
  225973. {
  225974. public:
  225975. ScreenSaverDefeater()
  225976. {
  225977. startTimer (10000);
  225978. timerCallback();
  225979. }
  225980. ~ScreenSaverDefeater() {}
  225981. void timerCallback()
  225982. {
  225983. if (Process::isForegroundProcess())
  225984. UpdateSystemActivity (UsrActivity);
  225985. }
  225986. };
  225987. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225988. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225989. {
  225990. if (isEnabled)
  225991. deleteAndZero (screenSaverDefeater);
  225992. else if (screenSaverDefeater == 0)
  225993. screenSaverDefeater = new ScreenSaverDefeater();
  225994. }
  225995. bool Desktop::isScreenSaverEnabled()
  225996. {
  225997. return screenSaverDefeater == 0;
  225998. }
  225999. #else
  226000. static IOPMAssertionID screenSaverDisablerID = 0;
  226001. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226002. {
  226003. if (isEnabled)
  226004. {
  226005. if (screenSaverDisablerID != 0)
  226006. {
  226007. IOPMAssertionRelease (screenSaverDisablerID);
  226008. screenSaverDisablerID = 0;
  226009. }
  226010. }
  226011. else
  226012. {
  226013. if (screenSaverDisablerID == 0)
  226014. {
  226015. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226016. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226017. CFSTR ("Juce"), &screenSaverDisablerID);
  226018. #else
  226019. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226020. &screenSaverDisablerID);
  226021. #endif
  226022. }
  226023. }
  226024. }
  226025. bool Desktop::isScreenSaverEnabled()
  226026. {
  226027. return screenSaverDisablerID == 0;
  226028. }
  226029. #endif
  226030. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226031. {
  226032. const ScopedAutoReleasePool pool;
  226033. monitorCoords.clear();
  226034. NSArray* screens = [NSScreen screens];
  226035. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226036. for (unsigned int i = 0; i < [screens count]; ++i)
  226037. {
  226038. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226039. NSRect r = clipToWorkArea ? [s visibleFrame]
  226040. : [s frame];
  226041. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  226042. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  226043. (int) r.size.width,
  226044. (int) r.size.height));
  226045. }
  226046. jassert (monitorCoords.size() > 0);
  226047. }
  226048. #endif
  226049. #endif
  226050. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226051. #endif
  226052. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226053. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226054. // compiled on its own).
  226055. #if JUCE_INCLUDED_FILE
  226056. void Logger::outputDebugString (const String& text)
  226057. {
  226058. std::cerr << text << std::endl;
  226059. }
  226060. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  226061. {
  226062. static char testResult = 0;
  226063. if (testResult == 0)
  226064. {
  226065. struct kinfo_proc info;
  226066. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226067. size_t sz = sizeof (info);
  226068. sysctl (m, 4, &info, &sz, 0, 0);
  226069. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226070. }
  226071. return testResult > 0;
  226072. }
  226073. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226074. {
  226075. return juce_isRunningUnderDebugger();
  226076. }
  226077. #endif
  226078. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226079. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226080. #if JUCE_IOS
  226081. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226082. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226083. // compiled on its own).
  226084. #if JUCE_INCLUDED_FILE
  226085. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226086. #define SUPPORT_10_4_FONTS 1
  226087. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226088. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226089. #define SUPPORT_ONLY_10_4_FONTS 1
  226090. #endif
  226091. END_JUCE_NAMESPACE
  226092. @interface NSFont (PrivateHack)
  226093. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226094. @end
  226095. BEGIN_JUCE_NAMESPACE
  226096. #endif
  226097. class MacTypeface : public Typeface
  226098. {
  226099. public:
  226100. MacTypeface (const Font& font)
  226101. : Typeface (font.getTypefaceName())
  226102. {
  226103. const ScopedAutoReleasePool pool;
  226104. renderingTransform = CGAffineTransformIdentity;
  226105. bool needsItalicTransform = false;
  226106. #if JUCE_IOS
  226107. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226108. if (font.isItalic() || font.isBold())
  226109. {
  226110. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226111. for (NSString* i in familyFonts)
  226112. {
  226113. const String fn (nsStringToJuce (i));
  226114. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226115. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226116. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226117. || afterDash.containsIgnoreCase ("italic")
  226118. || fn.endsWithIgnoreCase ("oblique")
  226119. || fn.endsWithIgnoreCase ("italic");
  226120. if (probablyBold == font.isBold()
  226121. && probablyItalic == font.isItalic())
  226122. {
  226123. fontName = i;
  226124. needsItalicTransform = false;
  226125. break;
  226126. }
  226127. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226128. {
  226129. fontName = i;
  226130. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226131. }
  226132. }
  226133. if (needsItalicTransform)
  226134. renderingTransform.c = 0.15f;
  226135. }
  226136. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226137. const int ascender = abs (CGFontGetAscent (fontRef));
  226138. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226139. ascent = ascender / totalHeight;
  226140. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226141. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226142. #else
  226143. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226144. if (font.isItalic())
  226145. {
  226146. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226147. toHaveTrait: NSItalicFontMask];
  226148. if (newFont == nsFont)
  226149. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226150. nsFont = newFont;
  226151. }
  226152. if (font.isBold())
  226153. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226154. [nsFont retain];
  226155. ascent = std::abs ((float) [nsFont ascender]);
  226156. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226157. ascent /= totalSize;
  226158. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226159. if (needsItalicTransform)
  226160. {
  226161. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226162. renderingTransform.c = 0.15f;
  226163. }
  226164. #if SUPPORT_ONLY_10_4_FONTS
  226165. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226166. if (atsFont == 0)
  226167. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226168. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226169. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226170. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226171. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226172. #else
  226173. #if SUPPORT_10_4_FONTS
  226174. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226175. {
  226176. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226177. if (atsFont == 0)
  226178. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226179. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226180. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226181. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226182. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226183. }
  226184. else
  226185. #endif
  226186. {
  226187. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226188. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226189. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226190. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226191. }
  226192. #endif
  226193. #endif
  226194. }
  226195. ~MacTypeface()
  226196. {
  226197. #if ! JUCE_IOS
  226198. [nsFont release];
  226199. #endif
  226200. if (fontRef != 0)
  226201. CGFontRelease (fontRef);
  226202. }
  226203. float getAscent() const
  226204. {
  226205. return ascent;
  226206. }
  226207. float getDescent() const
  226208. {
  226209. return 1.0f - ascent;
  226210. }
  226211. float getStringWidth (const String& text)
  226212. {
  226213. if (fontRef == 0 || text.isEmpty())
  226214. return 0;
  226215. const int length = text.length();
  226216. HeapBlock <CGGlyph> glyphs;
  226217. createGlyphsForString (text, length, glyphs);
  226218. float x = 0;
  226219. #if SUPPORT_ONLY_10_4_FONTS
  226220. HeapBlock <NSSize> advances (length);
  226221. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226222. for (int i = 0; i < length; ++i)
  226223. x += advances[i].width;
  226224. #else
  226225. #if SUPPORT_10_4_FONTS
  226226. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226227. {
  226228. HeapBlock <NSSize> advances (length);
  226229. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226230. for (int i = 0; i < length; ++i)
  226231. x += advances[i].width;
  226232. }
  226233. else
  226234. #endif
  226235. {
  226236. HeapBlock <int> advances (length);
  226237. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226238. for (int i = 0; i < length; ++i)
  226239. x += advances[i];
  226240. }
  226241. #endif
  226242. return x * unitsToHeightScaleFactor;
  226243. }
  226244. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226245. {
  226246. xOffsets.add (0);
  226247. if (fontRef == 0 || text.isEmpty())
  226248. return;
  226249. const int length = text.length();
  226250. HeapBlock <CGGlyph> glyphs;
  226251. createGlyphsForString (text, length, glyphs);
  226252. #if SUPPORT_ONLY_10_4_FONTS
  226253. HeapBlock <NSSize> advances (length);
  226254. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226255. int x = 0;
  226256. for (int i = 0; i < length; ++i)
  226257. {
  226258. x += advances[i].width;
  226259. xOffsets.add (x * unitsToHeightScaleFactor);
  226260. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226261. }
  226262. #else
  226263. #if SUPPORT_10_4_FONTS
  226264. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226265. {
  226266. HeapBlock <NSSize> advances (length);
  226267. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226268. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226269. float x = 0;
  226270. for (int i = 0; i < length; ++i)
  226271. {
  226272. x += advances[i].width;
  226273. xOffsets.add (x * unitsToHeightScaleFactor);
  226274. resultGlyphs.add (nsGlyphs[i]);
  226275. }
  226276. }
  226277. else
  226278. #endif
  226279. {
  226280. HeapBlock <int> advances (length);
  226281. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226282. {
  226283. int x = 0;
  226284. for (int i = 0; i < length; ++i)
  226285. {
  226286. x += advances [i];
  226287. xOffsets.add (x * unitsToHeightScaleFactor);
  226288. resultGlyphs.add (glyphs[i]);
  226289. }
  226290. }
  226291. }
  226292. #endif
  226293. }
  226294. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226295. {
  226296. #if JUCE_IOS
  226297. return false;
  226298. #else
  226299. if (nsFont == 0)
  226300. return false;
  226301. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226302. jassert (path.isEmpty());
  226303. const ScopedAutoReleasePool pool;
  226304. NSBezierPath* bez = [NSBezierPath bezierPath];
  226305. [bez moveToPoint: NSMakePoint (0, 0)];
  226306. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226307. inFont: nsFont];
  226308. for (int i = 0; i < [bez elementCount]; ++i)
  226309. {
  226310. NSPoint p[3];
  226311. switch ([bez elementAtIndex: i associatedPoints: p])
  226312. {
  226313. case NSMoveToBezierPathElement:
  226314. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226315. break;
  226316. case NSLineToBezierPathElement:
  226317. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226318. break;
  226319. case NSCurveToBezierPathElement:
  226320. path.cubicTo ((float) p[0].x, (float) -p[0].y, (float) p[1].x, (float) -p[1].y, (float) p[2].x, (float) -p[2].y);
  226321. break;
  226322. case NSClosePathBezierPathElement:
  226323. path.closeSubPath();
  226324. break;
  226325. default:
  226326. jassertfalse;
  226327. break;
  226328. }
  226329. }
  226330. path.applyTransform (pathTransform);
  226331. return true;
  226332. #endif
  226333. }
  226334. juce_UseDebuggingNewOperator
  226335. CGFontRef fontRef;
  226336. float fontHeightToCGSizeFactor;
  226337. CGAffineTransform renderingTransform;
  226338. private:
  226339. float ascent, unitsToHeightScaleFactor;
  226340. #if JUCE_IOS
  226341. #else
  226342. NSFont* nsFont;
  226343. AffineTransform pathTransform;
  226344. #endif
  226345. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226346. {
  226347. #if SUPPORT_10_4_FONTS
  226348. #if ! SUPPORT_ONLY_10_4_FONTS
  226349. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226350. #endif
  226351. {
  226352. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226353. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226354. for (int i = 0; i < length; ++i)
  226355. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226356. return;
  226357. }
  226358. #endif
  226359. #if ! SUPPORT_ONLY_10_4_FONTS
  226360. if (charToGlyphMapper == 0)
  226361. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226362. glyphs.malloc (length);
  226363. for (int i = 0; i < length; ++i)
  226364. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226365. #endif
  226366. }
  226367. #if ! SUPPORT_ONLY_10_4_FONTS
  226368. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226369. class CharToGlyphMapper
  226370. {
  226371. public:
  226372. CharToGlyphMapper (CGFontRef fontRef)
  226373. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226374. idRangeOffset (0), glyphIndexes (0)
  226375. {
  226376. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226377. if (cmapTable != 0)
  226378. {
  226379. const int numSubtables = getValue16 (cmapTable, 2);
  226380. for (int i = 0; i < numSubtables; ++i)
  226381. {
  226382. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226383. {
  226384. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226385. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226386. {
  226387. const int length = getValue16 (cmapTable, offset + 2);
  226388. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226389. segCount = segCountX2 / 2;
  226390. const int endCodeOffset = offset + 14;
  226391. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226392. const int idDeltaOffset = startCodeOffset + segCountX2;
  226393. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226394. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226395. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226396. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226397. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226398. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226399. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226400. }
  226401. break;
  226402. }
  226403. }
  226404. CFRelease (cmapTable);
  226405. }
  226406. }
  226407. ~CharToGlyphMapper()
  226408. {
  226409. if (endCode != 0)
  226410. {
  226411. CFRelease (endCode);
  226412. CFRelease (startCode);
  226413. CFRelease (idDelta);
  226414. CFRelease (idRangeOffset);
  226415. CFRelease (glyphIndexes);
  226416. }
  226417. }
  226418. int getGlyphForCharacter (const juce_wchar c) const
  226419. {
  226420. for (int i = 0; i < segCount; ++i)
  226421. {
  226422. if (getValue16 (endCode, i * 2) >= c)
  226423. {
  226424. const int start = getValue16 (startCode, i * 2);
  226425. if (start > c)
  226426. break;
  226427. const int delta = getValue16 (idDelta, i * 2);
  226428. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226429. if (rangeOffset == 0)
  226430. return delta + c;
  226431. else
  226432. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226433. }
  226434. }
  226435. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226436. return jmax (-1, c - 29);
  226437. }
  226438. private:
  226439. int segCount;
  226440. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226441. static uint16 getValue16 (CFDataRef data, const int index)
  226442. {
  226443. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226444. }
  226445. static uint32 getValue32 (CFDataRef data, const int index)
  226446. {
  226447. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226448. }
  226449. };
  226450. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226451. #endif
  226452. MacTypeface (const MacTypeface&);
  226453. MacTypeface& operator= (const MacTypeface&);
  226454. };
  226455. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226456. {
  226457. return new MacTypeface (font);
  226458. }
  226459. const StringArray Font::findAllTypefaceNames()
  226460. {
  226461. StringArray names;
  226462. const ScopedAutoReleasePool pool;
  226463. #if JUCE_IOS
  226464. NSArray* fonts = [UIFont familyNames];
  226465. #else
  226466. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226467. #endif
  226468. for (unsigned int i = 0; i < [fonts count]; ++i)
  226469. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226470. names.sort (true);
  226471. return names;
  226472. }
  226473. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226474. {
  226475. #if JUCE_IOS
  226476. defaultSans = "Helvetica";
  226477. defaultSerif = "Times New Roman";
  226478. defaultFixed = "Courier New";
  226479. #else
  226480. defaultSans = "Lucida Grande";
  226481. defaultSerif = "Times New Roman";
  226482. defaultFixed = "Monaco";
  226483. #endif
  226484. }
  226485. #endif
  226486. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226487. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226488. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226489. // compiled on its own).
  226490. #if JUCE_INCLUDED_FILE
  226491. class CoreGraphicsImage : public Image::SharedImage
  226492. {
  226493. public:
  226494. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226495. : Image::SharedImage (format_, width_, height_)
  226496. {
  226497. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226498. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226499. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226500. imageData = imageDataAllocated;
  226501. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226502. : CGColorSpaceCreateDeviceRGB();
  226503. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226504. colourSpace, getCGImageFlags (format_));
  226505. CGColorSpaceRelease (colourSpace);
  226506. }
  226507. ~CoreGraphicsImage()
  226508. {
  226509. CGContextRelease (context);
  226510. }
  226511. Image::ImageType getType() const { return Image::NativeImage; }
  226512. LowLevelGraphicsContext* createLowLevelContext();
  226513. SharedImage* clone()
  226514. {
  226515. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226516. memcpy (im->imageData, imageData, lineStride * height);
  226517. return im;
  226518. }
  226519. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226520. {
  226521. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226522. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226523. {
  226524. return CGBitmapContextCreateImage (nativeImage->context);
  226525. }
  226526. else
  226527. {
  226528. const Image::BitmapData srcData (juceImage, false);
  226529. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226530. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226531. 8, srcData.pixelStride * 8, srcData.lineStride,
  226532. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226533. 0, true, kCGRenderingIntentDefault);
  226534. CGDataProviderRelease (provider);
  226535. return imageRef;
  226536. }
  226537. }
  226538. #if JUCE_MAC
  226539. static NSImage* createNSImage (const Image& image)
  226540. {
  226541. const ScopedAutoReleasePool pool;
  226542. NSImage* im = [[NSImage alloc] init];
  226543. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226544. [im lockFocus];
  226545. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226546. CGImageRef imageRef = createImage (image, false, colourSpace);
  226547. CGColorSpaceRelease (colourSpace);
  226548. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226549. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226550. CGImageRelease (imageRef);
  226551. [im unlockFocus];
  226552. return im;
  226553. }
  226554. #endif
  226555. CGContextRef context;
  226556. HeapBlock<uint8> imageDataAllocated;
  226557. private:
  226558. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226559. {
  226560. #if JUCE_BIG_ENDIAN
  226561. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226562. #else
  226563. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226564. #endif
  226565. }
  226566. };
  226567. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226568. {
  226569. #if USE_COREGRAPHICS_RENDERING
  226570. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226571. #else
  226572. return createSoftwareImage (format, width, height, clearImage);
  226573. #endif
  226574. }
  226575. class CoreGraphicsContext : public LowLevelGraphicsContext
  226576. {
  226577. public:
  226578. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226579. : context (context_),
  226580. flipHeight (flipHeight_),
  226581. state (new SavedState()),
  226582. numGradientLookupEntries (0),
  226583. lastClipRectIsValid (false)
  226584. {
  226585. CGContextRetain (context);
  226586. CGContextSaveGState(context);
  226587. CGContextSetShouldSmoothFonts (context, true);
  226588. CGContextSetShouldAntialias (context, true);
  226589. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226590. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226591. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226592. gradientCallbacks.version = 0;
  226593. gradientCallbacks.evaluate = gradientCallback;
  226594. gradientCallbacks.releaseInfo = 0;
  226595. setFont (Font());
  226596. }
  226597. ~CoreGraphicsContext()
  226598. {
  226599. CGContextRestoreGState (context);
  226600. CGContextRelease (context);
  226601. CGColorSpaceRelease (rgbColourSpace);
  226602. CGColorSpaceRelease (greyColourSpace);
  226603. }
  226604. bool isVectorDevice() const { return false; }
  226605. void setOrigin (int x, int y)
  226606. {
  226607. CGContextTranslateCTM (context, x, -y);
  226608. if (lastClipRectIsValid)
  226609. lastClipRect.translate (-x, -y);
  226610. }
  226611. bool clipToRectangle (const Rectangle<int>& r)
  226612. {
  226613. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226614. if (lastClipRectIsValid)
  226615. {
  226616. // This is actually incorrect, because the actual clip region may be complex, and
  226617. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226618. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226619. // when calculating the resultant clip bounds, and makes the same mistake!
  226620. lastClipRect = lastClipRect.getIntersection (r);
  226621. return ! lastClipRect.isEmpty();
  226622. }
  226623. return ! isClipEmpty();
  226624. }
  226625. bool clipToRectangleList (const RectangleList& clipRegion)
  226626. {
  226627. if (clipRegion.isEmpty())
  226628. {
  226629. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226630. lastClipRectIsValid = true;
  226631. lastClipRect = Rectangle<int>();
  226632. return false;
  226633. }
  226634. else
  226635. {
  226636. const int numRects = clipRegion.getNumRectangles();
  226637. HeapBlock <CGRect> rects (numRects);
  226638. for (int i = 0; i < numRects; ++i)
  226639. {
  226640. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226641. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226642. }
  226643. CGContextClipToRects (context, rects, numRects);
  226644. lastClipRectIsValid = false;
  226645. return ! isClipEmpty();
  226646. }
  226647. }
  226648. void excludeClipRectangle (const Rectangle<int>& r)
  226649. {
  226650. RectangleList remaining (getClipBounds());
  226651. remaining.subtract (r);
  226652. clipToRectangleList (remaining);
  226653. lastClipRectIsValid = false;
  226654. }
  226655. void clipToPath (const Path& path, const AffineTransform& transform)
  226656. {
  226657. createPath (path, transform);
  226658. CGContextClip (context);
  226659. lastClipRectIsValid = false;
  226660. }
  226661. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226662. {
  226663. if (! transform.isSingularity())
  226664. {
  226665. Image singleChannelImage (sourceImage);
  226666. if (sourceImage.getFormat() != Image::SingleChannel)
  226667. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226668. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226669. flip();
  226670. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226671. applyTransform (t);
  226672. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226673. CGContextClipToMask (context, r, image);
  226674. applyTransform (t.inverted());
  226675. flip();
  226676. CGImageRelease (image);
  226677. lastClipRectIsValid = false;
  226678. }
  226679. }
  226680. bool clipRegionIntersects (const Rectangle<int>& r)
  226681. {
  226682. return getClipBounds().intersects (r);
  226683. }
  226684. const Rectangle<int> getClipBounds() const
  226685. {
  226686. if (! lastClipRectIsValid)
  226687. {
  226688. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226689. lastClipRectIsValid = true;
  226690. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226691. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226692. roundToInt (bounds.size.width),
  226693. roundToInt (bounds.size.height));
  226694. }
  226695. return lastClipRect;
  226696. }
  226697. bool isClipEmpty() const
  226698. {
  226699. return getClipBounds().isEmpty();
  226700. }
  226701. void saveState()
  226702. {
  226703. CGContextSaveGState (context);
  226704. stateStack.add (new SavedState (*state));
  226705. }
  226706. void restoreState()
  226707. {
  226708. CGContextRestoreGState (context);
  226709. SavedState* const top = stateStack.getLast();
  226710. if (top != 0)
  226711. {
  226712. state = top;
  226713. stateStack.removeLast (1, false);
  226714. lastClipRectIsValid = false;
  226715. }
  226716. else
  226717. {
  226718. jassertfalse; // trying to pop with an empty stack!
  226719. }
  226720. }
  226721. void setFill (const FillType& fillType)
  226722. {
  226723. state->fillType = fillType;
  226724. if (fillType.isColour())
  226725. {
  226726. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226727. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226728. CGContextSetAlpha (context, 1.0f);
  226729. }
  226730. }
  226731. void setOpacity (float newOpacity)
  226732. {
  226733. state->fillType.setOpacity (newOpacity);
  226734. setFill (state->fillType);
  226735. }
  226736. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226737. {
  226738. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226739. ? kCGInterpolationLow
  226740. : kCGInterpolationHigh);
  226741. }
  226742. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226743. {
  226744. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226745. }
  226746. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226747. {
  226748. if (replaceExistingContents)
  226749. {
  226750. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226751. CGContextClearRect (context, cgRect);
  226752. #else
  226753. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226754. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226755. CGContextClearRect (context, cgRect);
  226756. else
  226757. #endif
  226758. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226759. #endif
  226760. fillCGRect (cgRect, false);
  226761. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226762. }
  226763. else
  226764. {
  226765. if (state->fillType.isColour())
  226766. {
  226767. CGContextFillRect (context, cgRect);
  226768. }
  226769. else if (state->fillType.isGradient())
  226770. {
  226771. CGContextSaveGState (context);
  226772. CGContextClipToRect (context, cgRect);
  226773. drawGradient();
  226774. CGContextRestoreGState (context);
  226775. }
  226776. else
  226777. {
  226778. CGContextSaveGState (context);
  226779. CGContextClipToRect (context, cgRect);
  226780. drawImage (state->fillType.image, state->fillType.transform, true);
  226781. CGContextRestoreGState (context);
  226782. }
  226783. }
  226784. }
  226785. void fillPath (const Path& path, const AffineTransform& transform)
  226786. {
  226787. CGContextSaveGState (context);
  226788. if (state->fillType.isColour())
  226789. {
  226790. flip();
  226791. applyTransform (transform);
  226792. createPath (path);
  226793. if (path.isUsingNonZeroWinding())
  226794. CGContextFillPath (context);
  226795. else
  226796. CGContextEOFillPath (context);
  226797. }
  226798. else
  226799. {
  226800. createPath (path, transform);
  226801. if (path.isUsingNonZeroWinding())
  226802. CGContextClip (context);
  226803. else
  226804. CGContextEOClip (context);
  226805. if (state->fillType.isGradient())
  226806. drawGradient();
  226807. else
  226808. drawImage (state->fillType.image, state->fillType.transform, true);
  226809. }
  226810. CGContextRestoreGState (context);
  226811. }
  226812. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226813. {
  226814. const int iw = sourceImage.getWidth();
  226815. const int ih = sourceImage.getHeight();
  226816. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226817. CGContextSaveGState (context);
  226818. CGContextSetAlpha (context, state->fillType.getOpacity());
  226819. flip();
  226820. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226821. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226822. if (fillEntireClipAsTiles)
  226823. {
  226824. #if JUCE_IOS
  226825. CGContextDrawTiledImage (context, imageRect, image);
  226826. #else
  226827. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226828. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226829. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226830. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226831. CGContextDrawTiledImage (context, imageRect, image);
  226832. else
  226833. #endif
  226834. {
  226835. // Fallback to manually doing a tiled fill on 10.4
  226836. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226837. int x = 0, y = 0;
  226838. while (x > clip.origin.x) x -= iw;
  226839. while (y > clip.origin.y) y -= ih;
  226840. const int right = (int) (clip.origin.x + clip.size.width);
  226841. const int bottom = (int) (clip.origin.y + clip.size.height);
  226842. while (y < bottom)
  226843. {
  226844. for (int x2 = x; x2 < right; x2 += iw)
  226845. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226846. y += ih;
  226847. }
  226848. }
  226849. #endif
  226850. }
  226851. else
  226852. {
  226853. CGContextDrawImage (context, imageRect, image);
  226854. }
  226855. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226856. CGContextRestoreGState (context);
  226857. }
  226858. void drawLine (const Line<float>& line)
  226859. {
  226860. if (state->fillType.isColour())
  226861. {
  226862. CGContextSetLineCap (context, kCGLineCapSquare);
  226863. CGContextSetLineWidth (context, 1.0f);
  226864. CGContextSetRGBStrokeColor (context,
  226865. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226866. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226867. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226868. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226869. CGContextStrokeLineSegments (context, cgLine, 1);
  226870. }
  226871. else
  226872. {
  226873. Path p;
  226874. p.addLineSegment (line, 1.0f);
  226875. fillPath (p, AffineTransform::identity);
  226876. }
  226877. }
  226878. void drawVerticalLine (const int x, float top, float bottom)
  226879. {
  226880. if (state->fillType.isColour())
  226881. {
  226882. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226883. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226884. #else
  226885. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226886. // the x co-ord slightly to trick it..
  226887. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226888. #endif
  226889. }
  226890. else
  226891. {
  226892. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226893. }
  226894. }
  226895. void drawHorizontalLine (const int y, float left, float right)
  226896. {
  226897. if (state->fillType.isColour())
  226898. {
  226899. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226900. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226901. #else
  226902. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226903. // the x co-ord slightly to trick it..
  226904. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226905. #endif
  226906. }
  226907. else
  226908. {
  226909. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226910. }
  226911. }
  226912. void setFont (const Font& newFont)
  226913. {
  226914. if (state->font != newFont)
  226915. {
  226916. state->fontRef = 0;
  226917. state->font = newFont;
  226918. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226919. if (mf != 0)
  226920. {
  226921. state->fontRef = mf->fontRef;
  226922. CGContextSetFont (context, state->fontRef);
  226923. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226924. state->fontTransform = mf->renderingTransform;
  226925. state->fontTransform.a *= state->font.getHorizontalScale();
  226926. CGContextSetTextMatrix (context, state->fontTransform);
  226927. }
  226928. }
  226929. }
  226930. const Font getFont()
  226931. {
  226932. return state->font;
  226933. }
  226934. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226935. {
  226936. if (state->fontRef != 0 && state->fillType.isColour())
  226937. {
  226938. if (transform.isOnlyTranslation())
  226939. {
  226940. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226941. CGGlyph g = glyphNumber;
  226942. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226943. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226944. }
  226945. else
  226946. {
  226947. CGContextSaveGState (context);
  226948. flip();
  226949. applyTransform (transform);
  226950. CGAffineTransform t = state->fontTransform;
  226951. t.d = -t.d;
  226952. CGContextSetTextMatrix (context, t);
  226953. CGGlyph g = glyphNumber;
  226954. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226955. CGContextRestoreGState (context);
  226956. }
  226957. }
  226958. else
  226959. {
  226960. Path p;
  226961. Font& f = state->font;
  226962. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226963. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226964. .followedBy (transform));
  226965. }
  226966. }
  226967. private:
  226968. CGContextRef context;
  226969. const CGFloat flipHeight;
  226970. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226971. CGFunctionCallbacks gradientCallbacks;
  226972. mutable Rectangle<int> lastClipRect;
  226973. mutable bool lastClipRectIsValid;
  226974. struct SavedState
  226975. {
  226976. SavedState()
  226977. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226978. {
  226979. }
  226980. SavedState (const SavedState& other)
  226981. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226982. fontTransform (other.fontTransform)
  226983. {
  226984. }
  226985. ~SavedState()
  226986. {
  226987. }
  226988. FillType fillType;
  226989. Font font;
  226990. CGFontRef fontRef;
  226991. CGAffineTransform fontTransform;
  226992. };
  226993. ScopedPointer <SavedState> state;
  226994. OwnedArray <SavedState> stateStack;
  226995. HeapBlock <PixelARGB> gradientLookupTable;
  226996. int numGradientLookupEntries;
  226997. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226998. {
  226999. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227000. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227001. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227002. colour.unpremultiply();
  227003. outData[0] = colour.getRed() / 255.0f;
  227004. outData[1] = colour.getGreen() / 255.0f;
  227005. outData[2] = colour.getBlue() / 255.0f;
  227006. outData[3] = colour.getAlpha() / 255.0f;
  227007. }
  227008. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227009. {
  227010. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227011. --numGradientLookupEntries;
  227012. CGShadingRef result = 0;
  227013. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227014. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227015. if (gradient.isRadial)
  227016. {
  227017. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227018. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227019. function, true, true);
  227020. }
  227021. else
  227022. {
  227023. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227024. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227025. function, true, true);
  227026. }
  227027. CGFunctionRelease (function);
  227028. return result;
  227029. }
  227030. void drawGradient()
  227031. {
  227032. flip();
  227033. applyTransform (state->fillType.transform);
  227034. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227035. // you draw a gradient with high quality interp enabled).
  227036. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227037. CGContextSetAlpha (context, state->fillType.getOpacity());
  227038. CGContextDrawShading (context, shading);
  227039. CGShadingRelease (shading);
  227040. }
  227041. void createPath (const Path& path) const
  227042. {
  227043. CGContextBeginPath (context);
  227044. Path::Iterator i (path);
  227045. while (i.next())
  227046. {
  227047. switch (i.elementType)
  227048. {
  227049. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227050. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227051. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227052. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227053. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227054. default: jassertfalse; break;
  227055. }
  227056. }
  227057. }
  227058. void createPath (const Path& path, const AffineTransform& transform) const
  227059. {
  227060. CGContextBeginPath (context);
  227061. Path::Iterator i (path);
  227062. while (i.next())
  227063. {
  227064. switch (i.elementType)
  227065. {
  227066. case Path::Iterator::startNewSubPath:
  227067. transform.transformPoint (i.x1, i.y1);
  227068. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227069. break;
  227070. case Path::Iterator::lineTo:
  227071. transform.transformPoint (i.x1, i.y1);
  227072. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227073. break;
  227074. case Path::Iterator::quadraticTo:
  227075. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227076. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227077. break;
  227078. case Path::Iterator::cubicTo:
  227079. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227080. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227081. break;
  227082. case Path::Iterator::closePath:
  227083. CGContextClosePath (context); break;
  227084. default:
  227085. jassertfalse;
  227086. break;
  227087. }
  227088. }
  227089. }
  227090. void flip() const
  227091. {
  227092. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227093. }
  227094. void applyTransform (const AffineTransform& transform) const
  227095. {
  227096. CGAffineTransform t;
  227097. t.a = transform.mat00;
  227098. t.b = transform.mat10;
  227099. t.c = transform.mat01;
  227100. t.d = transform.mat11;
  227101. t.tx = transform.mat02;
  227102. t.ty = transform.mat12;
  227103. CGContextConcatCTM (context, t);
  227104. }
  227105. CoreGraphicsContext (const CoreGraphicsContext&);
  227106. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227107. };
  227108. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227109. {
  227110. return new CoreGraphicsContext (context, height);
  227111. }
  227112. #endif
  227113. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227114. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227115. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227116. // compiled on its own).
  227117. #if JUCE_INCLUDED_FILE
  227118. class UIViewComponentPeer;
  227119. END_JUCE_NAMESPACE
  227120. #define JuceUIView MakeObjCClassName(JuceUIView)
  227121. @interface JuceUIView : UIView <UITextViewDelegate>
  227122. {
  227123. @public
  227124. UIViewComponentPeer* owner;
  227125. UITextView* hiddenTextView;
  227126. }
  227127. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227128. - (void) dealloc;
  227129. - (void) drawRect: (CGRect) r;
  227130. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227131. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227132. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227133. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227134. - (BOOL) becomeFirstResponder;
  227135. - (BOOL) resignFirstResponder;
  227136. - (BOOL) canBecomeFirstResponder;
  227137. - (void) asyncRepaint: (id) rect;
  227138. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227139. @end
  227140. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227141. @interface JuceUIWindow : UIWindow
  227142. {
  227143. @private
  227144. UIViewComponentPeer* owner;
  227145. bool isZooming;
  227146. }
  227147. - (void) setOwner: (UIViewComponentPeer*) owner;
  227148. - (void) becomeKeyWindow;
  227149. @end
  227150. BEGIN_JUCE_NAMESPACE
  227151. class UIViewComponentPeer : public ComponentPeer,
  227152. public FocusChangeListener
  227153. {
  227154. public:
  227155. UIViewComponentPeer (Component* const component,
  227156. const int windowStyleFlags,
  227157. UIView* viewToAttachTo);
  227158. ~UIViewComponentPeer();
  227159. void* getNativeHandle() const;
  227160. void setVisible (bool shouldBeVisible);
  227161. void setTitle (const String& title);
  227162. void setPosition (int x, int y);
  227163. void setSize (int w, int h);
  227164. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227165. const Rectangle<int> getBounds() const;
  227166. const Rectangle<int> getBounds (const bool global) const;
  227167. const Point<int> getScreenPosition() const;
  227168. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227169. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227170. void setMinimised (bool shouldBeMinimised);
  227171. bool isMinimised() const;
  227172. void setFullScreen (bool shouldBeFullScreen);
  227173. bool isFullScreen() const;
  227174. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227175. const BorderSize getFrameSize() const;
  227176. bool setAlwaysOnTop (bool alwaysOnTop);
  227177. void toFront (bool makeActiveWindow);
  227178. void toBehind (ComponentPeer* other);
  227179. void setIcon (const Image& newIcon);
  227180. virtual void drawRect (CGRect r);
  227181. virtual bool canBecomeKeyWindow();
  227182. virtual bool windowShouldClose();
  227183. virtual void redirectMovedOrResized();
  227184. virtual CGRect constrainRect (CGRect r);
  227185. virtual void viewFocusGain();
  227186. virtual void viewFocusLoss();
  227187. bool isFocused() const;
  227188. void grabFocus();
  227189. void textInputRequired (const Point<int>& position);
  227190. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227191. void updateHiddenTextContent (TextInputTarget* target);
  227192. void globalFocusChanged (Component*);
  227193. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227194. void repaint (const Rectangle<int>& area);
  227195. void performAnyPendingRepaintsNow();
  227196. juce_UseDebuggingNewOperator
  227197. UIWindow* window;
  227198. JuceUIView* view;
  227199. bool isSharedWindow, fullScreen, insideDrawRect;
  227200. static ModifierKeys currentModifiers;
  227201. static int64 getMouseTime (UIEvent* e)
  227202. {
  227203. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227204. + (int64) ([e timestamp] * 1000.0);
  227205. }
  227206. Array <UITouch*> currentTouches;
  227207. };
  227208. END_JUCE_NAMESPACE
  227209. @implementation JuceUIView
  227210. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227211. withFrame: (CGRect) frame
  227212. {
  227213. [super initWithFrame: frame];
  227214. owner = owner_;
  227215. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227216. [self addSubview: hiddenTextView];
  227217. hiddenTextView.delegate = self;
  227218. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227219. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227220. return self;
  227221. }
  227222. - (void) dealloc
  227223. {
  227224. [hiddenTextView removeFromSuperview];
  227225. [hiddenTextView release];
  227226. [super dealloc];
  227227. }
  227228. - (void) drawRect: (CGRect) r
  227229. {
  227230. if (owner != 0)
  227231. owner->drawRect (r);
  227232. }
  227233. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227234. {
  227235. return false;
  227236. }
  227237. ModifierKeys UIViewComponentPeer::currentModifiers;
  227238. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227239. {
  227240. return UIViewComponentPeer::currentModifiers;
  227241. }
  227242. void ModifierKeys::updateCurrentModifiers() throw()
  227243. {
  227244. currentModifiers = UIViewComponentPeer::currentModifiers;
  227245. }
  227246. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227247. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227248. {
  227249. if (owner != 0)
  227250. owner->handleTouches (event, true, false, false);
  227251. }
  227252. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227253. {
  227254. if (owner != 0)
  227255. owner->handleTouches (event, false, false, false);
  227256. }
  227257. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227258. {
  227259. if (owner != 0)
  227260. owner->handleTouches (event, false, true, false);
  227261. }
  227262. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227263. {
  227264. if (owner != 0)
  227265. owner->handleTouches (event, false, true, true);
  227266. [self touchesEnded: touches withEvent: event];
  227267. }
  227268. - (BOOL) becomeFirstResponder
  227269. {
  227270. if (owner != 0)
  227271. owner->viewFocusGain();
  227272. return true;
  227273. }
  227274. - (BOOL) resignFirstResponder
  227275. {
  227276. if (owner != 0)
  227277. owner->viewFocusLoss();
  227278. return true;
  227279. }
  227280. - (BOOL) canBecomeFirstResponder
  227281. {
  227282. return owner != 0 && owner->canBecomeKeyWindow();
  227283. }
  227284. - (void) asyncRepaint: (id) rect
  227285. {
  227286. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227287. [self setNeedsDisplayInRect: *r];
  227288. }
  227289. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227290. {
  227291. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227292. nsStringToJuce (text));
  227293. }
  227294. @end
  227295. @implementation JuceUIWindow
  227296. - (void) setOwner: (UIViewComponentPeer*) owner_
  227297. {
  227298. owner = owner_;
  227299. isZooming = false;
  227300. }
  227301. - (void) becomeKeyWindow
  227302. {
  227303. [super becomeKeyWindow];
  227304. if (owner != 0)
  227305. owner->grabFocus();
  227306. }
  227307. @end
  227308. BEGIN_JUCE_NAMESPACE
  227309. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227310. const int windowStyleFlags,
  227311. UIView* viewToAttachTo)
  227312. : ComponentPeer (component, windowStyleFlags),
  227313. window (0),
  227314. view (0),
  227315. isSharedWindow (viewToAttachTo != 0),
  227316. fullScreen (false),
  227317. insideDrawRect (false)
  227318. {
  227319. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  227320. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227321. if (isSharedWindow)
  227322. {
  227323. window = [viewToAttachTo window];
  227324. [viewToAttachTo addSubview: view];
  227325. setVisible (component->isVisible());
  227326. }
  227327. else
  227328. {
  227329. r.origin.x = (float) component->getX();
  227330. r.origin.y = (float) component->getY();
  227331. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227332. window = [[JuceUIWindow alloc] init];
  227333. window.frame = r;
  227334. window.opaque = component->isOpaque();
  227335. view.opaque = component->isOpaque();
  227336. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227337. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227338. [((JuceUIWindow*) window) setOwner: this];
  227339. if (component->isAlwaysOnTop())
  227340. window.windowLevel = UIWindowLevelAlert;
  227341. [window addSubview: view];
  227342. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227343. view.hidden = ! component->isVisible();
  227344. window.hidden = ! component->isVisible();
  227345. view.multipleTouchEnabled = YES;
  227346. }
  227347. setTitle (component->getName());
  227348. Desktop::getInstance().addFocusChangeListener (this);
  227349. }
  227350. UIViewComponentPeer::~UIViewComponentPeer()
  227351. {
  227352. Desktop::getInstance().removeFocusChangeListener (this);
  227353. view->owner = 0;
  227354. [view removeFromSuperview];
  227355. [view release];
  227356. if (! isSharedWindow)
  227357. {
  227358. [((JuceUIWindow*) window) setOwner: 0];
  227359. [window release];
  227360. }
  227361. }
  227362. void* UIViewComponentPeer::getNativeHandle() const
  227363. {
  227364. return view;
  227365. }
  227366. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227367. {
  227368. view.hidden = ! shouldBeVisible;
  227369. if (! isSharedWindow)
  227370. window.hidden = ! shouldBeVisible;
  227371. }
  227372. void UIViewComponentPeer::setTitle (const String& title)
  227373. {
  227374. // xxx is this possible?
  227375. }
  227376. void UIViewComponentPeer::setPosition (int x, int y)
  227377. {
  227378. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227379. }
  227380. void UIViewComponentPeer::setSize (int w, int h)
  227381. {
  227382. setBounds (component->getX(), component->getY(), w, h, false);
  227383. }
  227384. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227385. {
  227386. fullScreen = isNowFullScreen;
  227387. w = jmax (0, w);
  227388. h = jmax (0, h);
  227389. CGRect r;
  227390. r.origin.x = (float) x;
  227391. r.origin.y = (float) y;
  227392. r.size.width = (float) w;
  227393. r.size.height = (float) h;
  227394. if (isSharedWindow)
  227395. {
  227396. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  227397. if ([view frame].size.width != r.size.width
  227398. || [view frame].size.height != r.size.height)
  227399. [view setNeedsDisplay];
  227400. view.frame = r;
  227401. }
  227402. else
  227403. {
  227404. window.frame = r;
  227405. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227406. }
  227407. }
  227408. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227409. {
  227410. CGRect r = [view frame];
  227411. if (global && [view window] != 0)
  227412. {
  227413. r = [view convertRect: r toView: nil];
  227414. CGRect wr = [[view window] frame];
  227415. r.origin.x += wr.origin.x;
  227416. r.origin.y += wr.origin.y;
  227417. }
  227418. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  227419. (int) r.size.width, (int) r.size.height);
  227420. }
  227421. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227422. {
  227423. return getBounds (! isSharedWindow);
  227424. }
  227425. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227426. {
  227427. return getBounds (true).getPosition();
  227428. }
  227429. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227430. {
  227431. return relativePosition + getScreenPosition();
  227432. }
  227433. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227434. {
  227435. return screenPosition - getScreenPosition();
  227436. }
  227437. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227438. {
  227439. if (constrainer != 0)
  227440. {
  227441. CGRect current = [window frame];
  227442. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227443. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227444. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  227445. (int) r.size.width, (int) r.size.height);
  227446. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  227447. (int) current.size.width, (int) current.size.height);
  227448. constrainer->checkBounds (pos, original,
  227449. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227450. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227451. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227452. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227453. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227454. r.origin.x = pos.getX();
  227455. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227456. r.size.width = pos.getWidth();
  227457. r.size.height = pos.getHeight();
  227458. }
  227459. return r;
  227460. }
  227461. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227462. {
  227463. // xxx
  227464. }
  227465. bool UIViewComponentPeer::isMinimised() const
  227466. {
  227467. return false;
  227468. }
  227469. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227470. {
  227471. if (! isSharedWindow)
  227472. {
  227473. Rectangle<int> r (lastNonFullscreenBounds);
  227474. setMinimised (false);
  227475. if (fullScreen != shouldBeFullScreen)
  227476. {
  227477. if (shouldBeFullScreen)
  227478. r = Desktop::getInstance().getMainMonitorArea();
  227479. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227480. if (r != getComponent()->getBounds() && ! r.isEmpty())
  227481. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227482. }
  227483. }
  227484. }
  227485. bool UIViewComponentPeer::isFullScreen() const
  227486. {
  227487. return fullScreen;
  227488. }
  227489. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227490. {
  227491. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227492. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227493. return false;
  227494. CGPoint p;
  227495. p.x = (float) position.getX();
  227496. p.y = (float) position.getY();
  227497. UIView* v = [view hitTest: p withEvent: nil];
  227498. if (trueIfInAChildWindow)
  227499. return v != nil;
  227500. return v == view;
  227501. }
  227502. const BorderSize UIViewComponentPeer::getFrameSize() const
  227503. {
  227504. BorderSize b;
  227505. if (! isSharedWindow)
  227506. {
  227507. CGRect v = [view convertRect: [view frame] toView: nil];
  227508. CGRect w = [window frame];
  227509. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  227510. b.setBottom ((int) v.origin.y);
  227511. b.setLeft ((int) v.origin.x);
  227512. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  227513. }
  227514. return b;
  227515. }
  227516. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227517. {
  227518. if (! isSharedWindow)
  227519. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227520. return true;
  227521. }
  227522. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227523. {
  227524. if (isSharedWindow)
  227525. [[view superview] bringSubviewToFront: view];
  227526. if (window != 0 && component->isVisible())
  227527. [window makeKeyAndVisible];
  227528. }
  227529. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227530. {
  227531. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227532. jassert (otherPeer != 0); // wrong type of window?
  227533. if (otherPeer != 0)
  227534. {
  227535. if (isSharedWindow)
  227536. {
  227537. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227538. }
  227539. else
  227540. {
  227541. jassertfalse; // don't know how to do this
  227542. }
  227543. }
  227544. }
  227545. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227546. {
  227547. // to do..
  227548. }
  227549. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227550. {
  227551. NSArray* touches = [[event touchesForView: view] allObjects];
  227552. for (unsigned int i = 0; i < [touches count]; ++i)
  227553. {
  227554. UITouch* touch = [touches objectAtIndex: i];
  227555. CGPoint p = [touch locationInView: view];
  227556. const Point<int> pos ((int) p.x, (int) p.y);
  227557. juce_lastMousePos = pos + getScreenPosition();
  227558. const int64 time = getMouseTime (event);
  227559. int touchIndex = currentTouches.indexOf (touch);
  227560. if (touchIndex < 0)
  227561. {
  227562. touchIndex = currentTouches.size();
  227563. currentTouches.add (touch);
  227564. }
  227565. if (isDown)
  227566. {
  227567. currentModifiers = currentModifiers.withoutMouseButtons();
  227568. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227569. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227570. }
  227571. else if (isUp)
  227572. {
  227573. currentModifiers = currentModifiers.withoutMouseButtons();
  227574. currentTouches.remove (touchIndex);
  227575. }
  227576. if (isCancel)
  227577. currentTouches.clear();
  227578. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227579. }
  227580. }
  227581. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227582. void UIViewComponentPeer::viewFocusGain()
  227583. {
  227584. if (currentlyFocusedPeer != this)
  227585. {
  227586. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227587. currentlyFocusedPeer->handleFocusLoss();
  227588. currentlyFocusedPeer = this;
  227589. handleFocusGain();
  227590. }
  227591. }
  227592. void UIViewComponentPeer::viewFocusLoss()
  227593. {
  227594. if (currentlyFocusedPeer == this)
  227595. {
  227596. currentlyFocusedPeer = 0;
  227597. handleFocusLoss();
  227598. }
  227599. }
  227600. void juce_HandleProcessFocusChange()
  227601. {
  227602. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227603. {
  227604. if (Process::isForegroundProcess())
  227605. {
  227606. currentlyFocusedPeer->handleFocusGain();
  227607. ComponentPeer::bringModalComponentToFront();
  227608. }
  227609. else
  227610. {
  227611. currentlyFocusedPeer->handleFocusLoss();
  227612. // turn kiosk mode off if we lose focus..
  227613. Desktop::getInstance().setKioskModeComponent (0);
  227614. }
  227615. }
  227616. }
  227617. bool UIViewComponentPeer::isFocused() const
  227618. {
  227619. return isSharedWindow ? this == currentlyFocusedPeer
  227620. : (window != 0 && [window isKeyWindow]);
  227621. }
  227622. void UIViewComponentPeer::grabFocus()
  227623. {
  227624. if (window != 0)
  227625. {
  227626. [window makeKeyWindow];
  227627. viewFocusGain();
  227628. }
  227629. }
  227630. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227631. {
  227632. }
  227633. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227634. {
  227635. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227636. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227637. }
  227638. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227639. {
  227640. TextInputTarget* const target = findCurrentTextInputTarget();
  227641. if (target != 0)
  227642. {
  227643. const Range<int> currentSelection (target->getHighlightedRegion());
  227644. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227645. if (currentSelection.isEmpty())
  227646. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227647. target->insertTextAtCaret (text);
  227648. updateHiddenTextContent (target);
  227649. }
  227650. return NO;
  227651. }
  227652. void UIViewComponentPeer::globalFocusChanged (Component*)
  227653. {
  227654. TextInputTarget* const target = findCurrentTextInputTarget();
  227655. if (target != 0)
  227656. {
  227657. Component* comp = dynamic_cast<Component*> (target);
  227658. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  227659. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227660. updateHiddenTextContent (target);
  227661. [view->hiddenTextView becomeFirstResponder];
  227662. }
  227663. else
  227664. {
  227665. [view->hiddenTextView resignFirstResponder];
  227666. }
  227667. }
  227668. void UIViewComponentPeer::drawRect (CGRect r)
  227669. {
  227670. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227671. return;
  227672. CGContextRef cg = UIGraphicsGetCurrentContext();
  227673. if (! component->isOpaque())
  227674. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227675. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227676. CoreGraphicsContext g (cg, view.bounds.size.height);
  227677. insideDrawRect = true;
  227678. handlePaint (g);
  227679. insideDrawRect = false;
  227680. }
  227681. bool UIViewComponentPeer::canBecomeKeyWindow()
  227682. {
  227683. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227684. }
  227685. bool UIViewComponentPeer::windowShouldClose()
  227686. {
  227687. if (! isValidPeer (this))
  227688. return YES;
  227689. handleUserClosingWindow();
  227690. return NO;
  227691. }
  227692. void UIViewComponentPeer::redirectMovedOrResized()
  227693. {
  227694. handleMovedOrResized();
  227695. }
  227696. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227697. {
  227698. }
  227699. class AsyncRepaintMessage : public CallbackMessage
  227700. {
  227701. public:
  227702. UIViewComponentPeer* const peer;
  227703. const Rectangle<int> rect;
  227704. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227705. : peer (peer_), rect (rect_)
  227706. {
  227707. }
  227708. void messageCallback()
  227709. {
  227710. if (ComponentPeer::isValidPeer (peer))
  227711. peer->repaint (rect);
  227712. }
  227713. };
  227714. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227715. {
  227716. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227717. {
  227718. (new AsyncRepaintMessage (this, area))->post();
  227719. }
  227720. else
  227721. {
  227722. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  227723. (float) area.getWidth(), (float) area.getHeight())];
  227724. }
  227725. }
  227726. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227727. {
  227728. }
  227729. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227730. {
  227731. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227732. }
  227733. const Image juce_createIconForFile (const File& file)
  227734. {
  227735. return Image::null;
  227736. }
  227737. void Desktop::createMouseInputSources()
  227738. {
  227739. for (int i = 0; i < 10; ++i)
  227740. mouseSources.add (new MouseInputSource (i, false));
  227741. }
  227742. bool Desktop::canUseSemiTransparentWindows() throw()
  227743. {
  227744. return true;
  227745. }
  227746. const Point<int> Desktop::getMousePosition()
  227747. {
  227748. return juce_lastMousePos;
  227749. }
  227750. void Desktop::setMousePosition (const Point<int>&)
  227751. {
  227752. }
  227753. const int KeyPress::spaceKey = ' ';
  227754. const int KeyPress::returnKey = 0x0d;
  227755. const int KeyPress::escapeKey = 0x1b;
  227756. const int KeyPress::backspaceKey = 0x7f;
  227757. const int KeyPress::leftKey = 0x1000;
  227758. const int KeyPress::rightKey = 0x1001;
  227759. const int KeyPress::upKey = 0x1002;
  227760. const int KeyPress::downKey = 0x1003;
  227761. const int KeyPress::pageUpKey = 0x1004;
  227762. const int KeyPress::pageDownKey = 0x1005;
  227763. const int KeyPress::endKey = 0x1006;
  227764. const int KeyPress::homeKey = 0x1007;
  227765. const int KeyPress::deleteKey = 0x1008;
  227766. const int KeyPress::insertKey = -1;
  227767. const int KeyPress::tabKey = 9;
  227768. const int KeyPress::F1Key = 0x2001;
  227769. const int KeyPress::F2Key = 0x2002;
  227770. const int KeyPress::F3Key = 0x2003;
  227771. const int KeyPress::F4Key = 0x2004;
  227772. const int KeyPress::F5Key = 0x2005;
  227773. const int KeyPress::F6Key = 0x2006;
  227774. const int KeyPress::F7Key = 0x2007;
  227775. const int KeyPress::F8Key = 0x2008;
  227776. const int KeyPress::F9Key = 0x2009;
  227777. const int KeyPress::F10Key = 0x200a;
  227778. const int KeyPress::F11Key = 0x200b;
  227779. const int KeyPress::F12Key = 0x200c;
  227780. const int KeyPress::F13Key = 0x200d;
  227781. const int KeyPress::F14Key = 0x200e;
  227782. const int KeyPress::F15Key = 0x200f;
  227783. const int KeyPress::F16Key = 0x2010;
  227784. const int KeyPress::numberPad0 = 0x30020;
  227785. const int KeyPress::numberPad1 = 0x30021;
  227786. const int KeyPress::numberPad2 = 0x30022;
  227787. const int KeyPress::numberPad3 = 0x30023;
  227788. const int KeyPress::numberPad4 = 0x30024;
  227789. const int KeyPress::numberPad5 = 0x30025;
  227790. const int KeyPress::numberPad6 = 0x30026;
  227791. const int KeyPress::numberPad7 = 0x30027;
  227792. const int KeyPress::numberPad8 = 0x30028;
  227793. const int KeyPress::numberPad9 = 0x30029;
  227794. const int KeyPress::numberPadAdd = 0x3002a;
  227795. const int KeyPress::numberPadSubtract = 0x3002b;
  227796. const int KeyPress::numberPadMultiply = 0x3002c;
  227797. const int KeyPress::numberPadDivide = 0x3002d;
  227798. const int KeyPress::numberPadSeparator = 0x3002e;
  227799. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227800. const int KeyPress::numberPadEquals = 0x30030;
  227801. const int KeyPress::numberPadDelete = 0x30031;
  227802. const int KeyPress::playKey = 0x30000;
  227803. const int KeyPress::stopKey = 0x30001;
  227804. const int KeyPress::fastForwardKey = 0x30002;
  227805. const int KeyPress::rewindKey = 0x30003;
  227806. #endif
  227807. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227808. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227809. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227810. // compiled on its own).
  227811. #if JUCE_INCLUDED_FILE
  227812. struct CallbackMessagePayload
  227813. {
  227814. MessageCallbackFunction* function;
  227815. void* parameter;
  227816. void* volatile result;
  227817. bool volatile hasBeenExecuted;
  227818. };
  227819. END_JUCE_NAMESPACE
  227820. @interface JuceCustomMessageHandler : NSObject
  227821. {
  227822. }
  227823. - (void) performCallback: (id) info;
  227824. @end
  227825. @implementation JuceCustomMessageHandler
  227826. - (void) performCallback: (id) info
  227827. {
  227828. if ([info isKindOfClass: [NSData class]])
  227829. {
  227830. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227831. if (pl != 0)
  227832. {
  227833. pl->result = (*pl->function) (pl->parameter);
  227834. pl->hasBeenExecuted = true;
  227835. }
  227836. }
  227837. else
  227838. {
  227839. jassertfalse; // should never get here!
  227840. }
  227841. }
  227842. @end
  227843. BEGIN_JUCE_NAMESPACE
  227844. void MessageManager::runDispatchLoop()
  227845. {
  227846. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227847. runDispatchLoopUntil (-1);
  227848. }
  227849. void MessageManager::stopDispatchLoop()
  227850. {
  227851. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227852. exit (0); // iPhone apps get no mercy..
  227853. }
  227854. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227855. {
  227856. const ScopedAutoReleasePool pool;
  227857. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227858. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227859. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227860. while (! quitMessagePosted)
  227861. {
  227862. const ScopedAutoReleasePool pool;
  227863. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227864. beforeDate: endDate];
  227865. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227866. break;
  227867. }
  227868. return ! quitMessagePosted;
  227869. }
  227870. static CFRunLoopRef runLoop = 0;
  227871. static CFRunLoopSourceRef runLoopSource = 0;
  227872. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  227873. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  227874. static void runLoopSourceCallback (void*)
  227875. {
  227876. if (pendingMessages != 0)
  227877. {
  227878. int numDispatched = 0;
  227879. do
  227880. {
  227881. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  227882. if (nextMessage == 0)
  227883. return;
  227884. const ScopedAutoReleasePool pool;
  227885. MessageManager::getInstance()->deliverMessage (nextMessage);
  227886. } while (++numDispatched <= 4);
  227887. CFRunLoopSourceSignal (runLoopSource);
  227888. CFRunLoopWakeUp (runLoop);
  227889. }
  227890. }
  227891. void MessageManager::doPlatformSpecificInitialisation()
  227892. {
  227893. pendingMessages = new OwnedArray <Message, CriticalSection>();
  227894. runLoop = CFRunLoopGetCurrent();
  227895. CFRunLoopSourceContext sourceContext;
  227896. zerostruct (sourceContext);
  227897. sourceContext.perform = runLoopSourceCallback;
  227898. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  227899. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  227900. if (juceCustomMessageHandler == 0)
  227901. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227902. }
  227903. void MessageManager::doPlatformSpecificShutdown()
  227904. {
  227905. CFRunLoopSourceInvalidate (runLoopSource);
  227906. CFRelease (runLoopSource);
  227907. runLoopSource = 0;
  227908. deleteAndZero (pendingMessages);
  227909. if (juceCustomMessageHandler != 0)
  227910. {
  227911. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227912. [juceCustomMessageHandler release];
  227913. juceCustomMessageHandler = 0;
  227914. }
  227915. }
  227916. bool juce_postMessageToSystemQueue (Message* message)
  227917. {
  227918. if (pendingMessages != 0)
  227919. {
  227920. pendingMessages->add (message);
  227921. CFRunLoopSourceSignal (runLoopSource);
  227922. CFRunLoopWakeUp (runLoop);
  227923. }
  227924. return true;
  227925. }
  227926. void MessageManager::broadcastMessage (const String& value) throw()
  227927. {
  227928. }
  227929. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  227930. void* data)
  227931. {
  227932. if (isThisTheMessageThread())
  227933. {
  227934. return (*callback) (data);
  227935. }
  227936. else
  227937. {
  227938. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227939. // deadlock because the message manager is blocked from running, so can never
  227940. // call your function..
  227941. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227942. const ScopedAutoReleasePool pool;
  227943. CallbackMessagePayload cmp;
  227944. cmp.function = callback;
  227945. cmp.parameter = data;
  227946. cmp.result = 0;
  227947. cmp.hasBeenExecuted = false;
  227948. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227949. withObject: [NSData dataWithBytesNoCopy: &cmp
  227950. length: sizeof (cmp)
  227951. freeWhenDone: NO]
  227952. waitUntilDone: YES];
  227953. return cmp.result;
  227954. }
  227955. }
  227956. #endif
  227957. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  227958. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227959. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227960. // compiled on its own).
  227961. #if JUCE_INCLUDED_FILE
  227962. #if JUCE_MAC
  227963. END_JUCE_NAMESPACE
  227964. using namespace JUCE_NAMESPACE;
  227965. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227966. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227967. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227968. #else
  227969. @interface JuceFileChooserDelegate : NSObject
  227970. #endif
  227971. {
  227972. StringArray* filters;
  227973. }
  227974. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227975. - (void) dealloc;
  227976. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227977. @end
  227978. @implementation JuceFileChooserDelegate
  227979. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227980. {
  227981. [super init];
  227982. filters = filters_;
  227983. return self;
  227984. }
  227985. - (void) dealloc
  227986. {
  227987. delete filters;
  227988. [super dealloc];
  227989. }
  227990. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227991. {
  227992. (void) sender;
  227993. const File f (nsStringToJuce (filename));
  227994. for (int i = filters->size(); --i >= 0;)
  227995. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227996. return true;
  227997. return f.isDirectory();
  227998. }
  227999. @end
  228000. BEGIN_JUCE_NAMESPACE
  228001. void FileChooser::showPlatformDialog (Array<File>& results,
  228002. const String& title,
  228003. const File& currentFileOrDirectory,
  228004. const String& filter,
  228005. bool selectsDirectory,
  228006. bool selectsFiles,
  228007. bool isSaveDialogue,
  228008. bool warnAboutOverwritingExistingFiles,
  228009. bool selectMultipleFiles,
  228010. FilePreviewComponent* extraInfoComponent)
  228011. {
  228012. const ScopedAutoReleasePool pool;
  228013. StringArray* filters = new StringArray();
  228014. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228015. filters->trim();
  228016. filters->removeEmptyStrings();
  228017. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228018. [delegate autorelease];
  228019. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228020. : [NSOpenPanel openPanel];
  228021. [panel setTitle: juceStringToNS (title)];
  228022. if (! isSaveDialogue)
  228023. {
  228024. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228025. [openPanel setCanChooseDirectories: selectsDirectory];
  228026. [openPanel setCanChooseFiles: selectsFiles];
  228027. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228028. }
  228029. [panel setDelegate: delegate];
  228030. if (isSaveDialogue || selectsDirectory)
  228031. [panel setCanCreateDirectories: YES];
  228032. String directory, filename;
  228033. if (currentFileOrDirectory.isDirectory())
  228034. {
  228035. directory = currentFileOrDirectory.getFullPathName();
  228036. }
  228037. else
  228038. {
  228039. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228040. filename = currentFileOrDirectory.getFileName();
  228041. }
  228042. if ([panel runModalForDirectory: juceStringToNS (directory)
  228043. file: juceStringToNS (filename)]
  228044. == NSOKButton)
  228045. {
  228046. if (isSaveDialogue)
  228047. {
  228048. results.add (File (nsStringToJuce ([panel filename])));
  228049. }
  228050. else
  228051. {
  228052. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228053. NSArray* urls = [openPanel filenames];
  228054. for (unsigned int i = 0; i < [urls count]; ++i)
  228055. {
  228056. NSString* f = [urls objectAtIndex: i];
  228057. results.add (File (nsStringToJuce (f)));
  228058. }
  228059. }
  228060. }
  228061. [panel setDelegate: nil];
  228062. }
  228063. #else
  228064. void FileChooser::showPlatformDialog (Array<File>& results,
  228065. const String& title,
  228066. const File& currentFileOrDirectory,
  228067. const String& filter,
  228068. bool selectsDirectory,
  228069. bool selectsFiles,
  228070. bool isSaveDialogue,
  228071. bool warnAboutOverwritingExistingFiles,
  228072. bool selectMultipleFiles,
  228073. FilePreviewComponent* extraInfoComponent)
  228074. {
  228075. const ScopedAutoReleasePool pool;
  228076. jassertfalse; //xxx to do
  228077. }
  228078. #endif
  228079. #endif
  228080. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228081. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228082. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228083. // compiled on its own).
  228084. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228085. #if JUCE_MAC
  228086. END_JUCE_NAMESPACE
  228087. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228088. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228089. {
  228090. CriticalSection* contextLock;
  228091. bool needsUpdate;
  228092. }
  228093. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228094. - (bool) makeActive;
  228095. - (void) makeInactive;
  228096. - (void) reshape;
  228097. @end
  228098. @implementation ThreadSafeNSOpenGLView
  228099. - (id) initWithFrame: (NSRect) frameRect
  228100. pixelFormat: (NSOpenGLPixelFormat*) format
  228101. {
  228102. contextLock = new CriticalSection();
  228103. self = [super initWithFrame: frameRect pixelFormat: format];
  228104. if (self != nil)
  228105. [[NSNotificationCenter defaultCenter] addObserver: self
  228106. selector: @selector (_surfaceNeedsUpdate:)
  228107. name: NSViewGlobalFrameDidChangeNotification
  228108. object: self];
  228109. return self;
  228110. }
  228111. - (void) dealloc
  228112. {
  228113. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228114. delete contextLock;
  228115. [super dealloc];
  228116. }
  228117. - (bool) makeActive
  228118. {
  228119. const ScopedLock sl (*contextLock);
  228120. if ([self openGLContext] == 0)
  228121. return false;
  228122. [[self openGLContext] makeCurrentContext];
  228123. if (needsUpdate)
  228124. {
  228125. [super update];
  228126. needsUpdate = false;
  228127. }
  228128. return true;
  228129. }
  228130. - (void) makeInactive
  228131. {
  228132. const ScopedLock sl (*contextLock);
  228133. [NSOpenGLContext clearCurrentContext];
  228134. }
  228135. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228136. {
  228137. const ScopedLock sl (*contextLock);
  228138. needsUpdate = true;
  228139. }
  228140. - (void) update
  228141. {
  228142. const ScopedLock sl (*contextLock);
  228143. needsUpdate = true;
  228144. }
  228145. - (void) reshape
  228146. {
  228147. const ScopedLock sl (*contextLock);
  228148. needsUpdate = true;
  228149. }
  228150. @end
  228151. BEGIN_JUCE_NAMESPACE
  228152. class WindowedGLContext : public OpenGLContext
  228153. {
  228154. public:
  228155. WindowedGLContext (Component* const component,
  228156. const OpenGLPixelFormat& pixelFormat_,
  228157. NSOpenGLContext* sharedContext)
  228158. : renderContext (0),
  228159. pixelFormat (pixelFormat_)
  228160. {
  228161. jassert (component != 0);
  228162. NSOpenGLPixelFormatAttribute attribs [64];
  228163. int n = 0;
  228164. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228165. attribs[n++] = NSOpenGLPFAAccelerated;
  228166. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228167. attribs[n++] = NSOpenGLPFAColorSize;
  228168. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228169. pixelFormat.greenBits,
  228170. pixelFormat.blueBits);
  228171. attribs[n++] = NSOpenGLPFAAlphaSize;
  228172. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228173. attribs[n++] = NSOpenGLPFADepthSize;
  228174. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228175. attribs[n++] = NSOpenGLPFAStencilSize;
  228176. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228177. attribs[n++] = NSOpenGLPFAAccumSize;
  228178. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228179. pixelFormat.accumulationBufferGreenBits,
  228180. pixelFormat.accumulationBufferBlueBits,
  228181. pixelFormat.accumulationBufferAlphaBits);
  228182. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228183. attribs[n++] = NSOpenGLPFASampleBuffers;
  228184. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228185. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228186. attribs[n++] = NSOpenGLPFANoRecovery;
  228187. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228188. NSOpenGLPixelFormat* format
  228189. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228190. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228191. pixelFormat: format];
  228192. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228193. shareContext: sharedContext] autorelease];
  228194. const GLint swapInterval = 1;
  228195. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228196. [view setOpenGLContext: renderContext];
  228197. [format release];
  228198. viewHolder = new NSViewComponentInternal (view, component);
  228199. }
  228200. ~WindowedGLContext()
  228201. {
  228202. deleteContext();
  228203. viewHolder = 0;
  228204. }
  228205. void deleteContext()
  228206. {
  228207. makeInactive();
  228208. [renderContext clearDrawable];
  228209. [renderContext setView: nil];
  228210. [view setOpenGLContext: nil];
  228211. renderContext = nil;
  228212. }
  228213. bool makeActive() const throw()
  228214. {
  228215. jassert (renderContext != 0);
  228216. if ([renderContext view] != view)
  228217. [renderContext setView: view];
  228218. [view makeActive];
  228219. return isActive();
  228220. }
  228221. bool makeInactive() const throw()
  228222. {
  228223. [view makeInactive];
  228224. return true;
  228225. }
  228226. bool isActive() const throw()
  228227. {
  228228. return [NSOpenGLContext currentContext] == renderContext;
  228229. }
  228230. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228231. void* getRawContext() const throw() { return renderContext; }
  228232. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228233. {
  228234. }
  228235. void swapBuffers()
  228236. {
  228237. [renderContext flushBuffer];
  228238. }
  228239. bool setSwapInterval (const int numFramesPerSwap)
  228240. {
  228241. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228242. forParameter: NSOpenGLCPSwapInterval];
  228243. return true;
  228244. }
  228245. int getSwapInterval() const
  228246. {
  228247. GLint numFrames = 0;
  228248. [renderContext getValues: &numFrames
  228249. forParameter: NSOpenGLCPSwapInterval];
  228250. return numFrames;
  228251. }
  228252. void repaint()
  228253. {
  228254. // we need to invalidate the juce view that holds this gl view, to make it
  228255. // cause a repaint callback
  228256. NSView* v = (NSView*) viewHolder->view;
  228257. NSRect r = [v frame];
  228258. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228259. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228260. // repaint message, thus never causing our paint() callback, and never repainting
  228261. // the comp. So invalidating just a little bit around the edge helps..
  228262. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228263. }
  228264. void* getNativeWindowHandle() const { return viewHolder->view; }
  228265. juce_UseDebuggingNewOperator
  228266. NSOpenGLContext* renderContext;
  228267. ThreadSafeNSOpenGLView* view;
  228268. private:
  228269. OpenGLPixelFormat pixelFormat;
  228270. ScopedPointer <NSViewComponentInternal> viewHolder;
  228271. WindowedGLContext (const WindowedGLContext&);
  228272. WindowedGLContext& operator= (const WindowedGLContext&);
  228273. };
  228274. OpenGLContext* OpenGLComponent::createContext()
  228275. {
  228276. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228277. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228278. return (c->renderContext != 0) ? c.release() : 0;
  228279. }
  228280. void* OpenGLComponent::getNativeWindowHandle() const
  228281. {
  228282. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228283. : 0;
  228284. }
  228285. void juce_glViewport (const int w, const int h)
  228286. {
  228287. glViewport (0, 0, w, h);
  228288. }
  228289. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228290. OwnedArray <OpenGLPixelFormat>& results)
  228291. {
  228292. /* GLint attribs [64];
  228293. int n = 0;
  228294. attribs[n++] = AGL_RGBA;
  228295. attribs[n++] = AGL_DOUBLEBUFFER;
  228296. attribs[n++] = AGL_ACCELERATED;
  228297. attribs[n++] = AGL_NO_RECOVERY;
  228298. attribs[n++] = AGL_NONE;
  228299. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228300. while (p != 0)
  228301. {
  228302. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228303. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228304. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228305. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228306. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228307. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228308. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228309. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228310. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228311. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228312. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228313. results.add (pf);
  228314. p = aglNextPixelFormat (p);
  228315. }*/
  228316. //jassertfalse // can't see how you do this in cocoa!
  228317. }
  228318. #else
  228319. END_JUCE_NAMESPACE
  228320. @interface JuceGLView : UIView
  228321. {
  228322. }
  228323. + (Class) layerClass;
  228324. @end
  228325. @implementation JuceGLView
  228326. + (Class) layerClass
  228327. {
  228328. return [CAEAGLLayer class];
  228329. }
  228330. @end
  228331. BEGIN_JUCE_NAMESPACE
  228332. class GLESContext : public OpenGLContext
  228333. {
  228334. public:
  228335. GLESContext (UIViewComponentPeer* peer,
  228336. Component* const component_,
  228337. const OpenGLPixelFormat& pixelFormat_,
  228338. const GLESContext* const sharedContext,
  228339. NSUInteger apiType)
  228340. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228341. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228342. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228343. {
  228344. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228345. view.opaque = YES;
  228346. view.hidden = NO;
  228347. view.backgroundColor = [UIColor blackColor];
  228348. view.userInteractionEnabled = NO;
  228349. glLayer = (CAEAGLLayer*) [view layer];
  228350. [peer->view addSubview: view];
  228351. if (sharedContext != 0)
  228352. context = [[EAGLContext alloc] initWithAPI: apiType
  228353. sharegroup: [sharedContext->context sharegroup]];
  228354. else
  228355. context = [[EAGLContext alloc] initWithAPI: apiType];
  228356. createGLBuffers();
  228357. }
  228358. ~GLESContext()
  228359. {
  228360. deleteContext();
  228361. [view removeFromSuperview];
  228362. [view release];
  228363. freeGLBuffers();
  228364. }
  228365. void deleteContext()
  228366. {
  228367. makeInactive();
  228368. [context release];
  228369. context = nil;
  228370. }
  228371. bool makeActive() const throw()
  228372. {
  228373. jassert (context != 0);
  228374. [EAGLContext setCurrentContext: context];
  228375. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228376. return true;
  228377. }
  228378. void swapBuffers()
  228379. {
  228380. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228381. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228382. }
  228383. bool makeInactive() const throw()
  228384. {
  228385. return [EAGLContext setCurrentContext: nil];
  228386. }
  228387. bool isActive() const throw()
  228388. {
  228389. return [EAGLContext currentContext] == context;
  228390. }
  228391. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228392. void* getRawContext() const throw() { return glLayer; }
  228393. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228394. {
  228395. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228396. if (lastWidth != w || lastHeight != h)
  228397. {
  228398. lastWidth = w;
  228399. lastHeight = h;
  228400. freeGLBuffers();
  228401. createGLBuffers();
  228402. }
  228403. }
  228404. bool setSwapInterval (const int numFramesPerSwap)
  228405. {
  228406. numFrames = numFramesPerSwap;
  228407. return true;
  228408. }
  228409. int getSwapInterval() const
  228410. {
  228411. return numFrames;
  228412. }
  228413. void repaint()
  228414. {
  228415. }
  228416. void createGLBuffers()
  228417. {
  228418. makeActive();
  228419. glGenFramebuffersOES (1, &frameBufferHandle);
  228420. glGenRenderbuffersOES (1, &colorBufferHandle);
  228421. glGenRenderbuffersOES (1, &depthBufferHandle);
  228422. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228423. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228424. GLint width, height;
  228425. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228426. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228427. if (useDepthBuffer)
  228428. {
  228429. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228430. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228431. }
  228432. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228433. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228434. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228435. if (useDepthBuffer)
  228436. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228437. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228438. }
  228439. void freeGLBuffers()
  228440. {
  228441. if (frameBufferHandle != 0)
  228442. {
  228443. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228444. frameBufferHandle = 0;
  228445. }
  228446. if (colorBufferHandle != 0)
  228447. {
  228448. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228449. colorBufferHandle = 0;
  228450. }
  228451. if (depthBufferHandle != 0)
  228452. {
  228453. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228454. depthBufferHandle = 0;
  228455. }
  228456. }
  228457. juce_UseDebuggingNewOperator
  228458. private:
  228459. Component::SafePointer<Component> component;
  228460. OpenGLPixelFormat pixelFormat;
  228461. JuceGLView* view;
  228462. CAEAGLLayer* glLayer;
  228463. EAGLContext* context;
  228464. bool useDepthBuffer;
  228465. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228466. int numFrames;
  228467. int lastWidth, lastHeight;
  228468. GLESContext (const GLESContext&);
  228469. GLESContext& operator= (const GLESContext&);
  228470. };
  228471. OpenGLContext* OpenGLComponent::createContext()
  228472. {
  228473. ScopedAutoReleasePool pool;
  228474. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228475. if (peer != 0)
  228476. return new GLESContext (peer, this, preferredPixelFormat,
  228477. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228478. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228479. return 0;
  228480. }
  228481. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228482. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228483. {
  228484. }
  228485. void juce_glViewport (const int w, const int h)
  228486. {
  228487. glViewport (0, 0, w, h);
  228488. }
  228489. #endif
  228490. #endif
  228491. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228492. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228493. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228494. // compiled on its own).
  228495. #if JUCE_INCLUDED_FILE
  228496. #if JUCE_MAC
  228497. namespace MouseCursorHelpers
  228498. {
  228499. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228500. {
  228501. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228502. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228503. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228504. [im release];
  228505. return c;
  228506. }
  228507. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228508. {
  228509. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228510. BufferedInputStream buf (&fileStream, 4096, false);
  228511. PNGImageFormat pngFormat;
  228512. Image im (pngFormat.decodeImage (buf));
  228513. if (im.isValid())
  228514. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228515. jassertfalse;
  228516. return 0;
  228517. }
  228518. }
  228519. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228520. {
  228521. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228522. }
  228523. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228524. {
  228525. const ScopedAutoReleasePool pool;
  228526. NSCursor* c = 0;
  228527. switch (type)
  228528. {
  228529. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228530. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228531. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228532. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228533. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228534. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228535. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228536. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228537. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228538. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228539. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228540. case UpDownResizeCursor:
  228541. case TopEdgeResizeCursor:
  228542. case BottomEdgeResizeCursor:
  228543. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228544. case TopLeftCornerResizeCursor:
  228545. case BottomRightCornerResizeCursor:
  228546. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228547. case TopRightCornerResizeCursor:
  228548. case BottomLeftCornerResizeCursor:
  228549. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228550. case UpDownLeftRightResizeCursor:
  228551. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228552. default:
  228553. jassertfalse;
  228554. break;
  228555. }
  228556. [c retain];
  228557. return c;
  228558. }
  228559. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228560. {
  228561. [((NSCursor*) cursorHandle) release];
  228562. }
  228563. void MouseCursor::showInAllWindows() const
  228564. {
  228565. showInWindow (0);
  228566. }
  228567. void MouseCursor::showInWindow (ComponentPeer*) const
  228568. {
  228569. [((NSCursor*) getHandle()) set];
  228570. }
  228571. #else
  228572. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228573. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228574. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228575. void MouseCursor::showInAllWindows() const {}
  228576. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228577. #endif
  228578. #endif
  228579. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228580. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228581. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228582. // compiled on its own).
  228583. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228584. #if JUCE_MAC
  228585. END_JUCE_NAMESPACE
  228586. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228587. @interface DownloadClickDetector : NSObject
  228588. {
  228589. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228590. }
  228591. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228592. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228593. request: (NSURLRequest*) request
  228594. frame: (WebFrame*) frame
  228595. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228596. @end
  228597. @implementation DownloadClickDetector
  228598. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228599. {
  228600. [super init];
  228601. ownerComponent = ownerComponent_;
  228602. return self;
  228603. }
  228604. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228605. request: (NSURLRequest*) request
  228606. frame: (WebFrame*) frame
  228607. decisionListener: (id <WebPolicyDecisionListener>) listener
  228608. {
  228609. (void) sender;
  228610. (void) request;
  228611. (void) frame;
  228612. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228613. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228614. [listener use];
  228615. else
  228616. [listener ignore];
  228617. }
  228618. @end
  228619. BEGIN_JUCE_NAMESPACE
  228620. class WebBrowserComponentInternal : public NSViewComponent
  228621. {
  228622. public:
  228623. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228624. {
  228625. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228626. frameName: @""
  228627. groupName: @""];
  228628. setView (webView);
  228629. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228630. [webView setPolicyDelegate: clickListener];
  228631. }
  228632. ~WebBrowserComponentInternal()
  228633. {
  228634. [webView setPolicyDelegate: nil];
  228635. [clickListener release];
  228636. setView (0);
  228637. }
  228638. void goToURL (const String& url,
  228639. const StringArray* headers,
  228640. const MemoryBlock* postData)
  228641. {
  228642. NSMutableURLRequest* r
  228643. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228644. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228645. timeoutInterval: 30.0];
  228646. if (postData != 0 && postData->getSize() > 0)
  228647. {
  228648. [r setHTTPMethod: @"POST"];
  228649. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228650. length: postData->getSize()]];
  228651. }
  228652. if (headers != 0)
  228653. {
  228654. for (int i = 0; i < headers->size(); ++i)
  228655. {
  228656. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228657. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228658. [r setValue: juceStringToNS (headerValue)
  228659. forHTTPHeaderField: juceStringToNS (headerName)];
  228660. }
  228661. }
  228662. stop();
  228663. [[webView mainFrame] loadRequest: r];
  228664. }
  228665. void goBack()
  228666. {
  228667. [webView goBack];
  228668. }
  228669. void goForward()
  228670. {
  228671. [webView goForward];
  228672. }
  228673. void stop()
  228674. {
  228675. [webView stopLoading: nil];
  228676. }
  228677. void refresh()
  228678. {
  228679. [webView reload: nil];
  228680. }
  228681. private:
  228682. WebView* webView;
  228683. DownloadClickDetector* clickListener;
  228684. };
  228685. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228686. : browser (0),
  228687. blankPageShown (false),
  228688. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228689. {
  228690. setOpaque (true);
  228691. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228692. }
  228693. WebBrowserComponent::~WebBrowserComponent()
  228694. {
  228695. deleteAndZero (browser);
  228696. }
  228697. void WebBrowserComponent::goToURL (const String& url,
  228698. const StringArray* headers,
  228699. const MemoryBlock* postData)
  228700. {
  228701. lastURL = url;
  228702. lastHeaders.clear();
  228703. if (headers != 0)
  228704. lastHeaders = *headers;
  228705. lastPostData.setSize (0);
  228706. if (postData != 0)
  228707. lastPostData = *postData;
  228708. blankPageShown = false;
  228709. browser->goToURL (url, headers, postData);
  228710. }
  228711. void WebBrowserComponent::stop()
  228712. {
  228713. browser->stop();
  228714. }
  228715. void WebBrowserComponent::goBack()
  228716. {
  228717. lastURL = String::empty;
  228718. blankPageShown = false;
  228719. browser->goBack();
  228720. }
  228721. void WebBrowserComponent::goForward()
  228722. {
  228723. lastURL = String::empty;
  228724. browser->goForward();
  228725. }
  228726. void WebBrowserComponent::refresh()
  228727. {
  228728. browser->refresh();
  228729. }
  228730. void WebBrowserComponent::paint (Graphics&)
  228731. {
  228732. }
  228733. void WebBrowserComponent::checkWindowAssociation()
  228734. {
  228735. if (isShowing())
  228736. {
  228737. if (blankPageShown)
  228738. goBack();
  228739. }
  228740. else
  228741. {
  228742. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228743. {
  228744. // when the component becomes invisible, some stuff like flash
  228745. // carries on playing audio, so we need to force it onto a blank
  228746. // page to avoid this, (and send it back when it's made visible again).
  228747. blankPageShown = true;
  228748. browser->goToURL ("about:blank", 0, 0);
  228749. }
  228750. }
  228751. }
  228752. void WebBrowserComponent::reloadLastURL()
  228753. {
  228754. if (lastURL.isNotEmpty())
  228755. {
  228756. goToURL (lastURL, &lastHeaders, &lastPostData);
  228757. lastURL = String::empty;
  228758. }
  228759. }
  228760. void WebBrowserComponent::parentHierarchyChanged()
  228761. {
  228762. checkWindowAssociation();
  228763. }
  228764. void WebBrowserComponent::resized()
  228765. {
  228766. browser->setSize (getWidth(), getHeight());
  228767. }
  228768. void WebBrowserComponent::visibilityChanged()
  228769. {
  228770. checkWindowAssociation();
  228771. }
  228772. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228773. {
  228774. return true;
  228775. }
  228776. #else
  228777. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228778. {
  228779. }
  228780. WebBrowserComponent::~WebBrowserComponent()
  228781. {
  228782. }
  228783. void WebBrowserComponent::goToURL (const String& url,
  228784. const StringArray* headers,
  228785. const MemoryBlock* postData)
  228786. {
  228787. }
  228788. void WebBrowserComponent::stop()
  228789. {
  228790. }
  228791. void WebBrowserComponent::goBack()
  228792. {
  228793. }
  228794. void WebBrowserComponent::goForward()
  228795. {
  228796. }
  228797. void WebBrowserComponent::refresh()
  228798. {
  228799. }
  228800. void WebBrowserComponent::paint (Graphics& g)
  228801. {
  228802. }
  228803. void WebBrowserComponent::checkWindowAssociation()
  228804. {
  228805. }
  228806. void WebBrowserComponent::reloadLastURL()
  228807. {
  228808. }
  228809. void WebBrowserComponent::parentHierarchyChanged()
  228810. {
  228811. }
  228812. void WebBrowserComponent::resized()
  228813. {
  228814. }
  228815. void WebBrowserComponent::visibilityChanged()
  228816. {
  228817. }
  228818. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228819. {
  228820. return true;
  228821. }
  228822. #endif
  228823. #endif
  228824. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228825. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228826. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228827. // compiled on its own).
  228828. #if JUCE_INCLUDED_FILE
  228829. class IPhoneAudioIODevice : public AudioIODevice
  228830. {
  228831. public:
  228832. IPhoneAudioIODevice (const String& deviceName)
  228833. : AudioIODevice (deviceName, "Audio"),
  228834. audioUnit (0),
  228835. isRunning (false),
  228836. callback (0),
  228837. actualBufferSize (0),
  228838. floatData (1, 2)
  228839. {
  228840. numInputChannels = 2;
  228841. numOutputChannels = 2;
  228842. preferredBufferSize = 0;
  228843. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228844. updateDeviceInfo();
  228845. }
  228846. ~IPhoneAudioIODevice()
  228847. {
  228848. close();
  228849. }
  228850. const StringArray getOutputChannelNames()
  228851. {
  228852. StringArray s;
  228853. s.add ("Left");
  228854. s.add ("Right");
  228855. return s;
  228856. }
  228857. const StringArray getInputChannelNames()
  228858. {
  228859. StringArray s;
  228860. if (audioInputIsAvailable)
  228861. {
  228862. s.add ("Left");
  228863. s.add ("Right");
  228864. }
  228865. return s;
  228866. }
  228867. int getNumSampleRates()
  228868. {
  228869. return 1;
  228870. }
  228871. double getSampleRate (int index)
  228872. {
  228873. return sampleRate;
  228874. }
  228875. int getNumBufferSizesAvailable()
  228876. {
  228877. return 1;
  228878. }
  228879. int getBufferSizeSamples (int index)
  228880. {
  228881. return getDefaultBufferSize();
  228882. }
  228883. int getDefaultBufferSize()
  228884. {
  228885. return 1024;
  228886. }
  228887. const String open (const BigInteger& inputChannels,
  228888. const BigInteger& outputChannels,
  228889. double sampleRate,
  228890. int bufferSize)
  228891. {
  228892. close();
  228893. lastError = String::empty;
  228894. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228895. // xxx set up channel mapping
  228896. activeOutputChans = outputChannels;
  228897. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228898. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228899. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228900. activeInputChans = inputChannels;
  228901. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228902. numInputChannels = activeInputChans.countNumberOfSetBits();
  228903. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228904. AudioSessionSetActive (true);
  228905. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228906. : kAudioSessionCategory_MediaPlayback;
  228907. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228908. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228909. fixAudioRouteIfSetToReceiver();
  228910. updateDeviceInfo();
  228911. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228912. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228913. actualBufferSize = preferredBufferSize;
  228914. prepareFloatBuffers();
  228915. isRunning = true;
  228916. propertyChanged (0, 0, 0); // creates and starts the AU
  228917. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228918. return lastError;
  228919. }
  228920. void close()
  228921. {
  228922. if (isRunning)
  228923. {
  228924. isRunning = false;
  228925. AudioSessionSetActive (false);
  228926. if (audioUnit != 0)
  228927. {
  228928. AudioComponentInstanceDispose (audioUnit);
  228929. audioUnit = 0;
  228930. }
  228931. }
  228932. }
  228933. bool isOpen()
  228934. {
  228935. return isRunning;
  228936. }
  228937. int getCurrentBufferSizeSamples()
  228938. {
  228939. return actualBufferSize;
  228940. }
  228941. double getCurrentSampleRate()
  228942. {
  228943. return sampleRate;
  228944. }
  228945. int getCurrentBitDepth()
  228946. {
  228947. return 16;
  228948. }
  228949. const BigInteger getActiveOutputChannels() const
  228950. {
  228951. return activeOutputChans;
  228952. }
  228953. const BigInteger getActiveInputChannels() const
  228954. {
  228955. return activeInputChans;
  228956. }
  228957. int getOutputLatencyInSamples()
  228958. {
  228959. return 0; //xxx
  228960. }
  228961. int getInputLatencyInSamples()
  228962. {
  228963. return 0; //xxx
  228964. }
  228965. void start (AudioIODeviceCallback* callback_)
  228966. {
  228967. if (isRunning && callback != callback_)
  228968. {
  228969. if (callback_ != 0)
  228970. callback_->audioDeviceAboutToStart (this);
  228971. const ScopedLock sl (callbackLock);
  228972. callback = callback_;
  228973. }
  228974. }
  228975. void stop()
  228976. {
  228977. if (isRunning)
  228978. {
  228979. AudioIODeviceCallback* lastCallback;
  228980. {
  228981. const ScopedLock sl (callbackLock);
  228982. lastCallback = callback;
  228983. callback = 0;
  228984. }
  228985. if (lastCallback != 0)
  228986. lastCallback->audioDeviceStopped();
  228987. }
  228988. }
  228989. bool isPlaying()
  228990. {
  228991. return isRunning && callback != 0;
  228992. }
  228993. const String getLastError()
  228994. {
  228995. return lastError;
  228996. }
  228997. private:
  228998. CriticalSection callbackLock;
  228999. Float64 sampleRate;
  229000. int numInputChannels, numOutputChannels;
  229001. int preferredBufferSize;
  229002. int actualBufferSize;
  229003. bool isRunning;
  229004. String lastError;
  229005. AudioStreamBasicDescription format;
  229006. AudioUnit audioUnit;
  229007. UInt32 audioInputIsAvailable;
  229008. AudioIODeviceCallback* callback;
  229009. BigInteger activeOutputChans, activeInputChans;
  229010. AudioSampleBuffer floatData;
  229011. float* inputChannels[3];
  229012. float* outputChannels[3];
  229013. bool monoInputChannelNumber, monoOutputChannelNumber;
  229014. void prepareFloatBuffers()
  229015. {
  229016. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229017. zerostruct (inputChannels);
  229018. zerostruct (outputChannels);
  229019. for (int i = 0; i < numInputChannels; ++i)
  229020. inputChannels[i] = floatData.getSampleData (i);
  229021. for (int i = 0; i < numOutputChannels; ++i)
  229022. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229023. }
  229024. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229025. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229026. {
  229027. OSStatus err = noErr;
  229028. if (audioInputIsAvailable)
  229029. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229030. const ScopedLock sl (callbackLock);
  229031. if (callback != 0)
  229032. {
  229033. if (audioInputIsAvailable && numInputChannels > 0)
  229034. {
  229035. short* shortData = (short*) ioData->mBuffers[0].mData;
  229036. if (numInputChannels >= 2)
  229037. {
  229038. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229039. {
  229040. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229041. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229042. }
  229043. }
  229044. else
  229045. {
  229046. if (monoInputChannelNumber > 0)
  229047. ++shortData;
  229048. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229049. {
  229050. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229051. ++shortData;
  229052. }
  229053. }
  229054. }
  229055. else
  229056. {
  229057. for (int i = numInputChannels; --i >= 0;)
  229058. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229059. }
  229060. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229061. outputChannels, numOutputChannels,
  229062. (int) inNumberFrames);
  229063. short* shortData = (short*) ioData->mBuffers[0].mData;
  229064. int n = 0;
  229065. if (numOutputChannels >= 2)
  229066. {
  229067. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229068. {
  229069. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229070. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229071. }
  229072. }
  229073. else if (numOutputChannels == 1)
  229074. {
  229075. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229076. {
  229077. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229078. shortData [n++] = s;
  229079. shortData [n++] = s;
  229080. }
  229081. }
  229082. else
  229083. {
  229084. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229085. }
  229086. }
  229087. else
  229088. {
  229089. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229090. }
  229091. return err;
  229092. }
  229093. void updateDeviceInfo()
  229094. {
  229095. UInt32 size = sizeof (sampleRate);
  229096. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229097. size = sizeof (audioInputIsAvailable);
  229098. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229099. }
  229100. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229101. {
  229102. if (! isRunning)
  229103. return;
  229104. if (inPropertyValue != 0)
  229105. {
  229106. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229107. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229108. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229109. SInt32 routeChangeReason;
  229110. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229111. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229112. fixAudioRouteIfSetToReceiver();
  229113. }
  229114. updateDeviceInfo();
  229115. createAudioUnit();
  229116. AudioSessionSetActive (true);
  229117. if (audioUnit != 0)
  229118. {
  229119. UInt32 formatSize = sizeof (format);
  229120. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229121. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229122. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229123. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229124. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229125. AudioOutputUnitStart (audioUnit);
  229126. }
  229127. }
  229128. void interruptionListener (UInt32 inInterruption)
  229129. {
  229130. /*if (inInterruption == kAudioSessionBeginInterruption)
  229131. {
  229132. isRunning = false;
  229133. AudioOutputUnitStop (audioUnit);
  229134. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229135. "This could have been interrupted by another application or by unplugging a headset",
  229136. @"Resume",
  229137. @"Cancel"))
  229138. {
  229139. isRunning = true;
  229140. propertyChanged (0, 0, 0);
  229141. }
  229142. }*/
  229143. if (inInterruption == kAudioSessionEndInterruption)
  229144. {
  229145. isRunning = true;
  229146. AudioSessionSetActive (true);
  229147. AudioOutputUnitStart (audioUnit);
  229148. }
  229149. }
  229150. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229151. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229152. {
  229153. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229154. }
  229155. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229156. {
  229157. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229158. }
  229159. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229160. {
  229161. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229162. }
  229163. void resetFormat (const int numChannels)
  229164. {
  229165. memset (&format, 0, sizeof (format));
  229166. format.mFormatID = kAudioFormatLinearPCM;
  229167. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229168. format.mBitsPerChannel = 8 * sizeof (short);
  229169. format.mChannelsPerFrame = 2;
  229170. format.mFramesPerPacket = 1;
  229171. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229172. }
  229173. bool createAudioUnit()
  229174. {
  229175. if (audioUnit != 0)
  229176. {
  229177. AudioComponentInstanceDispose (audioUnit);
  229178. audioUnit = 0;
  229179. }
  229180. resetFormat (2);
  229181. AudioComponentDescription desc;
  229182. desc.componentType = kAudioUnitType_Output;
  229183. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229184. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229185. desc.componentFlags = 0;
  229186. desc.componentFlagsMask = 0;
  229187. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229188. AudioComponentInstanceNew (comp, &audioUnit);
  229189. if (audioUnit == 0)
  229190. return false;
  229191. const UInt32 one = 1;
  229192. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229193. AudioChannelLayout layout;
  229194. layout.mChannelBitmap = 0;
  229195. layout.mNumberChannelDescriptions = 0;
  229196. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229197. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229198. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229199. AURenderCallbackStruct inputProc;
  229200. inputProc.inputProc = processStatic;
  229201. inputProc.inputProcRefCon = this;
  229202. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229203. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229204. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229205. AudioUnitInitialize (audioUnit);
  229206. return true;
  229207. }
  229208. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229209. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229210. static void fixAudioRouteIfSetToReceiver()
  229211. {
  229212. CFStringRef audioRoute = 0;
  229213. UInt32 propertySize = sizeof (audioRoute);
  229214. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229215. {
  229216. NSString* route = (NSString*) audioRoute;
  229217. //DBG ("audio route: " + nsStringToJuce (route));
  229218. if ([route hasPrefix: @"Receiver"])
  229219. {
  229220. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229221. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229222. }
  229223. CFRelease (audioRoute);
  229224. }
  229225. }
  229226. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229227. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229228. };
  229229. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229230. {
  229231. public:
  229232. IPhoneAudioIODeviceType()
  229233. : AudioIODeviceType ("iPhone Audio")
  229234. {
  229235. }
  229236. ~IPhoneAudioIODeviceType()
  229237. {
  229238. }
  229239. void scanForDevices()
  229240. {
  229241. }
  229242. const StringArray getDeviceNames (bool wantInputNames) const
  229243. {
  229244. StringArray s;
  229245. s.add ("iPhone Audio");
  229246. return s;
  229247. }
  229248. int getDefaultDeviceIndex (bool forInput) const
  229249. {
  229250. return 0;
  229251. }
  229252. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229253. {
  229254. return device != 0 ? 0 : -1;
  229255. }
  229256. bool hasSeparateInputsAndOutputs() const { return false; }
  229257. AudioIODevice* createDevice (const String& outputDeviceName,
  229258. const String& inputDeviceName)
  229259. {
  229260. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229261. {
  229262. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229263. : inputDeviceName);
  229264. }
  229265. return 0;
  229266. }
  229267. juce_UseDebuggingNewOperator
  229268. private:
  229269. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229270. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229271. };
  229272. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229273. {
  229274. return new IPhoneAudioIODeviceType();
  229275. }
  229276. #endif
  229277. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229278. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229279. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229280. // compiled on its own).
  229281. #if JUCE_INCLUDED_FILE
  229282. #if JUCE_MAC
  229283. #undef log
  229284. #define log(a) Logger::writeToLog(a)
  229285. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  229286. {
  229287. if (err == noErr)
  229288. return true;
  229289. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229290. jassertfalse;
  229291. return false;
  229292. }
  229293. #undef OK
  229294. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  229295. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229296. {
  229297. String result;
  229298. CFStringRef str = 0;
  229299. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229300. if (str != 0)
  229301. {
  229302. result = PlatformUtilities::cfStringToJuceString (str);
  229303. CFRelease (str);
  229304. str = 0;
  229305. }
  229306. MIDIEntityRef entity = 0;
  229307. MIDIEndpointGetEntity (endpoint, &entity);
  229308. if (entity == 0)
  229309. return result; // probably virtual
  229310. if (result.isEmpty())
  229311. {
  229312. // endpoint name has zero length - try the entity
  229313. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229314. if (str != 0)
  229315. {
  229316. result += PlatformUtilities::cfStringToJuceString (str);
  229317. CFRelease (str);
  229318. str = 0;
  229319. }
  229320. }
  229321. // now consider the device's name
  229322. MIDIDeviceRef device = 0;
  229323. MIDIEntityGetDevice (entity, &device);
  229324. if (device == 0)
  229325. return result;
  229326. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229327. if (str != 0)
  229328. {
  229329. const String s (PlatformUtilities::cfStringToJuceString (str));
  229330. CFRelease (str);
  229331. // if an external device has only one entity, throw away
  229332. // the endpoint name and just use the device name
  229333. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229334. {
  229335. result = s;
  229336. }
  229337. else if (! result.startsWithIgnoreCase (s))
  229338. {
  229339. // prepend the device name to the entity name
  229340. result = (s + " " + result).trimEnd();
  229341. }
  229342. }
  229343. return result;
  229344. }
  229345. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229346. {
  229347. String result;
  229348. // Does the endpoint have connections?
  229349. CFDataRef connections = 0;
  229350. int numConnections = 0;
  229351. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229352. if (connections != 0)
  229353. {
  229354. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229355. if (numConnections > 0)
  229356. {
  229357. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229358. for (int i = 0; i < numConnections; ++i, ++pid)
  229359. {
  229360. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229361. MIDIObjectRef connObject;
  229362. MIDIObjectType connObjectType;
  229363. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229364. if (err == noErr)
  229365. {
  229366. String s;
  229367. if (connObjectType == kMIDIObjectType_ExternalSource
  229368. || connObjectType == kMIDIObjectType_ExternalDestination)
  229369. {
  229370. // Connected to an external device's endpoint (10.3 and later).
  229371. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229372. }
  229373. else
  229374. {
  229375. // Connected to an external device (10.2) (or something else, catch-all)
  229376. CFStringRef str = 0;
  229377. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229378. if (str != 0)
  229379. {
  229380. s = PlatformUtilities::cfStringToJuceString (str);
  229381. CFRelease (str);
  229382. }
  229383. }
  229384. if (s.isNotEmpty())
  229385. {
  229386. if (result.isNotEmpty())
  229387. result += ", ";
  229388. result += s;
  229389. }
  229390. }
  229391. }
  229392. }
  229393. CFRelease (connections);
  229394. }
  229395. if (result.isNotEmpty())
  229396. return result;
  229397. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229398. return getEndpointName (endpoint, false);
  229399. }
  229400. const StringArray MidiOutput::getDevices()
  229401. {
  229402. StringArray s;
  229403. const ItemCount num = MIDIGetNumberOfDestinations();
  229404. for (ItemCount i = 0; i < num; ++i)
  229405. {
  229406. MIDIEndpointRef dest = MIDIGetDestination (i);
  229407. if (dest != 0)
  229408. {
  229409. String name (getConnectedEndpointName (dest));
  229410. if (name.isEmpty())
  229411. name = "<error>";
  229412. s.add (name);
  229413. }
  229414. else
  229415. {
  229416. s.add ("<error>");
  229417. }
  229418. }
  229419. return s;
  229420. }
  229421. int MidiOutput::getDefaultDeviceIndex()
  229422. {
  229423. return 0;
  229424. }
  229425. static MIDIClientRef globalMidiClient;
  229426. static bool hasGlobalClientBeenCreated = false;
  229427. static bool makeSureClientExists()
  229428. {
  229429. if (! hasGlobalClientBeenCreated)
  229430. {
  229431. String name ("JUCE");
  229432. if (JUCEApplication::getInstance() != 0)
  229433. name = JUCEApplication::getInstance()->getApplicationName();
  229434. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229435. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229436. CFRelease (appName);
  229437. }
  229438. return hasGlobalClientBeenCreated;
  229439. }
  229440. class MidiPortAndEndpoint
  229441. {
  229442. public:
  229443. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229444. : port (port_), endPoint (endPoint_)
  229445. {
  229446. }
  229447. ~MidiPortAndEndpoint()
  229448. {
  229449. if (port != 0)
  229450. MIDIPortDispose (port);
  229451. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229452. MIDIEndpointDispose (endPoint);
  229453. }
  229454. MIDIPortRef port;
  229455. MIDIEndpointRef endPoint;
  229456. };
  229457. MidiOutput* MidiOutput::openDevice (int index)
  229458. {
  229459. MidiOutput* mo = 0;
  229460. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229461. {
  229462. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229463. CFStringRef pname;
  229464. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229465. {
  229466. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  229467. if (makeSureClientExists())
  229468. {
  229469. MIDIPortRef port;
  229470. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  229471. {
  229472. mo = new MidiOutput();
  229473. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  229474. }
  229475. }
  229476. CFRelease (pname);
  229477. }
  229478. }
  229479. return mo;
  229480. }
  229481. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229482. {
  229483. MidiOutput* mo = 0;
  229484. if (makeSureClientExists())
  229485. {
  229486. MIDIEndpointRef endPoint;
  229487. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229488. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  229489. {
  229490. mo = new MidiOutput();
  229491. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  229492. }
  229493. CFRelease (name);
  229494. }
  229495. return mo;
  229496. }
  229497. MidiOutput::~MidiOutput()
  229498. {
  229499. delete static_cast<MidiPortAndEndpoint*> (internal);
  229500. }
  229501. void MidiOutput::reset()
  229502. {
  229503. }
  229504. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229505. {
  229506. return false;
  229507. }
  229508. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229509. {
  229510. }
  229511. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229512. {
  229513. MidiPortAndEndpoint* const mpe = static_cast<MidiPortAndEndpoint*> (internal);
  229514. if (message.isSysEx())
  229515. {
  229516. const int maxPacketSize = 256;
  229517. int pos = 0, bytesLeft = message.getRawDataSize();
  229518. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229519. HeapBlock <MIDIPacketList> packets;
  229520. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229521. packets->numPackets = numPackets;
  229522. MIDIPacket* p = packets->packet;
  229523. for (int i = 0; i < numPackets; ++i)
  229524. {
  229525. p->timeStamp = 0;
  229526. p->length = jmin (maxPacketSize, bytesLeft);
  229527. memcpy (p->data, message.getRawData() + pos, p->length);
  229528. pos += p->length;
  229529. bytesLeft -= p->length;
  229530. p = MIDIPacketNext (p);
  229531. }
  229532. if (mpe->port != 0)
  229533. MIDISend (mpe->port, mpe->endPoint, packets);
  229534. else
  229535. MIDIReceived (mpe->endPoint, packets);
  229536. }
  229537. else
  229538. {
  229539. MIDIPacketList packets;
  229540. packets.numPackets = 1;
  229541. packets.packet[0].timeStamp = 0;
  229542. packets.packet[0].length = message.getRawDataSize();
  229543. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229544. if (mpe->port != 0)
  229545. MIDISend (mpe->port, mpe->endPoint, &packets);
  229546. else
  229547. MIDIReceived (mpe->endPoint, &packets);
  229548. }
  229549. }
  229550. const StringArray MidiInput::getDevices()
  229551. {
  229552. StringArray s;
  229553. const ItemCount num = MIDIGetNumberOfSources();
  229554. for (ItemCount i = 0; i < num; ++i)
  229555. {
  229556. MIDIEndpointRef source = MIDIGetSource (i);
  229557. if (source != 0)
  229558. {
  229559. String name (getConnectedEndpointName (source));
  229560. if (name.isEmpty())
  229561. name = "<error>";
  229562. s.add (name);
  229563. }
  229564. else
  229565. {
  229566. s.add ("<error>");
  229567. }
  229568. }
  229569. return s;
  229570. }
  229571. int MidiInput::getDefaultDeviceIndex()
  229572. {
  229573. return 0;
  229574. }
  229575. struct MidiPortAndCallback
  229576. {
  229577. MidiInput* input;
  229578. MidiPortAndEndpoint* portAndEndpoint;
  229579. MidiInputCallback* callback;
  229580. MemoryBlock pendingData;
  229581. int pendingBytes;
  229582. double pendingDataTime;
  229583. bool active;
  229584. void processSysex (const uint8*& d, int& size, const double time)
  229585. {
  229586. if (*d == 0xf0)
  229587. {
  229588. pendingBytes = 0;
  229589. pendingDataTime = time;
  229590. }
  229591. pendingData.ensureSize (pendingBytes + size, false);
  229592. uint8* totalMessage = (uint8*) pendingData.getData();
  229593. uint8* dest = totalMessage + pendingBytes;
  229594. while (size > 0)
  229595. {
  229596. if (pendingBytes > 0 && *d >= 0x80)
  229597. {
  229598. if (*d >= 0xfa || *d == 0xf8)
  229599. {
  229600. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  229601. ++d;
  229602. --size;
  229603. }
  229604. else
  229605. {
  229606. if (*d == 0xf7)
  229607. {
  229608. *dest++ = *d++;
  229609. pendingBytes++;
  229610. --size;
  229611. }
  229612. break;
  229613. }
  229614. }
  229615. else
  229616. {
  229617. *dest++ = *d++;
  229618. pendingBytes++;
  229619. --size;
  229620. }
  229621. }
  229622. if (totalMessage [pendingBytes - 1] == 0xf7)
  229623. {
  229624. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  229625. pendingBytes = 0;
  229626. }
  229627. else
  229628. {
  229629. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  229630. }
  229631. }
  229632. };
  229633. namespace CoreMidiCallbacks
  229634. {
  229635. static CriticalSection callbackLock;
  229636. static Array<void*> activeCallbacks;
  229637. }
  229638. static void midiInputProc (const MIDIPacketList* pktlist,
  229639. void* readProcRefCon,
  229640. void* /*srcConnRefCon*/)
  229641. {
  229642. double time = Time::getMillisecondCounterHiRes() * 0.001;
  229643. const double originalTime = time;
  229644. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  229645. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229646. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  229647. {
  229648. const MIDIPacket* packet = &pktlist->packet[0];
  229649. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229650. {
  229651. const uint8* d = (const uint8*) (packet->data);
  229652. int size = packet->length;
  229653. while (size > 0)
  229654. {
  229655. time = originalTime;
  229656. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  229657. {
  229658. mpc->processSysex (d, size, time);
  229659. }
  229660. else
  229661. {
  229662. int used = 0;
  229663. const MidiMessage m (d, size, used, 0, time);
  229664. if (used <= 0)
  229665. {
  229666. jassertfalse; // malformed midi message
  229667. break;
  229668. }
  229669. else
  229670. {
  229671. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  229672. }
  229673. size -= used;
  229674. d += used;
  229675. }
  229676. }
  229677. packet = MIDIPacketNext (packet);
  229678. }
  229679. }
  229680. }
  229681. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229682. {
  229683. MidiInput* mi = 0;
  229684. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  229685. {
  229686. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229687. if (endPoint != 0)
  229688. {
  229689. CFStringRef pname;
  229690. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229691. {
  229692. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  229693. if (makeSureClientExists())
  229694. {
  229695. MIDIPortRef port;
  229696. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  229697. mpc->active = false;
  229698. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  229699. {
  229700. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  229701. {
  229702. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229703. mpc->callback = callback;
  229704. mpc->pendingBytes = 0;
  229705. mpc->pendingData.ensureSize (128);
  229706. mi = new MidiInput (getDevices() [index]);
  229707. mpc->input = mi;
  229708. mi->internal = mpc;
  229709. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229710. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  229711. }
  229712. else
  229713. {
  229714. OK (MIDIPortDispose (port));
  229715. }
  229716. }
  229717. }
  229718. }
  229719. CFRelease (pname);
  229720. }
  229721. }
  229722. return mi;
  229723. }
  229724. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229725. {
  229726. MidiInput* mi = 0;
  229727. if (makeSureClientExists())
  229728. {
  229729. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  229730. mpc->active = false;
  229731. MIDIEndpointRef endPoint;
  229732. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229733. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  229734. {
  229735. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229736. mpc->callback = callback;
  229737. mpc->pendingBytes = 0;
  229738. mpc->pendingData.ensureSize (128);
  229739. mi = new MidiInput (deviceName);
  229740. mpc->input = mi;
  229741. mi->internal = mpc;
  229742. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229743. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  229744. }
  229745. CFRelease (name);
  229746. }
  229747. return mi;
  229748. }
  229749. MidiInput::MidiInput (const String& name_)
  229750. : name (name_)
  229751. {
  229752. }
  229753. MidiInput::~MidiInput()
  229754. {
  229755. MidiPortAndCallback* const mpc = static_cast<MidiPortAndCallback*> (internal);
  229756. mpc->active = false;
  229757. {
  229758. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229759. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  229760. }
  229761. if (mpc->portAndEndpoint->port != 0)
  229762. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  229763. delete mpc->portAndEndpoint;
  229764. delete mpc;
  229765. }
  229766. void MidiInput::start()
  229767. {
  229768. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229769. static_cast<MidiPortAndCallback*> (internal)->active = true;
  229770. }
  229771. void MidiInput::stop()
  229772. {
  229773. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  229774. static_cast<MidiPortAndCallback*> (internal)->active = false;
  229775. }
  229776. #undef log
  229777. #else
  229778. MidiOutput::~MidiOutput()
  229779. {
  229780. }
  229781. void MidiOutput::reset()
  229782. {
  229783. }
  229784. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229785. {
  229786. return false;
  229787. }
  229788. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229789. {
  229790. }
  229791. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229792. {
  229793. }
  229794. const StringArray MidiOutput::getDevices()
  229795. {
  229796. return StringArray();
  229797. }
  229798. MidiOutput* MidiOutput::openDevice (int index)
  229799. {
  229800. return 0;
  229801. }
  229802. const StringArray MidiInput::getDevices()
  229803. {
  229804. return StringArray();
  229805. }
  229806. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229807. {
  229808. return 0;
  229809. }
  229810. #endif
  229811. #endif
  229812. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229813. #else
  229814. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229815. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229816. // compiled on its own).
  229817. #if JUCE_INCLUDED_FILE
  229818. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229819. #define SUPPORT_10_4_FONTS 1
  229820. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229821. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229822. #define SUPPORT_ONLY_10_4_FONTS 1
  229823. #endif
  229824. END_JUCE_NAMESPACE
  229825. @interface NSFont (PrivateHack)
  229826. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229827. @end
  229828. BEGIN_JUCE_NAMESPACE
  229829. #endif
  229830. class MacTypeface : public Typeface
  229831. {
  229832. public:
  229833. MacTypeface (const Font& font)
  229834. : Typeface (font.getTypefaceName())
  229835. {
  229836. const ScopedAutoReleasePool pool;
  229837. renderingTransform = CGAffineTransformIdentity;
  229838. bool needsItalicTransform = false;
  229839. #if JUCE_IOS
  229840. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229841. if (font.isItalic() || font.isBold())
  229842. {
  229843. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229844. for (NSString* i in familyFonts)
  229845. {
  229846. const String fn (nsStringToJuce (i));
  229847. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229848. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229849. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229850. || afterDash.containsIgnoreCase ("italic")
  229851. || fn.endsWithIgnoreCase ("oblique")
  229852. || fn.endsWithIgnoreCase ("italic");
  229853. if (probablyBold == font.isBold()
  229854. && probablyItalic == font.isItalic())
  229855. {
  229856. fontName = i;
  229857. needsItalicTransform = false;
  229858. break;
  229859. }
  229860. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229861. {
  229862. fontName = i;
  229863. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229864. }
  229865. }
  229866. if (needsItalicTransform)
  229867. renderingTransform.c = 0.15f;
  229868. }
  229869. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229870. const int ascender = abs (CGFontGetAscent (fontRef));
  229871. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229872. ascent = ascender / totalHeight;
  229873. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229874. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229875. #else
  229876. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229877. if (font.isItalic())
  229878. {
  229879. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229880. toHaveTrait: NSItalicFontMask];
  229881. if (newFont == nsFont)
  229882. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229883. nsFont = newFont;
  229884. }
  229885. if (font.isBold())
  229886. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229887. [nsFont retain];
  229888. ascent = std::abs ((float) [nsFont ascender]);
  229889. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229890. ascent /= totalSize;
  229891. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229892. if (needsItalicTransform)
  229893. {
  229894. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229895. renderingTransform.c = 0.15f;
  229896. }
  229897. #if SUPPORT_ONLY_10_4_FONTS
  229898. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229899. if (atsFont == 0)
  229900. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229901. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229902. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229903. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229904. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229905. #else
  229906. #if SUPPORT_10_4_FONTS
  229907. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229908. {
  229909. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229910. if (atsFont == 0)
  229911. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229912. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229913. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229914. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229915. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229916. }
  229917. else
  229918. #endif
  229919. {
  229920. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229921. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229922. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229923. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229924. }
  229925. #endif
  229926. #endif
  229927. }
  229928. ~MacTypeface()
  229929. {
  229930. #if ! JUCE_IOS
  229931. [nsFont release];
  229932. #endif
  229933. if (fontRef != 0)
  229934. CGFontRelease (fontRef);
  229935. }
  229936. float getAscent() const
  229937. {
  229938. return ascent;
  229939. }
  229940. float getDescent() const
  229941. {
  229942. return 1.0f - ascent;
  229943. }
  229944. float getStringWidth (const String& text)
  229945. {
  229946. if (fontRef == 0 || text.isEmpty())
  229947. return 0;
  229948. const int length = text.length();
  229949. HeapBlock <CGGlyph> glyphs;
  229950. createGlyphsForString (text, length, glyphs);
  229951. float x = 0;
  229952. #if SUPPORT_ONLY_10_4_FONTS
  229953. HeapBlock <NSSize> advances (length);
  229954. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229955. for (int i = 0; i < length; ++i)
  229956. x += advances[i].width;
  229957. #else
  229958. #if SUPPORT_10_4_FONTS
  229959. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229960. {
  229961. HeapBlock <NSSize> advances (length);
  229962. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229963. for (int i = 0; i < length; ++i)
  229964. x += advances[i].width;
  229965. }
  229966. else
  229967. #endif
  229968. {
  229969. HeapBlock <int> advances (length);
  229970. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229971. for (int i = 0; i < length; ++i)
  229972. x += advances[i];
  229973. }
  229974. #endif
  229975. return x * unitsToHeightScaleFactor;
  229976. }
  229977. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229978. {
  229979. xOffsets.add (0);
  229980. if (fontRef == 0 || text.isEmpty())
  229981. return;
  229982. const int length = text.length();
  229983. HeapBlock <CGGlyph> glyphs;
  229984. createGlyphsForString (text, length, glyphs);
  229985. #if SUPPORT_ONLY_10_4_FONTS
  229986. HeapBlock <NSSize> advances (length);
  229987. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229988. int x = 0;
  229989. for (int i = 0; i < length; ++i)
  229990. {
  229991. x += advances[i].width;
  229992. xOffsets.add (x * unitsToHeightScaleFactor);
  229993. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229994. }
  229995. #else
  229996. #if SUPPORT_10_4_FONTS
  229997. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229998. {
  229999. HeapBlock <NSSize> advances (length);
  230000. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230001. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230002. float x = 0;
  230003. for (int i = 0; i < length; ++i)
  230004. {
  230005. x += advances[i].width;
  230006. xOffsets.add (x * unitsToHeightScaleFactor);
  230007. resultGlyphs.add (nsGlyphs[i]);
  230008. }
  230009. }
  230010. else
  230011. #endif
  230012. {
  230013. HeapBlock <int> advances (length);
  230014. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230015. {
  230016. int x = 0;
  230017. for (int i = 0; i < length; ++i)
  230018. {
  230019. x += advances [i];
  230020. xOffsets.add (x * unitsToHeightScaleFactor);
  230021. resultGlyphs.add (glyphs[i]);
  230022. }
  230023. }
  230024. }
  230025. #endif
  230026. }
  230027. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230028. {
  230029. #if JUCE_IOS
  230030. return false;
  230031. #else
  230032. if (nsFont == 0)
  230033. return false;
  230034. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230035. jassert (path.isEmpty());
  230036. const ScopedAutoReleasePool pool;
  230037. NSBezierPath* bez = [NSBezierPath bezierPath];
  230038. [bez moveToPoint: NSMakePoint (0, 0)];
  230039. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230040. inFont: nsFont];
  230041. for (int i = 0; i < [bez elementCount]; ++i)
  230042. {
  230043. NSPoint p[3];
  230044. switch ([bez elementAtIndex: i associatedPoints: p])
  230045. {
  230046. case NSMoveToBezierPathElement:
  230047. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230048. break;
  230049. case NSLineToBezierPathElement:
  230050. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230051. break;
  230052. case NSCurveToBezierPathElement:
  230053. path.cubicTo ((float) p[0].x, (float) -p[0].y, (float) p[1].x, (float) -p[1].y, (float) p[2].x, (float) -p[2].y);
  230054. break;
  230055. case NSClosePathBezierPathElement:
  230056. path.closeSubPath();
  230057. break;
  230058. default:
  230059. jassertfalse;
  230060. break;
  230061. }
  230062. }
  230063. path.applyTransform (pathTransform);
  230064. return true;
  230065. #endif
  230066. }
  230067. juce_UseDebuggingNewOperator
  230068. CGFontRef fontRef;
  230069. float fontHeightToCGSizeFactor;
  230070. CGAffineTransform renderingTransform;
  230071. private:
  230072. float ascent, unitsToHeightScaleFactor;
  230073. #if JUCE_IOS
  230074. #else
  230075. NSFont* nsFont;
  230076. AffineTransform pathTransform;
  230077. #endif
  230078. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230079. {
  230080. #if SUPPORT_10_4_FONTS
  230081. #if ! SUPPORT_ONLY_10_4_FONTS
  230082. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230083. #endif
  230084. {
  230085. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230086. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230087. for (int i = 0; i < length; ++i)
  230088. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230089. return;
  230090. }
  230091. #endif
  230092. #if ! SUPPORT_ONLY_10_4_FONTS
  230093. if (charToGlyphMapper == 0)
  230094. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230095. glyphs.malloc (length);
  230096. for (int i = 0; i < length; ++i)
  230097. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230098. #endif
  230099. }
  230100. #if ! SUPPORT_ONLY_10_4_FONTS
  230101. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230102. class CharToGlyphMapper
  230103. {
  230104. public:
  230105. CharToGlyphMapper (CGFontRef fontRef)
  230106. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230107. idRangeOffset (0), glyphIndexes (0)
  230108. {
  230109. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230110. if (cmapTable != 0)
  230111. {
  230112. const int numSubtables = getValue16 (cmapTable, 2);
  230113. for (int i = 0; i < numSubtables; ++i)
  230114. {
  230115. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230116. {
  230117. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230118. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230119. {
  230120. const int length = getValue16 (cmapTable, offset + 2);
  230121. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230122. segCount = segCountX2 / 2;
  230123. const int endCodeOffset = offset + 14;
  230124. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230125. const int idDeltaOffset = startCodeOffset + segCountX2;
  230126. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230127. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230128. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230129. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230130. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230131. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230132. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230133. }
  230134. break;
  230135. }
  230136. }
  230137. CFRelease (cmapTable);
  230138. }
  230139. }
  230140. ~CharToGlyphMapper()
  230141. {
  230142. if (endCode != 0)
  230143. {
  230144. CFRelease (endCode);
  230145. CFRelease (startCode);
  230146. CFRelease (idDelta);
  230147. CFRelease (idRangeOffset);
  230148. CFRelease (glyphIndexes);
  230149. }
  230150. }
  230151. int getGlyphForCharacter (const juce_wchar c) const
  230152. {
  230153. for (int i = 0; i < segCount; ++i)
  230154. {
  230155. if (getValue16 (endCode, i * 2) >= c)
  230156. {
  230157. const int start = getValue16 (startCode, i * 2);
  230158. if (start > c)
  230159. break;
  230160. const int delta = getValue16 (idDelta, i * 2);
  230161. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230162. if (rangeOffset == 0)
  230163. return delta + c;
  230164. else
  230165. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230166. }
  230167. }
  230168. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230169. return jmax (-1, c - 29);
  230170. }
  230171. private:
  230172. int segCount;
  230173. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230174. static uint16 getValue16 (CFDataRef data, const int index)
  230175. {
  230176. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230177. }
  230178. static uint32 getValue32 (CFDataRef data, const int index)
  230179. {
  230180. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230181. }
  230182. };
  230183. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230184. #endif
  230185. MacTypeface (const MacTypeface&);
  230186. MacTypeface& operator= (const MacTypeface&);
  230187. };
  230188. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230189. {
  230190. return new MacTypeface (font);
  230191. }
  230192. const StringArray Font::findAllTypefaceNames()
  230193. {
  230194. StringArray names;
  230195. const ScopedAutoReleasePool pool;
  230196. #if JUCE_IOS
  230197. NSArray* fonts = [UIFont familyNames];
  230198. #else
  230199. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230200. #endif
  230201. for (unsigned int i = 0; i < [fonts count]; ++i)
  230202. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230203. names.sort (true);
  230204. return names;
  230205. }
  230206. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230207. {
  230208. #if JUCE_IOS
  230209. defaultSans = "Helvetica";
  230210. defaultSerif = "Times New Roman";
  230211. defaultFixed = "Courier New";
  230212. #else
  230213. defaultSans = "Lucida Grande";
  230214. defaultSerif = "Times New Roman";
  230215. defaultFixed = "Monaco";
  230216. #endif
  230217. }
  230218. #endif
  230219. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230220. // (must go before juce_mac_CoreGraphicsContext.mm)
  230221. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230222. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230223. // compiled on its own).
  230224. #if JUCE_INCLUDED_FILE
  230225. class CoreGraphicsImage : public Image::SharedImage
  230226. {
  230227. public:
  230228. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230229. : Image::SharedImage (format_, width_, height_)
  230230. {
  230231. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230232. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230233. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230234. imageData = imageDataAllocated;
  230235. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230236. : CGColorSpaceCreateDeviceRGB();
  230237. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230238. colourSpace, getCGImageFlags (format_));
  230239. CGColorSpaceRelease (colourSpace);
  230240. }
  230241. ~CoreGraphicsImage()
  230242. {
  230243. CGContextRelease (context);
  230244. }
  230245. Image::ImageType getType() const { return Image::NativeImage; }
  230246. LowLevelGraphicsContext* createLowLevelContext();
  230247. SharedImage* clone()
  230248. {
  230249. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230250. memcpy (im->imageData, imageData, lineStride * height);
  230251. return im;
  230252. }
  230253. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230254. {
  230255. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230256. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230257. {
  230258. return CGBitmapContextCreateImage (nativeImage->context);
  230259. }
  230260. else
  230261. {
  230262. const Image::BitmapData srcData (juceImage, false);
  230263. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230264. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230265. 8, srcData.pixelStride * 8, srcData.lineStride,
  230266. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230267. 0, true, kCGRenderingIntentDefault);
  230268. CGDataProviderRelease (provider);
  230269. return imageRef;
  230270. }
  230271. }
  230272. #if JUCE_MAC
  230273. static NSImage* createNSImage (const Image& image)
  230274. {
  230275. const ScopedAutoReleasePool pool;
  230276. NSImage* im = [[NSImage alloc] init];
  230277. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230278. [im lockFocus];
  230279. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230280. CGImageRef imageRef = createImage (image, false, colourSpace);
  230281. CGColorSpaceRelease (colourSpace);
  230282. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230283. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230284. CGImageRelease (imageRef);
  230285. [im unlockFocus];
  230286. return im;
  230287. }
  230288. #endif
  230289. CGContextRef context;
  230290. HeapBlock<uint8> imageDataAllocated;
  230291. private:
  230292. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230293. {
  230294. #if JUCE_BIG_ENDIAN
  230295. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230296. #else
  230297. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230298. #endif
  230299. }
  230300. };
  230301. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230302. {
  230303. #if USE_COREGRAPHICS_RENDERING
  230304. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230305. #else
  230306. return createSoftwareImage (format, width, height, clearImage);
  230307. #endif
  230308. }
  230309. class CoreGraphicsContext : public LowLevelGraphicsContext
  230310. {
  230311. public:
  230312. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230313. : context (context_),
  230314. flipHeight (flipHeight_),
  230315. state (new SavedState()),
  230316. numGradientLookupEntries (0),
  230317. lastClipRectIsValid (false)
  230318. {
  230319. CGContextRetain (context);
  230320. CGContextSaveGState(context);
  230321. CGContextSetShouldSmoothFonts (context, true);
  230322. CGContextSetShouldAntialias (context, true);
  230323. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230324. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230325. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230326. gradientCallbacks.version = 0;
  230327. gradientCallbacks.evaluate = gradientCallback;
  230328. gradientCallbacks.releaseInfo = 0;
  230329. setFont (Font());
  230330. }
  230331. ~CoreGraphicsContext()
  230332. {
  230333. CGContextRestoreGState (context);
  230334. CGContextRelease (context);
  230335. CGColorSpaceRelease (rgbColourSpace);
  230336. CGColorSpaceRelease (greyColourSpace);
  230337. }
  230338. bool isVectorDevice() const { return false; }
  230339. void setOrigin (int x, int y)
  230340. {
  230341. CGContextTranslateCTM (context, x, -y);
  230342. if (lastClipRectIsValid)
  230343. lastClipRect.translate (-x, -y);
  230344. }
  230345. bool clipToRectangle (const Rectangle<int>& r)
  230346. {
  230347. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230348. if (lastClipRectIsValid)
  230349. {
  230350. // This is actually incorrect, because the actual clip region may be complex, and
  230351. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230352. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230353. // when calculating the resultant clip bounds, and makes the same mistake!
  230354. lastClipRect = lastClipRect.getIntersection (r);
  230355. return ! lastClipRect.isEmpty();
  230356. }
  230357. return ! isClipEmpty();
  230358. }
  230359. bool clipToRectangleList (const RectangleList& clipRegion)
  230360. {
  230361. if (clipRegion.isEmpty())
  230362. {
  230363. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230364. lastClipRectIsValid = true;
  230365. lastClipRect = Rectangle<int>();
  230366. return false;
  230367. }
  230368. else
  230369. {
  230370. const int numRects = clipRegion.getNumRectangles();
  230371. HeapBlock <CGRect> rects (numRects);
  230372. for (int i = 0; i < numRects; ++i)
  230373. {
  230374. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230375. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230376. }
  230377. CGContextClipToRects (context, rects, numRects);
  230378. lastClipRectIsValid = false;
  230379. return ! isClipEmpty();
  230380. }
  230381. }
  230382. void excludeClipRectangle (const Rectangle<int>& r)
  230383. {
  230384. RectangleList remaining (getClipBounds());
  230385. remaining.subtract (r);
  230386. clipToRectangleList (remaining);
  230387. lastClipRectIsValid = false;
  230388. }
  230389. void clipToPath (const Path& path, const AffineTransform& transform)
  230390. {
  230391. createPath (path, transform);
  230392. CGContextClip (context);
  230393. lastClipRectIsValid = false;
  230394. }
  230395. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230396. {
  230397. if (! transform.isSingularity())
  230398. {
  230399. Image singleChannelImage (sourceImage);
  230400. if (sourceImage.getFormat() != Image::SingleChannel)
  230401. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230402. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230403. flip();
  230404. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230405. applyTransform (t);
  230406. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230407. CGContextClipToMask (context, r, image);
  230408. applyTransform (t.inverted());
  230409. flip();
  230410. CGImageRelease (image);
  230411. lastClipRectIsValid = false;
  230412. }
  230413. }
  230414. bool clipRegionIntersects (const Rectangle<int>& r)
  230415. {
  230416. return getClipBounds().intersects (r);
  230417. }
  230418. const Rectangle<int> getClipBounds() const
  230419. {
  230420. if (! lastClipRectIsValid)
  230421. {
  230422. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230423. lastClipRectIsValid = true;
  230424. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230425. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230426. roundToInt (bounds.size.width),
  230427. roundToInt (bounds.size.height));
  230428. }
  230429. return lastClipRect;
  230430. }
  230431. bool isClipEmpty() const
  230432. {
  230433. return getClipBounds().isEmpty();
  230434. }
  230435. void saveState()
  230436. {
  230437. CGContextSaveGState (context);
  230438. stateStack.add (new SavedState (*state));
  230439. }
  230440. void restoreState()
  230441. {
  230442. CGContextRestoreGState (context);
  230443. SavedState* const top = stateStack.getLast();
  230444. if (top != 0)
  230445. {
  230446. state = top;
  230447. stateStack.removeLast (1, false);
  230448. lastClipRectIsValid = false;
  230449. }
  230450. else
  230451. {
  230452. jassertfalse; // trying to pop with an empty stack!
  230453. }
  230454. }
  230455. void setFill (const FillType& fillType)
  230456. {
  230457. state->fillType = fillType;
  230458. if (fillType.isColour())
  230459. {
  230460. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230461. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230462. CGContextSetAlpha (context, 1.0f);
  230463. }
  230464. }
  230465. void setOpacity (float newOpacity)
  230466. {
  230467. state->fillType.setOpacity (newOpacity);
  230468. setFill (state->fillType);
  230469. }
  230470. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230471. {
  230472. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230473. ? kCGInterpolationLow
  230474. : kCGInterpolationHigh);
  230475. }
  230476. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230477. {
  230478. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230479. }
  230480. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230481. {
  230482. if (replaceExistingContents)
  230483. {
  230484. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230485. CGContextClearRect (context, cgRect);
  230486. #else
  230487. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230488. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230489. CGContextClearRect (context, cgRect);
  230490. else
  230491. #endif
  230492. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230493. #endif
  230494. fillCGRect (cgRect, false);
  230495. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230496. }
  230497. else
  230498. {
  230499. if (state->fillType.isColour())
  230500. {
  230501. CGContextFillRect (context, cgRect);
  230502. }
  230503. else if (state->fillType.isGradient())
  230504. {
  230505. CGContextSaveGState (context);
  230506. CGContextClipToRect (context, cgRect);
  230507. drawGradient();
  230508. CGContextRestoreGState (context);
  230509. }
  230510. else
  230511. {
  230512. CGContextSaveGState (context);
  230513. CGContextClipToRect (context, cgRect);
  230514. drawImage (state->fillType.image, state->fillType.transform, true);
  230515. CGContextRestoreGState (context);
  230516. }
  230517. }
  230518. }
  230519. void fillPath (const Path& path, const AffineTransform& transform)
  230520. {
  230521. CGContextSaveGState (context);
  230522. if (state->fillType.isColour())
  230523. {
  230524. flip();
  230525. applyTransform (transform);
  230526. createPath (path);
  230527. if (path.isUsingNonZeroWinding())
  230528. CGContextFillPath (context);
  230529. else
  230530. CGContextEOFillPath (context);
  230531. }
  230532. else
  230533. {
  230534. createPath (path, transform);
  230535. if (path.isUsingNonZeroWinding())
  230536. CGContextClip (context);
  230537. else
  230538. CGContextEOClip (context);
  230539. if (state->fillType.isGradient())
  230540. drawGradient();
  230541. else
  230542. drawImage (state->fillType.image, state->fillType.transform, true);
  230543. }
  230544. CGContextRestoreGState (context);
  230545. }
  230546. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230547. {
  230548. const int iw = sourceImage.getWidth();
  230549. const int ih = sourceImage.getHeight();
  230550. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230551. CGContextSaveGState (context);
  230552. CGContextSetAlpha (context, state->fillType.getOpacity());
  230553. flip();
  230554. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230555. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230556. if (fillEntireClipAsTiles)
  230557. {
  230558. #if JUCE_IOS
  230559. CGContextDrawTiledImage (context, imageRect, image);
  230560. #else
  230561. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230562. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230563. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230564. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230565. CGContextDrawTiledImage (context, imageRect, image);
  230566. else
  230567. #endif
  230568. {
  230569. // Fallback to manually doing a tiled fill on 10.4
  230570. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230571. int x = 0, y = 0;
  230572. while (x > clip.origin.x) x -= iw;
  230573. while (y > clip.origin.y) y -= ih;
  230574. const int right = (int) (clip.origin.x + clip.size.width);
  230575. const int bottom = (int) (clip.origin.y + clip.size.height);
  230576. while (y < bottom)
  230577. {
  230578. for (int x2 = x; x2 < right; x2 += iw)
  230579. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230580. y += ih;
  230581. }
  230582. }
  230583. #endif
  230584. }
  230585. else
  230586. {
  230587. CGContextDrawImage (context, imageRect, image);
  230588. }
  230589. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230590. CGContextRestoreGState (context);
  230591. }
  230592. void drawLine (const Line<float>& line)
  230593. {
  230594. if (state->fillType.isColour())
  230595. {
  230596. CGContextSetLineCap (context, kCGLineCapSquare);
  230597. CGContextSetLineWidth (context, 1.0f);
  230598. CGContextSetRGBStrokeColor (context,
  230599. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230600. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230601. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230602. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230603. CGContextStrokeLineSegments (context, cgLine, 1);
  230604. }
  230605. else
  230606. {
  230607. Path p;
  230608. p.addLineSegment (line, 1.0f);
  230609. fillPath (p, AffineTransform::identity);
  230610. }
  230611. }
  230612. void drawVerticalLine (const int x, float top, float bottom)
  230613. {
  230614. if (state->fillType.isColour())
  230615. {
  230616. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230617. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230618. #else
  230619. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230620. // the x co-ord slightly to trick it..
  230621. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230622. #endif
  230623. }
  230624. else
  230625. {
  230626. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230627. }
  230628. }
  230629. void drawHorizontalLine (const int y, float left, float right)
  230630. {
  230631. if (state->fillType.isColour())
  230632. {
  230633. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230634. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230635. #else
  230636. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230637. // the x co-ord slightly to trick it..
  230638. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230639. #endif
  230640. }
  230641. else
  230642. {
  230643. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230644. }
  230645. }
  230646. void setFont (const Font& newFont)
  230647. {
  230648. if (state->font != newFont)
  230649. {
  230650. state->fontRef = 0;
  230651. state->font = newFont;
  230652. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230653. if (mf != 0)
  230654. {
  230655. state->fontRef = mf->fontRef;
  230656. CGContextSetFont (context, state->fontRef);
  230657. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230658. state->fontTransform = mf->renderingTransform;
  230659. state->fontTransform.a *= state->font.getHorizontalScale();
  230660. CGContextSetTextMatrix (context, state->fontTransform);
  230661. }
  230662. }
  230663. }
  230664. const Font getFont()
  230665. {
  230666. return state->font;
  230667. }
  230668. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230669. {
  230670. if (state->fontRef != 0 && state->fillType.isColour())
  230671. {
  230672. if (transform.isOnlyTranslation())
  230673. {
  230674. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230675. CGGlyph g = glyphNumber;
  230676. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230677. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230678. }
  230679. else
  230680. {
  230681. CGContextSaveGState (context);
  230682. flip();
  230683. applyTransform (transform);
  230684. CGAffineTransform t = state->fontTransform;
  230685. t.d = -t.d;
  230686. CGContextSetTextMatrix (context, t);
  230687. CGGlyph g = glyphNumber;
  230688. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230689. CGContextRestoreGState (context);
  230690. }
  230691. }
  230692. else
  230693. {
  230694. Path p;
  230695. Font& f = state->font;
  230696. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230697. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230698. .followedBy (transform));
  230699. }
  230700. }
  230701. private:
  230702. CGContextRef context;
  230703. const CGFloat flipHeight;
  230704. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230705. CGFunctionCallbacks gradientCallbacks;
  230706. mutable Rectangle<int> lastClipRect;
  230707. mutable bool lastClipRectIsValid;
  230708. struct SavedState
  230709. {
  230710. SavedState()
  230711. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230712. {
  230713. }
  230714. SavedState (const SavedState& other)
  230715. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230716. fontTransform (other.fontTransform)
  230717. {
  230718. }
  230719. ~SavedState()
  230720. {
  230721. }
  230722. FillType fillType;
  230723. Font font;
  230724. CGFontRef fontRef;
  230725. CGAffineTransform fontTransform;
  230726. };
  230727. ScopedPointer <SavedState> state;
  230728. OwnedArray <SavedState> stateStack;
  230729. HeapBlock <PixelARGB> gradientLookupTable;
  230730. int numGradientLookupEntries;
  230731. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230732. {
  230733. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230734. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230735. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230736. colour.unpremultiply();
  230737. outData[0] = colour.getRed() / 255.0f;
  230738. outData[1] = colour.getGreen() / 255.0f;
  230739. outData[2] = colour.getBlue() / 255.0f;
  230740. outData[3] = colour.getAlpha() / 255.0f;
  230741. }
  230742. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230743. {
  230744. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  230745. --numGradientLookupEntries;
  230746. CGShadingRef result = 0;
  230747. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230748. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230749. if (gradient.isRadial)
  230750. {
  230751. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230752. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230753. function, true, true);
  230754. }
  230755. else
  230756. {
  230757. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230758. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230759. function, true, true);
  230760. }
  230761. CGFunctionRelease (function);
  230762. return result;
  230763. }
  230764. void drawGradient()
  230765. {
  230766. flip();
  230767. applyTransform (state->fillType.transform);
  230768. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230769. // you draw a gradient with high quality interp enabled).
  230770. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230771. CGContextSetAlpha (context, state->fillType.getOpacity());
  230772. CGContextDrawShading (context, shading);
  230773. CGShadingRelease (shading);
  230774. }
  230775. void createPath (const Path& path) const
  230776. {
  230777. CGContextBeginPath (context);
  230778. Path::Iterator i (path);
  230779. while (i.next())
  230780. {
  230781. switch (i.elementType)
  230782. {
  230783. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230784. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230785. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230786. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230787. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230788. default: jassertfalse; break;
  230789. }
  230790. }
  230791. }
  230792. void createPath (const Path& path, const AffineTransform& transform) const
  230793. {
  230794. CGContextBeginPath (context);
  230795. Path::Iterator i (path);
  230796. while (i.next())
  230797. {
  230798. switch (i.elementType)
  230799. {
  230800. case Path::Iterator::startNewSubPath:
  230801. transform.transformPoint (i.x1, i.y1);
  230802. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230803. break;
  230804. case Path::Iterator::lineTo:
  230805. transform.transformPoint (i.x1, i.y1);
  230806. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230807. break;
  230808. case Path::Iterator::quadraticTo:
  230809. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230810. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230811. break;
  230812. case Path::Iterator::cubicTo:
  230813. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230814. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230815. break;
  230816. case Path::Iterator::closePath:
  230817. CGContextClosePath (context); break;
  230818. default:
  230819. jassertfalse;
  230820. break;
  230821. }
  230822. }
  230823. }
  230824. void flip() const
  230825. {
  230826. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230827. }
  230828. void applyTransform (const AffineTransform& transform) const
  230829. {
  230830. CGAffineTransform t;
  230831. t.a = transform.mat00;
  230832. t.b = transform.mat10;
  230833. t.c = transform.mat01;
  230834. t.d = transform.mat11;
  230835. t.tx = transform.mat02;
  230836. t.ty = transform.mat12;
  230837. CGContextConcatCTM (context, t);
  230838. }
  230839. CoreGraphicsContext (const CoreGraphicsContext&);
  230840. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  230841. };
  230842. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230843. {
  230844. return new CoreGraphicsContext (context, height);
  230845. }
  230846. #endif
  230847. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230848. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230849. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230850. // compiled on its own).
  230851. #if JUCE_INCLUDED_FILE
  230852. class NSViewComponentPeer;
  230853. END_JUCE_NAMESPACE
  230854. @interface NSEvent (JuceDeviceDelta)
  230855. - (float) deviceDeltaX;
  230856. - (float) deviceDeltaY;
  230857. @end
  230858. #define JuceNSView MakeObjCClassName(JuceNSView)
  230859. @interface JuceNSView : NSView<NSTextInput>
  230860. {
  230861. @public
  230862. NSViewComponentPeer* owner;
  230863. NSNotificationCenter* notificationCenter;
  230864. String* stringBeingComposed;
  230865. bool textWasInserted;
  230866. }
  230867. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230868. - (void) dealloc;
  230869. - (BOOL) isOpaque;
  230870. - (void) drawRect: (NSRect) r;
  230871. - (void) mouseDown: (NSEvent*) ev;
  230872. - (void) asyncMouseDown: (NSEvent*) ev;
  230873. - (void) mouseUp: (NSEvent*) ev;
  230874. - (void) asyncMouseUp: (NSEvent*) ev;
  230875. - (void) mouseDragged: (NSEvent*) ev;
  230876. - (void) mouseMoved: (NSEvent*) ev;
  230877. - (void) mouseEntered: (NSEvent*) ev;
  230878. - (void) mouseExited: (NSEvent*) ev;
  230879. - (void) rightMouseDown: (NSEvent*) ev;
  230880. - (void) rightMouseDragged: (NSEvent*) ev;
  230881. - (void) rightMouseUp: (NSEvent*) ev;
  230882. - (void) otherMouseDown: (NSEvent*) ev;
  230883. - (void) otherMouseDragged: (NSEvent*) ev;
  230884. - (void) otherMouseUp: (NSEvent*) ev;
  230885. - (void) scrollWheel: (NSEvent*) ev;
  230886. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230887. - (void) frameChanged: (NSNotification*) n;
  230888. - (void) viewDidMoveToWindow;
  230889. - (void) keyDown: (NSEvent*) ev;
  230890. - (void) keyUp: (NSEvent*) ev;
  230891. // NSTextInput Methods
  230892. - (void) insertText: (id) aString;
  230893. - (void) doCommandBySelector: (SEL) aSelector;
  230894. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230895. - (void) unmarkText;
  230896. - (BOOL) hasMarkedText;
  230897. - (long) conversationIdentifier;
  230898. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230899. - (NSRange) markedRange;
  230900. - (NSRange) selectedRange;
  230901. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230902. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230903. - (NSArray*) validAttributesForMarkedText;
  230904. - (void) flagsChanged: (NSEvent*) ev;
  230905. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230906. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230907. #endif
  230908. - (BOOL) becomeFirstResponder;
  230909. - (BOOL) resignFirstResponder;
  230910. - (BOOL) acceptsFirstResponder;
  230911. - (void) asyncRepaint: (id) rect;
  230912. - (NSArray*) getSupportedDragTypes;
  230913. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230914. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230915. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230916. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230917. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230918. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230919. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230920. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230921. @end
  230922. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230923. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230924. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230925. #else
  230926. @interface JuceNSWindow : NSWindow
  230927. #endif
  230928. {
  230929. @private
  230930. NSViewComponentPeer* owner;
  230931. bool isZooming;
  230932. }
  230933. - (void) setOwner: (NSViewComponentPeer*) owner;
  230934. - (BOOL) canBecomeKeyWindow;
  230935. - (void) becomeKeyWindow;
  230936. - (BOOL) windowShouldClose: (id) window;
  230937. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230938. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230939. - (void) zoom: (id) sender;
  230940. @end
  230941. BEGIN_JUCE_NAMESPACE
  230942. class NSViewComponentPeer : public ComponentPeer
  230943. {
  230944. public:
  230945. NSViewComponentPeer (Component* const component,
  230946. const int windowStyleFlags,
  230947. NSView* viewToAttachTo);
  230948. ~NSViewComponentPeer();
  230949. void* getNativeHandle() const;
  230950. void setVisible (bool shouldBeVisible);
  230951. void setTitle (const String& title);
  230952. void setPosition (int x, int y);
  230953. void setSize (int w, int h);
  230954. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230955. const Rectangle<int> getBounds (const bool global) const;
  230956. const Rectangle<int> getBounds() const;
  230957. const Point<int> getScreenPosition() const;
  230958. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  230959. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  230960. void setMinimised (bool shouldBeMinimised);
  230961. bool isMinimised() const;
  230962. void setFullScreen (bool shouldBeFullScreen);
  230963. bool isFullScreen() const;
  230964. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230965. const BorderSize getFrameSize() const;
  230966. bool setAlwaysOnTop (bool alwaysOnTop);
  230967. void toFront (bool makeActiveWindow);
  230968. void toBehind (ComponentPeer* other);
  230969. void setIcon (const Image& newIcon);
  230970. const StringArray getAvailableRenderingEngines();
  230971. int getCurrentRenderingEngine() throw();
  230972. void setCurrentRenderingEngine (int index);
  230973. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230974. for example having more than one juce plugin loaded into a host, then when a
  230975. method is called, the actual code that runs might actually be in a different module
  230976. than the one you expect... So any calls to library functions or statics that are
  230977. made inside obj-c methods will probably end up getting executed in a different DLL's
  230978. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230979. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230980. virtual methods of an object that's known to live inside the right module's space.
  230981. */
  230982. virtual void redirectMouseDown (NSEvent* ev);
  230983. virtual void redirectMouseUp (NSEvent* ev);
  230984. virtual void redirectMouseDrag (NSEvent* ev);
  230985. virtual void redirectMouseMove (NSEvent* ev);
  230986. virtual void redirectMouseEnter (NSEvent* ev);
  230987. virtual void redirectMouseExit (NSEvent* ev);
  230988. virtual void redirectMouseWheel (NSEvent* ev);
  230989. void sendMouseEvent (NSEvent* ev);
  230990. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230991. virtual bool redirectKeyDown (NSEvent* ev);
  230992. virtual bool redirectKeyUp (NSEvent* ev);
  230993. virtual void redirectModKeyChange (NSEvent* ev);
  230994. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230995. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230996. #endif
  230997. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230998. virtual bool isOpaque();
  230999. virtual void drawRect (NSRect r);
  231000. virtual bool canBecomeKeyWindow();
  231001. virtual bool windowShouldClose();
  231002. virtual void redirectMovedOrResized();
  231003. virtual void viewMovedToWindow();
  231004. virtual NSRect constrainRect (NSRect r);
  231005. static void showArrowCursorIfNeeded();
  231006. static void updateModifiers (NSEvent* e);
  231007. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231008. static int getKeyCodeFromEvent (NSEvent* ev)
  231009. {
  231010. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231011. int keyCode = unmodified[0];
  231012. if (keyCode == 0x19) // (backwards-tab)
  231013. keyCode = '\t';
  231014. else if (keyCode == 0x03) // (enter)
  231015. keyCode = '\r';
  231016. return keyCode;
  231017. }
  231018. static int64 getMouseTime (NSEvent* e)
  231019. {
  231020. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231021. + (int64) ([e timestamp] * 1000.0);
  231022. }
  231023. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231024. {
  231025. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231026. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231027. }
  231028. static int getModifierForButtonNumber (const NSInteger num)
  231029. {
  231030. return num == 0 ? ModifierKeys::leftButtonModifier
  231031. : (num == 1 ? ModifierKeys::rightButtonModifier
  231032. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231033. }
  231034. virtual void viewFocusGain();
  231035. virtual void viewFocusLoss();
  231036. bool isFocused() const;
  231037. void grabFocus();
  231038. void textInputRequired (const Point<int>& position);
  231039. void repaint (const Rectangle<int>& area);
  231040. void performAnyPendingRepaintsNow();
  231041. juce_UseDebuggingNewOperator
  231042. NSWindow* window;
  231043. JuceNSView* view;
  231044. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231045. static ModifierKeys currentModifiers;
  231046. static ComponentPeer* currentlyFocusedPeer;
  231047. static Array<int> keysCurrentlyDown;
  231048. };
  231049. END_JUCE_NAMESPACE
  231050. @implementation JuceNSView
  231051. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231052. withFrame: (NSRect) frame
  231053. {
  231054. [super initWithFrame: frame];
  231055. owner = owner_;
  231056. stringBeingComposed = 0;
  231057. textWasInserted = false;
  231058. notificationCenter = [NSNotificationCenter defaultCenter];
  231059. [notificationCenter addObserver: self
  231060. selector: @selector (frameChanged:)
  231061. name: NSViewFrameDidChangeNotification
  231062. object: self];
  231063. if (! owner_->isSharedWindow)
  231064. {
  231065. [notificationCenter addObserver: self
  231066. selector: @selector (frameChanged:)
  231067. name: NSWindowDidMoveNotification
  231068. object: owner_->window];
  231069. }
  231070. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231071. return self;
  231072. }
  231073. - (void) dealloc
  231074. {
  231075. [notificationCenter removeObserver: self];
  231076. delete stringBeingComposed;
  231077. [super dealloc];
  231078. }
  231079. - (void) drawRect: (NSRect) r
  231080. {
  231081. if (owner != 0)
  231082. owner->drawRect (r);
  231083. }
  231084. - (BOOL) isOpaque
  231085. {
  231086. return owner == 0 || owner->isOpaque();
  231087. }
  231088. - (void) mouseDown: (NSEvent*) ev
  231089. {
  231090. if (JUCEApplication::isStandaloneApp())
  231091. [self asyncMouseDown: ev];
  231092. else
  231093. // In some host situations, the host will stop modal loops from working
  231094. // correctly if they're called from a mouse event, so we'll trigger
  231095. // the event asynchronously..
  231096. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231097. withObject: ev
  231098. waitUntilDone: NO];
  231099. }
  231100. - (void) asyncMouseDown: (NSEvent*) ev
  231101. {
  231102. if (owner != 0)
  231103. owner->redirectMouseDown (ev);
  231104. }
  231105. - (void) mouseUp: (NSEvent*) ev
  231106. {
  231107. if (! JUCEApplication::isStandaloneApp())
  231108. [self asyncMouseUp: ev];
  231109. else
  231110. // In some host situations, the host will stop modal loops from working
  231111. // correctly if they're called from a mouse event, so we'll trigger
  231112. // the event asynchronously..
  231113. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231114. withObject: ev
  231115. waitUntilDone: NO];
  231116. }
  231117. - (void) asyncMouseUp: (NSEvent*) ev
  231118. {
  231119. if (owner != 0)
  231120. owner->redirectMouseUp (ev);
  231121. }
  231122. - (void) mouseDragged: (NSEvent*) ev
  231123. {
  231124. if (owner != 0)
  231125. owner->redirectMouseDrag (ev);
  231126. }
  231127. - (void) mouseMoved: (NSEvent*) ev
  231128. {
  231129. if (owner != 0)
  231130. owner->redirectMouseMove (ev);
  231131. }
  231132. - (void) mouseEntered: (NSEvent*) ev
  231133. {
  231134. if (owner != 0)
  231135. owner->redirectMouseEnter (ev);
  231136. }
  231137. - (void) mouseExited: (NSEvent*) ev
  231138. {
  231139. if (owner != 0)
  231140. owner->redirectMouseExit (ev);
  231141. }
  231142. - (void) rightMouseDown: (NSEvent*) ev
  231143. {
  231144. [self mouseDown: ev];
  231145. }
  231146. - (void) rightMouseDragged: (NSEvent*) ev
  231147. {
  231148. [self mouseDragged: ev];
  231149. }
  231150. - (void) rightMouseUp: (NSEvent*) ev
  231151. {
  231152. [self mouseUp: ev];
  231153. }
  231154. - (void) otherMouseDown: (NSEvent*) ev
  231155. {
  231156. [self mouseDown: ev];
  231157. }
  231158. - (void) otherMouseDragged: (NSEvent*) ev
  231159. {
  231160. [self mouseDragged: ev];
  231161. }
  231162. - (void) otherMouseUp: (NSEvent*) ev
  231163. {
  231164. [self mouseUp: ev];
  231165. }
  231166. - (void) scrollWheel: (NSEvent*) ev
  231167. {
  231168. if (owner != 0)
  231169. owner->redirectMouseWheel (ev);
  231170. }
  231171. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231172. {
  231173. (void) ev;
  231174. return YES;
  231175. }
  231176. - (void) frameChanged: (NSNotification*) n
  231177. {
  231178. (void) n;
  231179. if (owner != 0)
  231180. owner->redirectMovedOrResized();
  231181. }
  231182. - (void) viewDidMoveToWindow
  231183. {
  231184. if (owner != 0)
  231185. owner->viewMovedToWindow();
  231186. }
  231187. - (void) asyncRepaint: (id) rect
  231188. {
  231189. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231190. [self setNeedsDisplayInRect: *r];
  231191. }
  231192. - (void) keyDown: (NSEvent*) ev
  231193. {
  231194. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231195. textWasInserted = false;
  231196. if (target != 0)
  231197. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231198. else
  231199. deleteAndZero (stringBeingComposed);
  231200. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231201. [super keyDown: ev];
  231202. }
  231203. - (void) keyUp: (NSEvent*) ev
  231204. {
  231205. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231206. [super keyUp: ev];
  231207. }
  231208. - (void) insertText: (id) aString
  231209. {
  231210. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231211. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231212. if ([newText length] > 0)
  231213. {
  231214. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231215. if (target != 0)
  231216. {
  231217. target->insertTextAtCaret (nsStringToJuce (newText));
  231218. textWasInserted = true;
  231219. }
  231220. }
  231221. deleteAndZero (stringBeingComposed);
  231222. }
  231223. - (void) doCommandBySelector: (SEL) aSelector
  231224. {
  231225. (void) aSelector;
  231226. }
  231227. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231228. {
  231229. (void) selectionRange;
  231230. if (stringBeingComposed == 0)
  231231. stringBeingComposed = new String();
  231232. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231233. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231234. if (target != 0)
  231235. {
  231236. const Range<int> currentHighlight (target->getHighlightedRegion());
  231237. target->insertTextAtCaret (*stringBeingComposed);
  231238. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231239. textWasInserted = true;
  231240. }
  231241. }
  231242. - (void) unmarkText
  231243. {
  231244. if (stringBeingComposed != 0)
  231245. {
  231246. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231247. if (target != 0)
  231248. {
  231249. target->insertTextAtCaret (*stringBeingComposed);
  231250. textWasInserted = true;
  231251. }
  231252. }
  231253. deleteAndZero (stringBeingComposed);
  231254. }
  231255. - (BOOL) hasMarkedText
  231256. {
  231257. return stringBeingComposed != 0;
  231258. }
  231259. - (long) conversationIdentifier
  231260. {
  231261. return (long) (pointer_sized_int) self;
  231262. }
  231263. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231264. {
  231265. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231266. if (target != 0)
  231267. {
  231268. const Range<int> r ((int) theRange.location,
  231269. (int) (theRange.location + theRange.length));
  231270. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231271. }
  231272. return nil;
  231273. }
  231274. - (NSRange) markedRange
  231275. {
  231276. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231277. : NSMakeRange (NSNotFound, 0);
  231278. }
  231279. - (NSRange) selectedRange
  231280. {
  231281. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231282. if (target != 0)
  231283. {
  231284. const Range<int> highlight (target->getHighlightedRegion());
  231285. if (! highlight.isEmpty())
  231286. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231287. }
  231288. return NSMakeRange (NSNotFound, 0);
  231289. }
  231290. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231291. {
  231292. (void) theRange;
  231293. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231294. if (comp == 0)
  231295. return NSMakeRect (0, 0, 0, 0);
  231296. const Rectangle<int> bounds (comp->getScreenBounds());
  231297. return NSMakeRect (bounds.getX(),
  231298. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231299. bounds.getWidth(),
  231300. bounds.getHeight());
  231301. }
  231302. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231303. {
  231304. (void) thePoint;
  231305. return NSNotFound;
  231306. }
  231307. - (NSArray*) validAttributesForMarkedText
  231308. {
  231309. return [NSArray array];
  231310. }
  231311. - (void) flagsChanged: (NSEvent*) ev
  231312. {
  231313. if (owner != 0)
  231314. owner->redirectModKeyChange (ev);
  231315. }
  231316. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231317. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231318. {
  231319. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231320. return true;
  231321. return [super performKeyEquivalent: ev];
  231322. }
  231323. #endif
  231324. - (BOOL) becomeFirstResponder
  231325. {
  231326. if (owner != 0)
  231327. owner->viewFocusGain();
  231328. return true;
  231329. }
  231330. - (BOOL) resignFirstResponder
  231331. {
  231332. if (owner != 0)
  231333. owner->viewFocusLoss();
  231334. return true;
  231335. }
  231336. - (BOOL) acceptsFirstResponder
  231337. {
  231338. return owner != 0 && owner->canBecomeKeyWindow();
  231339. }
  231340. - (NSArray*) getSupportedDragTypes
  231341. {
  231342. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231343. }
  231344. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231345. {
  231346. return owner != 0 && owner->sendDragCallback (type, sender);
  231347. }
  231348. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231349. {
  231350. if ([self sendDragCallback: 0 sender: sender])
  231351. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231352. else
  231353. return NSDragOperationNone;
  231354. }
  231355. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231356. {
  231357. if ([self sendDragCallback: 0 sender: sender])
  231358. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231359. else
  231360. return NSDragOperationNone;
  231361. }
  231362. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231363. {
  231364. [self sendDragCallback: 1 sender: sender];
  231365. }
  231366. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231367. {
  231368. [self sendDragCallback: 1 sender: sender];
  231369. }
  231370. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231371. {
  231372. (void) sender;
  231373. return YES;
  231374. }
  231375. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231376. {
  231377. return [self sendDragCallback: 2 sender: sender];
  231378. }
  231379. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231380. {
  231381. (void) sender;
  231382. }
  231383. @end
  231384. @implementation JuceNSWindow
  231385. - (void) setOwner: (NSViewComponentPeer*) owner_
  231386. {
  231387. owner = owner_;
  231388. isZooming = false;
  231389. }
  231390. - (BOOL) canBecomeKeyWindow
  231391. {
  231392. return owner != 0 && owner->canBecomeKeyWindow();
  231393. }
  231394. - (void) becomeKeyWindow
  231395. {
  231396. [super becomeKeyWindow];
  231397. if (owner != 0)
  231398. owner->grabFocus();
  231399. }
  231400. - (BOOL) windowShouldClose: (id) window
  231401. {
  231402. (void) window;
  231403. return owner == 0 || owner->windowShouldClose();
  231404. }
  231405. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231406. {
  231407. (void) screen;
  231408. if (owner != 0)
  231409. frameRect = owner->constrainRect (frameRect);
  231410. return frameRect;
  231411. }
  231412. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231413. {
  231414. (void) window;
  231415. if (isZooming)
  231416. return proposedFrameSize;
  231417. NSRect frameRect = [self frame];
  231418. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231419. frameRect.size = proposedFrameSize;
  231420. if (owner != 0)
  231421. frameRect = owner->constrainRect (frameRect);
  231422. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231423. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231424. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231425. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231426. return frameRect.size;
  231427. }
  231428. - (void) zoom: (id) sender
  231429. {
  231430. isZooming = true;
  231431. [super zoom: sender];
  231432. isZooming = false;
  231433. }
  231434. - (void) windowWillMove: (NSNotification*) notification
  231435. {
  231436. (void) notification;
  231437. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231438. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231439. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231440. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231441. }
  231442. @end
  231443. BEGIN_JUCE_NAMESPACE
  231444. ModifierKeys NSViewComponentPeer::currentModifiers;
  231445. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231446. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231447. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231448. {
  231449. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231450. return true;
  231451. if (keyCode >= 'A' && keyCode <= 'Z'
  231452. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231453. return true;
  231454. if (keyCode >= 'a' && keyCode <= 'z'
  231455. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231456. return true;
  231457. return false;
  231458. }
  231459. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231460. {
  231461. int m = 0;
  231462. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231463. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231464. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231465. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231466. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231467. }
  231468. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231469. {
  231470. updateModifiers (ev);
  231471. int keyCode = getKeyCodeFromEvent (ev);
  231472. if (keyCode != 0)
  231473. {
  231474. if (isKeyDown)
  231475. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231476. else
  231477. keysCurrentlyDown.removeValue (keyCode);
  231478. }
  231479. }
  231480. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231481. {
  231482. return NSViewComponentPeer::currentModifiers;
  231483. }
  231484. void ModifierKeys::updateCurrentModifiers() throw()
  231485. {
  231486. currentModifiers = NSViewComponentPeer::currentModifiers;
  231487. }
  231488. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231489. const int windowStyleFlags,
  231490. NSView* viewToAttachTo)
  231491. : ComponentPeer (component_, windowStyleFlags),
  231492. window (0),
  231493. view (0),
  231494. isSharedWindow (viewToAttachTo != 0),
  231495. fullScreen (false),
  231496. insideDrawRect (false),
  231497. #if USE_COREGRAPHICS_RENDERING
  231498. usingCoreGraphics (true),
  231499. #else
  231500. usingCoreGraphics (false),
  231501. #endif
  231502. recursiveToFrontCall (false)
  231503. {
  231504. NSRect r;
  231505. r.origin.x = 0;
  231506. r.origin.y = 0;
  231507. r.size.width = (float) component->getWidth();
  231508. r.size.height = (float) component->getHeight();
  231509. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231510. [view setPostsFrameChangedNotifications: YES];
  231511. if (isSharedWindow)
  231512. {
  231513. window = [viewToAttachTo window];
  231514. [viewToAttachTo addSubview: view];
  231515. setVisible (component->isVisible());
  231516. }
  231517. else
  231518. {
  231519. r.origin.x = (float) component->getX();
  231520. r.origin.y = (float) component->getY();
  231521. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231522. unsigned int style = 0;
  231523. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231524. style = NSBorderlessWindowMask;
  231525. else
  231526. style = NSTitledWindowMask;
  231527. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231528. style |= NSMiniaturizableWindowMask;
  231529. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231530. style |= NSClosableWindowMask;
  231531. if ((windowStyleFlags & windowIsResizable) != 0)
  231532. style |= NSResizableWindowMask;
  231533. window = [[JuceNSWindow alloc] initWithContentRect: r
  231534. styleMask: style
  231535. backing: NSBackingStoreBuffered
  231536. defer: YES];
  231537. [((JuceNSWindow*) window) setOwner: this];
  231538. [window orderOut: nil];
  231539. [window setDelegate: (JuceNSWindow*) window];
  231540. [window setOpaque: component->isOpaque()];
  231541. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231542. if (component->isAlwaysOnTop())
  231543. [window setLevel: NSFloatingWindowLevel];
  231544. [window setContentView: view];
  231545. [window setAutodisplay: YES];
  231546. [window setAcceptsMouseMovedEvents: YES];
  231547. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231548. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231549. [window setReleasedWhenClosed: YES];
  231550. [window retain];
  231551. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231552. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231553. }
  231554. setTitle (component->getName());
  231555. }
  231556. NSViewComponentPeer::~NSViewComponentPeer()
  231557. {
  231558. view->owner = 0;
  231559. [view removeFromSuperview];
  231560. [view release];
  231561. if (! isSharedWindow)
  231562. {
  231563. [((JuceNSWindow*) window) setOwner: 0];
  231564. [window close];
  231565. [window release];
  231566. }
  231567. }
  231568. void* NSViewComponentPeer::getNativeHandle() const
  231569. {
  231570. return view;
  231571. }
  231572. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231573. {
  231574. if (isSharedWindow)
  231575. {
  231576. [view setHidden: ! shouldBeVisible];
  231577. }
  231578. else
  231579. {
  231580. if (shouldBeVisible)
  231581. {
  231582. [window orderFront: nil];
  231583. handleBroughtToFront();
  231584. }
  231585. else
  231586. {
  231587. [window orderOut: nil];
  231588. }
  231589. }
  231590. }
  231591. void NSViewComponentPeer::setTitle (const String& title)
  231592. {
  231593. const ScopedAutoReleasePool pool;
  231594. if (! isSharedWindow)
  231595. [window setTitle: juceStringToNS (title)];
  231596. }
  231597. void NSViewComponentPeer::setPosition (int x, int y)
  231598. {
  231599. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231600. }
  231601. void NSViewComponentPeer::setSize (int w, int h)
  231602. {
  231603. setBounds (component->getX(), component->getY(), w, h, false);
  231604. }
  231605. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231606. {
  231607. fullScreen = isNowFullScreen;
  231608. w = jmax (0, w);
  231609. h = jmax (0, h);
  231610. NSRect r;
  231611. r.origin.x = (float) x;
  231612. r.origin.y = (float) y;
  231613. r.size.width = (float) w;
  231614. r.size.height = (float) h;
  231615. if (isSharedWindow)
  231616. {
  231617. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231618. if ([view frame].size.width != r.size.width
  231619. || [view frame].size.height != r.size.height)
  231620. [view setNeedsDisplay: true];
  231621. [view setFrame: r];
  231622. }
  231623. else
  231624. {
  231625. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231626. [window setFrame: [window frameRectForContentRect: r]
  231627. display: true];
  231628. }
  231629. }
  231630. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231631. {
  231632. NSRect r = [view frame];
  231633. if (global && [view window] != 0)
  231634. {
  231635. r = [view convertRect: r toView: nil];
  231636. NSRect wr = [[view window] frame];
  231637. r.origin.x += wr.origin.x;
  231638. r.origin.y += wr.origin.y;
  231639. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231640. }
  231641. else
  231642. {
  231643. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231644. }
  231645. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  231646. }
  231647. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231648. {
  231649. return getBounds (! isSharedWindow);
  231650. }
  231651. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231652. {
  231653. return getBounds (true).getPosition();
  231654. }
  231655. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  231656. {
  231657. return relativePosition + getScreenPosition();
  231658. }
  231659. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  231660. {
  231661. return screenPosition - getScreenPosition();
  231662. }
  231663. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231664. {
  231665. if (constrainer != 0)
  231666. {
  231667. NSRect current = [window frame];
  231668. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231669. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231670. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  231671. (int) r.size.width, (int) r.size.height);
  231672. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  231673. (int) current.size.width, (int) current.size.height);
  231674. constrainer->checkBounds (pos, original,
  231675. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231676. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231677. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231678. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231679. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231680. r.origin.x = pos.getX();
  231681. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231682. r.size.width = pos.getWidth();
  231683. r.size.height = pos.getHeight();
  231684. }
  231685. return r;
  231686. }
  231687. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231688. {
  231689. if (! isSharedWindow)
  231690. {
  231691. if (shouldBeMinimised)
  231692. [window miniaturize: nil];
  231693. else
  231694. [window deminiaturize: nil];
  231695. }
  231696. }
  231697. bool NSViewComponentPeer::isMinimised() const
  231698. {
  231699. return window != 0 && [window isMiniaturized];
  231700. }
  231701. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231702. {
  231703. if (! isSharedWindow)
  231704. {
  231705. Rectangle<int> r (lastNonFullscreenBounds);
  231706. setMinimised (false);
  231707. if (fullScreen != shouldBeFullScreen)
  231708. {
  231709. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231710. {
  231711. fullScreen = true;
  231712. [window performZoom: nil];
  231713. }
  231714. else
  231715. {
  231716. if (shouldBeFullScreen)
  231717. r = Desktop::getInstance().getMainMonitorArea();
  231718. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231719. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231720. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231721. }
  231722. }
  231723. }
  231724. }
  231725. bool NSViewComponentPeer::isFullScreen() const
  231726. {
  231727. return fullScreen;
  231728. }
  231729. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231730. {
  231731. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  231732. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  231733. return false;
  231734. NSPoint p;
  231735. p.x = (float) position.getX();
  231736. p.y = (float) position.getY();
  231737. NSView* v = [view hitTest: p];
  231738. if (trueIfInAChildWindow)
  231739. return v != nil;
  231740. return v == view;
  231741. }
  231742. const BorderSize NSViewComponentPeer::getFrameSize() const
  231743. {
  231744. BorderSize b;
  231745. if (! isSharedWindow)
  231746. {
  231747. NSRect v = [view convertRect: [view frame] toView: nil];
  231748. NSRect w = [window frame];
  231749. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231750. b.setBottom ((int) v.origin.y);
  231751. b.setLeft ((int) v.origin.x);
  231752. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231753. }
  231754. return b;
  231755. }
  231756. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231757. {
  231758. if (! isSharedWindow)
  231759. {
  231760. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231761. : NSNormalWindowLevel];
  231762. }
  231763. return true;
  231764. }
  231765. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231766. {
  231767. if (isSharedWindow)
  231768. {
  231769. [[view superview] addSubview: view
  231770. positioned: NSWindowAbove
  231771. relativeTo: nil];
  231772. }
  231773. if (window != 0 && component->isVisible())
  231774. {
  231775. if (makeActiveWindow)
  231776. [window makeKeyAndOrderFront: nil];
  231777. else
  231778. [window orderFront: nil];
  231779. if (! recursiveToFrontCall)
  231780. {
  231781. recursiveToFrontCall = true;
  231782. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231783. handleBroughtToFront();
  231784. recursiveToFrontCall = false;
  231785. }
  231786. }
  231787. }
  231788. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231789. {
  231790. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231791. jassert (otherPeer != 0); // wrong type of window?
  231792. if (otherPeer != 0)
  231793. {
  231794. if (isSharedWindow)
  231795. {
  231796. [[view superview] addSubview: view
  231797. positioned: NSWindowBelow
  231798. relativeTo: otherPeer->view];
  231799. }
  231800. else
  231801. {
  231802. [window orderWindow: NSWindowBelow
  231803. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231804. : nil ];
  231805. }
  231806. }
  231807. }
  231808. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231809. {
  231810. // to do..
  231811. }
  231812. void NSViewComponentPeer::viewFocusGain()
  231813. {
  231814. if (currentlyFocusedPeer != this)
  231815. {
  231816. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231817. currentlyFocusedPeer->handleFocusLoss();
  231818. currentlyFocusedPeer = this;
  231819. handleFocusGain();
  231820. }
  231821. }
  231822. void NSViewComponentPeer::viewFocusLoss()
  231823. {
  231824. if (currentlyFocusedPeer == this)
  231825. {
  231826. currentlyFocusedPeer = 0;
  231827. handleFocusLoss();
  231828. }
  231829. }
  231830. void juce_HandleProcessFocusChange()
  231831. {
  231832. NSViewComponentPeer::keysCurrentlyDown.clear();
  231833. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231834. {
  231835. if (Process::isForegroundProcess())
  231836. {
  231837. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231838. ComponentPeer::bringModalComponentToFront();
  231839. }
  231840. else
  231841. {
  231842. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231843. // turn kiosk mode off if we lose focus..
  231844. Desktop::getInstance().setKioskModeComponent (0);
  231845. }
  231846. }
  231847. }
  231848. bool NSViewComponentPeer::isFocused() const
  231849. {
  231850. return isSharedWindow ? this == currentlyFocusedPeer
  231851. : (window != 0 && [window isKeyWindow]);
  231852. }
  231853. void NSViewComponentPeer::grabFocus()
  231854. {
  231855. if (window != 0)
  231856. {
  231857. [window makeKeyWindow];
  231858. [window makeFirstResponder: view];
  231859. viewFocusGain();
  231860. }
  231861. }
  231862. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231863. {
  231864. }
  231865. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231866. {
  231867. String unicode (nsStringToJuce ([ev characters]));
  231868. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231869. int keyCode = getKeyCodeFromEvent (ev);
  231870. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231871. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231872. if (unicode.isNotEmpty() || keyCode != 0)
  231873. {
  231874. if (isKeyDown)
  231875. {
  231876. bool used = false;
  231877. while (unicode.length() > 0)
  231878. {
  231879. juce_wchar textCharacter = unicode[0];
  231880. unicode = unicode.substring (1);
  231881. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231882. textCharacter = 0;
  231883. used = handleKeyUpOrDown (true) || used;
  231884. used = handleKeyPress (keyCode, textCharacter) || used;
  231885. }
  231886. return used;
  231887. }
  231888. else
  231889. {
  231890. if (handleKeyUpOrDown (false))
  231891. return true;
  231892. }
  231893. }
  231894. return false;
  231895. }
  231896. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231897. {
  231898. updateKeysDown (ev, true);
  231899. bool used = handleKeyEvent (ev, true);
  231900. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231901. {
  231902. // for command keys, the key-up event is thrown away, so simulate one..
  231903. updateKeysDown (ev, false);
  231904. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231905. }
  231906. // (If we're running modally, don't allow unused keystrokes to be passed
  231907. // along to other blocked views..)
  231908. if (Component::getCurrentlyModalComponent() != 0)
  231909. used = true;
  231910. return used;
  231911. }
  231912. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231913. {
  231914. updateKeysDown (ev, false);
  231915. return handleKeyEvent (ev, false)
  231916. || Component::getCurrentlyModalComponent() != 0;
  231917. }
  231918. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231919. {
  231920. keysCurrentlyDown.clear();
  231921. handleKeyUpOrDown (true);
  231922. updateModifiers (ev);
  231923. handleModifierKeysChange();
  231924. }
  231925. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231926. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231927. {
  231928. if ([ev type] == NSKeyDown)
  231929. return redirectKeyDown (ev);
  231930. else if ([ev type] == NSKeyUp)
  231931. return redirectKeyUp (ev);
  231932. return false;
  231933. }
  231934. #endif
  231935. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231936. {
  231937. updateModifiers (ev);
  231938. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231939. }
  231940. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231941. {
  231942. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231943. sendMouseEvent (ev);
  231944. }
  231945. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231946. {
  231947. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231948. sendMouseEvent (ev);
  231949. showArrowCursorIfNeeded();
  231950. }
  231951. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231952. {
  231953. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231954. sendMouseEvent (ev);
  231955. }
  231956. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231957. {
  231958. currentModifiers = currentModifiers.withoutMouseButtons();
  231959. sendMouseEvent (ev);
  231960. showArrowCursorIfNeeded();
  231961. }
  231962. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231963. {
  231964. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231965. currentModifiers = currentModifiers.withoutMouseButtons();
  231966. sendMouseEvent (ev);
  231967. }
  231968. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231969. {
  231970. currentModifiers = currentModifiers.withoutMouseButtons();
  231971. sendMouseEvent (ev);
  231972. }
  231973. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231974. {
  231975. updateModifiers (ev);
  231976. float x = 0, y = 0;
  231977. @try
  231978. {
  231979. x = [ev deviceDeltaX] * 0.5f;
  231980. y = [ev deviceDeltaY] * 0.5f;
  231981. }
  231982. @catch (...)
  231983. {}
  231984. if (x == 0 && y == 0)
  231985. {
  231986. x = [ev deltaX] * 10.0f;
  231987. y = [ev deltaY] * 10.0f;
  231988. }
  231989. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231990. }
  231991. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231992. {
  231993. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231994. if (mouse.getComponentUnderMouse() == 0
  231995. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231996. {
  231997. [[NSCursor arrowCursor] set];
  231998. }
  231999. }
  232000. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232001. {
  232002. NSString* bestType
  232003. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232004. if (bestType == nil)
  232005. return false;
  232006. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232007. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232008. StringArray files;
  232009. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232010. if (list == nil)
  232011. return false;
  232012. if ([list isKindOfClass: [NSArray class]])
  232013. {
  232014. NSArray* items = (NSArray*) list;
  232015. for (unsigned int i = 0; i < [items count]; ++i)
  232016. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232017. }
  232018. if (files.size() == 0)
  232019. return false;
  232020. if (type == 0)
  232021. handleFileDragMove (files, pos);
  232022. else if (type == 1)
  232023. handleFileDragExit (files);
  232024. else if (type == 2)
  232025. handleFileDragDrop (files, pos);
  232026. return true;
  232027. }
  232028. bool NSViewComponentPeer::isOpaque()
  232029. {
  232030. return component == 0 || component->isOpaque();
  232031. }
  232032. void NSViewComponentPeer::drawRect (NSRect r)
  232033. {
  232034. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232035. return;
  232036. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232037. if (! component->isOpaque())
  232038. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232039. #if USE_COREGRAPHICS_RENDERING
  232040. if (usingCoreGraphics)
  232041. {
  232042. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232043. insideDrawRect = true;
  232044. handlePaint (context);
  232045. insideDrawRect = false;
  232046. }
  232047. else
  232048. #endif
  232049. {
  232050. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232051. (int) (r.size.width + 0.5f),
  232052. (int) (r.size.height + 0.5f),
  232053. ! getComponent()->isOpaque());
  232054. const int xOffset = -roundToInt (r.origin.x);
  232055. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232056. const NSRect* rects = 0;
  232057. NSInteger numRects = 0;
  232058. [view getRectsBeingDrawn: &rects count: &numRects];
  232059. const Rectangle<int> clipBounds (temp.getBounds());
  232060. RectangleList clip;
  232061. for (int i = 0; i < numRects; ++i)
  232062. {
  232063. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232064. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232065. roundToInt (rects[i].size.width),
  232066. roundToInt (rects[i].size.height))));
  232067. }
  232068. if (! clip.isEmpty())
  232069. {
  232070. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232071. insideDrawRect = true;
  232072. handlePaint (context);
  232073. insideDrawRect = false;
  232074. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232075. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232076. CGColorSpaceRelease (colourSpace);
  232077. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232078. CGImageRelease (image);
  232079. }
  232080. }
  232081. }
  232082. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232083. {
  232084. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232085. #if USE_COREGRAPHICS_RENDERING
  232086. s.add ("CoreGraphics Renderer");
  232087. #endif
  232088. return s;
  232089. }
  232090. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232091. {
  232092. return usingCoreGraphics ? 1 : 0;
  232093. }
  232094. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232095. {
  232096. #if USE_COREGRAPHICS_RENDERING
  232097. if (usingCoreGraphics != (index > 0))
  232098. {
  232099. usingCoreGraphics = index > 0;
  232100. [view setNeedsDisplay: true];
  232101. }
  232102. #endif
  232103. }
  232104. bool NSViewComponentPeer::canBecomeKeyWindow()
  232105. {
  232106. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232107. }
  232108. bool NSViewComponentPeer::windowShouldClose()
  232109. {
  232110. if (! isValidPeer (this))
  232111. return YES;
  232112. handleUserClosingWindow();
  232113. return NO;
  232114. }
  232115. void NSViewComponentPeer::redirectMovedOrResized()
  232116. {
  232117. handleMovedOrResized();
  232118. }
  232119. void NSViewComponentPeer::viewMovedToWindow()
  232120. {
  232121. if (isSharedWindow)
  232122. window = [view window];
  232123. }
  232124. void Desktop::createMouseInputSources()
  232125. {
  232126. mouseSources.add (new MouseInputSource (0, true));
  232127. }
  232128. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232129. {
  232130. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232131. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232132. // is apparently still available in 64-bit apps..
  232133. if (enableOrDisable)
  232134. {
  232135. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232136. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232137. }
  232138. else
  232139. {
  232140. SetSystemUIMode (kUIModeNormal, 0);
  232141. }
  232142. }
  232143. class AsyncRepaintMessage : public CallbackMessage
  232144. {
  232145. public:
  232146. NSViewComponentPeer* const peer;
  232147. const Rectangle<int> rect;
  232148. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232149. : peer (peer_), rect (rect_)
  232150. {
  232151. }
  232152. void messageCallback()
  232153. {
  232154. if (ComponentPeer::isValidPeer (peer))
  232155. peer->repaint (rect);
  232156. }
  232157. };
  232158. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232159. {
  232160. if (insideDrawRect)
  232161. {
  232162. (new AsyncRepaintMessage (this, area))->post();
  232163. }
  232164. else
  232165. {
  232166. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232167. (float) area.getWidth(), (float) area.getHeight())];
  232168. }
  232169. }
  232170. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232171. {
  232172. [view displayIfNeeded];
  232173. }
  232174. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232175. {
  232176. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232177. }
  232178. const Image juce_createIconForFile (const File& file)
  232179. {
  232180. const ScopedAutoReleasePool pool;
  232181. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232182. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232183. [NSGraphicsContext saveGraphicsState];
  232184. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232185. [image drawAtPoint: NSMakePoint (0, 0)
  232186. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232187. operation: NSCompositeSourceOver fraction: 1.0f];
  232188. [[NSGraphicsContext currentContext] flushGraphics];
  232189. [NSGraphicsContext restoreGraphicsState];
  232190. return Image (result);
  232191. }
  232192. const int KeyPress::spaceKey = ' ';
  232193. const int KeyPress::returnKey = 0x0d;
  232194. const int KeyPress::escapeKey = 0x1b;
  232195. const int KeyPress::backspaceKey = 0x7f;
  232196. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232197. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232198. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232199. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232200. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232201. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232202. const int KeyPress::endKey = NSEndFunctionKey;
  232203. const int KeyPress::homeKey = NSHomeFunctionKey;
  232204. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232205. const int KeyPress::insertKey = -1;
  232206. const int KeyPress::tabKey = 9;
  232207. const int KeyPress::F1Key = NSF1FunctionKey;
  232208. const int KeyPress::F2Key = NSF2FunctionKey;
  232209. const int KeyPress::F3Key = NSF3FunctionKey;
  232210. const int KeyPress::F4Key = NSF4FunctionKey;
  232211. const int KeyPress::F5Key = NSF5FunctionKey;
  232212. const int KeyPress::F6Key = NSF6FunctionKey;
  232213. const int KeyPress::F7Key = NSF7FunctionKey;
  232214. const int KeyPress::F8Key = NSF8FunctionKey;
  232215. const int KeyPress::F9Key = NSF9FunctionKey;
  232216. const int KeyPress::F10Key = NSF10FunctionKey;
  232217. const int KeyPress::F11Key = NSF1FunctionKey;
  232218. const int KeyPress::F12Key = NSF12FunctionKey;
  232219. const int KeyPress::F13Key = NSF13FunctionKey;
  232220. const int KeyPress::F14Key = NSF14FunctionKey;
  232221. const int KeyPress::F15Key = NSF15FunctionKey;
  232222. const int KeyPress::F16Key = NSF16FunctionKey;
  232223. const int KeyPress::numberPad0 = 0x30020;
  232224. const int KeyPress::numberPad1 = 0x30021;
  232225. const int KeyPress::numberPad2 = 0x30022;
  232226. const int KeyPress::numberPad3 = 0x30023;
  232227. const int KeyPress::numberPad4 = 0x30024;
  232228. const int KeyPress::numberPad5 = 0x30025;
  232229. const int KeyPress::numberPad6 = 0x30026;
  232230. const int KeyPress::numberPad7 = 0x30027;
  232231. const int KeyPress::numberPad8 = 0x30028;
  232232. const int KeyPress::numberPad9 = 0x30029;
  232233. const int KeyPress::numberPadAdd = 0x3002a;
  232234. const int KeyPress::numberPadSubtract = 0x3002b;
  232235. const int KeyPress::numberPadMultiply = 0x3002c;
  232236. const int KeyPress::numberPadDivide = 0x3002d;
  232237. const int KeyPress::numberPadSeparator = 0x3002e;
  232238. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232239. const int KeyPress::numberPadEquals = 0x30030;
  232240. const int KeyPress::numberPadDelete = 0x30031;
  232241. const int KeyPress::playKey = 0x30000;
  232242. const int KeyPress::stopKey = 0x30001;
  232243. const int KeyPress::fastForwardKey = 0x30002;
  232244. const int KeyPress::rewindKey = 0x30003;
  232245. #endif
  232246. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232247. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232248. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232249. // compiled on its own).
  232250. #if JUCE_INCLUDED_FILE
  232251. #if JUCE_MAC
  232252. namespace MouseCursorHelpers
  232253. {
  232254. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232255. {
  232256. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232257. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232258. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232259. [im release];
  232260. return c;
  232261. }
  232262. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232263. {
  232264. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232265. BufferedInputStream buf (&fileStream, 4096, false);
  232266. PNGImageFormat pngFormat;
  232267. Image im (pngFormat.decodeImage (buf));
  232268. if (im.isValid())
  232269. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232270. jassertfalse;
  232271. return 0;
  232272. }
  232273. }
  232274. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232275. {
  232276. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232277. }
  232278. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232279. {
  232280. const ScopedAutoReleasePool pool;
  232281. NSCursor* c = 0;
  232282. switch (type)
  232283. {
  232284. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232285. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232286. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232287. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232288. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232289. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232290. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232291. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232292. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232293. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232294. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232295. case UpDownResizeCursor:
  232296. case TopEdgeResizeCursor:
  232297. case BottomEdgeResizeCursor:
  232298. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232299. case TopLeftCornerResizeCursor:
  232300. case BottomRightCornerResizeCursor:
  232301. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232302. case TopRightCornerResizeCursor:
  232303. case BottomLeftCornerResizeCursor:
  232304. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232305. case UpDownLeftRightResizeCursor:
  232306. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232307. default:
  232308. jassertfalse;
  232309. break;
  232310. }
  232311. [c retain];
  232312. return c;
  232313. }
  232314. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232315. {
  232316. [((NSCursor*) cursorHandle) release];
  232317. }
  232318. void MouseCursor::showInAllWindows() const
  232319. {
  232320. showInWindow (0);
  232321. }
  232322. void MouseCursor::showInWindow (ComponentPeer*) const
  232323. {
  232324. [((NSCursor*) getHandle()) set];
  232325. }
  232326. #else
  232327. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232328. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232329. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232330. void MouseCursor::showInAllWindows() const {}
  232331. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232332. #endif
  232333. #endif
  232334. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232335. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232336. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232337. // compiled on its own).
  232338. #if JUCE_INCLUDED_FILE
  232339. class NSViewComponentInternal : public ComponentMovementWatcher
  232340. {
  232341. Component* const owner;
  232342. NSViewComponentPeer* currentPeer;
  232343. bool wasShowing;
  232344. public:
  232345. NSView* const view;
  232346. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232347. : ComponentMovementWatcher (owner_),
  232348. owner (owner_),
  232349. currentPeer (0),
  232350. wasShowing (false),
  232351. view (view_)
  232352. {
  232353. [view_ retain];
  232354. if (owner_->isShowing())
  232355. componentPeerChanged();
  232356. }
  232357. ~NSViewComponentInternal()
  232358. {
  232359. [view removeFromSuperview];
  232360. [view release];
  232361. }
  232362. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232363. {
  232364. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232365. // The ComponentMovementWatcher version of this method avoids calling
  232366. // us when the top-level comp is resized, but for an NSView we need to know this
  232367. // because with inverted co-ords, we need to update the position even if the
  232368. // top-left pos hasn't changed
  232369. if (comp.isOnDesktop() && wasResized)
  232370. componentMovedOrResized (wasMoved, wasResized);
  232371. }
  232372. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232373. {
  232374. Component* const topComp = owner->getTopLevelComponent();
  232375. if (topComp->getPeer() != 0)
  232376. {
  232377. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232378. NSRect r;
  232379. r.origin.x = (float) pos.getX();
  232380. r.origin.y = (float) pos.getY();
  232381. r.size.width = (float) owner->getWidth();
  232382. r.size.height = (float) owner->getHeight();
  232383. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232384. [view setFrame: r];
  232385. }
  232386. }
  232387. void componentPeerChanged()
  232388. {
  232389. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232390. if (currentPeer != peer)
  232391. {
  232392. [view removeFromSuperview];
  232393. currentPeer = peer;
  232394. if (peer != 0)
  232395. {
  232396. [peer->view addSubview: view];
  232397. componentMovedOrResized (false, false);
  232398. }
  232399. }
  232400. [view setHidden: ! owner->isShowing()];
  232401. }
  232402. void componentVisibilityChanged (Component&)
  232403. {
  232404. componentPeerChanged();
  232405. }
  232406. juce_UseDebuggingNewOperator
  232407. private:
  232408. NSViewComponentInternal (const NSViewComponentInternal&);
  232409. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232410. };
  232411. NSViewComponent::NSViewComponent()
  232412. {
  232413. }
  232414. NSViewComponent::~NSViewComponent()
  232415. {
  232416. }
  232417. void NSViewComponent::setView (void* view)
  232418. {
  232419. if (view != getView())
  232420. {
  232421. if (view != 0)
  232422. info = new NSViewComponentInternal ((NSView*) view, this);
  232423. else
  232424. info = 0;
  232425. }
  232426. }
  232427. void* NSViewComponent::getView() const
  232428. {
  232429. return info == 0 ? 0 : info->view;
  232430. }
  232431. void NSViewComponent::paint (Graphics&)
  232432. {
  232433. }
  232434. #endif
  232435. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232436. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232437. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232438. // compiled on its own).
  232439. #if JUCE_INCLUDED_FILE
  232440. AppleRemoteDevice::AppleRemoteDevice()
  232441. : device (0),
  232442. queue (0),
  232443. remoteId (0)
  232444. {
  232445. }
  232446. AppleRemoteDevice::~AppleRemoteDevice()
  232447. {
  232448. stop();
  232449. }
  232450. static io_object_t getAppleRemoteDevice()
  232451. {
  232452. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232453. io_iterator_t iter = 0;
  232454. io_object_t iod = 0;
  232455. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232456. && iter != 0)
  232457. {
  232458. iod = IOIteratorNext (iter);
  232459. }
  232460. IOObjectRelease (iter);
  232461. return iod;
  232462. }
  232463. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  232464. {
  232465. jassert (*device == 0);
  232466. io_name_t classname;
  232467. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232468. {
  232469. IOCFPlugInInterface** cfPlugInInterface = 0;
  232470. SInt32 score = 0;
  232471. if (IOCreatePlugInInterfaceForService (iod,
  232472. kIOHIDDeviceUserClientTypeID,
  232473. kIOCFPlugInInterfaceID,
  232474. &cfPlugInInterface,
  232475. &score) == kIOReturnSuccess)
  232476. {
  232477. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232478. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232479. device);
  232480. (void) hr;
  232481. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232482. }
  232483. }
  232484. return *device != 0;
  232485. }
  232486. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232487. {
  232488. if (queue != 0)
  232489. return true;
  232490. stop();
  232491. bool result = false;
  232492. io_object_t iod = getAppleRemoteDevice();
  232493. if (iod != 0)
  232494. {
  232495. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232496. result = true;
  232497. else
  232498. stop();
  232499. IOObjectRelease (iod);
  232500. }
  232501. return result;
  232502. }
  232503. void AppleRemoteDevice::stop()
  232504. {
  232505. if (queue != 0)
  232506. {
  232507. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232508. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232509. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232510. queue = 0;
  232511. }
  232512. if (device != 0)
  232513. {
  232514. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232515. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232516. device = 0;
  232517. }
  232518. }
  232519. bool AppleRemoteDevice::isActive() const
  232520. {
  232521. return queue != 0;
  232522. }
  232523. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232524. {
  232525. if (result == kIOReturnSuccess)
  232526. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232527. }
  232528. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232529. {
  232530. Array <int> cookies;
  232531. CFArrayRef elements;
  232532. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232533. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232534. return false;
  232535. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232536. {
  232537. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232538. // get the cookie
  232539. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232540. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232541. continue;
  232542. long number;
  232543. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232544. continue;
  232545. cookies.add ((int) number);
  232546. }
  232547. CFRelease (elements);
  232548. if ((*(IOHIDDeviceInterface**) device)
  232549. ->open ((IOHIDDeviceInterface**) device,
  232550. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232551. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232552. {
  232553. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232554. if (queue != 0)
  232555. {
  232556. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232557. for (int i = 0; i < cookies.size(); ++i)
  232558. {
  232559. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232560. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232561. }
  232562. CFRunLoopSourceRef eventSource;
  232563. if ((*(IOHIDQueueInterface**) queue)
  232564. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232565. {
  232566. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232567. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232568. {
  232569. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232570. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232571. return true;
  232572. }
  232573. }
  232574. }
  232575. }
  232576. return false;
  232577. }
  232578. void AppleRemoteDevice::handleCallbackInternal()
  232579. {
  232580. int totalValues = 0;
  232581. AbsoluteTime nullTime = { 0, 0 };
  232582. char cookies [12];
  232583. int numCookies = 0;
  232584. while (numCookies < numElementsInArray (cookies))
  232585. {
  232586. IOHIDEventStruct e;
  232587. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232588. break;
  232589. if ((int) e.elementCookie == 19)
  232590. {
  232591. remoteId = e.value;
  232592. buttonPressed (switched, false);
  232593. }
  232594. else
  232595. {
  232596. totalValues += e.value;
  232597. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232598. }
  232599. }
  232600. cookies [numCookies++] = 0;
  232601. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232602. static const char buttonPatterns[] =
  232603. {
  232604. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232605. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232606. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232607. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232608. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232609. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232610. 0x1f, 0x12, 0x04, 0x02, 0,
  232611. 0x1f, 0x12, 0x03, 0x02, 0,
  232612. 0x1f, 0x12, 0x1f, 0x12, 0,
  232613. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232614. 19, 0
  232615. };
  232616. int buttonNum = (int) menuButton;
  232617. int i = 0;
  232618. while (i < numElementsInArray (buttonPatterns))
  232619. {
  232620. if (strcmp (cookies, buttonPatterns + i) == 0)
  232621. {
  232622. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232623. break;
  232624. }
  232625. i += (int) strlen (buttonPatterns + i) + 1;
  232626. ++buttonNum;
  232627. }
  232628. }
  232629. #endif
  232630. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232631. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232632. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232633. // compiled on its own).
  232634. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232635. #if JUCE_MAC
  232636. END_JUCE_NAMESPACE
  232637. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232638. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232639. {
  232640. CriticalSection* contextLock;
  232641. bool needsUpdate;
  232642. }
  232643. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232644. - (bool) makeActive;
  232645. - (void) makeInactive;
  232646. - (void) reshape;
  232647. @end
  232648. @implementation ThreadSafeNSOpenGLView
  232649. - (id) initWithFrame: (NSRect) frameRect
  232650. pixelFormat: (NSOpenGLPixelFormat*) format
  232651. {
  232652. contextLock = new CriticalSection();
  232653. self = [super initWithFrame: frameRect pixelFormat: format];
  232654. if (self != nil)
  232655. [[NSNotificationCenter defaultCenter] addObserver: self
  232656. selector: @selector (_surfaceNeedsUpdate:)
  232657. name: NSViewGlobalFrameDidChangeNotification
  232658. object: self];
  232659. return self;
  232660. }
  232661. - (void) dealloc
  232662. {
  232663. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232664. delete contextLock;
  232665. [super dealloc];
  232666. }
  232667. - (bool) makeActive
  232668. {
  232669. const ScopedLock sl (*contextLock);
  232670. if ([self openGLContext] == 0)
  232671. return false;
  232672. [[self openGLContext] makeCurrentContext];
  232673. if (needsUpdate)
  232674. {
  232675. [super update];
  232676. needsUpdate = false;
  232677. }
  232678. return true;
  232679. }
  232680. - (void) makeInactive
  232681. {
  232682. const ScopedLock sl (*contextLock);
  232683. [NSOpenGLContext clearCurrentContext];
  232684. }
  232685. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232686. {
  232687. const ScopedLock sl (*contextLock);
  232688. needsUpdate = true;
  232689. }
  232690. - (void) update
  232691. {
  232692. const ScopedLock sl (*contextLock);
  232693. needsUpdate = true;
  232694. }
  232695. - (void) reshape
  232696. {
  232697. const ScopedLock sl (*contextLock);
  232698. needsUpdate = true;
  232699. }
  232700. @end
  232701. BEGIN_JUCE_NAMESPACE
  232702. class WindowedGLContext : public OpenGLContext
  232703. {
  232704. public:
  232705. WindowedGLContext (Component* const component,
  232706. const OpenGLPixelFormat& pixelFormat_,
  232707. NSOpenGLContext* sharedContext)
  232708. : renderContext (0),
  232709. pixelFormat (pixelFormat_)
  232710. {
  232711. jassert (component != 0);
  232712. NSOpenGLPixelFormatAttribute attribs [64];
  232713. int n = 0;
  232714. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232715. attribs[n++] = NSOpenGLPFAAccelerated;
  232716. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232717. attribs[n++] = NSOpenGLPFAColorSize;
  232718. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232719. pixelFormat.greenBits,
  232720. pixelFormat.blueBits);
  232721. attribs[n++] = NSOpenGLPFAAlphaSize;
  232722. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232723. attribs[n++] = NSOpenGLPFADepthSize;
  232724. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232725. attribs[n++] = NSOpenGLPFAStencilSize;
  232726. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232727. attribs[n++] = NSOpenGLPFAAccumSize;
  232728. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232729. pixelFormat.accumulationBufferGreenBits,
  232730. pixelFormat.accumulationBufferBlueBits,
  232731. pixelFormat.accumulationBufferAlphaBits);
  232732. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232733. attribs[n++] = NSOpenGLPFASampleBuffers;
  232734. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232735. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232736. attribs[n++] = NSOpenGLPFANoRecovery;
  232737. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232738. NSOpenGLPixelFormat* format
  232739. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232740. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232741. pixelFormat: format];
  232742. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232743. shareContext: sharedContext] autorelease];
  232744. const GLint swapInterval = 1;
  232745. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232746. [view setOpenGLContext: renderContext];
  232747. [format release];
  232748. viewHolder = new NSViewComponentInternal (view, component);
  232749. }
  232750. ~WindowedGLContext()
  232751. {
  232752. deleteContext();
  232753. viewHolder = 0;
  232754. }
  232755. void deleteContext()
  232756. {
  232757. makeInactive();
  232758. [renderContext clearDrawable];
  232759. [renderContext setView: nil];
  232760. [view setOpenGLContext: nil];
  232761. renderContext = nil;
  232762. }
  232763. bool makeActive() const throw()
  232764. {
  232765. jassert (renderContext != 0);
  232766. if ([renderContext view] != view)
  232767. [renderContext setView: view];
  232768. [view makeActive];
  232769. return isActive();
  232770. }
  232771. bool makeInactive() const throw()
  232772. {
  232773. [view makeInactive];
  232774. return true;
  232775. }
  232776. bool isActive() const throw()
  232777. {
  232778. return [NSOpenGLContext currentContext] == renderContext;
  232779. }
  232780. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232781. void* getRawContext() const throw() { return renderContext; }
  232782. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232783. {
  232784. }
  232785. void swapBuffers()
  232786. {
  232787. [renderContext flushBuffer];
  232788. }
  232789. bool setSwapInterval (const int numFramesPerSwap)
  232790. {
  232791. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232792. forParameter: NSOpenGLCPSwapInterval];
  232793. return true;
  232794. }
  232795. int getSwapInterval() const
  232796. {
  232797. GLint numFrames = 0;
  232798. [renderContext getValues: &numFrames
  232799. forParameter: NSOpenGLCPSwapInterval];
  232800. return numFrames;
  232801. }
  232802. void repaint()
  232803. {
  232804. // we need to invalidate the juce view that holds this gl view, to make it
  232805. // cause a repaint callback
  232806. NSView* v = (NSView*) viewHolder->view;
  232807. NSRect r = [v frame];
  232808. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232809. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232810. // repaint message, thus never causing our paint() callback, and never repainting
  232811. // the comp. So invalidating just a little bit around the edge helps..
  232812. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232813. }
  232814. void* getNativeWindowHandle() const { return viewHolder->view; }
  232815. juce_UseDebuggingNewOperator
  232816. NSOpenGLContext* renderContext;
  232817. ThreadSafeNSOpenGLView* view;
  232818. private:
  232819. OpenGLPixelFormat pixelFormat;
  232820. ScopedPointer <NSViewComponentInternal> viewHolder;
  232821. WindowedGLContext (const WindowedGLContext&);
  232822. WindowedGLContext& operator= (const WindowedGLContext&);
  232823. };
  232824. OpenGLContext* OpenGLComponent::createContext()
  232825. {
  232826. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  232827. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232828. return (c->renderContext != 0) ? c.release() : 0;
  232829. }
  232830. void* OpenGLComponent::getNativeWindowHandle() const
  232831. {
  232832. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232833. : 0;
  232834. }
  232835. void juce_glViewport (const int w, const int h)
  232836. {
  232837. glViewport (0, 0, w, h);
  232838. }
  232839. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232840. OwnedArray <OpenGLPixelFormat>& results)
  232841. {
  232842. /* GLint attribs [64];
  232843. int n = 0;
  232844. attribs[n++] = AGL_RGBA;
  232845. attribs[n++] = AGL_DOUBLEBUFFER;
  232846. attribs[n++] = AGL_ACCELERATED;
  232847. attribs[n++] = AGL_NO_RECOVERY;
  232848. attribs[n++] = AGL_NONE;
  232849. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232850. while (p != 0)
  232851. {
  232852. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232853. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232854. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232855. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232856. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232857. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232858. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232859. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232860. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232861. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232862. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232863. results.add (pf);
  232864. p = aglNextPixelFormat (p);
  232865. }*/
  232866. //jassertfalse // can't see how you do this in cocoa!
  232867. }
  232868. #else
  232869. END_JUCE_NAMESPACE
  232870. @interface JuceGLView : UIView
  232871. {
  232872. }
  232873. + (Class) layerClass;
  232874. @end
  232875. @implementation JuceGLView
  232876. + (Class) layerClass
  232877. {
  232878. return [CAEAGLLayer class];
  232879. }
  232880. @end
  232881. BEGIN_JUCE_NAMESPACE
  232882. class GLESContext : public OpenGLContext
  232883. {
  232884. public:
  232885. GLESContext (UIViewComponentPeer* peer,
  232886. Component* const component_,
  232887. const OpenGLPixelFormat& pixelFormat_,
  232888. const GLESContext* const sharedContext,
  232889. NSUInteger apiType)
  232890. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232891. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232892. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232893. {
  232894. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232895. view.opaque = YES;
  232896. view.hidden = NO;
  232897. view.backgroundColor = [UIColor blackColor];
  232898. view.userInteractionEnabled = NO;
  232899. glLayer = (CAEAGLLayer*) [view layer];
  232900. [peer->view addSubview: view];
  232901. if (sharedContext != 0)
  232902. context = [[EAGLContext alloc] initWithAPI: apiType
  232903. sharegroup: [sharedContext->context sharegroup]];
  232904. else
  232905. context = [[EAGLContext alloc] initWithAPI: apiType];
  232906. createGLBuffers();
  232907. }
  232908. ~GLESContext()
  232909. {
  232910. deleteContext();
  232911. [view removeFromSuperview];
  232912. [view release];
  232913. freeGLBuffers();
  232914. }
  232915. void deleteContext()
  232916. {
  232917. makeInactive();
  232918. [context release];
  232919. context = nil;
  232920. }
  232921. bool makeActive() const throw()
  232922. {
  232923. jassert (context != 0);
  232924. [EAGLContext setCurrentContext: context];
  232925. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232926. return true;
  232927. }
  232928. void swapBuffers()
  232929. {
  232930. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232931. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232932. }
  232933. bool makeInactive() const throw()
  232934. {
  232935. return [EAGLContext setCurrentContext: nil];
  232936. }
  232937. bool isActive() const throw()
  232938. {
  232939. return [EAGLContext currentContext] == context;
  232940. }
  232941. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232942. void* getRawContext() const throw() { return glLayer; }
  232943. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232944. {
  232945. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232946. if (lastWidth != w || lastHeight != h)
  232947. {
  232948. lastWidth = w;
  232949. lastHeight = h;
  232950. freeGLBuffers();
  232951. createGLBuffers();
  232952. }
  232953. }
  232954. bool setSwapInterval (const int numFramesPerSwap)
  232955. {
  232956. numFrames = numFramesPerSwap;
  232957. return true;
  232958. }
  232959. int getSwapInterval() const
  232960. {
  232961. return numFrames;
  232962. }
  232963. void repaint()
  232964. {
  232965. }
  232966. void createGLBuffers()
  232967. {
  232968. makeActive();
  232969. glGenFramebuffersOES (1, &frameBufferHandle);
  232970. glGenRenderbuffersOES (1, &colorBufferHandle);
  232971. glGenRenderbuffersOES (1, &depthBufferHandle);
  232972. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232973. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232974. GLint width, height;
  232975. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232976. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232977. if (useDepthBuffer)
  232978. {
  232979. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232980. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232981. }
  232982. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232983. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232984. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232985. if (useDepthBuffer)
  232986. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232987. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232988. }
  232989. void freeGLBuffers()
  232990. {
  232991. if (frameBufferHandle != 0)
  232992. {
  232993. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232994. frameBufferHandle = 0;
  232995. }
  232996. if (colorBufferHandle != 0)
  232997. {
  232998. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232999. colorBufferHandle = 0;
  233000. }
  233001. if (depthBufferHandle != 0)
  233002. {
  233003. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233004. depthBufferHandle = 0;
  233005. }
  233006. }
  233007. juce_UseDebuggingNewOperator
  233008. private:
  233009. Component::SafePointer<Component> component;
  233010. OpenGLPixelFormat pixelFormat;
  233011. JuceGLView* view;
  233012. CAEAGLLayer* glLayer;
  233013. EAGLContext* context;
  233014. bool useDepthBuffer;
  233015. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233016. int numFrames;
  233017. int lastWidth, lastHeight;
  233018. GLESContext (const GLESContext&);
  233019. GLESContext& operator= (const GLESContext&);
  233020. };
  233021. OpenGLContext* OpenGLComponent::createContext()
  233022. {
  233023. ScopedAutoReleasePool pool;
  233024. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233025. if (peer != 0)
  233026. return new GLESContext (peer, this, preferredPixelFormat,
  233027. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233028. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233029. return 0;
  233030. }
  233031. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233032. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233033. {
  233034. }
  233035. void juce_glViewport (const int w, const int h)
  233036. {
  233037. glViewport (0, 0, w, h);
  233038. }
  233039. #endif
  233040. #endif
  233041. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233042. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233043. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233044. // compiled on its own).
  233045. #if JUCE_INCLUDED_FILE
  233046. class JuceMainMenuHandler;
  233047. END_JUCE_NAMESPACE
  233048. using namespace JUCE_NAMESPACE;
  233049. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233050. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233051. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233052. #else
  233053. @interface JuceMenuCallback : NSObject
  233054. #endif
  233055. {
  233056. JuceMainMenuHandler* owner;
  233057. }
  233058. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233059. - (void) dealloc;
  233060. - (void) menuItemInvoked: (id) menu;
  233061. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233062. @end
  233063. BEGIN_JUCE_NAMESPACE
  233064. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233065. private DeletedAtShutdown
  233066. {
  233067. public:
  233068. static JuceMainMenuHandler* instance;
  233069. JuceMainMenuHandler()
  233070. : currentModel (0),
  233071. lastUpdateTime (0)
  233072. {
  233073. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233074. }
  233075. ~JuceMainMenuHandler()
  233076. {
  233077. setMenu (0);
  233078. jassert (instance == this);
  233079. instance = 0;
  233080. [callback release];
  233081. }
  233082. void setMenu (MenuBarModel* const newMenuBarModel)
  233083. {
  233084. if (currentModel != newMenuBarModel)
  233085. {
  233086. if (currentModel != 0)
  233087. currentModel->removeListener (this);
  233088. currentModel = newMenuBarModel;
  233089. if (currentModel != 0)
  233090. currentModel->addListener (this);
  233091. menuBarItemsChanged (0);
  233092. }
  233093. }
  233094. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233095. const String& name, const int menuId, const int tag)
  233096. {
  233097. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233098. action: nil
  233099. keyEquivalent: @""];
  233100. [item setTag: tag];
  233101. NSMenu* sub = createMenu (child, name, menuId, tag);
  233102. [parent setSubmenu: sub forItem: item];
  233103. [sub setAutoenablesItems: false];
  233104. [sub release];
  233105. }
  233106. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233107. const String& name, const int menuId, const int tag)
  233108. {
  233109. [parentItem setTag: tag];
  233110. NSMenu* menu = [parentItem submenu];
  233111. [menu setTitle: juceStringToNS (name)];
  233112. while ([menu numberOfItems] > 0)
  233113. [menu removeItemAtIndex: 0];
  233114. PopupMenu::MenuItemIterator iter (menuToCopy);
  233115. while (iter.next())
  233116. addMenuItem (iter, menu, menuId, tag);
  233117. [menu setAutoenablesItems: false];
  233118. [menu update];
  233119. }
  233120. void menuBarItemsChanged (MenuBarModel*)
  233121. {
  233122. lastUpdateTime = Time::getMillisecondCounter();
  233123. StringArray menuNames;
  233124. if (currentModel != 0)
  233125. menuNames = currentModel->getMenuBarNames();
  233126. NSMenu* menuBar = [NSApp mainMenu];
  233127. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233128. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233129. int menuId = 1;
  233130. for (int i = 0; i < menuNames.size(); ++i)
  233131. {
  233132. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233133. if (i >= [menuBar numberOfItems] - 1)
  233134. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233135. else
  233136. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233137. }
  233138. }
  233139. static void flashMenuBar (NSMenu* menu)
  233140. {
  233141. if ([[menu title] isEqualToString: @"Apple"])
  233142. return;
  233143. [menu retain];
  233144. const unichar f35Key = NSF35FunctionKey;
  233145. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233146. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233147. action: nil
  233148. keyEquivalent: f35String];
  233149. [item setTarget: nil];
  233150. [menu insertItem: item atIndex: [menu numberOfItems]];
  233151. [item release];
  233152. if ([menu indexOfItem: item] >= 0)
  233153. {
  233154. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233155. location: NSZeroPoint
  233156. modifierFlags: NSCommandKeyMask
  233157. timestamp: 0
  233158. windowNumber: 0
  233159. context: [NSGraphicsContext currentContext]
  233160. characters: f35String
  233161. charactersIgnoringModifiers: f35String
  233162. isARepeat: NO
  233163. keyCode: 0];
  233164. [menu performKeyEquivalent: f35Event];
  233165. if ([menu indexOfItem: item] >= 0)
  233166. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233167. }
  233168. [menu release];
  233169. }
  233170. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233171. {
  233172. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233173. {
  233174. NSMenuItem* m = [menu itemAtIndex: i];
  233175. if ([m tag] == info.commandID)
  233176. return m;
  233177. if ([m submenu] != 0)
  233178. {
  233179. NSMenuItem* found = findMenuItem ([m submenu], info);
  233180. if (found != 0)
  233181. return found;
  233182. }
  233183. }
  233184. return 0;
  233185. }
  233186. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233187. {
  233188. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233189. if (item != 0)
  233190. flashMenuBar ([item menu]);
  233191. }
  233192. void updateMenus()
  233193. {
  233194. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233195. menuBarItemsChanged (0);
  233196. }
  233197. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233198. {
  233199. if (currentModel != 0)
  233200. {
  233201. if (commandManager != 0)
  233202. {
  233203. ApplicationCommandTarget::InvocationInfo info (commandId);
  233204. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233205. commandManager->invoke (info, true);
  233206. }
  233207. currentModel->menuItemSelected (commandId, topLevelIndex);
  233208. }
  233209. }
  233210. MenuBarModel* currentModel;
  233211. uint32 lastUpdateTime;
  233212. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233213. const int topLevelMenuId, const int topLevelIndex)
  233214. {
  233215. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233216. if (text == 0)
  233217. text = @"";
  233218. if (iter.isSeparator)
  233219. {
  233220. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233221. }
  233222. else if (iter.isSectionHeader)
  233223. {
  233224. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233225. action: nil
  233226. keyEquivalent: @""];
  233227. [item setEnabled: false];
  233228. }
  233229. else if (iter.subMenu != 0)
  233230. {
  233231. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233232. action: nil
  233233. keyEquivalent: @""];
  233234. [item setTag: iter.itemId];
  233235. [item setEnabled: iter.isEnabled];
  233236. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233237. [sub setDelegate: nil];
  233238. [menuToAddTo setSubmenu: sub forItem: item];
  233239. [sub release];
  233240. }
  233241. else
  233242. {
  233243. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233244. action: @selector (menuItemInvoked:)
  233245. keyEquivalent: @""];
  233246. [item setTag: iter.itemId];
  233247. [item setEnabled: iter.isEnabled];
  233248. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233249. [item setTarget: (id) callback];
  233250. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233251. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233252. [item setRepresentedObject: info];
  233253. if (iter.commandManager != 0)
  233254. {
  233255. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233256. ->getKeyPressesAssignedToCommand (iter.itemId));
  233257. if (keyPresses.size() > 0)
  233258. {
  233259. const KeyPress& kp = keyPresses.getReference(0);
  233260. if (kp.getKeyCode() != KeyPress::backspaceKey
  233261. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233262. // every time you press the key while editing text)
  233263. {
  233264. juce_wchar key = kp.getTextCharacter();
  233265. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233266. key = NSBackspaceCharacter;
  233267. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233268. key = NSDeleteCharacter;
  233269. else if (key == 0)
  233270. key = (juce_wchar) kp.getKeyCode();
  233271. unsigned int mods = 0;
  233272. if (kp.getModifiers().isShiftDown())
  233273. mods |= NSShiftKeyMask;
  233274. if (kp.getModifiers().isCtrlDown())
  233275. mods |= NSControlKeyMask;
  233276. if (kp.getModifiers().isAltDown())
  233277. mods |= NSAlternateKeyMask;
  233278. if (kp.getModifiers().isCommandDown())
  233279. mods |= NSCommandKeyMask;
  233280. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233281. [item setKeyEquivalentModifierMask: mods];
  233282. }
  233283. }
  233284. }
  233285. }
  233286. }
  233287. JuceMenuCallback* callback;
  233288. private:
  233289. NSMenu* createMenu (const PopupMenu menu,
  233290. const String& menuName,
  233291. const int topLevelMenuId,
  233292. const int topLevelIndex)
  233293. {
  233294. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233295. [m setAutoenablesItems: false];
  233296. [m setDelegate: callback];
  233297. PopupMenu::MenuItemIterator iter (menu);
  233298. while (iter.next())
  233299. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233300. [m update];
  233301. return m;
  233302. }
  233303. };
  233304. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233305. END_JUCE_NAMESPACE
  233306. @implementation JuceMenuCallback
  233307. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233308. {
  233309. [super init];
  233310. owner = owner_;
  233311. return self;
  233312. }
  233313. - (void) dealloc
  233314. {
  233315. [super dealloc];
  233316. }
  233317. - (void) menuItemInvoked: (id) menu
  233318. {
  233319. NSMenuItem* item = (NSMenuItem*) menu;
  233320. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233321. {
  233322. // If the menu is being triggered by a keypress, the OS will have picked it up before we had a chance to offer it to
  233323. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233324. // into the focused component and let it trigger the menu item indirectly.
  233325. NSEvent* e = [NSApp currentEvent];
  233326. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233327. {
  233328. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233329. {
  233330. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233331. if (peer != 0)
  233332. {
  233333. if ([e type] == NSKeyDown)
  233334. peer->redirectKeyDown (e);
  233335. else
  233336. peer->redirectKeyUp (e);
  233337. return;
  233338. }
  233339. }
  233340. }
  233341. NSArray* info = (NSArray*) [item representedObject];
  233342. owner->invoke ((int) [item tag],
  233343. (ApplicationCommandManager*) (pointer_sized_int)
  233344. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233345. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233346. }
  233347. }
  233348. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233349. {
  233350. (void) menu;
  233351. if (JuceMainMenuHandler::instance != 0)
  233352. JuceMainMenuHandler::instance->updateMenus();
  233353. }
  233354. @end
  233355. BEGIN_JUCE_NAMESPACE
  233356. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  233357. const PopupMenu* extraItems)
  233358. {
  233359. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233360. {
  233361. PopupMenu::MenuItemIterator iter (*extraItems);
  233362. while (iter.next())
  233363. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233364. [menu addItem: [NSMenuItem separatorItem]];
  233365. }
  233366. NSMenuItem* item;
  233367. // Services...
  233368. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233369. action: nil keyEquivalent: @""];
  233370. [menu addItem: item];
  233371. [item release];
  233372. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233373. [menu setSubmenu: servicesMenu forItem: item];
  233374. [NSApp setServicesMenu: servicesMenu];
  233375. [servicesMenu release];
  233376. [menu addItem: [NSMenuItem separatorItem]];
  233377. // Hide + Show stuff...
  233378. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233379. action: @selector (hide:) keyEquivalent: @"h"];
  233380. [item setTarget: NSApp];
  233381. [menu addItem: item];
  233382. [item release];
  233383. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233384. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233385. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233386. [item setTarget: NSApp];
  233387. [menu addItem: item];
  233388. [item release];
  233389. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233390. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233391. [item setTarget: NSApp];
  233392. [menu addItem: item];
  233393. [item release];
  233394. [menu addItem: [NSMenuItem separatorItem]];
  233395. // Quit item....
  233396. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233397. action: @selector (terminate:) keyEquivalent: @"q"];
  233398. [item setTarget: NSApp];
  233399. [menu addItem: item];
  233400. [item release];
  233401. return menu;
  233402. }
  233403. // Since our app has no NIB, this initialises a standard app menu...
  233404. static void rebuildMainMenu (const PopupMenu* extraItems)
  233405. {
  233406. // this can't be used in a plugin!
  233407. jassert (JUCEApplication::isStandaloneApp());
  233408. if (JUCEApplication::getInstance() != 0)
  233409. {
  233410. const ScopedAutoReleasePool pool;
  233411. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233412. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233413. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233414. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233415. [mainMenu setSubmenu: appMenu forItem: item];
  233416. [NSApp setMainMenu: mainMenu];
  233417. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233418. [appMenu release];
  233419. [mainMenu release];
  233420. }
  233421. }
  233422. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233423. const PopupMenu* extraAppleMenuItems)
  233424. {
  233425. if (getMacMainMenu() != newMenuBarModel)
  233426. {
  233427. const ScopedAutoReleasePool pool;
  233428. if (newMenuBarModel == 0)
  233429. {
  233430. delete JuceMainMenuHandler::instance;
  233431. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233432. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233433. extraAppleMenuItems = 0;
  233434. }
  233435. else
  233436. {
  233437. if (JuceMainMenuHandler::instance == 0)
  233438. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233439. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233440. }
  233441. }
  233442. rebuildMainMenu (extraAppleMenuItems);
  233443. if (newMenuBarModel != 0)
  233444. newMenuBarModel->menuItemsChanged();
  233445. }
  233446. MenuBarModel* MenuBarModel::getMacMainMenu()
  233447. {
  233448. return JuceMainMenuHandler::instance != 0
  233449. ? JuceMainMenuHandler::instance->currentModel : 0;
  233450. }
  233451. void juce_initialiseMacMainMenu()
  233452. {
  233453. if (JuceMainMenuHandler::instance == 0)
  233454. rebuildMainMenu (0);
  233455. }
  233456. #endif
  233457. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233458. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233459. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233460. // compiled on its own).
  233461. #if JUCE_INCLUDED_FILE
  233462. #if JUCE_MAC
  233463. END_JUCE_NAMESPACE
  233464. using namespace JUCE_NAMESPACE;
  233465. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233466. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233467. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233468. #else
  233469. @interface JuceFileChooserDelegate : NSObject
  233470. #endif
  233471. {
  233472. StringArray* filters;
  233473. }
  233474. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233475. - (void) dealloc;
  233476. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233477. @end
  233478. @implementation JuceFileChooserDelegate
  233479. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233480. {
  233481. [super init];
  233482. filters = filters_;
  233483. return self;
  233484. }
  233485. - (void) dealloc
  233486. {
  233487. delete filters;
  233488. [super dealloc];
  233489. }
  233490. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233491. {
  233492. (void) sender;
  233493. const File f (nsStringToJuce (filename));
  233494. for (int i = filters->size(); --i >= 0;)
  233495. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233496. return true;
  233497. return f.isDirectory();
  233498. }
  233499. @end
  233500. BEGIN_JUCE_NAMESPACE
  233501. void FileChooser::showPlatformDialog (Array<File>& results,
  233502. const String& title,
  233503. const File& currentFileOrDirectory,
  233504. const String& filter,
  233505. bool selectsDirectory,
  233506. bool selectsFiles,
  233507. bool isSaveDialogue,
  233508. bool warnAboutOverwritingExistingFiles,
  233509. bool selectMultipleFiles,
  233510. FilePreviewComponent* extraInfoComponent)
  233511. {
  233512. const ScopedAutoReleasePool pool;
  233513. StringArray* filters = new StringArray();
  233514. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233515. filters->trim();
  233516. filters->removeEmptyStrings();
  233517. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233518. [delegate autorelease];
  233519. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233520. : [NSOpenPanel openPanel];
  233521. [panel setTitle: juceStringToNS (title)];
  233522. if (! isSaveDialogue)
  233523. {
  233524. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233525. [openPanel setCanChooseDirectories: selectsDirectory];
  233526. [openPanel setCanChooseFiles: selectsFiles];
  233527. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233528. }
  233529. [panel setDelegate: delegate];
  233530. if (isSaveDialogue || selectsDirectory)
  233531. [panel setCanCreateDirectories: YES];
  233532. String directory, filename;
  233533. if (currentFileOrDirectory.isDirectory())
  233534. {
  233535. directory = currentFileOrDirectory.getFullPathName();
  233536. }
  233537. else
  233538. {
  233539. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233540. filename = currentFileOrDirectory.getFileName();
  233541. }
  233542. if ([panel runModalForDirectory: juceStringToNS (directory)
  233543. file: juceStringToNS (filename)]
  233544. == NSOKButton)
  233545. {
  233546. if (isSaveDialogue)
  233547. {
  233548. results.add (File (nsStringToJuce ([panel filename])));
  233549. }
  233550. else
  233551. {
  233552. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233553. NSArray* urls = [openPanel filenames];
  233554. for (unsigned int i = 0; i < [urls count]; ++i)
  233555. {
  233556. NSString* f = [urls objectAtIndex: i];
  233557. results.add (File (nsStringToJuce (f)));
  233558. }
  233559. }
  233560. }
  233561. [panel setDelegate: nil];
  233562. }
  233563. #else
  233564. void FileChooser::showPlatformDialog (Array<File>& results,
  233565. const String& title,
  233566. const File& currentFileOrDirectory,
  233567. const String& filter,
  233568. bool selectsDirectory,
  233569. bool selectsFiles,
  233570. bool isSaveDialogue,
  233571. bool warnAboutOverwritingExistingFiles,
  233572. bool selectMultipleFiles,
  233573. FilePreviewComponent* extraInfoComponent)
  233574. {
  233575. const ScopedAutoReleasePool pool;
  233576. jassertfalse; //xxx to do
  233577. }
  233578. #endif
  233579. #endif
  233580. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233581. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233582. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233583. // compiled on its own).
  233584. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233585. END_JUCE_NAMESPACE
  233586. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233587. @interface NonInterceptingQTMovieView : QTMovieView
  233588. {
  233589. }
  233590. - (id) initWithFrame: (NSRect) frame;
  233591. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233592. - (NSView*) hitTest: (NSPoint) p;
  233593. @end
  233594. @implementation NonInterceptingQTMovieView
  233595. - (id) initWithFrame: (NSRect) frame
  233596. {
  233597. self = [super initWithFrame: frame];
  233598. [self setNextResponder: [self superview]];
  233599. return self;
  233600. }
  233601. - (void) dealloc
  233602. {
  233603. [super dealloc];
  233604. }
  233605. - (NSView*) hitTest: (NSPoint) point
  233606. {
  233607. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233608. }
  233609. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233610. {
  233611. return YES;
  233612. }
  233613. @end
  233614. BEGIN_JUCE_NAMESPACE
  233615. #define theMovie (static_cast <QTMovie*> (movie))
  233616. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233617. : movie (0)
  233618. {
  233619. setOpaque (true);
  233620. setVisible (true);
  233621. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233622. setView (view);
  233623. [view release];
  233624. }
  233625. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233626. {
  233627. closeMovie();
  233628. setView (0);
  233629. }
  233630. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233631. {
  233632. return true;
  233633. }
  233634. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233635. {
  233636. // unfortunately, QTMovie objects can only be created on the main thread..
  233637. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233638. QTMovie* movie = 0;
  233639. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233640. if (fin != 0)
  233641. {
  233642. movieFile = fin->getFile();
  233643. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233644. error: nil];
  233645. }
  233646. else
  233647. {
  233648. MemoryBlock temp;
  233649. movieStream->readIntoMemoryBlock (temp);
  233650. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233651. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233652. {
  233653. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233654. length: temp.getSize()]
  233655. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233656. MIMEType: @""]
  233657. error: nil];
  233658. if (movie != 0)
  233659. break;
  233660. }
  233661. }
  233662. return movie;
  233663. }
  233664. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233665. const bool isControllerVisible_)
  233666. {
  233667. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233668. }
  233669. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233670. const bool controllerVisible_)
  233671. {
  233672. closeMovie();
  233673. if (getPeer() == 0)
  233674. {
  233675. // To open a movie, this component must be visible inside a functioning window, so that
  233676. // the QT control can be assigned to the window.
  233677. jassertfalse;
  233678. return false;
  233679. }
  233680. movie = openMovieFromStream (movieStream, movieFile);
  233681. [theMovie retain];
  233682. QTMovieView* view = (QTMovieView*) getView();
  233683. [view setMovie: theMovie];
  233684. [view setControllerVisible: controllerVisible_];
  233685. setLooping (looping);
  233686. return movie != nil;
  233687. }
  233688. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233689. const bool isControllerVisible_)
  233690. {
  233691. // unfortunately, QTMovie objects can only be created on the main thread..
  233692. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233693. closeMovie();
  233694. if (getPeer() == 0)
  233695. {
  233696. // To open a movie, this component must be visible inside a functioning window, so that
  233697. // the QT control can be assigned to the window.
  233698. jassertfalse;
  233699. return false;
  233700. }
  233701. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233702. NSError* err;
  233703. if ([QTMovie canInitWithURL: url])
  233704. movie = [QTMovie movieWithURL: url error: &err];
  233705. [theMovie retain];
  233706. QTMovieView* view = (QTMovieView*) getView();
  233707. [view setMovie: theMovie];
  233708. [view setControllerVisible: controllerVisible];
  233709. setLooping (looping);
  233710. return movie != nil;
  233711. }
  233712. void QuickTimeMovieComponent::closeMovie()
  233713. {
  233714. stop();
  233715. QTMovieView* view = (QTMovieView*) getView();
  233716. [view setMovie: nil];
  233717. [theMovie release];
  233718. movie = 0;
  233719. movieFile = File::nonexistent;
  233720. }
  233721. bool QuickTimeMovieComponent::isMovieOpen() const
  233722. {
  233723. return movie != nil;
  233724. }
  233725. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233726. {
  233727. return movieFile;
  233728. }
  233729. void QuickTimeMovieComponent::play()
  233730. {
  233731. [theMovie play];
  233732. }
  233733. void QuickTimeMovieComponent::stop()
  233734. {
  233735. [theMovie stop];
  233736. }
  233737. bool QuickTimeMovieComponent::isPlaying() const
  233738. {
  233739. return movie != 0 && [theMovie rate] != 0;
  233740. }
  233741. void QuickTimeMovieComponent::setPosition (const double seconds)
  233742. {
  233743. if (movie != 0)
  233744. {
  233745. QTTime t;
  233746. t.timeValue = (uint64) (100000.0 * seconds);
  233747. t.timeScale = 100000;
  233748. t.flags = 0;
  233749. [theMovie setCurrentTime: t];
  233750. }
  233751. }
  233752. double QuickTimeMovieComponent::getPosition() const
  233753. {
  233754. if (movie == 0)
  233755. return 0.0;
  233756. QTTime t = [theMovie currentTime];
  233757. return t.timeValue / (double) t.timeScale;
  233758. }
  233759. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233760. {
  233761. [theMovie setRate: newSpeed];
  233762. }
  233763. double QuickTimeMovieComponent::getMovieDuration() const
  233764. {
  233765. if (movie == 0)
  233766. return 0.0;
  233767. QTTime t = [theMovie duration];
  233768. return t.timeValue / (double) t.timeScale;
  233769. }
  233770. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233771. {
  233772. looping = shouldLoop;
  233773. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233774. forKey: QTMovieLoopsAttribute];
  233775. }
  233776. bool QuickTimeMovieComponent::isLooping() const
  233777. {
  233778. return looping;
  233779. }
  233780. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233781. {
  233782. [theMovie setVolume: newVolume];
  233783. }
  233784. float QuickTimeMovieComponent::getMovieVolume() const
  233785. {
  233786. return movie != 0 ? [theMovie volume] : 0.0f;
  233787. }
  233788. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233789. {
  233790. width = 0;
  233791. height = 0;
  233792. if (movie != 0)
  233793. {
  233794. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233795. width = (int) s.width;
  233796. height = (int) s.height;
  233797. }
  233798. }
  233799. void QuickTimeMovieComponent::paint (Graphics& g)
  233800. {
  233801. if (movie == 0)
  233802. g.fillAll (Colours::black);
  233803. }
  233804. bool QuickTimeMovieComponent::isControllerVisible() const
  233805. {
  233806. return controllerVisible;
  233807. }
  233808. void QuickTimeMovieComponent::goToStart()
  233809. {
  233810. setPosition (0.0);
  233811. }
  233812. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233813. const RectanglePlacement& placement)
  233814. {
  233815. int normalWidth, normalHeight;
  233816. getMovieNormalSize (normalWidth, normalHeight);
  233817. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  233818. {
  233819. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  233820. placement.applyTo (x, y, w, h,
  233821. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  233822. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  233823. if (w > 0 && h > 0)
  233824. {
  233825. setBounds (roundToInt (x), roundToInt (y),
  233826. roundToInt (w), roundToInt (h));
  233827. }
  233828. }
  233829. else
  233830. {
  233831. setBounds (spaceToFitWithin);
  233832. }
  233833. }
  233834. #if ! (JUCE_MAC && JUCE_64BIT)
  233835. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233836. {
  233837. if (movieStream == 0)
  233838. return false;
  233839. File file;
  233840. QTMovie* movie = openMovieFromStream (movieStream, file);
  233841. if (movie != nil)
  233842. result = [movie quickTimeMovie];
  233843. return movie != nil;
  233844. }
  233845. #endif
  233846. #endif
  233847. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233848. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233849. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233850. // compiled on its own).
  233851. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233852. const int kilobytesPerSecond1x = 176;
  233853. END_JUCE_NAMESPACE
  233854. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233855. @interface OpenDiskDevice : NSObject
  233856. {
  233857. @public
  233858. DRDevice* device;
  233859. NSMutableArray* tracks;
  233860. bool underrunProtection;
  233861. }
  233862. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233863. - (void) dealloc;
  233864. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233865. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233866. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233867. @end
  233868. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233869. @interface AudioTrackProducer : NSObject
  233870. {
  233871. JUCE_NAMESPACE::AudioSource* source;
  233872. int readPosition, lengthInFrames;
  233873. }
  233874. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233875. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233876. - (void) dealloc;
  233877. - (void) setupTrackProperties: (DRTrack*) track;
  233878. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233879. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233880. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233881. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233882. toMedia:(NSDictionary*)mediaInfo;
  233883. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233884. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233885. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233886. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233887. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233888. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233889. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233890. ioFlags:(uint32_t*)flags;
  233891. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233892. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233893. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233894. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233895. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233896. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233897. ioFlags:(uint32_t*)flags;
  233898. @end
  233899. @implementation OpenDiskDevice
  233900. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233901. {
  233902. [super init];
  233903. device = device_;
  233904. tracks = [[NSMutableArray alloc] init];
  233905. underrunProtection = true;
  233906. return self;
  233907. }
  233908. - (void) dealloc
  233909. {
  233910. [tracks release];
  233911. [super dealloc];
  233912. }
  233913. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233914. {
  233915. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233916. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233917. [p setupTrackProperties: t];
  233918. [tracks addObject: t];
  233919. [t release];
  233920. [p release];
  233921. }
  233922. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233923. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233924. {
  233925. DRBurn* burn = [DRBurn burnForDevice: device];
  233926. if (! [device acquireExclusiveAccess])
  233927. {
  233928. *error = "Couldn't open or write to the CD device";
  233929. return;
  233930. }
  233931. [device acquireMediaReservation];
  233932. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233933. [d autorelease];
  233934. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233935. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233936. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233937. if (burnSpeed > 0)
  233938. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233939. if (! underrunProtection)
  233940. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233941. [burn setProperties: d];
  233942. [burn writeLayout: tracks];
  233943. for (;;)
  233944. {
  233945. JUCE_NAMESPACE::Thread::sleep (300);
  233946. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233947. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233948. {
  233949. [burn abort];
  233950. *error = "User cancelled the write operation";
  233951. break;
  233952. }
  233953. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233954. {
  233955. *error = "Write operation failed";
  233956. break;
  233957. }
  233958. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233959. {
  233960. break;
  233961. }
  233962. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233963. objectForKey: DRErrorStatusErrorStringKey];
  233964. if ([err length] > 0)
  233965. {
  233966. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233967. break;
  233968. }
  233969. }
  233970. [device releaseMediaReservation];
  233971. [device releaseExclusiveAccess];
  233972. }
  233973. @end
  233974. @implementation AudioTrackProducer
  233975. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233976. {
  233977. lengthInFrames = lengthInFrames_;
  233978. readPosition = 0;
  233979. return self;
  233980. }
  233981. - (void) setupTrackProperties: (DRTrack*) track
  233982. {
  233983. NSMutableDictionary* p = [[track properties] mutableCopy];
  233984. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233985. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233986. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233987. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233988. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233989. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233990. [track setProperties: p];
  233991. [p release];
  233992. }
  233993. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233994. {
  233995. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233996. if (s != nil)
  233997. s->source = source_;
  233998. return s;
  233999. }
  234000. - (void) dealloc
  234001. {
  234002. if (source != 0)
  234003. {
  234004. source->releaseResources();
  234005. delete source;
  234006. }
  234007. [super dealloc];
  234008. }
  234009. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234010. {
  234011. }
  234012. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234013. {
  234014. return true;
  234015. }
  234016. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234017. {
  234018. return lengthInFrames;
  234019. }
  234020. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234021. toMedia: (NSDictionary*) mediaInfo
  234022. {
  234023. if (source != 0)
  234024. source->prepareToPlay (44100 / 75, 44100);
  234025. readPosition = 0;
  234026. return true;
  234027. }
  234028. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234029. {
  234030. if (source != 0)
  234031. source->prepareToPlay (44100 / 75, 44100);
  234032. return true;
  234033. }
  234034. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234035. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234036. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234037. {
  234038. if (source != 0)
  234039. {
  234040. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234041. if (numSamples > 0)
  234042. {
  234043. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234044. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234045. info.buffer = &tempBuffer;
  234046. info.startSample = 0;
  234047. info.numSamples = numSamples;
  234048. source->getNextAudioBlock (info);
  234049. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  234050. buffer, numSamples, 4);
  234051. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  234052. buffer + 2, numSamples, 4);
  234053. readPosition += numSamples;
  234054. }
  234055. return numSamples * 4;
  234056. }
  234057. return 0;
  234058. }
  234059. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234060. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234061. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234062. ioFlags: (uint32_t*) flags
  234063. {
  234064. zeromem (buffer, bufferLength);
  234065. return bufferLength;
  234066. }
  234067. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234068. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234069. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234070. {
  234071. return true;
  234072. }
  234073. @end
  234074. BEGIN_JUCE_NAMESPACE
  234075. class AudioCDBurner::Pimpl : public Timer
  234076. {
  234077. public:
  234078. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234079. : device (0), owner (owner_)
  234080. {
  234081. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234082. if (dev != 0)
  234083. {
  234084. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234085. lastState = getDiskState();
  234086. startTimer (1000);
  234087. }
  234088. }
  234089. ~Pimpl()
  234090. {
  234091. stopTimer();
  234092. [device release];
  234093. }
  234094. void timerCallback()
  234095. {
  234096. const DiskState state = getDiskState();
  234097. if (state != lastState)
  234098. {
  234099. lastState = state;
  234100. owner.sendChangeMessage (&owner);
  234101. }
  234102. }
  234103. DiskState getDiskState() const
  234104. {
  234105. if ([device->device isValid])
  234106. {
  234107. NSDictionary* status = [device->device status];
  234108. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234109. if ([state isEqualTo: DRDeviceMediaStateNone])
  234110. {
  234111. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234112. return trayOpen;
  234113. return noDisc;
  234114. }
  234115. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234116. {
  234117. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234118. return writableDiskPresent;
  234119. else
  234120. return readOnlyDiskPresent;
  234121. }
  234122. }
  234123. return unknown;
  234124. }
  234125. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234126. const Array<int> getAvailableWriteSpeeds() const
  234127. {
  234128. Array<int> results;
  234129. if ([device->device isValid])
  234130. {
  234131. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234132. for (unsigned int i = 0; i < [speeds count]; ++i)
  234133. {
  234134. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234135. results.add (kbPerSec / kilobytesPerSecond1x);
  234136. }
  234137. }
  234138. return results;
  234139. }
  234140. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234141. {
  234142. if ([device->device isValid])
  234143. {
  234144. device->underrunProtection = shouldBeEnabled;
  234145. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234146. }
  234147. return false;
  234148. }
  234149. int getNumAvailableAudioBlocks() const
  234150. {
  234151. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234152. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234153. }
  234154. OpenDiskDevice* device;
  234155. private:
  234156. DiskState lastState;
  234157. AudioCDBurner& owner;
  234158. };
  234159. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234160. {
  234161. pimpl = new Pimpl (*this, deviceIndex);
  234162. }
  234163. AudioCDBurner::~AudioCDBurner()
  234164. {
  234165. }
  234166. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234167. {
  234168. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234169. if (b->pimpl->device == 0)
  234170. b = 0;
  234171. return b.release();
  234172. }
  234173. static NSArray* findDiskBurnerDevices()
  234174. {
  234175. NSMutableArray* results = [NSMutableArray array];
  234176. NSArray* devs = [DRDevice devices];
  234177. if (devs != 0)
  234178. {
  234179. int num = [devs count];
  234180. int i;
  234181. for (i = 0; i < num; ++i)
  234182. {
  234183. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234184. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234185. if (name != nil)
  234186. [results addObject: name];
  234187. }
  234188. }
  234189. return results;
  234190. }
  234191. const StringArray AudioCDBurner::findAvailableDevices()
  234192. {
  234193. NSArray* names = findDiskBurnerDevices();
  234194. StringArray s;
  234195. for (unsigned int i = 0; i < [names count]; ++i)
  234196. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234197. return s;
  234198. }
  234199. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234200. {
  234201. return pimpl->getDiskState();
  234202. }
  234203. bool AudioCDBurner::isDiskPresent() const
  234204. {
  234205. return getDiskState() == writableDiskPresent;
  234206. }
  234207. bool AudioCDBurner::openTray()
  234208. {
  234209. return pimpl->openTray();
  234210. }
  234211. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234212. {
  234213. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234214. DiskState oldState = getDiskState();
  234215. DiskState newState = oldState;
  234216. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234217. {
  234218. newState = getDiskState();
  234219. Thread::sleep (100);
  234220. }
  234221. return newState;
  234222. }
  234223. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234224. {
  234225. return pimpl->getAvailableWriteSpeeds();
  234226. }
  234227. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234228. {
  234229. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234230. }
  234231. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234232. {
  234233. return pimpl->getNumAvailableAudioBlocks();
  234234. }
  234235. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234236. {
  234237. if ([pimpl->device->device isValid])
  234238. {
  234239. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234240. return true;
  234241. }
  234242. return false;
  234243. }
  234244. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234245. bool ejectDiscAfterwards,
  234246. bool performFakeBurnForTesting,
  234247. int writeSpeed)
  234248. {
  234249. String error ("Couldn't open or write to the CD device");
  234250. if ([pimpl->device->device isValid])
  234251. {
  234252. error = String::empty;
  234253. [pimpl->device burn: listener
  234254. errorString: &error
  234255. ejectAfterwards: ejectDiscAfterwards
  234256. isFake: performFakeBurnForTesting
  234257. speed: writeSpeed];
  234258. }
  234259. return error;
  234260. }
  234261. #endif
  234262. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234263. void AudioCDReader::ejectDisk()
  234264. {
  234265. const ScopedAutoReleasePool p;
  234266. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234267. }
  234268. #endif
  234269. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234270. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234271. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234272. // compiled on its own).
  234273. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234274. namespace CDReaderHelpers
  234275. {
  234276. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234277. {
  234278. forEachXmlChildElementWithTagName (xml, child, "key")
  234279. if (child->getAllSubText() == key)
  234280. return child->getNextElement();
  234281. return 0;
  234282. }
  234283. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234284. {
  234285. const XmlElement* const block = getElementForKey (xml, key);
  234286. return block != 0 ? block->getAllSubText().getIntValue() : defaultValue;
  234287. }
  234288. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234289. // Returns NULL on success, otherwise a const char* representing an error.
  234290. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234291. {
  234292. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234293. if (xml == 0)
  234294. return "Couldn't parse XML in file";
  234295. const XmlElement* const dict = xml->getChildByName ("dict");
  234296. if (dict == 0)
  234297. return "Couldn't get top level dictionary";
  234298. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234299. if (sessions == 0)
  234300. return "Couldn't find sessions key";
  234301. const XmlElement* const session = sessions->getFirstChildElement();
  234302. if (session == 0)
  234303. return "Couldn't find first session";
  234304. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234305. if (leadOut < 0)
  234306. return "Couldn't find Leadout Block";
  234307. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234308. if (trackArray == 0)
  234309. return "Couldn't find Track Array";
  234310. forEachXmlChildElement (*trackArray, track)
  234311. {
  234312. const int trackValue = getIntValueForKey (*track, "Start Block");
  234313. if (trackValue < 0)
  234314. return "Couldn't find Start Block in the track";
  234315. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234316. }
  234317. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234318. return 0;
  234319. }
  234320. static void findDevices (Array<File>& cds)
  234321. {
  234322. File volumes ("/Volumes");
  234323. volumes.findChildFiles (cds, File::findDirectories, false);
  234324. for (int i = cds.size(); --i >= 0;)
  234325. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234326. cds.remove (i);
  234327. }
  234328. struct TrackSorter
  234329. {
  234330. static int getCDTrackNumber (const File& file)
  234331. {
  234332. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234333. }
  234334. static int compareElements (const File& first, const File& second)
  234335. {
  234336. const int firstTrack = getCDTrackNumber (first);
  234337. const int secondTrack = getCDTrackNumber (second);
  234338. jassert (firstTrack > 0 && secondTrack > 0);
  234339. return firstTrack - secondTrack;
  234340. }
  234341. };
  234342. }
  234343. const StringArray AudioCDReader::getAvailableCDNames()
  234344. {
  234345. Array<File> cds;
  234346. CDReaderHelpers::findDevices (cds);
  234347. StringArray names;
  234348. for (int i = 0; i < cds.size(); ++i)
  234349. names.add (cds.getReference(i).getFileName());
  234350. return names;
  234351. }
  234352. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234353. {
  234354. Array<File> cds;
  234355. CDReaderHelpers::findDevices (cds);
  234356. if (cds[index].exists())
  234357. return new AudioCDReader (cds[index]);
  234358. return 0;
  234359. }
  234360. AudioCDReader::AudioCDReader (const File& volume)
  234361. : AudioFormatReader (0, "CD Audio"),
  234362. volumeDir (volume),
  234363. currentReaderTrack (-1),
  234364. reader (0)
  234365. {
  234366. sampleRate = 44100.0;
  234367. bitsPerSample = 16;
  234368. numChannels = 2;
  234369. usesFloatingPointData = false;
  234370. refreshTrackLengths();
  234371. }
  234372. AudioCDReader::~AudioCDReader()
  234373. {
  234374. }
  234375. void AudioCDReader::refreshTrackLengths()
  234376. {
  234377. tracks.clear();
  234378. trackStartSamples.clear();
  234379. lengthInSamples = 0;
  234380. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234381. CDReaderHelpers::TrackSorter sorter;
  234382. tracks.sort (sorter);
  234383. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234384. if (toc.exists())
  234385. {
  234386. XmlDocument doc (toc);
  234387. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234388. (void) error; // could be logged..
  234389. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234390. }
  234391. }
  234392. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234393. int64 startSampleInFile, int numSamples)
  234394. {
  234395. while (numSamples > 0)
  234396. {
  234397. int track = -1;
  234398. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234399. {
  234400. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234401. {
  234402. track = i;
  234403. break;
  234404. }
  234405. }
  234406. if (track < 0)
  234407. return false;
  234408. if (track != currentReaderTrack)
  234409. {
  234410. reader = 0;
  234411. FileInputStream* const in = tracks [track].createInputStream();
  234412. if (in != 0)
  234413. {
  234414. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234415. AiffAudioFormat format;
  234416. reader = format.createReaderFor (bin, true);
  234417. if (reader == 0)
  234418. currentReaderTrack = -1;
  234419. else
  234420. currentReaderTrack = track;
  234421. }
  234422. }
  234423. if (reader == 0)
  234424. return false;
  234425. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234426. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234427. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234428. numSamples -= numAvailable;
  234429. startSampleInFile += numAvailable;
  234430. }
  234431. return true;
  234432. }
  234433. bool AudioCDReader::isCDStillPresent() const
  234434. {
  234435. return volumeDir.exists();
  234436. }
  234437. bool AudioCDReader::isTrackAudio (int trackNum) const
  234438. {
  234439. return tracks [trackNum].hasFileExtension (".aiff");
  234440. }
  234441. void AudioCDReader::enableIndexScanning (bool b)
  234442. {
  234443. // any way to do this on a Mac??
  234444. }
  234445. int AudioCDReader::getLastIndex() const
  234446. {
  234447. return 0;
  234448. }
  234449. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234450. {
  234451. return Array <int>();
  234452. }
  234453. #endif
  234454. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234455. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234456. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234457. // compiled on its own).
  234458. #if JUCE_INCLUDED_FILE
  234459. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234460. for example having more than one juce plugin loaded into a host, then when a
  234461. method is called, the actual code that runs might actually be in a different module
  234462. than the one you expect... So any calls to library functions or statics that are
  234463. made inside obj-c methods will probably end up getting executed in a different DLL's
  234464. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234465. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234466. virtual methods of an object that's known to live inside the right module's space.
  234467. */
  234468. class AppDelegateRedirector
  234469. {
  234470. public:
  234471. AppDelegateRedirector()
  234472. {
  234473. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234474. runLoop = CFRunLoopGetMain();
  234475. #else
  234476. runLoop = CFRunLoopGetCurrent();
  234477. #endif
  234478. CFRunLoopSourceContext sourceContext;
  234479. zerostruct (sourceContext);
  234480. sourceContext.info = this;
  234481. sourceContext.perform = runLoopSourceCallback;
  234482. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234483. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234484. }
  234485. virtual ~AppDelegateRedirector()
  234486. {
  234487. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234488. CFRunLoopSourceInvalidate (runLoopSource);
  234489. CFRelease (runLoopSource);
  234490. }
  234491. virtual NSApplicationTerminateReply shouldTerminate()
  234492. {
  234493. if (JUCEApplication::getInstance() != 0)
  234494. {
  234495. JUCEApplication::getInstance()->systemRequestedQuit();
  234496. return NSTerminateCancel;
  234497. }
  234498. return NSTerminateNow;
  234499. }
  234500. virtual BOOL openFile (const NSString* filename)
  234501. {
  234502. if (JUCEApplication::getInstance() != 0)
  234503. {
  234504. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234505. return YES;
  234506. }
  234507. return NO;
  234508. }
  234509. virtual void openFiles (NSArray* filenames)
  234510. {
  234511. StringArray files;
  234512. for (unsigned int i = 0; i < [filenames count]; ++i)
  234513. {
  234514. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234515. if (filename.containsChar (' '))
  234516. filename = filename.quoted('"');
  234517. files.add (filename);
  234518. }
  234519. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234520. {
  234521. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234522. }
  234523. }
  234524. virtual void focusChanged()
  234525. {
  234526. juce_HandleProcessFocusChange();
  234527. }
  234528. struct CallbackMessagePayload
  234529. {
  234530. MessageCallbackFunction* function;
  234531. void* parameter;
  234532. void* volatile result;
  234533. bool volatile hasBeenExecuted;
  234534. };
  234535. virtual void performCallback (CallbackMessagePayload* pl)
  234536. {
  234537. pl->result = (*pl->function) (pl->parameter);
  234538. pl->hasBeenExecuted = true;
  234539. }
  234540. virtual void deleteSelf()
  234541. {
  234542. delete this;
  234543. }
  234544. void postMessage (Message* const m)
  234545. {
  234546. messages.add (m);
  234547. CFRunLoopSourceSignal (runLoopSource);
  234548. CFRunLoopWakeUp (runLoop);
  234549. }
  234550. private:
  234551. CFRunLoopRef runLoop;
  234552. CFRunLoopSourceRef runLoopSource;
  234553. OwnedArray <Message, CriticalSection> messages;
  234554. void runLoopCallback()
  234555. {
  234556. int numDispatched = 0;
  234557. do
  234558. {
  234559. Message* const nextMessage = messages.removeAndReturn (0);
  234560. if (nextMessage == 0)
  234561. return;
  234562. const ScopedAutoReleasePool pool;
  234563. MessageManager::getInstance()->deliverMessage (nextMessage);
  234564. } while (++numDispatched <= 4);
  234565. CFRunLoopSourceSignal (runLoopSource);
  234566. CFRunLoopWakeUp (runLoop);
  234567. }
  234568. static void runLoopSourceCallback (void* info)
  234569. {
  234570. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  234571. }
  234572. };
  234573. END_JUCE_NAMESPACE
  234574. using namespace JUCE_NAMESPACE;
  234575. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234576. @interface JuceAppDelegate : NSObject
  234577. {
  234578. @private
  234579. id oldDelegate;
  234580. @public
  234581. AppDelegateRedirector* redirector;
  234582. }
  234583. - (JuceAppDelegate*) init;
  234584. - (void) dealloc;
  234585. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234586. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234587. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234588. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234589. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234590. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234591. - (void) performCallback: (id) info;
  234592. - (void) dummyMethod;
  234593. @end
  234594. @implementation JuceAppDelegate
  234595. - (JuceAppDelegate*) init
  234596. {
  234597. [super init];
  234598. redirector = new AppDelegateRedirector();
  234599. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234600. if (JUCEApplication::isStandaloneApp())
  234601. {
  234602. oldDelegate = [NSApp delegate];
  234603. [NSApp setDelegate: self];
  234604. }
  234605. else
  234606. {
  234607. oldDelegate = 0;
  234608. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234609. name: NSApplicationDidResignActiveNotification object: NSApp];
  234610. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234611. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234612. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234613. name: NSApplicationWillUnhideNotification object: NSApp];
  234614. }
  234615. return self;
  234616. }
  234617. - (void) dealloc
  234618. {
  234619. if (oldDelegate != 0)
  234620. [NSApp setDelegate: oldDelegate];
  234621. redirector->deleteSelf();
  234622. [super dealloc];
  234623. }
  234624. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234625. {
  234626. (void) app;
  234627. return redirector->shouldTerminate();
  234628. }
  234629. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234630. {
  234631. (void) app;
  234632. return redirector->openFile (filename);
  234633. }
  234634. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234635. {
  234636. (void) sender;
  234637. return redirector->openFiles (filenames);
  234638. }
  234639. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234640. {
  234641. (void) notification;
  234642. redirector->focusChanged();
  234643. }
  234644. - (void) applicationDidResignActive: (NSNotification*) notification
  234645. {
  234646. (void) notification;
  234647. redirector->focusChanged();
  234648. }
  234649. - (void) applicationWillUnhide: (NSNotification*) notification
  234650. {
  234651. (void) notification;
  234652. redirector->focusChanged();
  234653. }
  234654. - (void) performCallback: (id) info
  234655. {
  234656. if ([info isKindOfClass: [NSData class]])
  234657. {
  234658. AppDelegateRedirector::CallbackMessagePayload* pl
  234659. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234660. if (pl != 0)
  234661. redirector->performCallback (pl);
  234662. }
  234663. else
  234664. {
  234665. jassertfalse; // should never get here!
  234666. }
  234667. }
  234668. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234669. @end
  234670. BEGIN_JUCE_NAMESPACE
  234671. static JuceAppDelegate* juceAppDelegate = 0;
  234672. void MessageManager::runDispatchLoop()
  234673. {
  234674. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234675. {
  234676. const ScopedAutoReleasePool pool;
  234677. // must only be called by the message thread!
  234678. jassert (isThisTheMessageThread());
  234679. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234680. @try
  234681. {
  234682. [NSApp run];
  234683. }
  234684. @catch (NSException* e)
  234685. {
  234686. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234687. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234688. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234689. }
  234690. @finally
  234691. {
  234692. }
  234693. #else
  234694. [NSApp run];
  234695. #endif
  234696. }
  234697. }
  234698. void MessageManager::stopDispatchLoop()
  234699. {
  234700. quitMessagePosted = true;
  234701. [NSApp stop: nil];
  234702. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234703. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234704. }
  234705. static bool isEventBlockedByModalComps (NSEvent* e)
  234706. {
  234707. if (Component::getNumCurrentlyModalComponents() == 0)
  234708. return false;
  234709. NSWindow* const w = [e window];
  234710. if (w == 0 || [w worksWhenModal])
  234711. return false;
  234712. bool isKey = false, isInputAttempt = false;
  234713. switch ([e type])
  234714. {
  234715. case NSKeyDown:
  234716. case NSKeyUp:
  234717. isKey = isInputAttempt = true;
  234718. break;
  234719. case NSLeftMouseDown:
  234720. case NSRightMouseDown:
  234721. case NSOtherMouseDown:
  234722. isInputAttempt = true;
  234723. break;
  234724. case NSLeftMouseDragged:
  234725. case NSRightMouseDragged:
  234726. case NSLeftMouseUp:
  234727. case NSRightMouseUp:
  234728. case NSOtherMouseUp:
  234729. case NSOtherMouseDragged:
  234730. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234731. return false;
  234732. break;
  234733. case NSMouseMoved:
  234734. case NSMouseEntered:
  234735. case NSMouseExited:
  234736. case NSCursorUpdate:
  234737. case NSScrollWheel:
  234738. case NSTabletPoint:
  234739. case NSTabletProximity:
  234740. break;
  234741. default:
  234742. return false;
  234743. }
  234744. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234745. {
  234746. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234747. NSView* const compView = (NSView*) peer->getNativeHandle();
  234748. if ([compView window] == w)
  234749. {
  234750. if (isKey)
  234751. {
  234752. if (compView == [w firstResponder])
  234753. return false;
  234754. }
  234755. else
  234756. {
  234757. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  234758. [compView bounds]))
  234759. return false;
  234760. }
  234761. }
  234762. }
  234763. if (isInputAttempt)
  234764. {
  234765. if (! [NSApp isActive])
  234766. [NSApp activateIgnoringOtherApps: YES];
  234767. Component* const modal = Component::getCurrentlyModalComponent (0);
  234768. if (modal != 0)
  234769. modal->inputAttemptWhenModal();
  234770. }
  234771. return true;
  234772. }
  234773. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234774. {
  234775. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234776. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234777. while (! quitMessagePosted)
  234778. {
  234779. const ScopedAutoReleasePool pool;
  234780. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234781. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234782. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234783. inMode: NSDefaultRunLoopMode
  234784. dequeue: YES];
  234785. if (e != 0 && ! isEventBlockedByModalComps (e))
  234786. [NSApp sendEvent: e];
  234787. if (Time::getMillisecondCounter() >= endTime)
  234788. break;
  234789. }
  234790. return ! quitMessagePosted;
  234791. }
  234792. void MessageManager::doPlatformSpecificInitialisation()
  234793. {
  234794. if (juceAppDelegate == 0)
  234795. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234796. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234797. // correctly (needed prior to 10.5)
  234798. if (! [NSThread isMultiThreaded])
  234799. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234800. toTarget: juceAppDelegate
  234801. withObject: nil];
  234802. }
  234803. void MessageManager::doPlatformSpecificShutdown()
  234804. {
  234805. if (juceAppDelegate != 0)
  234806. {
  234807. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234808. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234809. [juceAppDelegate release];
  234810. juceAppDelegate = 0;
  234811. }
  234812. }
  234813. bool juce_postMessageToSystemQueue (Message* message)
  234814. {
  234815. juceAppDelegate->redirector->postMessage (message);
  234816. return true;
  234817. }
  234818. void MessageManager::broadcastMessage (const String& value) throw()
  234819. {
  234820. }
  234821. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234822. {
  234823. if (isThisTheMessageThread())
  234824. {
  234825. return (*callback) (data);
  234826. }
  234827. else
  234828. {
  234829. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234830. // deadlock because the message manager is blocked from running, so can never
  234831. // call your function..
  234832. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234833. const ScopedAutoReleasePool pool;
  234834. AppDelegateRedirector::CallbackMessagePayload cmp;
  234835. cmp.function = callback;
  234836. cmp.parameter = data;
  234837. cmp.result = 0;
  234838. cmp.hasBeenExecuted = false;
  234839. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234840. withObject: [NSData dataWithBytesNoCopy: &cmp
  234841. length: sizeof (cmp)
  234842. freeWhenDone: NO]
  234843. waitUntilDone: YES];
  234844. return cmp.result;
  234845. }
  234846. }
  234847. #endif
  234848. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234849. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234850. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234851. // compiled on its own).
  234852. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234853. #if JUCE_MAC
  234854. END_JUCE_NAMESPACE
  234855. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234856. @interface DownloadClickDetector : NSObject
  234857. {
  234858. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234859. }
  234860. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234861. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234862. request: (NSURLRequest*) request
  234863. frame: (WebFrame*) frame
  234864. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234865. @end
  234866. @implementation DownloadClickDetector
  234867. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234868. {
  234869. [super init];
  234870. ownerComponent = ownerComponent_;
  234871. return self;
  234872. }
  234873. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234874. request: (NSURLRequest*) request
  234875. frame: (WebFrame*) frame
  234876. decisionListener: (id <WebPolicyDecisionListener>) listener
  234877. {
  234878. (void) sender;
  234879. (void) request;
  234880. (void) frame;
  234881. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234882. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234883. [listener use];
  234884. else
  234885. [listener ignore];
  234886. }
  234887. @end
  234888. BEGIN_JUCE_NAMESPACE
  234889. class WebBrowserComponentInternal : public NSViewComponent
  234890. {
  234891. public:
  234892. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234893. {
  234894. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234895. frameName: @""
  234896. groupName: @""];
  234897. setView (webView);
  234898. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234899. [webView setPolicyDelegate: clickListener];
  234900. }
  234901. ~WebBrowserComponentInternal()
  234902. {
  234903. [webView setPolicyDelegate: nil];
  234904. [clickListener release];
  234905. setView (0);
  234906. }
  234907. void goToURL (const String& url,
  234908. const StringArray* headers,
  234909. const MemoryBlock* postData)
  234910. {
  234911. NSMutableURLRequest* r
  234912. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234913. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234914. timeoutInterval: 30.0];
  234915. if (postData != 0 && postData->getSize() > 0)
  234916. {
  234917. [r setHTTPMethod: @"POST"];
  234918. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234919. length: postData->getSize()]];
  234920. }
  234921. if (headers != 0)
  234922. {
  234923. for (int i = 0; i < headers->size(); ++i)
  234924. {
  234925. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234926. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234927. [r setValue: juceStringToNS (headerValue)
  234928. forHTTPHeaderField: juceStringToNS (headerName)];
  234929. }
  234930. }
  234931. stop();
  234932. [[webView mainFrame] loadRequest: r];
  234933. }
  234934. void goBack()
  234935. {
  234936. [webView goBack];
  234937. }
  234938. void goForward()
  234939. {
  234940. [webView goForward];
  234941. }
  234942. void stop()
  234943. {
  234944. [webView stopLoading: nil];
  234945. }
  234946. void refresh()
  234947. {
  234948. [webView reload: nil];
  234949. }
  234950. private:
  234951. WebView* webView;
  234952. DownloadClickDetector* clickListener;
  234953. };
  234954. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234955. : browser (0),
  234956. blankPageShown (false),
  234957. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234958. {
  234959. setOpaque (true);
  234960. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234961. }
  234962. WebBrowserComponent::~WebBrowserComponent()
  234963. {
  234964. deleteAndZero (browser);
  234965. }
  234966. void WebBrowserComponent::goToURL (const String& url,
  234967. const StringArray* headers,
  234968. const MemoryBlock* postData)
  234969. {
  234970. lastURL = url;
  234971. lastHeaders.clear();
  234972. if (headers != 0)
  234973. lastHeaders = *headers;
  234974. lastPostData.setSize (0);
  234975. if (postData != 0)
  234976. lastPostData = *postData;
  234977. blankPageShown = false;
  234978. browser->goToURL (url, headers, postData);
  234979. }
  234980. void WebBrowserComponent::stop()
  234981. {
  234982. browser->stop();
  234983. }
  234984. void WebBrowserComponent::goBack()
  234985. {
  234986. lastURL = String::empty;
  234987. blankPageShown = false;
  234988. browser->goBack();
  234989. }
  234990. void WebBrowserComponent::goForward()
  234991. {
  234992. lastURL = String::empty;
  234993. browser->goForward();
  234994. }
  234995. void WebBrowserComponent::refresh()
  234996. {
  234997. browser->refresh();
  234998. }
  234999. void WebBrowserComponent::paint (Graphics&)
  235000. {
  235001. }
  235002. void WebBrowserComponent::checkWindowAssociation()
  235003. {
  235004. if (isShowing())
  235005. {
  235006. if (blankPageShown)
  235007. goBack();
  235008. }
  235009. else
  235010. {
  235011. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235012. {
  235013. // when the component becomes invisible, some stuff like flash
  235014. // carries on playing audio, so we need to force it onto a blank
  235015. // page to avoid this, (and send it back when it's made visible again).
  235016. blankPageShown = true;
  235017. browser->goToURL ("about:blank", 0, 0);
  235018. }
  235019. }
  235020. }
  235021. void WebBrowserComponent::reloadLastURL()
  235022. {
  235023. if (lastURL.isNotEmpty())
  235024. {
  235025. goToURL (lastURL, &lastHeaders, &lastPostData);
  235026. lastURL = String::empty;
  235027. }
  235028. }
  235029. void WebBrowserComponent::parentHierarchyChanged()
  235030. {
  235031. checkWindowAssociation();
  235032. }
  235033. void WebBrowserComponent::resized()
  235034. {
  235035. browser->setSize (getWidth(), getHeight());
  235036. }
  235037. void WebBrowserComponent::visibilityChanged()
  235038. {
  235039. checkWindowAssociation();
  235040. }
  235041. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235042. {
  235043. return true;
  235044. }
  235045. #else
  235046. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235047. {
  235048. }
  235049. WebBrowserComponent::~WebBrowserComponent()
  235050. {
  235051. }
  235052. void WebBrowserComponent::goToURL (const String& url,
  235053. const StringArray* headers,
  235054. const MemoryBlock* postData)
  235055. {
  235056. }
  235057. void WebBrowserComponent::stop()
  235058. {
  235059. }
  235060. void WebBrowserComponent::goBack()
  235061. {
  235062. }
  235063. void WebBrowserComponent::goForward()
  235064. {
  235065. }
  235066. void WebBrowserComponent::refresh()
  235067. {
  235068. }
  235069. void WebBrowserComponent::paint (Graphics& g)
  235070. {
  235071. }
  235072. void WebBrowserComponent::checkWindowAssociation()
  235073. {
  235074. }
  235075. void WebBrowserComponent::reloadLastURL()
  235076. {
  235077. }
  235078. void WebBrowserComponent::parentHierarchyChanged()
  235079. {
  235080. }
  235081. void WebBrowserComponent::resized()
  235082. {
  235083. }
  235084. void WebBrowserComponent::visibilityChanged()
  235085. {
  235086. }
  235087. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235088. {
  235089. return true;
  235090. }
  235091. #endif
  235092. #endif
  235093. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235094. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235095. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235096. // compiled on its own).
  235097. #if JUCE_INCLUDED_FILE
  235098. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235099. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235100. #endif
  235101. #undef log
  235102. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235103. #define log(a) Logger::writeToLog (a)
  235104. #else
  235105. #define log(a)
  235106. #endif
  235107. #undef OK
  235108. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235109. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235110. {
  235111. if (err == noErr)
  235112. return true;
  235113. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235114. jassertfalse;
  235115. return false;
  235116. }
  235117. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235118. #else
  235119. #define OK(a) (a == noErr)
  235120. #endif
  235121. class CoreAudioInternal : public Timer
  235122. {
  235123. public:
  235124. CoreAudioInternal (AudioDeviceID id)
  235125. : inputLatency (0),
  235126. outputLatency (0),
  235127. callback (0),
  235128. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235129. audioProcID (0),
  235130. #endif
  235131. isSlaveDevice (false),
  235132. deviceID (id),
  235133. started (false),
  235134. sampleRate (0),
  235135. bufferSize (512),
  235136. numInputChans (0),
  235137. numOutputChans (0),
  235138. callbacksAllowed (true),
  235139. numInputChannelInfos (0),
  235140. numOutputChannelInfos (0)
  235141. {
  235142. jassert (deviceID != 0);
  235143. updateDetailsFromDevice();
  235144. AudioObjectPropertyAddress pa;
  235145. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235146. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235147. pa.mElement = kAudioObjectPropertyElementWildcard;
  235148. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235149. }
  235150. ~CoreAudioInternal()
  235151. {
  235152. AudioObjectPropertyAddress pa;
  235153. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235154. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235155. pa.mElement = kAudioObjectPropertyElementWildcard;
  235156. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235157. stop (false);
  235158. }
  235159. void allocateTempBuffers()
  235160. {
  235161. const int tempBufSize = bufferSize + 4;
  235162. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235163. tempInputBuffers.calloc (numInputChans + 2);
  235164. tempOutputBuffers.calloc (numOutputChans + 2);
  235165. int i, count = 0;
  235166. for (i = 0; i < numInputChans; ++i)
  235167. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235168. for (i = 0; i < numOutputChans; ++i)
  235169. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235170. }
  235171. // returns the number of actual available channels
  235172. void fillInChannelInfo (const bool input)
  235173. {
  235174. int chanNum = 0;
  235175. UInt32 size;
  235176. AudioObjectPropertyAddress pa;
  235177. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235178. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235179. pa.mElement = kAudioObjectPropertyElementMaster;
  235180. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235181. {
  235182. HeapBlock <AudioBufferList> bufList;
  235183. bufList.calloc (size, 1);
  235184. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235185. {
  235186. const int numStreams = bufList->mNumberBuffers;
  235187. for (int i = 0; i < numStreams; ++i)
  235188. {
  235189. const AudioBuffer& b = bufList->mBuffers[i];
  235190. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235191. {
  235192. String name;
  235193. {
  235194. char channelName [256];
  235195. zerostruct (channelName);
  235196. UInt32 nameSize = sizeof (channelName);
  235197. UInt32 channelNum = chanNum + 1;
  235198. pa.mSelector = kAudioDevicePropertyChannelName;
  235199. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235200. name = String::fromUTF8 (channelName, nameSize);
  235201. }
  235202. if (input)
  235203. {
  235204. if (activeInputChans[chanNum])
  235205. {
  235206. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235207. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235208. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235209. ++numInputChannelInfos;
  235210. }
  235211. if (name.isEmpty())
  235212. name << "Input " << (chanNum + 1);
  235213. inChanNames.add (name);
  235214. }
  235215. else
  235216. {
  235217. if (activeOutputChans[chanNum])
  235218. {
  235219. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235220. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235221. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235222. ++numOutputChannelInfos;
  235223. }
  235224. if (name.isEmpty())
  235225. name << "Output " << (chanNum + 1);
  235226. outChanNames.add (name);
  235227. }
  235228. ++chanNum;
  235229. }
  235230. }
  235231. }
  235232. }
  235233. }
  235234. void updateDetailsFromDevice()
  235235. {
  235236. stopTimer();
  235237. if (deviceID == 0)
  235238. return;
  235239. const ScopedLock sl (callbackLock);
  235240. Float64 sr;
  235241. UInt32 size = sizeof (Float64);
  235242. AudioObjectPropertyAddress pa;
  235243. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235244. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235245. pa.mElement = kAudioObjectPropertyElementMaster;
  235246. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235247. sampleRate = sr;
  235248. UInt32 framesPerBuf;
  235249. size = sizeof (framesPerBuf);
  235250. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235251. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235252. {
  235253. bufferSize = framesPerBuf;
  235254. allocateTempBuffers();
  235255. }
  235256. bufferSizes.clear();
  235257. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235258. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235259. {
  235260. HeapBlock <AudioValueRange> ranges;
  235261. ranges.calloc (size, 1);
  235262. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235263. {
  235264. bufferSizes.add ((int) ranges[0].mMinimum);
  235265. for (int i = 32; i < 2048; i += 32)
  235266. {
  235267. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235268. {
  235269. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235270. {
  235271. bufferSizes.addIfNotAlreadyThere (i);
  235272. break;
  235273. }
  235274. }
  235275. }
  235276. if (bufferSize > 0)
  235277. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235278. }
  235279. }
  235280. if (bufferSizes.size() == 0 && bufferSize > 0)
  235281. bufferSizes.add (bufferSize);
  235282. sampleRates.clear();
  235283. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235284. String rates;
  235285. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235286. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235287. {
  235288. HeapBlock <AudioValueRange> ranges;
  235289. ranges.calloc (size, 1);
  235290. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235291. {
  235292. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235293. {
  235294. bool ok = false;
  235295. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235296. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235297. ok = true;
  235298. if (ok)
  235299. {
  235300. sampleRates.add (possibleRates[i]);
  235301. rates << possibleRates[i] << ' ';
  235302. }
  235303. }
  235304. }
  235305. }
  235306. if (sampleRates.size() == 0 && sampleRate > 0)
  235307. {
  235308. sampleRates.add (sampleRate);
  235309. rates << sampleRate;
  235310. }
  235311. log ("sr: " + rates);
  235312. inputLatency = 0;
  235313. outputLatency = 0;
  235314. UInt32 lat;
  235315. size = sizeof (lat);
  235316. pa.mSelector = kAudioDevicePropertyLatency;
  235317. pa.mScope = kAudioDevicePropertyScopeInput;
  235318. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  235319. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235320. inputLatency = (int) lat;
  235321. pa.mScope = kAudioDevicePropertyScopeOutput;
  235322. size = sizeof (lat);
  235323. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235324. outputLatency = (int) lat;
  235325. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235326. inChanNames.clear();
  235327. outChanNames.clear();
  235328. inputChannelInfo.calloc (numInputChans + 2);
  235329. numInputChannelInfos = 0;
  235330. outputChannelInfo.calloc (numOutputChans + 2);
  235331. numOutputChannelInfos = 0;
  235332. fillInChannelInfo (true);
  235333. fillInChannelInfo (false);
  235334. }
  235335. const StringArray getSources (bool input)
  235336. {
  235337. StringArray s;
  235338. HeapBlock <OSType> types;
  235339. const int num = getAllDataSourcesForDevice (deviceID, types);
  235340. for (int i = 0; i < num; ++i)
  235341. {
  235342. AudioValueTranslation avt;
  235343. char buffer[256];
  235344. avt.mInputData = &(types[i]);
  235345. avt.mInputDataSize = sizeof (UInt32);
  235346. avt.mOutputData = buffer;
  235347. avt.mOutputDataSize = 256;
  235348. UInt32 transSize = sizeof (avt);
  235349. AudioObjectPropertyAddress pa;
  235350. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235351. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235352. pa.mElement = kAudioObjectPropertyElementMaster;
  235353. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235354. {
  235355. DBG (buffer);
  235356. s.add (buffer);
  235357. }
  235358. }
  235359. return s;
  235360. }
  235361. int getCurrentSourceIndex (bool input) const
  235362. {
  235363. OSType currentSourceID = 0;
  235364. UInt32 size = sizeof (currentSourceID);
  235365. int result = -1;
  235366. AudioObjectPropertyAddress pa;
  235367. pa.mSelector = kAudioDevicePropertyDataSource;
  235368. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235369. pa.mElement = kAudioObjectPropertyElementMaster;
  235370. if (deviceID != 0)
  235371. {
  235372. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235373. {
  235374. HeapBlock <OSType> types;
  235375. const int num = getAllDataSourcesForDevice (deviceID, types);
  235376. for (int i = 0; i < num; ++i)
  235377. {
  235378. if (types[num] == currentSourceID)
  235379. {
  235380. result = i;
  235381. break;
  235382. }
  235383. }
  235384. }
  235385. }
  235386. return result;
  235387. }
  235388. void setCurrentSourceIndex (int index, bool input)
  235389. {
  235390. if (deviceID != 0)
  235391. {
  235392. HeapBlock <OSType> types;
  235393. const int num = getAllDataSourcesForDevice (deviceID, types);
  235394. if (((unsigned int) index) < (unsigned int) num)
  235395. {
  235396. AudioObjectPropertyAddress pa;
  235397. pa.mSelector = kAudioDevicePropertyDataSource;
  235398. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235399. pa.mElement = kAudioObjectPropertyElementMaster;
  235400. OSType typeId = types[index];
  235401. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235402. }
  235403. }
  235404. }
  235405. const String reopen (const BigInteger& inputChannels,
  235406. const BigInteger& outputChannels,
  235407. double newSampleRate,
  235408. int bufferSizeSamples)
  235409. {
  235410. String error;
  235411. log ("CoreAudio reopen");
  235412. callbacksAllowed = false;
  235413. stopTimer();
  235414. stop (false);
  235415. activeInputChans = inputChannels;
  235416. activeInputChans.setRange (inChanNames.size(),
  235417. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235418. false);
  235419. activeOutputChans = outputChannels;
  235420. activeOutputChans.setRange (outChanNames.size(),
  235421. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235422. false);
  235423. numInputChans = activeInputChans.countNumberOfSetBits();
  235424. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235425. // set sample rate
  235426. AudioObjectPropertyAddress pa;
  235427. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235428. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235429. pa.mElement = kAudioObjectPropertyElementMaster;
  235430. Float64 sr = newSampleRate;
  235431. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235432. {
  235433. error = "Couldn't change sample rate";
  235434. }
  235435. else
  235436. {
  235437. // change buffer size
  235438. UInt32 framesPerBuf = bufferSizeSamples;
  235439. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235440. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235441. {
  235442. error = "Couldn't change buffer size";
  235443. }
  235444. else
  235445. {
  235446. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235447. // correctly report their new settings until some random time in the future, so
  235448. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235449. // to make sure we're using the correct numbers..
  235450. updateDetailsFromDevice();
  235451. sampleRate = newSampleRate;
  235452. bufferSize = bufferSizeSamples;
  235453. if (sampleRates.size() == 0)
  235454. error = "Device has no available sample-rates";
  235455. else if (bufferSizes.size() == 0)
  235456. error = "Device has no available buffer-sizes";
  235457. else if (inputDevice != 0)
  235458. error = inputDevice->reopen (inputChannels,
  235459. outputChannels,
  235460. newSampleRate,
  235461. bufferSizeSamples);
  235462. }
  235463. }
  235464. callbacksAllowed = true;
  235465. return error;
  235466. }
  235467. bool start (AudioIODeviceCallback* cb)
  235468. {
  235469. if (! started)
  235470. {
  235471. callback = 0;
  235472. if (deviceID != 0)
  235473. {
  235474. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235475. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235476. #else
  235477. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235478. #endif
  235479. {
  235480. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235481. {
  235482. started = true;
  235483. }
  235484. else
  235485. {
  235486. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235487. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235488. #else
  235489. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235490. audioProcID = 0;
  235491. #endif
  235492. }
  235493. }
  235494. }
  235495. }
  235496. if (started)
  235497. {
  235498. const ScopedLock sl (callbackLock);
  235499. callback = cb;
  235500. }
  235501. if (inputDevice != 0)
  235502. return started && inputDevice->start (cb);
  235503. else
  235504. return started;
  235505. }
  235506. void stop (bool leaveInterruptRunning)
  235507. {
  235508. {
  235509. const ScopedLock sl (callbackLock);
  235510. callback = 0;
  235511. }
  235512. if (started
  235513. && (deviceID != 0)
  235514. && ! leaveInterruptRunning)
  235515. {
  235516. OK (AudioDeviceStop (deviceID, audioIOProc));
  235517. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235518. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235519. #else
  235520. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235521. audioProcID = 0;
  235522. #endif
  235523. started = false;
  235524. { const ScopedLock sl (callbackLock); }
  235525. // wait until it's definately stopped calling back..
  235526. for (int i = 40; --i >= 0;)
  235527. {
  235528. Thread::sleep (50);
  235529. UInt32 running = 0;
  235530. UInt32 size = sizeof (running);
  235531. AudioObjectPropertyAddress pa;
  235532. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235533. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235534. pa.mElement = kAudioObjectPropertyElementMaster;
  235535. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235536. if (running == 0)
  235537. break;
  235538. }
  235539. const ScopedLock sl (callbackLock);
  235540. }
  235541. if (inputDevice != 0)
  235542. inputDevice->stop (leaveInterruptRunning);
  235543. }
  235544. double getSampleRate() const
  235545. {
  235546. return sampleRate;
  235547. }
  235548. int getBufferSize() const
  235549. {
  235550. return bufferSize;
  235551. }
  235552. void audioCallback (const AudioBufferList* inInputData,
  235553. AudioBufferList* outOutputData)
  235554. {
  235555. int i;
  235556. const ScopedLock sl (callbackLock);
  235557. if (callback != 0)
  235558. {
  235559. if (inputDevice == 0)
  235560. {
  235561. for (i = numInputChans; --i >= 0;)
  235562. {
  235563. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235564. float* dest = tempInputBuffers [i];
  235565. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235566. + info.dataOffsetSamples;
  235567. const int stride = info.dataStrideSamples;
  235568. if (stride != 0) // if this is zero, info is invalid
  235569. {
  235570. for (int j = bufferSize; --j >= 0;)
  235571. {
  235572. *dest++ = *src;
  235573. src += stride;
  235574. }
  235575. }
  235576. }
  235577. }
  235578. if (! isSlaveDevice)
  235579. {
  235580. if (inputDevice == 0)
  235581. {
  235582. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235583. numInputChans,
  235584. tempOutputBuffers,
  235585. numOutputChans,
  235586. bufferSize);
  235587. }
  235588. else
  235589. {
  235590. jassert (inputDevice->bufferSize == bufferSize);
  235591. // Sometimes the two linked devices seem to get their callbacks in
  235592. // parallel, so we need to lock both devices to stop the input data being
  235593. // changed while inside our callback..
  235594. const ScopedLock sl2 (inputDevice->callbackLock);
  235595. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235596. inputDevice->numInputChans,
  235597. tempOutputBuffers,
  235598. numOutputChans,
  235599. bufferSize);
  235600. }
  235601. for (i = numOutputChans; --i >= 0;)
  235602. {
  235603. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235604. const float* src = tempOutputBuffers [i];
  235605. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235606. + info.dataOffsetSamples;
  235607. const int stride = info.dataStrideSamples;
  235608. if (stride != 0) // if this is zero, info is invalid
  235609. {
  235610. for (int j = bufferSize; --j >= 0;)
  235611. {
  235612. *dest = *src++;
  235613. dest += stride;
  235614. }
  235615. }
  235616. }
  235617. }
  235618. }
  235619. else
  235620. {
  235621. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235622. {
  235623. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235624. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235625. + info.dataOffsetSamples;
  235626. const int stride = info.dataStrideSamples;
  235627. if (stride != 0) // if this is zero, info is invalid
  235628. {
  235629. for (int j = bufferSize; --j >= 0;)
  235630. {
  235631. *dest = 0.0f;
  235632. dest += stride;
  235633. }
  235634. }
  235635. }
  235636. }
  235637. }
  235638. // called by callbacks
  235639. void deviceDetailsChanged()
  235640. {
  235641. if (callbacksAllowed)
  235642. startTimer (100);
  235643. }
  235644. void timerCallback()
  235645. {
  235646. stopTimer();
  235647. log ("CoreAudio device changed callback");
  235648. const double oldSampleRate = sampleRate;
  235649. const int oldBufferSize = bufferSize;
  235650. updateDetailsFromDevice();
  235651. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235652. {
  235653. callbacksAllowed = false;
  235654. stop (false);
  235655. updateDetailsFromDevice();
  235656. callbacksAllowed = true;
  235657. }
  235658. }
  235659. CoreAudioInternal* getRelatedDevice() const
  235660. {
  235661. UInt32 size = 0;
  235662. ScopedPointer <CoreAudioInternal> result;
  235663. AudioObjectPropertyAddress pa;
  235664. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235665. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235666. pa.mElement = kAudioObjectPropertyElementMaster;
  235667. if (deviceID != 0
  235668. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235669. && size > 0)
  235670. {
  235671. HeapBlock <AudioDeviceID> devs;
  235672. devs.calloc (size, 1);
  235673. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235674. {
  235675. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235676. {
  235677. if (devs[i] != deviceID && devs[i] != 0)
  235678. {
  235679. result = new CoreAudioInternal (devs[i]);
  235680. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235681. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235682. if (thisIsInput != otherIsInput
  235683. || (inChanNames.size() + outChanNames.size() == 0)
  235684. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235685. break;
  235686. result = 0;
  235687. }
  235688. }
  235689. }
  235690. }
  235691. return result.release();
  235692. }
  235693. juce_UseDebuggingNewOperator
  235694. int inputLatency, outputLatency;
  235695. BigInteger activeInputChans, activeOutputChans;
  235696. StringArray inChanNames, outChanNames;
  235697. Array <double> sampleRates;
  235698. Array <int> bufferSizes;
  235699. AudioIODeviceCallback* callback;
  235700. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235701. AudioDeviceIOProcID audioProcID;
  235702. #endif
  235703. ScopedPointer<CoreAudioInternal> inputDevice;
  235704. bool isSlaveDevice;
  235705. private:
  235706. CriticalSection callbackLock;
  235707. AudioDeviceID deviceID;
  235708. bool started;
  235709. double sampleRate;
  235710. int bufferSize;
  235711. HeapBlock <float> audioBuffer;
  235712. int numInputChans, numOutputChans;
  235713. bool callbacksAllowed;
  235714. struct CallbackDetailsForChannel
  235715. {
  235716. int streamNum;
  235717. int dataOffsetSamples;
  235718. int dataStrideSamples;
  235719. };
  235720. int numInputChannelInfos, numOutputChannelInfos;
  235721. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235722. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235723. CoreAudioInternal (const CoreAudioInternal&);
  235724. CoreAudioInternal& operator= (const CoreAudioInternal&);
  235725. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235726. const AudioTimeStamp* /*inNow*/,
  235727. const AudioBufferList* inInputData,
  235728. const AudioTimeStamp* /*inInputTime*/,
  235729. AudioBufferList* outOutputData,
  235730. const AudioTimeStamp* /*inOutputTime*/,
  235731. void* device)
  235732. {
  235733. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235734. return noErr;
  235735. }
  235736. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235737. {
  235738. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235739. switch (pa->mSelector)
  235740. {
  235741. case kAudioDevicePropertyBufferSize:
  235742. case kAudioDevicePropertyBufferFrameSize:
  235743. case kAudioDevicePropertyNominalSampleRate:
  235744. case kAudioDevicePropertyStreamFormat:
  235745. case kAudioDevicePropertyDeviceIsAlive:
  235746. intern->deviceDetailsChanged();
  235747. break;
  235748. case kAudioDevicePropertyBufferSizeRange:
  235749. case kAudioDevicePropertyVolumeScalar:
  235750. case kAudioDevicePropertyMute:
  235751. case kAudioDevicePropertyPlayThru:
  235752. case kAudioDevicePropertyDataSource:
  235753. case kAudioDevicePropertyDeviceIsRunning:
  235754. break;
  235755. }
  235756. return noErr;
  235757. }
  235758. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235759. {
  235760. AudioObjectPropertyAddress pa;
  235761. pa.mSelector = kAudioDevicePropertyDataSources;
  235762. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235763. pa.mElement = kAudioObjectPropertyElementMaster;
  235764. UInt32 size = 0;
  235765. if (deviceID != 0
  235766. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235767. {
  235768. types.calloc (size, 1);
  235769. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235770. return size / (int) sizeof (OSType);
  235771. }
  235772. return 0;
  235773. }
  235774. };
  235775. class CoreAudioIODevice : public AudioIODevice
  235776. {
  235777. public:
  235778. CoreAudioIODevice (const String& deviceName,
  235779. AudioDeviceID inputDeviceId,
  235780. const int inputIndex_,
  235781. AudioDeviceID outputDeviceId,
  235782. const int outputIndex_)
  235783. : AudioIODevice (deviceName, "CoreAudio"),
  235784. inputIndex (inputIndex_),
  235785. outputIndex (outputIndex_),
  235786. isOpen_ (false),
  235787. isStarted (false)
  235788. {
  235789. CoreAudioInternal* device = 0;
  235790. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235791. {
  235792. jassert (inputDeviceId != 0);
  235793. device = new CoreAudioInternal (inputDeviceId);
  235794. }
  235795. else
  235796. {
  235797. device = new CoreAudioInternal (outputDeviceId);
  235798. if (inputDeviceId != 0)
  235799. {
  235800. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235801. device->inputDevice = secondDevice;
  235802. secondDevice->isSlaveDevice = true;
  235803. }
  235804. }
  235805. internal = device;
  235806. AudioObjectPropertyAddress pa;
  235807. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235808. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235809. pa.mElement = kAudioObjectPropertyElementWildcard;
  235810. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235811. }
  235812. ~CoreAudioIODevice()
  235813. {
  235814. AudioObjectPropertyAddress pa;
  235815. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235816. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235817. pa.mElement = kAudioObjectPropertyElementWildcard;
  235818. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235819. }
  235820. const StringArray getOutputChannelNames()
  235821. {
  235822. return internal->outChanNames;
  235823. }
  235824. const StringArray getInputChannelNames()
  235825. {
  235826. if (internal->inputDevice != 0)
  235827. return internal->inputDevice->inChanNames;
  235828. else
  235829. return internal->inChanNames;
  235830. }
  235831. int getNumSampleRates()
  235832. {
  235833. return internal->sampleRates.size();
  235834. }
  235835. double getSampleRate (int index)
  235836. {
  235837. return internal->sampleRates [index];
  235838. }
  235839. int getNumBufferSizesAvailable()
  235840. {
  235841. return internal->bufferSizes.size();
  235842. }
  235843. int getBufferSizeSamples (int index)
  235844. {
  235845. return internal->bufferSizes [index];
  235846. }
  235847. int getDefaultBufferSize()
  235848. {
  235849. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235850. if (getBufferSizeSamples(i) >= 512)
  235851. return getBufferSizeSamples(i);
  235852. return 512;
  235853. }
  235854. const String open (const BigInteger& inputChannels,
  235855. const BigInteger& outputChannels,
  235856. double sampleRate,
  235857. int bufferSizeSamples)
  235858. {
  235859. isOpen_ = true;
  235860. if (bufferSizeSamples <= 0)
  235861. bufferSizeSamples = getDefaultBufferSize();
  235862. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235863. isOpen_ = lastError.isEmpty();
  235864. return lastError;
  235865. }
  235866. void close()
  235867. {
  235868. isOpen_ = false;
  235869. internal->stop (false);
  235870. }
  235871. bool isOpen()
  235872. {
  235873. return isOpen_;
  235874. }
  235875. int getCurrentBufferSizeSamples()
  235876. {
  235877. return internal != 0 ? internal->getBufferSize() : 512;
  235878. }
  235879. double getCurrentSampleRate()
  235880. {
  235881. return internal != 0 ? internal->getSampleRate() : 0;
  235882. }
  235883. int getCurrentBitDepth()
  235884. {
  235885. return 32; // no way to find out, so just assume it's high..
  235886. }
  235887. const BigInteger getActiveOutputChannels() const
  235888. {
  235889. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235890. }
  235891. const BigInteger getActiveInputChannels() const
  235892. {
  235893. BigInteger chans;
  235894. if (internal != 0)
  235895. {
  235896. chans = internal->activeInputChans;
  235897. if (internal->inputDevice != 0)
  235898. chans |= internal->inputDevice->activeInputChans;
  235899. }
  235900. return chans;
  235901. }
  235902. int getOutputLatencyInSamples()
  235903. {
  235904. if (internal == 0)
  235905. return 0;
  235906. // this seems like a good guess at getting the latency right - comparing
  235907. // this with a round-trip measurement, it gets it to within a few millisecs
  235908. // for the built-in mac soundcard
  235909. return internal->outputLatency + internal->getBufferSize() * 2;
  235910. }
  235911. int getInputLatencyInSamples()
  235912. {
  235913. if (internal == 0)
  235914. return 0;
  235915. return internal->inputLatency + internal->getBufferSize() * 2;
  235916. }
  235917. void start (AudioIODeviceCallback* callback)
  235918. {
  235919. if (internal != 0 && ! isStarted)
  235920. {
  235921. if (callback != 0)
  235922. callback->audioDeviceAboutToStart (this);
  235923. isStarted = true;
  235924. internal->start (callback);
  235925. }
  235926. }
  235927. void stop()
  235928. {
  235929. if (isStarted && internal != 0)
  235930. {
  235931. AudioIODeviceCallback* const lastCallback = internal->callback;
  235932. isStarted = false;
  235933. internal->stop (true);
  235934. if (lastCallback != 0)
  235935. lastCallback->audioDeviceStopped();
  235936. }
  235937. }
  235938. bool isPlaying()
  235939. {
  235940. if (internal->callback == 0)
  235941. isStarted = false;
  235942. return isStarted;
  235943. }
  235944. const String getLastError()
  235945. {
  235946. return lastError;
  235947. }
  235948. int inputIndex, outputIndex;
  235949. juce_UseDebuggingNewOperator
  235950. private:
  235951. ScopedPointer<CoreAudioInternal> internal;
  235952. bool isOpen_, isStarted;
  235953. String lastError;
  235954. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235955. {
  235956. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235957. switch (pa->mSelector)
  235958. {
  235959. case kAudioHardwarePropertyDevices:
  235960. intern->deviceDetailsChanged();
  235961. break;
  235962. case kAudioHardwarePropertyDefaultOutputDevice:
  235963. case kAudioHardwarePropertyDefaultInputDevice:
  235964. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235965. break;
  235966. }
  235967. return noErr;
  235968. }
  235969. CoreAudioIODevice (const CoreAudioIODevice&);
  235970. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  235971. };
  235972. class CoreAudioIODeviceType : public AudioIODeviceType
  235973. {
  235974. public:
  235975. CoreAudioIODeviceType()
  235976. : AudioIODeviceType ("CoreAudio"),
  235977. hasScanned (false)
  235978. {
  235979. }
  235980. ~CoreAudioIODeviceType()
  235981. {
  235982. }
  235983. void scanForDevices()
  235984. {
  235985. hasScanned = true;
  235986. inputDeviceNames.clear();
  235987. outputDeviceNames.clear();
  235988. inputIds.clear();
  235989. outputIds.clear();
  235990. UInt32 size;
  235991. AudioObjectPropertyAddress pa;
  235992. pa.mSelector = kAudioHardwarePropertyDevices;
  235993. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235994. pa.mElement = kAudioObjectPropertyElementMaster;
  235995. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235996. {
  235997. HeapBlock <AudioDeviceID> devs;
  235998. devs.calloc (size, 1);
  235999. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236000. {
  236001. const int num = size / (int) sizeof (AudioDeviceID);
  236002. for (int i = 0; i < num; ++i)
  236003. {
  236004. char name [1024];
  236005. size = sizeof (name);
  236006. pa.mSelector = kAudioDevicePropertyDeviceName;
  236007. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236008. {
  236009. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236010. const int numIns = getNumChannels (devs[i], true);
  236011. const int numOuts = getNumChannels (devs[i], false);
  236012. if (numIns > 0)
  236013. {
  236014. inputDeviceNames.add (nameString);
  236015. inputIds.add (devs[i]);
  236016. }
  236017. if (numOuts > 0)
  236018. {
  236019. outputDeviceNames.add (nameString);
  236020. outputIds.add (devs[i]);
  236021. }
  236022. }
  236023. }
  236024. }
  236025. }
  236026. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236027. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236028. }
  236029. const StringArray getDeviceNames (bool wantInputNames) const
  236030. {
  236031. jassert (hasScanned); // need to call scanForDevices() before doing this
  236032. if (wantInputNames)
  236033. return inputDeviceNames;
  236034. else
  236035. return outputDeviceNames;
  236036. }
  236037. int getDefaultDeviceIndex (bool forInput) const
  236038. {
  236039. jassert (hasScanned); // need to call scanForDevices() before doing this
  236040. AudioDeviceID deviceID;
  236041. UInt32 size = sizeof (deviceID);
  236042. // if they're asking for any input channels at all, use the default input, so we
  236043. // get the built-in mic rather than the built-in output with no inputs..
  236044. AudioObjectPropertyAddress pa;
  236045. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236046. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236047. pa.mElement = kAudioObjectPropertyElementMaster;
  236048. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236049. {
  236050. if (forInput)
  236051. {
  236052. for (int i = inputIds.size(); --i >= 0;)
  236053. if (inputIds[i] == deviceID)
  236054. return i;
  236055. }
  236056. else
  236057. {
  236058. for (int i = outputIds.size(); --i >= 0;)
  236059. if (outputIds[i] == deviceID)
  236060. return i;
  236061. }
  236062. }
  236063. return 0;
  236064. }
  236065. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236066. {
  236067. jassert (hasScanned); // need to call scanForDevices() before doing this
  236068. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236069. if (d == 0)
  236070. return -1;
  236071. return asInput ? d->inputIndex
  236072. : d->outputIndex;
  236073. }
  236074. bool hasSeparateInputsAndOutputs() const { return true; }
  236075. AudioIODevice* createDevice (const String& outputDeviceName,
  236076. const String& inputDeviceName)
  236077. {
  236078. jassert (hasScanned); // need to call scanForDevices() before doing this
  236079. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236080. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236081. String deviceName (outputDeviceName);
  236082. if (deviceName.isEmpty())
  236083. deviceName = inputDeviceName;
  236084. if (index >= 0)
  236085. return new CoreAudioIODevice (deviceName,
  236086. inputIds [inputIndex],
  236087. inputIndex,
  236088. outputIds [outputIndex],
  236089. outputIndex);
  236090. return 0;
  236091. }
  236092. juce_UseDebuggingNewOperator
  236093. private:
  236094. StringArray inputDeviceNames, outputDeviceNames;
  236095. Array <AudioDeviceID> inputIds, outputIds;
  236096. bool hasScanned;
  236097. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236098. {
  236099. int total = 0;
  236100. UInt32 size;
  236101. AudioObjectPropertyAddress pa;
  236102. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236103. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236104. pa.mElement = kAudioObjectPropertyElementMaster;
  236105. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236106. {
  236107. HeapBlock <AudioBufferList> bufList;
  236108. bufList.calloc (size, 1);
  236109. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236110. {
  236111. const int numStreams = bufList->mNumberBuffers;
  236112. for (int i = 0; i < numStreams; ++i)
  236113. {
  236114. const AudioBuffer& b = bufList->mBuffers[i];
  236115. total += b.mNumberChannels;
  236116. }
  236117. }
  236118. }
  236119. return total;
  236120. }
  236121. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236122. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236123. };
  236124. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236125. {
  236126. return new CoreAudioIODeviceType();
  236127. }
  236128. #undef log
  236129. #endif
  236130. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236131. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236132. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236133. // compiled on its own).
  236134. #if JUCE_INCLUDED_FILE
  236135. #if JUCE_MAC
  236136. #undef log
  236137. #define log(a) Logger::writeToLog(a)
  236138. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  236139. {
  236140. if (err == noErr)
  236141. return true;
  236142. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236143. jassertfalse;
  236144. return false;
  236145. }
  236146. #undef OK
  236147. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  236148. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236149. {
  236150. String result;
  236151. CFStringRef str = 0;
  236152. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236153. if (str != 0)
  236154. {
  236155. result = PlatformUtilities::cfStringToJuceString (str);
  236156. CFRelease (str);
  236157. str = 0;
  236158. }
  236159. MIDIEntityRef entity = 0;
  236160. MIDIEndpointGetEntity (endpoint, &entity);
  236161. if (entity == 0)
  236162. return result; // probably virtual
  236163. if (result.isEmpty())
  236164. {
  236165. // endpoint name has zero length - try the entity
  236166. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236167. if (str != 0)
  236168. {
  236169. result += PlatformUtilities::cfStringToJuceString (str);
  236170. CFRelease (str);
  236171. str = 0;
  236172. }
  236173. }
  236174. // now consider the device's name
  236175. MIDIDeviceRef device = 0;
  236176. MIDIEntityGetDevice (entity, &device);
  236177. if (device == 0)
  236178. return result;
  236179. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236180. if (str != 0)
  236181. {
  236182. const String s (PlatformUtilities::cfStringToJuceString (str));
  236183. CFRelease (str);
  236184. // if an external device has only one entity, throw away
  236185. // the endpoint name and just use the device name
  236186. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236187. {
  236188. result = s;
  236189. }
  236190. else if (! result.startsWithIgnoreCase (s))
  236191. {
  236192. // prepend the device name to the entity name
  236193. result = (s + " " + result).trimEnd();
  236194. }
  236195. }
  236196. return result;
  236197. }
  236198. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236199. {
  236200. String result;
  236201. // Does the endpoint have connections?
  236202. CFDataRef connections = 0;
  236203. int numConnections = 0;
  236204. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236205. if (connections != 0)
  236206. {
  236207. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236208. if (numConnections > 0)
  236209. {
  236210. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236211. for (int i = 0; i < numConnections; ++i, ++pid)
  236212. {
  236213. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236214. MIDIObjectRef connObject;
  236215. MIDIObjectType connObjectType;
  236216. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236217. if (err == noErr)
  236218. {
  236219. String s;
  236220. if (connObjectType == kMIDIObjectType_ExternalSource
  236221. || connObjectType == kMIDIObjectType_ExternalDestination)
  236222. {
  236223. // Connected to an external device's endpoint (10.3 and later).
  236224. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236225. }
  236226. else
  236227. {
  236228. // Connected to an external device (10.2) (or something else, catch-all)
  236229. CFStringRef str = 0;
  236230. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236231. if (str != 0)
  236232. {
  236233. s = PlatformUtilities::cfStringToJuceString (str);
  236234. CFRelease (str);
  236235. }
  236236. }
  236237. if (s.isNotEmpty())
  236238. {
  236239. if (result.isNotEmpty())
  236240. result += ", ";
  236241. result += s;
  236242. }
  236243. }
  236244. }
  236245. }
  236246. CFRelease (connections);
  236247. }
  236248. if (result.isNotEmpty())
  236249. return result;
  236250. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236251. return getEndpointName (endpoint, false);
  236252. }
  236253. const StringArray MidiOutput::getDevices()
  236254. {
  236255. StringArray s;
  236256. const ItemCount num = MIDIGetNumberOfDestinations();
  236257. for (ItemCount i = 0; i < num; ++i)
  236258. {
  236259. MIDIEndpointRef dest = MIDIGetDestination (i);
  236260. if (dest != 0)
  236261. {
  236262. String name (getConnectedEndpointName (dest));
  236263. if (name.isEmpty())
  236264. name = "<error>";
  236265. s.add (name);
  236266. }
  236267. else
  236268. {
  236269. s.add ("<error>");
  236270. }
  236271. }
  236272. return s;
  236273. }
  236274. int MidiOutput::getDefaultDeviceIndex()
  236275. {
  236276. return 0;
  236277. }
  236278. static MIDIClientRef globalMidiClient;
  236279. static bool hasGlobalClientBeenCreated = false;
  236280. static bool makeSureClientExists()
  236281. {
  236282. if (! hasGlobalClientBeenCreated)
  236283. {
  236284. String name ("JUCE");
  236285. if (JUCEApplication::getInstance() != 0)
  236286. name = JUCEApplication::getInstance()->getApplicationName();
  236287. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236288. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236289. CFRelease (appName);
  236290. }
  236291. return hasGlobalClientBeenCreated;
  236292. }
  236293. class MidiPortAndEndpoint
  236294. {
  236295. public:
  236296. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236297. : port (port_), endPoint (endPoint_)
  236298. {
  236299. }
  236300. ~MidiPortAndEndpoint()
  236301. {
  236302. if (port != 0)
  236303. MIDIPortDispose (port);
  236304. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236305. MIDIEndpointDispose (endPoint);
  236306. }
  236307. MIDIPortRef port;
  236308. MIDIEndpointRef endPoint;
  236309. };
  236310. MidiOutput* MidiOutput::openDevice (int index)
  236311. {
  236312. MidiOutput* mo = 0;
  236313. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236314. {
  236315. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236316. CFStringRef pname;
  236317. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236318. {
  236319. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  236320. if (makeSureClientExists())
  236321. {
  236322. MIDIPortRef port;
  236323. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  236324. {
  236325. mo = new MidiOutput();
  236326. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  236327. }
  236328. }
  236329. CFRelease (pname);
  236330. }
  236331. }
  236332. return mo;
  236333. }
  236334. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236335. {
  236336. MidiOutput* mo = 0;
  236337. if (makeSureClientExists())
  236338. {
  236339. MIDIEndpointRef endPoint;
  236340. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236341. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  236342. {
  236343. mo = new MidiOutput();
  236344. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  236345. }
  236346. CFRelease (name);
  236347. }
  236348. return mo;
  236349. }
  236350. MidiOutput::~MidiOutput()
  236351. {
  236352. delete static_cast<MidiPortAndEndpoint*> (internal);
  236353. }
  236354. void MidiOutput::reset()
  236355. {
  236356. }
  236357. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236358. {
  236359. return false;
  236360. }
  236361. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236362. {
  236363. }
  236364. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236365. {
  236366. MidiPortAndEndpoint* const mpe = static_cast<MidiPortAndEndpoint*> (internal);
  236367. if (message.isSysEx())
  236368. {
  236369. const int maxPacketSize = 256;
  236370. int pos = 0, bytesLeft = message.getRawDataSize();
  236371. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236372. HeapBlock <MIDIPacketList> packets;
  236373. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236374. packets->numPackets = numPackets;
  236375. MIDIPacket* p = packets->packet;
  236376. for (int i = 0; i < numPackets; ++i)
  236377. {
  236378. p->timeStamp = 0;
  236379. p->length = jmin (maxPacketSize, bytesLeft);
  236380. memcpy (p->data, message.getRawData() + pos, p->length);
  236381. pos += p->length;
  236382. bytesLeft -= p->length;
  236383. p = MIDIPacketNext (p);
  236384. }
  236385. if (mpe->port != 0)
  236386. MIDISend (mpe->port, mpe->endPoint, packets);
  236387. else
  236388. MIDIReceived (mpe->endPoint, packets);
  236389. }
  236390. else
  236391. {
  236392. MIDIPacketList packets;
  236393. packets.numPackets = 1;
  236394. packets.packet[0].timeStamp = 0;
  236395. packets.packet[0].length = message.getRawDataSize();
  236396. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236397. if (mpe->port != 0)
  236398. MIDISend (mpe->port, mpe->endPoint, &packets);
  236399. else
  236400. MIDIReceived (mpe->endPoint, &packets);
  236401. }
  236402. }
  236403. const StringArray MidiInput::getDevices()
  236404. {
  236405. StringArray s;
  236406. const ItemCount num = MIDIGetNumberOfSources();
  236407. for (ItemCount i = 0; i < num; ++i)
  236408. {
  236409. MIDIEndpointRef source = MIDIGetSource (i);
  236410. if (source != 0)
  236411. {
  236412. String name (getConnectedEndpointName (source));
  236413. if (name.isEmpty())
  236414. name = "<error>";
  236415. s.add (name);
  236416. }
  236417. else
  236418. {
  236419. s.add ("<error>");
  236420. }
  236421. }
  236422. return s;
  236423. }
  236424. int MidiInput::getDefaultDeviceIndex()
  236425. {
  236426. return 0;
  236427. }
  236428. struct MidiPortAndCallback
  236429. {
  236430. MidiInput* input;
  236431. MidiPortAndEndpoint* portAndEndpoint;
  236432. MidiInputCallback* callback;
  236433. MemoryBlock pendingData;
  236434. int pendingBytes;
  236435. double pendingDataTime;
  236436. bool active;
  236437. void processSysex (const uint8*& d, int& size, const double time)
  236438. {
  236439. if (*d == 0xf0)
  236440. {
  236441. pendingBytes = 0;
  236442. pendingDataTime = time;
  236443. }
  236444. pendingData.ensureSize (pendingBytes + size, false);
  236445. uint8* totalMessage = (uint8*) pendingData.getData();
  236446. uint8* dest = totalMessage + pendingBytes;
  236447. while (size > 0)
  236448. {
  236449. if (pendingBytes > 0 && *d >= 0x80)
  236450. {
  236451. if (*d >= 0xfa || *d == 0xf8)
  236452. {
  236453. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  236454. ++d;
  236455. --size;
  236456. }
  236457. else
  236458. {
  236459. if (*d == 0xf7)
  236460. {
  236461. *dest++ = *d++;
  236462. pendingBytes++;
  236463. --size;
  236464. }
  236465. break;
  236466. }
  236467. }
  236468. else
  236469. {
  236470. *dest++ = *d++;
  236471. pendingBytes++;
  236472. --size;
  236473. }
  236474. }
  236475. if (totalMessage [pendingBytes - 1] == 0xf7)
  236476. {
  236477. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  236478. pendingBytes = 0;
  236479. }
  236480. else
  236481. {
  236482. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  236483. }
  236484. }
  236485. };
  236486. namespace CoreMidiCallbacks
  236487. {
  236488. static CriticalSection callbackLock;
  236489. static Array<void*> activeCallbacks;
  236490. }
  236491. static void midiInputProc (const MIDIPacketList* pktlist,
  236492. void* readProcRefCon,
  236493. void* /*srcConnRefCon*/)
  236494. {
  236495. double time = Time::getMillisecondCounterHiRes() * 0.001;
  236496. const double originalTime = time;
  236497. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  236498. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236499. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  236500. {
  236501. const MIDIPacket* packet = &pktlist->packet[0];
  236502. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236503. {
  236504. const uint8* d = (const uint8*) (packet->data);
  236505. int size = packet->length;
  236506. while (size > 0)
  236507. {
  236508. time = originalTime;
  236509. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  236510. {
  236511. mpc->processSysex (d, size, time);
  236512. }
  236513. else
  236514. {
  236515. int used = 0;
  236516. const MidiMessage m (d, size, used, 0, time);
  236517. if (used <= 0)
  236518. {
  236519. jassertfalse; // malformed midi message
  236520. break;
  236521. }
  236522. else
  236523. {
  236524. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  236525. }
  236526. size -= used;
  236527. d += used;
  236528. }
  236529. }
  236530. packet = MIDIPacketNext (packet);
  236531. }
  236532. }
  236533. }
  236534. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236535. {
  236536. MidiInput* mi = 0;
  236537. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236538. {
  236539. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236540. if (endPoint != 0)
  236541. {
  236542. CFStringRef pname;
  236543. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236544. {
  236545. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  236546. if (makeSureClientExists())
  236547. {
  236548. MIDIPortRef port;
  236549. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  236550. mpc->active = false;
  236551. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  236552. {
  236553. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  236554. {
  236555. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236556. mpc->callback = callback;
  236557. mpc->pendingBytes = 0;
  236558. mpc->pendingData.ensureSize (128);
  236559. mi = new MidiInput (getDevices() [index]);
  236560. mpc->input = mi;
  236561. mi->internal = mpc;
  236562. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236563. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  236564. }
  236565. else
  236566. {
  236567. OK (MIDIPortDispose (port));
  236568. }
  236569. }
  236570. }
  236571. }
  236572. CFRelease (pname);
  236573. }
  236574. }
  236575. return mi;
  236576. }
  236577. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236578. {
  236579. MidiInput* mi = 0;
  236580. if (makeSureClientExists())
  236581. {
  236582. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  236583. mpc->active = false;
  236584. MIDIEndpointRef endPoint;
  236585. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236586. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  236587. {
  236588. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236589. mpc->callback = callback;
  236590. mpc->pendingBytes = 0;
  236591. mpc->pendingData.ensureSize (128);
  236592. mi = new MidiInput (deviceName);
  236593. mpc->input = mi;
  236594. mi->internal = mpc;
  236595. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236596. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  236597. }
  236598. CFRelease (name);
  236599. }
  236600. return mi;
  236601. }
  236602. MidiInput::MidiInput (const String& name_)
  236603. : name (name_)
  236604. {
  236605. }
  236606. MidiInput::~MidiInput()
  236607. {
  236608. MidiPortAndCallback* const mpc = static_cast<MidiPortAndCallback*> (internal);
  236609. mpc->active = false;
  236610. {
  236611. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236612. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  236613. }
  236614. if (mpc->portAndEndpoint->port != 0)
  236615. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  236616. delete mpc->portAndEndpoint;
  236617. delete mpc;
  236618. }
  236619. void MidiInput::start()
  236620. {
  236621. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236622. static_cast<MidiPortAndCallback*> (internal)->active = true;
  236623. }
  236624. void MidiInput::stop()
  236625. {
  236626. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236627. static_cast<MidiPortAndCallback*> (internal)->active = false;
  236628. }
  236629. #undef log
  236630. #else
  236631. MidiOutput::~MidiOutput()
  236632. {
  236633. }
  236634. void MidiOutput::reset()
  236635. {
  236636. }
  236637. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236638. {
  236639. return false;
  236640. }
  236641. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236642. {
  236643. }
  236644. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236645. {
  236646. }
  236647. const StringArray MidiOutput::getDevices()
  236648. {
  236649. return StringArray();
  236650. }
  236651. MidiOutput* MidiOutput::openDevice (int index)
  236652. {
  236653. return 0;
  236654. }
  236655. const StringArray MidiInput::getDevices()
  236656. {
  236657. return StringArray();
  236658. }
  236659. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236660. {
  236661. return 0;
  236662. }
  236663. #endif
  236664. #endif
  236665. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236666. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236667. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236668. // compiled on its own).
  236669. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236670. #if ! JUCE_QUICKTIME
  236671. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236672. #endif
  236673. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236674. class QTCameraDeviceInteral;
  236675. END_JUCE_NAMESPACE
  236676. @interface QTCaptureCallbackDelegate : NSObject
  236677. {
  236678. @public
  236679. CameraDevice* owner;
  236680. QTCameraDeviceInteral* internal;
  236681. int64 firstPresentationTime;
  236682. int64 averageTimeOffset;
  236683. }
  236684. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236685. - (void) dealloc;
  236686. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236687. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236688. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236689. fromConnection: (QTCaptureConnection*) connection;
  236690. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236691. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236692. fromConnection: (QTCaptureConnection*) connection;
  236693. @end
  236694. BEGIN_JUCE_NAMESPACE
  236695. class QTCameraDeviceInteral
  236696. {
  236697. public:
  236698. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236699. {
  236700. const ScopedAutoReleasePool pool;
  236701. session = [[QTCaptureSession alloc] init];
  236702. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236703. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236704. input = 0;
  236705. audioInput = 0;
  236706. audioDevice = 0;
  236707. fileOutput = 0;
  236708. imageOutput = 0;
  236709. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236710. internalDev: this];
  236711. NSError* err = 0;
  236712. [device retain];
  236713. [device open: &err];
  236714. if (err == 0)
  236715. {
  236716. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236717. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236718. [session addInput: input error: &err];
  236719. if (err == 0)
  236720. {
  236721. resetFile();
  236722. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236723. [imageOutput setDelegate: callbackDelegate];
  236724. if (err == 0)
  236725. {
  236726. [session startRunning];
  236727. return;
  236728. }
  236729. }
  236730. }
  236731. openingError = nsStringToJuce ([err description]);
  236732. DBG (openingError);
  236733. }
  236734. ~QTCameraDeviceInteral()
  236735. {
  236736. [session stopRunning];
  236737. [session removeOutput: imageOutput];
  236738. [session release];
  236739. [input release];
  236740. [device release];
  236741. [audioDevice release];
  236742. [audioInput release];
  236743. [fileOutput release];
  236744. [imageOutput release];
  236745. [callbackDelegate release];
  236746. }
  236747. void resetFile()
  236748. {
  236749. [fileOutput recordToOutputFileURL: nil];
  236750. [session removeOutput: fileOutput];
  236751. [fileOutput release];
  236752. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236753. [session removeInput: audioInput];
  236754. [audioInput release];
  236755. audioInput = 0;
  236756. [audioDevice release];
  236757. audioDevice = 0;
  236758. [fileOutput setDelegate: callbackDelegate];
  236759. }
  236760. void addDefaultAudioInput()
  236761. {
  236762. NSError* err = nil;
  236763. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236764. if ([audioDevice open: &err])
  236765. [audioDevice retain];
  236766. else
  236767. audioDevice = nil;
  236768. if (audioDevice != 0)
  236769. {
  236770. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236771. [session addInput: audioInput error: &err];
  236772. }
  236773. }
  236774. void addListener (CameraDevice::Listener* listenerToAdd)
  236775. {
  236776. const ScopedLock sl (listenerLock);
  236777. if (listeners.size() == 0)
  236778. [session addOutput: imageOutput error: nil];
  236779. listeners.addIfNotAlreadyThere (listenerToAdd);
  236780. }
  236781. void removeListener (CameraDevice::Listener* listenerToRemove)
  236782. {
  236783. const ScopedLock sl (listenerLock);
  236784. listeners.removeValue (listenerToRemove);
  236785. if (listeners.size() == 0)
  236786. [session removeOutput: imageOutput];
  236787. }
  236788. void callListeners (CIImage* frame, int w, int h)
  236789. {
  236790. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236791. Image image (cgImage);
  236792. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236793. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236794. CGContextFlush (cgImage->context);
  236795. const ScopedLock sl (listenerLock);
  236796. for (int i = listeners.size(); --i >= 0;)
  236797. {
  236798. CameraDevice::Listener* const l = listeners[i];
  236799. if (l != 0)
  236800. l->imageReceived (image);
  236801. }
  236802. }
  236803. QTCaptureDevice* device;
  236804. QTCaptureDeviceInput* input;
  236805. QTCaptureDevice* audioDevice;
  236806. QTCaptureDeviceInput* audioInput;
  236807. QTCaptureSession* session;
  236808. QTCaptureMovieFileOutput* fileOutput;
  236809. QTCaptureDecompressedVideoOutput* imageOutput;
  236810. QTCaptureCallbackDelegate* callbackDelegate;
  236811. String openingError;
  236812. Array<CameraDevice::Listener*> listeners;
  236813. CriticalSection listenerLock;
  236814. };
  236815. END_JUCE_NAMESPACE
  236816. @implementation QTCaptureCallbackDelegate
  236817. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236818. internalDev: (QTCameraDeviceInteral*) d
  236819. {
  236820. [super init];
  236821. owner = owner_;
  236822. internal = d;
  236823. firstPresentationTime = 0;
  236824. averageTimeOffset = 0;
  236825. return self;
  236826. }
  236827. - (void) dealloc
  236828. {
  236829. [super dealloc];
  236830. }
  236831. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236832. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236833. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236834. fromConnection: (QTCaptureConnection*) connection
  236835. {
  236836. if (internal->listeners.size() > 0)
  236837. {
  236838. const ScopedAutoReleasePool pool;
  236839. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236840. CVPixelBufferGetWidth (videoFrame),
  236841. CVPixelBufferGetHeight (videoFrame));
  236842. }
  236843. }
  236844. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236845. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236846. fromConnection: (QTCaptureConnection*) connection
  236847. {
  236848. const Time now (Time::getCurrentTime());
  236849. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236850. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236851. #else
  236852. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236853. #endif
  236854. int64 presentationTime = (hosttime != nil)
  236855. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236856. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236857. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236858. if (firstPresentationTime == 0)
  236859. {
  236860. firstPresentationTime = presentationTime;
  236861. averageTimeOffset = timeDiff;
  236862. }
  236863. else
  236864. {
  236865. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236866. }
  236867. }
  236868. @end
  236869. BEGIN_JUCE_NAMESPACE
  236870. class QTCaptureViewerComp : public NSViewComponent
  236871. {
  236872. public:
  236873. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236874. {
  236875. const ScopedAutoReleasePool pool;
  236876. captureView = [[QTCaptureView alloc] init];
  236877. [captureView setCaptureSession: internal->session];
  236878. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236879. setView (captureView);
  236880. }
  236881. ~QTCaptureViewerComp()
  236882. {
  236883. setView (0);
  236884. [captureView setCaptureSession: nil];
  236885. [captureView release];
  236886. }
  236887. QTCaptureView* captureView;
  236888. };
  236889. CameraDevice::CameraDevice (const String& name_, int index)
  236890. : name (name_)
  236891. {
  236892. isRecording = false;
  236893. internal = new QTCameraDeviceInteral (this, index);
  236894. }
  236895. CameraDevice::~CameraDevice()
  236896. {
  236897. stopRecording();
  236898. delete static_cast <QTCameraDeviceInteral*> (internal);
  236899. internal = 0;
  236900. }
  236901. Component* CameraDevice::createViewerComponent()
  236902. {
  236903. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236904. }
  236905. const String CameraDevice::getFileExtension()
  236906. {
  236907. return ".mov";
  236908. }
  236909. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236910. {
  236911. stopRecording();
  236912. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236913. d->callbackDelegate->firstPresentationTime = 0;
  236914. file.deleteFile();
  236915. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236916. // out wrong, so we'll put some audio in there too..,
  236917. d->addDefaultAudioInput();
  236918. [d->session addOutput: d->fileOutput error: nil];
  236919. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236920. for (;;)
  236921. {
  236922. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236923. if (connection == 0)
  236924. break;
  236925. QTCompressionOptions* options = 0;
  236926. NSString* mediaType = [connection mediaType];
  236927. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236928. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236929. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236930. : @"QTCompressionOptions240SizeH264Video"];
  236931. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236932. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236933. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236934. }
  236935. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236936. isRecording = true;
  236937. }
  236938. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236939. {
  236940. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236941. if (d->callbackDelegate->firstPresentationTime != 0)
  236942. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236943. return Time();
  236944. }
  236945. void CameraDevice::stopRecording()
  236946. {
  236947. if (isRecording)
  236948. {
  236949. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236950. isRecording = false;
  236951. }
  236952. }
  236953. void CameraDevice::addListener (Listener* listenerToAdd)
  236954. {
  236955. if (listenerToAdd != 0)
  236956. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236957. }
  236958. void CameraDevice::removeListener (Listener* listenerToRemove)
  236959. {
  236960. if (listenerToRemove != 0)
  236961. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236962. }
  236963. const StringArray CameraDevice::getAvailableDevices()
  236964. {
  236965. const ScopedAutoReleasePool pool;
  236966. StringArray results;
  236967. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236968. for (int i = 0; i < (int) [devs count]; ++i)
  236969. {
  236970. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236971. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236972. }
  236973. return results;
  236974. }
  236975. CameraDevice* CameraDevice::openDevice (int index,
  236976. int minWidth, int minHeight,
  236977. int maxWidth, int maxHeight)
  236978. {
  236979. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236980. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236981. return d.release();
  236982. return 0;
  236983. }
  236984. #endif
  236985. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236986. #endif
  236987. #endif
  236988. END_JUCE_NAMESPACE
  236989. #endif
  236990. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236991. #endif
  236992. #endif